File: | clang/lib/Sema/SemaType.cpp |
Warning: | line 7956, column 27 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// | ||||
2 | // | ||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
6 | // | ||||
7 | //===----------------------------------------------------------------------===// | ||||
8 | // | ||||
9 | // This file implements type-related semantic analysis. | ||||
10 | // | ||||
11 | //===----------------------------------------------------------------------===// | ||||
12 | |||||
13 | #include "TypeLocBuilder.h" | ||||
14 | #include "clang/AST/ASTConsumer.h" | ||||
15 | #include "clang/AST/ASTContext.h" | ||||
16 | #include "clang/AST/ASTMutationListener.h" | ||||
17 | #include "clang/AST/ASTStructuralEquivalence.h" | ||||
18 | #include "clang/AST/CXXInheritance.h" | ||||
19 | #include "clang/AST/DeclObjC.h" | ||||
20 | #include "clang/AST/DeclTemplate.h" | ||||
21 | #include "clang/AST/Expr.h" | ||||
22 | #include "clang/AST/TypeLoc.h" | ||||
23 | #include "clang/AST/TypeLocVisitor.h" | ||||
24 | #include "clang/Basic/PartialDiagnostic.h" | ||||
25 | #include "clang/Basic/TargetInfo.h" | ||||
26 | #include "clang/Lex/Preprocessor.h" | ||||
27 | #include "clang/Sema/DeclSpec.h" | ||||
28 | #include "clang/Sema/DelayedDiagnostic.h" | ||||
29 | #include "clang/Sema/Lookup.h" | ||||
30 | #include "clang/Sema/ParsedTemplate.h" | ||||
31 | #include "clang/Sema/ScopeInfo.h" | ||||
32 | #include "clang/Sema/SemaInternal.h" | ||||
33 | #include "clang/Sema/Template.h" | ||||
34 | #include "clang/Sema/TemplateInstCallback.h" | ||||
35 | #include "llvm/ADT/SmallPtrSet.h" | ||||
36 | #include "llvm/ADT/SmallString.h" | ||||
37 | #include "llvm/ADT/StringSwitch.h" | ||||
38 | #include "llvm/IR/DerivedTypes.h" | ||||
39 | #include "llvm/Support/ErrorHandling.h" | ||||
40 | #include <bitset> | ||||
41 | |||||
42 | using namespace clang; | ||||
43 | |||||
44 | enum TypeDiagSelector { | ||||
45 | TDS_Function, | ||||
46 | TDS_Pointer, | ||||
47 | TDS_ObjCObjOrBlock | ||||
48 | }; | ||||
49 | |||||
50 | /// isOmittedBlockReturnType - Return true if this declarator is missing a | ||||
51 | /// return type because this is a omitted return type on a block literal. | ||||
52 | static bool isOmittedBlockReturnType(const Declarator &D) { | ||||
53 | if (D.getContext() != DeclaratorContext::BlockLiteral || | ||||
54 | D.getDeclSpec().hasTypeSpecifier()) | ||||
55 | return false; | ||||
56 | |||||
57 | if (D.getNumTypeObjects() == 0) | ||||
58 | return true; // ^{ ... } | ||||
59 | |||||
60 | if (D.getNumTypeObjects() == 1 && | ||||
61 | D.getTypeObject(0).Kind == DeclaratorChunk::Function) | ||||
62 | return true; // ^(int X, float Y) { ... } | ||||
63 | |||||
64 | return false; | ||||
65 | } | ||||
66 | |||||
67 | /// diagnoseBadTypeAttribute - Diagnoses a type attribute which | ||||
68 | /// doesn't apply to the given type. | ||||
69 | static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, | ||||
70 | QualType type) { | ||||
71 | TypeDiagSelector WhichType; | ||||
72 | bool useExpansionLoc = true; | ||||
73 | switch (attr.getKind()) { | ||||
74 | case ParsedAttr::AT_ObjCGC: | ||||
75 | WhichType = TDS_Pointer; | ||||
76 | break; | ||||
77 | case ParsedAttr::AT_ObjCOwnership: | ||||
78 | WhichType = TDS_ObjCObjOrBlock; | ||||
79 | break; | ||||
80 | default: | ||||
81 | // Assume everything else was a function attribute. | ||||
82 | WhichType = TDS_Function; | ||||
83 | useExpansionLoc = false; | ||||
84 | break; | ||||
85 | } | ||||
86 | |||||
87 | SourceLocation loc = attr.getLoc(); | ||||
88 | StringRef name = attr.getAttrName()->getName(); | ||||
89 | |||||
90 | // The GC attributes are usually written with macros; special-case them. | ||||
91 | IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident | ||||
92 | : nullptr; | ||||
93 | if (useExpansionLoc && loc.isMacroID() && II) { | ||||
94 | if (II->isStr("strong")) { | ||||
95 | if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; | ||||
96 | } else if (II->isStr("weak")) { | ||||
97 | if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; | ||||
98 | } | ||||
99 | } | ||||
100 | |||||
101 | S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType | ||||
102 | << type; | ||||
103 | } | ||||
104 | |||||
105 | // objc_gc applies to Objective-C pointers or, otherwise, to the | ||||
106 | // smallest available pointer type (i.e. 'void*' in 'void**'). | ||||
107 | #define OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership \ | ||||
108 | case ParsedAttr::AT_ObjCGC: \ | ||||
109 | case ParsedAttr::AT_ObjCOwnership | ||||
110 | |||||
111 | // Calling convention attributes. | ||||
112 | #define CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll \ | ||||
113 | case ParsedAttr::AT_CDecl: \ | ||||
114 | case ParsedAttr::AT_FastCall: \ | ||||
115 | case ParsedAttr::AT_StdCall: \ | ||||
116 | case ParsedAttr::AT_ThisCall: \ | ||||
117 | case ParsedAttr::AT_RegCall: \ | ||||
118 | case ParsedAttr::AT_Pascal: \ | ||||
119 | case ParsedAttr::AT_SwiftCall: \ | ||||
120 | case ParsedAttr::AT_VectorCall: \ | ||||
121 | case ParsedAttr::AT_AArch64VectorPcs: \ | ||||
122 | case ParsedAttr::AT_MSABI: \ | ||||
123 | case ParsedAttr::AT_SysVABI: \ | ||||
124 | case ParsedAttr::AT_Pcs: \ | ||||
125 | case ParsedAttr::AT_IntelOclBicc: \ | ||||
126 | case ParsedAttr::AT_PreserveMost: \ | ||||
127 | case ParsedAttr::AT_PreserveAll | ||||
128 | |||||
129 | // Function type attributes. | ||||
130 | #define FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll \ | ||||
131 | case ParsedAttr::AT_NSReturnsRetained: \ | ||||
132 | case ParsedAttr::AT_NoReturn: \ | ||||
133 | case ParsedAttr::AT_Regparm: \ | ||||
134 | case ParsedAttr::AT_CmseNSCall: \ | ||||
135 | case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ | ||||
136 | case ParsedAttr::AT_AnyX86NoCfCheck: \ | ||||
137 | CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll | ||||
138 | |||||
139 | // Microsoft-specific type qualifiers. | ||||
140 | #define MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr \ | ||||
141 | case ParsedAttr::AT_Ptr32: \ | ||||
142 | case ParsedAttr::AT_Ptr64: \ | ||||
143 | case ParsedAttr::AT_SPtr: \ | ||||
144 | case ParsedAttr::AT_UPtr | ||||
145 | |||||
146 | // Nullability qualifiers. | ||||
147 | #define NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullUnspecified \ | ||||
148 | case ParsedAttr::AT_TypeNonNull: \ | ||||
149 | case ParsedAttr::AT_TypeNullable: \ | ||||
150 | case ParsedAttr::AT_TypeNullUnspecified | ||||
151 | |||||
152 | namespace { | ||||
153 | /// An object which stores processing state for the entire | ||||
154 | /// GetTypeForDeclarator process. | ||||
155 | class TypeProcessingState { | ||||
156 | Sema &sema; | ||||
157 | |||||
158 | /// The declarator being processed. | ||||
159 | Declarator &declarator; | ||||
160 | |||||
161 | /// The index of the declarator chunk we're currently processing. | ||||
162 | /// May be the total number of valid chunks, indicating the | ||||
163 | /// DeclSpec. | ||||
164 | unsigned chunkIndex; | ||||
165 | |||||
166 | /// Whether there are non-trivial modifications to the decl spec. | ||||
167 | bool trivial; | ||||
168 | |||||
169 | /// Whether we saved the attributes in the decl spec. | ||||
170 | bool hasSavedAttrs; | ||||
171 | |||||
172 | /// The original set of attributes on the DeclSpec. | ||||
173 | SmallVector<ParsedAttr *, 2> savedAttrs; | ||||
174 | |||||
175 | /// A list of attributes to diagnose the uselessness of when the | ||||
176 | /// processing is complete. | ||||
177 | SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; | ||||
178 | |||||
179 | /// Attributes corresponding to AttributedTypeLocs that we have not yet | ||||
180 | /// populated. | ||||
181 | // FIXME: The two-phase mechanism by which we construct Types and fill | ||||
182 | // their TypeLocs makes it hard to correctly assign these. We keep the | ||||
183 | // attributes in creation order as an attempt to make them line up | ||||
184 | // properly. | ||||
185 | using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; | ||||
186 | SmallVector<TypeAttrPair, 8> AttrsForTypes; | ||||
187 | bool AttrsForTypesSorted = true; | ||||
188 | |||||
189 | /// MacroQualifiedTypes mapping to macro expansion locations that will be | ||||
190 | /// stored in a MacroQualifiedTypeLoc. | ||||
191 | llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros; | ||||
192 | |||||
193 | /// Flag to indicate we parsed a noderef attribute. This is used for | ||||
194 | /// validating that noderef was used on a pointer or array. | ||||
195 | bool parsedNoDeref; | ||||
196 | |||||
197 | public: | ||||
198 | TypeProcessingState(Sema &sema, Declarator &declarator) | ||||
199 | : sema(sema), declarator(declarator), | ||||
200 | chunkIndex(declarator.getNumTypeObjects()), trivial(true), | ||||
201 | hasSavedAttrs(false), parsedNoDeref(false) {} | ||||
202 | |||||
203 | Sema &getSema() const { | ||||
204 | return sema; | ||||
205 | } | ||||
206 | |||||
207 | Declarator &getDeclarator() const { | ||||
208 | return declarator; | ||||
209 | } | ||||
210 | |||||
211 | bool isProcessingDeclSpec() const { | ||||
212 | return chunkIndex == declarator.getNumTypeObjects(); | ||||
213 | } | ||||
214 | |||||
215 | unsigned getCurrentChunkIndex() const { | ||||
216 | return chunkIndex; | ||||
217 | } | ||||
218 | |||||
219 | void setCurrentChunkIndex(unsigned idx) { | ||||
220 | assert(idx <= declarator.getNumTypeObjects())((idx <= declarator.getNumTypeObjects()) ? static_cast< void> (0) : __assert_fail ("idx <= declarator.getNumTypeObjects()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 220, __PRETTY_FUNCTION__)); | ||||
221 | chunkIndex = idx; | ||||
222 | } | ||||
223 | |||||
224 | ParsedAttributesView &getCurrentAttributes() const { | ||||
225 | if (isProcessingDeclSpec()) | ||||
226 | return getMutableDeclSpec().getAttributes(); | ||||
227 | return declarator.getTypeObject(chunkIndex).getAttrs(); | ||||
228 | } | ||||
229 | |||||
230 | /// Save the current set of attributes on the DeclSpec. | ||||
231 | void saveDeclSpecAttrs() { | ||||
232 | // Don't try to save them multiple times. | ||||
233 | if (hasSavedAttrs) return; | ||||
234 | |||||
235 | DeclSpec &spec = getMutableDeclSpec(); | ||||
236 | for (ParsedAttr &AL : spec.getAttributes()) | ||||
237 | savedAttrs.push_back(&AL); | ||||
238 | trivial &= savedAttrs.empty(); | ||||
239 | hasSavedAttrs = true; | ||||
240 | } | ||||
241 | |||||
242 | /// Record that we had nowhere to put the given type attribute. | ||||
243 | /// We will diagnose such attributes later. | ||||
244 | void addIgnoredTypeAttr(ParsedAttr &attr) { | ||||
245 | ignoredTypeAttrs.push_back(&attr); | ||||
246 | } | ||||
247 | |||||
248 | /// Diagnose all the ignored type attributes, given that the | ||||
249 | /// declarator worked out to the given type. | ||||
250 | void diagnoseIgnoredTypeAttrs(QualType type) const { | ||||
251 | for (auto *Attr : ignoredTypeAttrs) | ||||
252 | diagnoseBadTypeAttribute(getSema(), *Attr, type); | ||||
253 | } | ||||
254 | |||||
255 | /// Get an attributed type for the given attribute, and remember the Attr | ||||
256 | /// object so that we can attach it to the AttributedTypeLoc. | ||||
257 | QualType getAttributedType(Attr *A, QualType ModifiedType, | ||||
258 | QualType EquivType) { | ||||
259 | QualType T = | ||||
260 | sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType); | ||||
261 | AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); | ||||
262 | AttrsForTypesSorted = false; | ||||
263 | return T; | ||||
264 | } | ||||
265 | |||||
266 | /// Completely replace the \c auto in \p TypeWithAuto by | ||||
267 | /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if | ||||
268 | /// necessary. | ||||
269 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { | ||||
270 | QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); | ||||
271 | if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { | ||||
272 | // Attributed type still should be an attributed type after replacement. | ||||
273 | auto *NewAttrTy = cast<AttributedType>(T.getTypePtr()); | ||||
274 | for (TypeAttrPair &A : AttrsForTypes) { | ||||
275 | if (A.first == AttrTy) | ||||
276 | A.first = NewAttrTy; | ||||
277 | } | ||||
278 | AttrsForTypesSorted = false; | ||||
279 | } | ||||
280 | return T; | ||||
281 | } | ||||
282 | |||||
283 | /// Extract and remove the Attr* for a given attributed type. | ||||
284 | const Attr *takeAttrForAttributedType(const AttributedType *AT) { | ||||
285 | if (!AttrsForTypesSorted) { | ||||
286 | llvm::stable_sort(AttrsForTypes, llvm::less_first()); | ||||
287 | AttrsForTypesSorted = true; | ||||
288 | } | ||||
289 | |||||
290 | // FIXME: This is quadratic if we have lots of reuses of the same | ||||
291 | // attributed type. | ||||
292 | for (auto It = std::partition_point( | ||||
293 | AttrsForTypes.begin(), AttrsForTypes.end(), | ||||
294 | [=](const TypeAttrPair &A) { return A.first < AT; }); | ||||
295 | It != AttrsForTypes.end() && It->first == AT; ++It) { | ||||
296 | if (It->second) { | ||||
297 | const Attr *Result = It->second; | ||||
298 | It->second = nullptr; | ||||
299 | return Result; | ||||
300 | } | ||||
301 | } | ||||
302 | |||||
303 | llvm_unreachable("no Attr* for AttributedType*")::llvm::llvm_unreachable_internal("no Attr* for AttributedType*" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 303); | ||||
304 | } | ||||
305 | |||||
306 | SourceLocation | ||||
307 | getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const { | ||||
308 | auto FoundLoc = LocsForMacros.find(MQT); | ||||
309 | assert(FoundLoc != LocsForMacros.end() &&((FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType" ) ? static_cast<void> (0) : __assert_fail ("FoundLoc != LocsForMacros.end() && \"Unable to find macro expansion location for MacroQualifedType\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 310, __PRETTY_FUNCTION__)) | ||||
310 | "Unable to find macro expansion location for MacroQualifedType")((FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType" ) ? static_cast<void> (0) : __assert_fail ("FoundLoc != LocsForMacros.end() && \"Unable to find macro expansion location for MacroQualifedType\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 310, __PRETTY_FUNCTION__)); | ||||
311 | return FoundLoc->second; | ||||
312 | } | ||||
313 | |||||
314 | void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT, | ||||
315 | SourceLocation Loc) { | ||||
316 | LocsForMacros[MQT] = Loc; | ||||
317 | } | ||||
318 | |||||
319 | void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } | ||||
320 | |||||
321 | bool didParseNoDeref() const { return parsedNoDeref; } | ||||
322 | |||||
323 | ~TypeProcessingState() { | ||||
324 | if (trivial) return; | ||||
325 | |||||
326 | restoreDeclSpecAttrs(); | ||||
327 | } | ||||
328 | |||||
329 | private: | ||||
330 | DeclSpec &getMutableDeclSpec() const { | ||||
331 | return const_cast<DeclSpec&>(declarator.getDeclSpec()); | ||||
332 | } | ||||
333 | |||||
334 | void restoreDeclSpecAttrs() { | ||||
335 | assert(hasSavedAttrs)((hasSavedAttrs) ? static_cast<void> (0) : __assert_fail ("hasSavedAttrs", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 335, __PRETTY_FUNCTION__)); | ||||
336 | |||||
337 | getMutableDeclSpec().getAttributes().clearListOnly(); | ||||
338 | for (ParsedAttr *AL : savedAttrs) | ||||
339 | getMutableDeclSpec().getAttributes().addAtEnd(AL); | ||||
340 | } | ||||
341 | }; | ||||
342 | } // end anonymous namespace | ||||
343 | |||||
344 | static void moveAttrFromListToList(ParsedAttr &attr, | ||||
345 | ParsedAttributesView &fromList, | ||||
346 | ParsedAttributesView &toList) { | ||||
347 | fromList.remove(&attr); | ||||
348 | toList.addAtEnd(&attr); | ||||
349 | } | ||||
350 | |||||
351 | /// The location of a type attribute. | ||||
352 | enum TypeAttrLocation { | ||||
353 | /// The attribute is in the decl-specifier-seq. | ||||
354 | TAL_DeclSpec, | ||||
355 | /// The attribute is part of a DeclaratorChunk. | ||||
356 | TAL_DeclChunk, | ||||
357 | /// The attribute is immediately after the declaration's name. | ||||
358 | TAL_DeclName | ||||
359 | }; | ||||
360 | |||||
361 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, | ||||
362 | TypeAttrLocation TAL, ParsedAttributesView &attrs); | ||||
363 | |||||
364 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | ||||
365 | QualType &type); | ||||
366 | |||||
367 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, | ||||
368 | ParsedAttr &attr, QualType &type); | ||||
369 | |||||
370 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | ||||
371 | QualType &type); | ||||
372 | |||||
373 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | ||||
374 | ParsedAttr &attr, QualType &type); | ||||
375 | |||||
376 | static bool handleObjCPointerTypeAttr(TypeProcessingState &state, | ||||
377 | ParsedAttr &attr, QualType &type) { | ||||
378 | if (attr.getKind() == ParsedAttr::AT_ObjCGC) | ||||
379 | return handleObjCGCTypeAttr(state, attr, type); | ||||
380 | assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership)((attr.getKind() == ParsedAttr::AT_ObjCOwnership) ? static_cast <void> (0) : __assert_fail ("attr.getKind() == ParsedAttr::AT_ObjCOwnership" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 380, __PRETTY_FUNCTION__)); | ||||
381 | return handleObjCOwnershipTypeAttr(state, attr, type); | ||||
382 | } | ||||
383 | |||||
384 | /// Given the index of a declarator chunk, check whether that chunk | ||||
385 | /// directly specifies the return type of a function and, if so, find | ||||
386 | /// an appropriate place for it. | ||||
387 | /// | ||||
388 | /// \param i - a notional index which the search will start | ||||
389 | /// immediately inside | ||||
390 | /// | ||||
391 | /// \param onlyBlockPointers Whether we should only look into block | ||||
392 | /// pointer types (vs. all pointer types). | ||||
393 | static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, | ||||
394 | unsigned i, | ||||
395 | bool onlyBlockPointers) { | ||||
396 | assert(i <= declarator.getNumTypeObjects())((i <= declarator.getNumTypeObjects()) ? static_cast<void > (0) : __assert_fail ("i <= declarator.getNumTypeObjects()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 396, __PRETTY_FUNCTION__)); | ||||
397 | |||||
398 | DeclaratorChunk *result = nullptr; | ||||
399 | |||||
400 | // First, look inwards past parens for a function declarator. | ||||
401 | for (; i != 0; --i) { | ||||
402 | DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); | ||||
403 | switch (fnChunk.Kind) { | ||||
404 | case DeclaratorChunk::Paren: | ||||
405 | continue; | ||||
406 | |||||
407 | // If we find anything except a function, bail out. | ||||
408 | case DeclaratorChunk::Pointer: | ||||
409 | case DeclaratorChunk::BlockPointer: | ||||
410 | case DeclaratorChunk::Array: | ||||
411 | case DeclaratorChunk::Reference: | ||||
412 | case DeclaratorChunk::MemberPointer: | ||||
413 | case DeclaratorChunk::Pipe: | ||||
414 | return result; | ||||
415 | |||||
416 | // If we do find a function declarator, scan inwards from that, | ||||
417 | // looking for a (block-)pointer declarator. | ||||
418 | case DeclaratorChunk::Function: | ||||
419 | for (--i; i != 0; --i) { | ||||
420 | DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); | ||||
421 | switch (ptrChunk.Kind) { | ||||
422 | case DeclaratorChunk::Paren: | ||||
423 | case DeclaratorChunk::Array: | ||||
424 | case DeclaratorChunk::Function: | ||||
425 | case DeclaratorChunk::Reference: | ||||
426 | case DeclaratorChunk::Pipe: | ||||
427 | continue; | ||||
428 | |||||
429 | case DeclaratorChunk::MemberPointer: | ||||
430 | case DeclaratorChunk::Pointer: | ||||
431 | if (onlyBlockPointers) | ||||
432 | continue; | ||||
433 | |||||
434 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
435 | |||||
436 | case DeclaratorChunk::BlockPointer: | ||||
437 | result = &ptrChunk; | ||||
438 | goto continue_outer; | ||||
439 | } | ||||
440 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 440); | ||||
441 | } | ||||
442 | |||||
443 | // If we run out of declarators doing that, we're done. | ||||
444 | return result; | ||||
445 | } | ||||
446 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 446); | ||||
447 | |||||
448 | // Okay, reconsider from our new point. | ||||
449 | continue_outer: ; | ||||
450 | } | ||||
451 | |||||
452 | // Ran out of chunks, bail out. | ||||
453 | return result; | ||||
454 | } | ||||
455 | |||||
456 | /// Given that an objc_gc attribute was written somewhere on a | ||||
457 | /// declaration *other* than on the declarator itself (for which, use | ||||
458 | /// distributeObjCPointerTypeAttrFromDeclarator), and given that it | ||||
459 | /// didn't apply in whatever position it was written in, try to move | ||||
460 | /// it to a more appropriate position. | ||||
461 | static void distributeObjCPointerTypeAttr(TypeProcessingState &state, | ||||
462 | ParsedAttr &attr, QualType type) { | ||||
463 | Declarator &declarator = state.getDeclarator(); | ||||
464 | |||||
465 | // Move it to the outermost normal or block pointer declarator. | ||||
466 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | ||||
467 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | ||||
468 | switch (chunk.Kind) { | ||||
469 | case DeclaratorChunk::Pointer: | ||||
470 | case DeclaratorChunk::BlockPointer: { | ||||
471 | // But don't move an ARC ownership attribute to the return type | ||||
472 | // of a block. | ||||
473 | DeclaratorChunk *destChunk = nullptr; | ||||
474 | if (state.isProcessingDeclSpec() && | ||||
475 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) | ||||
476 | destChunk = maybeMovePastReturnType(declarator, i - 1, | ||||
477 | /*onlyBlockPointers=*/true); | ||||
478 | if (!destChunk) destChunk = &chunk; | ||||
479 | |||||
480 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | ||||
481 | destChunk->getAttrs()); | ||||
482 | return; | ||||
483 | } | ||||
484 | |||||
485 | case DeclaratorChunk::Paren: | ||||
486 | case DeclaratorChunk::Array: | ||||
487 | continue; | ||||
488 | |||||
489 | // We may be starting at the return type of a block. | ||||
490 | case DeclaratorChunk::Function: | ||||
491 | if (state.isProcessingDeclSpec() && | ||||
492 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) { | ||||
493 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | ||||
494 | declarator, i, | ||||
495 | /*onlyBlockPointers=*/true)) { | ||||
496 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | ||||
497 | dest->getAttrs()); | ||||
498 | return; | ||||
499 | } | ||||
500 | } | ||||
501 | goto error; | ||||
502 | |||||
503 | // Don't walk through these. | ||||
504 | case DeclaratorChunk::Reference: | ||||
505 | case DeclaratorChunk::MemberPointer: | ||||
506 | case DeclaratorChunk::Pipe: | ||||
507 | goto error; | ||||
508 | } | ||||
509 | } | ||||
510 | error: | ||||
511 | |||||
512 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | ||||
513 | } | ||||
514 | |||||
515 | /// Distribute an objc_gc type attribute that was written on the | ||||
516 | /// declarator. | ||||
517 | static void distributeObjCPointerTypeAttrFromDeclarator( | ||||
518 | TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { | ||||
519 | Declarator &declarator = state.getDeclarator(); | ||||
520 | |||||
521 | // objc_gc goes on the innermost pointer to something that's not a | ||||
522 | // pointer. | ||||
523 | unsigned innermost = -1U; | ||||
524 | bool considerDeclSpec = true; | ||||
525 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | ||||
526 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | ||||
527 | switch (chunk.Kind) { | ||||
528 | case DeclaratorChunk::Pointer: | ||||
529 | case DeclaratorChunk::BlockPointer: | ||||
530 | innermost = i; | ||||
531 | continue; | ||||
532 | |||||
533 | case DeclaratorChunk::Reference: | ||||
534 | case DeclaratorChunk::MemberPointer: | ||||
535 | case DeclaratorChunk::Paren: | ||||
536 | case DeclaratorChunk::Array: | ||||
537 | case DeclaratorChunk::Pipe: | ||||
538 | continue; | ||||
539 | |||||
540 | case DeclaratorChunk::Function: | ||||
541 | considerDeclSpec = false; | ||||
542 | goto done; | ||||
543 | } | ||||
544 | } | ||||
545 | done: | ||||
546 | |||||
547 | // That might actually be the decl spec if we weren't blocked by | ||||
548 | // anything in the declarator. | ||||
549 | if (considerDeclSpec) { | ||||
550 | if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { | ||||
551 | // Splice the attribute into the decl spec. Prevents the | ||||
552 | // attribute from being applied multiple times and gives | ||||
553 | // the source-location-filler something to work with. | ||||
554 | state.saveDeclSpecAttrs(); | ||||
555 | declarator.getMutableDeclSpec().getAttributes().takeOneFrom( | ||||
556 | declarator.getAttributes(), &attr); | ||||
557 | return; | ||||
558 | } | ||||
559 | } | ||||
560 | |||||
561 | // Otherwise, if we found an appropriate chunk, splice the attribute | ||||
562 | // into it. | ||||
563 | if (innermost != -1U) { | ||||
564 | moveAttrFromListToList(attr, declarator.getAttributes(), | ||||
565 | declarator.getTypeObject(innermost).getAttrs()); | ||||
566 | return; | ||||
567 | } | ||||
568 | |||||
569 | // Otherwise, diagnose when we're done building the type. | ||||
570 | declarator.getAttributes().remove(&attr); | ||||
571 | state.addIgnoredTypeAttr(attr); | ||||
572 | } | ||||
573 | |||||
574 | /// A function type attribute was written somewhere in a declaration | ||||
575 | /// *other* than on the declarator itself or in the decl spec. Given | ||||
576 | /// that it didn't apply in whatever position it was written in, try | ||||
577 | /// to move it to a more appropriate position. | ||||
578 | static void distributeFunctionTypeAttr(TypeProcessingState &state, | ||||
579 | ParsedAttr &attr, QualType type) { | ||||
580 | Declarator &declarator = state.getDeclarator(); | ||||
581 | |||||
582 | // Try to push the attribute from the return type of a function to | ||||
583 | // the function itself. | ||||
584 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | ||||
585 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | ||||
586 | switch (chunk.Kind) { | ||||
587 | case DeclaratorChunk::Function: | ||||
588 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | ||||
589 | chunk.getAttrs()); | ||||
590 | return; | ||||
591 | |||||
592 | case DeclaratorChunk::Paren: | ||||
593 | case DeclaratorChunk::Pointer: | ||||
594 | case DeclaratorChunk::BlockPointer: | ||||
595 | case DeclaratorChunk::Array: | ||||
596 | case DeclaratorChunk::Reference: | ||||
597 | case DeclaratorChunk::MemberPointer: | ||||
598 | case DeclaratorChunk::Pipe: | ||||
599 | continue; | ||||
600 | } | ||||
601 | } | ||||
602 | |||||
603 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | ||||
604 | } | ||||
605 | |||||
606 | /// Try to distribute a function type attribute to the innermost | ||||
607 | /// function chunk or type. Returns true if the attribute was | ||||
608 | /// distributed, false if no location was found. | ||||
609 | static bool distributeFunctionTypeAttrToInnermost( | ||||
610 | TypeProcessingState &state, ParsedAttr &attr, | ||||
611 | ParsedAttributesView &attrList, QualType &declSpecType) { | ||||
612 | Declarator &declarator = state.getDeclarator(); | ||||
613 | |||||
614 | // Put it on the innermost function chunk, if there is one. | ||||
615 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | ||||
616 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | ||||
617 | if (chunk.Kind != DeclaratorChunk::Function) continue; | ||||
618 | |||||
619 | moveAttrFromListToList(attr, attrList, chunk.getAttrs()); | ||||
620 | return true; | ||||
621 | } | ||||
622 | |||||
623 | return handleFunctionTypeAttr(state, attr, declSpecType); | ||||
624 | } | ||||
625 | |||||
626 | /// A function type attribute was written in the decl spec. Try to | ||||
627 | /// apply it somewhere. | ||||
628 | static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, | ||||
629 | ParsedAttr &attr, | ||||
630 | QualType &declSpecType) { | ||||
631 | state.saveDeclSpecAttrs(); | ||||
632 | |||||
633 | // C++11 attributes before the decl specifiers actually appertain to | ||||
634 | // the declarators. Move them straight there. We don't support the | ||||
635 | // 'put them wherever you like' semantics we allow for GNU attributes. | ||||
636 | if (attr.isCXX11Attribute()) { | ||||
637 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | ||||
638 | state.getDeclarator().getAttributes()); | ||||
639 | return; | ||||
640 | } | ||||
641 | |||||
642 | // Try to distribute to the innermost. | ||||
643 | if (distributeFunctionTypeAttrToInnermost( | ||||
644 | state, attr, state.getCurrentAttributes(), declSpecType)) | ||||
645 | return; | ||||
646 | |||||
647 | // If that failed, diagnose the bad attribute when the declarator is | ||||
648 | // fully built. | ||||
649 | state.addIgnoredTypeAttr(attr); | ||||
650 | } | ||||
651 | |||||
652 | /// A function type attribute was written on the declarator. Try to | ||||
653 | /// apply it somewhere. | ||||
654 | static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, | ||||
655 | ParsedAttr &attr, | ||||
656 | QualType &declSpecType) { | ||||
657 | Declarator &declarator = state.getDeclarator(); | ||||
658 | |||||
659 | // Try to distribute to the innermost. | ||||
660 | if (distributeFunctionTypeAttrToInnermost( | ||||
661 | state, attr, declarator.getAttributes(), declSpecType)) | ||||
662 | return; | ||||
663 | |||||
664 | // If that failed, diagnose the bad attribute when the declarator is | ||||
665 | // fully built. | ||||
666 | declarator.getAttributes().remove(&attr); | ||||
667 | state.addIgnoredTypeAttr(attr); | ||||
668 | } | ||||
669 | |||||
670 | /// Given that there are attributes written on the declarator | ||||
671 | /// itself, try to distribute any type attributes to the appropriate | ||||
672 | /// declarator chunk. | ||||
673 | /// | ||||
674 | /// These are attributes like the following: | ||||
675 | /// int f ATTR; | ||||
676 | /// int (f ATTR)(); | ||||
677 | /// but not necessarily this: | ||||
678 | /// int f() ATTR; | ||||
679 | static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, | ||||
680 | QualType &declSpecType) { | ||||
681 | // Collect all the type attributes from the declarator itself. | ||||
682 | assert(!state.getDeclarator().getAttributes().empty() &&((!state.getDeclarator().getAttributes().empty() && "declarator has no attrs!" ) ? static_cast<void> (0) : __assert_fail ("!state.getDeclarator().getAttributes().empty() && \"declarator has no attrs!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 683, __PRETTY_FUNCTION__)) | ||||
683 | "declarator has no attrs!")((!state.getDeclarator().getAttributes().empty() && "declarator has no attrs!" ) ? static_cast<void> (0) : __assert_fail ("!state.getDeclarator().getAttributes().empty() && \"declarator has no attrs!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 683, __PRETTY_FUNCTION__)); | ||||
684 | // The called functions in this loop actually remove things from the current | ||||
685 | // list, so iterating over the existing list isn't possible. Instead, make a | ||||
686 | // non-owning copy and iterate over that. | ||||
687 | ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; | ||||
688 | for (ParsedAttr &attr : AttrsCopy) { | ||||
689 | // Do not distribute C++11 attributes. They have strict rules for what | ||||
690 | // they appertain to. | ||||
691 | if (attr.isCXX11Attribute()) | ||||
692 | continue; | ||||
693 | |||||
694 | switch (attr.getKind()) { | ||||
695 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: | ||||
696 | distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); | ||||
697 | break; | ||||
698 | |||||
699 | FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll: | ||||
700 | distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType); | ||||
701 | break; | ||||
702 | |||||
703 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: | ||||
704 | // Microsoft type attributes cannot go after the declarator-id. | ||||
705 | continue; | ||||
706 | |||||
707 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullUnspecified: | ||||
708 | // Nullability specifiers cannot go after the declarator-id. | ||||
709 | |||||
710 | // Objective-C __kindof does not get distributed. | ||||
711 | case ParsedAttr::AT_ObjCKindOf: | ||||
712 | continue; | ||||
713 | |||||
714 | default: | ||||
715 | break; | ||||
716 | } | ||||
717 | } | ||||
718 | } | ||||
719 | |||||
720 | /// Add a synthetic '()' to a block-literal declarator if it is | ||||
721 | /// required, given the return type. | ||||
722 | static void maybeSynthesizeBlockSignature(TypeProcessingState &state, | ||||
723 | QualType declSpecType) { | ||||
724 | Declarator &declarator = state.getDeclarator(); | ||||
725 | |||||
726 | // First, check whether the declarator would produce a function, | ||||
727 | // i.e. whether the innermost semantic chunk is a function. | ||||
728 | if (declarator.isFunctionDeclarator()) { | ||||
729 | // If so, make that declarator a prototyped declarator. | ||||
730 | declarator.getFunctionTypeInfo().hasPrototype = true; | ||||
731 | return; | ||||
732 | } | ||||
733 | |||||
734 | // If there are any type objects, the type as written won't name a | ||||
735 | // function, regardless of the decl spec type. This is because a | ||||
736 | // block signature declarator is always an abstract-declarator, and | ||||
737 | // abstract-declarators can't just be parentheses chunks. Therefore | ||||
738 | // we need to build a function chunk unless there are no type | ||||
739 | // objects and the decl spec type is a function. | ||||
740 | if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) | ||||
741 | return; | ||||
742 | |||||
743 | // Note that there *are* cases with invalid declarators where | ||||
744 | // declarators consist solely of parentheses. In general, these | ||||
745 | // occur only in failed efforts to make function declarators, so | ||||
746 | // faking up the function chunk is still the right thing to do. | ||||
747 | |||||
748 | // Otherwise, we need to fake up a function declarator. | ||||
749 | SourceLocation loc = declarator.getBeginLoc(); | ||||
750 | |||||
751 | // ...and *prepend* it to the declarator. | ||||
752 | SourceLocation NoLoc; | ||||
753 | declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( | ||||
754 | /*HasProto=*/true, | ||||
755 | /*IsAmbiguous=*/false, | ||||
756 | /*LParenLoc=*/NoLoc, | ||||
757 | /*ArgInfo=*/nullptr, | ||||
758 | /*NumParams=*/0, | ||||
759 | /*EllipsisLoc=*/NoLoc, | ||||
760 | /*RParenLoc=*/NoLoc, | ||||
761 | /*RefQualifierIsLvalueRef=*/true, | ||||
762 | /*RefQualifierLoc=*/NoLoc, | ||||
763 | /*MutableLoc=*/NoLoc, EST_None, | ||||
764 | /*ESpecRange=*/SourceRange(), | ||||
765 | /*Exceptions=*/nullptr, | ||||
766 | /*ExceptionRanges=*/nullptr, | ||||
767 | /*NumExceptions=*/0, | ||||
768 | /*NoexceptExpr=*/nullptr, | ||||
769 | /*ExceptionSpecTokens=*/nullptr, | ||||
770 | /*DeclsInPrototype=*/None, loc, loc, declarator)); | ||||
771 | |||||
772 | // For consistency, make sure the state still has us as processing | ||||
773 | // the decl spec. | ||||
774 | assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1)((state.getCurrentChunkIndex() == declarator.getNumTypeObjects () - 1) ? static_cast<void> (0) : __assert_fail ("state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 774, __PRETTY_FUNCTION__)); | ||||
775 | state.setCurrentChunkIndex(declarator.getNumTypeObjects()); | ||||
776 | } | ||||
777 | |||||
778 | static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, | ||||
779 | unsigned &TypeQuals, | ||||
780 | QualType TypeSoFar, | ||||
781 | unsigned RemoveTQs, | ||||
782 | unsigned DiagID) { | ||||
783 | // If this occurs outside a template instantiation, warn the user about | ||||
784 | // it; they probably didn't mean to specify a redundant qualifier. | ||||
785 | typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; | ||||
786 | for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), | ||||
787 | QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), | ||||
788 | QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), | ||||
789 | QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { | ||||
790 | if (!(RemoveTQs & Qual.first)) | ||||
791 | continue; | ||||
792 | |||||
793 | if (!S.inTemplateInstantiation()) { | ||||
794 | if (TypeQuals & Qual.first) | ||||
795 | S.Diag(Qual.second, DiagID) | ||||
796 | << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar | ||||
797 | << FixItHint::CreateRemoval(Qual.second); | ||||
798 | } | ||||
799 | |||||
800 | TypeQuals &= ~Qual.first; | ||||
801 | } | ||||
802 | } | ||||
803 | |||||
804 | /// Return true if this is omitted block return type. Also check type | ||||
805 | /// attributes and type qualifiers when returning true. | ||||
806 | static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, | ||||
807 | QualType Result) { | ||||
808 | if (!isOmittedBlockReturnType(declarator)) | ||||
809 | return false; | ||||
810 | |||||
811 | // Warn if we see type attributes for omitted return type on a block literal. | ||||
812 | SmallVector<ParsedAttr *, 2> ToBeRemoved; | ||||
813 | for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { | ||||
814 | if (AL.isInvalid() || !AL.isTypeAttr()) | ||||
815 | continue; | ||||
816 | S.Diag(AL.getLoc(), | ||||
817 | diag::warn_block_literal_attributes_on_omitted_return_type) | ||||
818 | << AL; | ||||
819 | ToBeRemoved.push_back(&AL); | ||||
820 | } | ||||
821 | // Remove bad attributes from the list. | ||||
822 | for (ParsedAttr *AL : ToBeRemoved) | ||||
823 | declarator.getMutableDeclSpec().getAttributes().remove(AL); | ||||
824 | |||||
825 | // Warn if we see type qualifiers for omitted return type on a block literal. | ||||
826 | const DeclSpec &DS = declarator.getDeclSpec(); | ||||
827 | unsigned TypeQuals = DS.getTypeQualifiers(); | ||||
828 | diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, | ||||
829 | diag::warn_block_literal_qualifiers_on_omitted_return_type); | ||||
830 | declarator.getMutableDeclSpec().ClearTypeQualifiers(); | ||||
831 | |||||
832 | return true; | ||||
833 | } | ||||
834 | |||||
835 | /// Apply Objective-C type arguments to the given type. | ||||
836 | static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, | ||||
837 | ArrayRef<TypeSourceInfo *> typeArgs, | ||||
838 | SourceRange typeArgsRange, | ||||
839 | bool failOnError = false) { | ||||
840 | // We can only apply type arguments to an Objective-C class type. | ||||
841 | const auto *objcObjectType = type->getAs<ObjCObjectType>(); | ||||
842 | if (!objcObjectType || !objcObjectType->getInterface()) { | ||||
843 | S.Diag(loc, diag::err_objc_type_args_non_class) | ||||
844 | << type | ||||
845 | << typeArgsRange; | ||||
846 | |||||
847 | if (failOnError) | ||||
848 | return QualType(); | ||||
849 | return type; | ||||
850 | } | ||||
851 | |||||
852 | // The class type must be parameterized. | ||||
853 | ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); | ||||
854 | ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); | ||||
855 | if (!typeParams) { | ||||
856 | S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) | ||||
857 | << objcClass->getDeclName() | ||||
858 | << FixItHint::CreateRemoval(typeArgsRange); | ||||
859 | |||||
860 | if (failOnError) | ||||
861 | return QualType(); | ||||
862 | |||||
863 | return type; | ||||
864 | } | ||||
865 | |||||
866 | // The type must not already be specialized. | ||||
867 | if (objcObjectType->isSpecialized()) { | ||||
868 | S.Diag(loc, diag::err_objc_type_args_specialized_class) | ||||
869 | << type | ||||
870 | << FixItHint::CreateRemoval(typeArgsRange); | ||||
871 | |||||
872 | if (failOnError) | ||||
873 | return QualType(); | ||||
874 | |||||
875 | return type; | ||||
876 | } | ||||
877 | |||||
878 | // Check the type arguments. | ||||
879 | SmallVector<QualType, 4> finalTypeArgs; | ||||
880 | unsigned numTypeParams = typeParams->size(); | ||||
881 | bool anyPackExpansions = false; | ||||
882 | for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { | ||||
883 | TypeSourceInfo *typeArgInfo = typeArgs[i]; | ||||
884 | QualType typeArg = typeArgInfo->getType(); | ||||
885 | |||||
886 | // Type arguments cannot have explicit qualifiers or nullability. | ||||
887 | // We ignore indirect sources of these, e.g. behind typedefs or | ||||
888 | // template arguments. | ||||
889 | if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { | ||||
890 | bool diagnosed = false; | ||||
891 | SourceRange rangeToRemove; | ||||
892 | if (auto attr = qual.getAs<AttributedTypeLoc>()) { | ||||
893 | rangeToRemove = attr.getLocalSourceRange(); | ||||
894 | if (attr.getTypePtr()->getImmediateNullability()) { | ||||
895 | typeArg = attr.getTypePtr()->getModifiedType(); | ||||
896 | S.Diag(attr.getBeginLoc(), | ||||
897 | diag::err_objc_type_arg_explicit_nullability) | ||||
898 | << typeArg << FixItHint::CreateRemoval(rangeToRemove); | ||||
899 | diagnosed = true; | ||||
900 | } | ||||
901 | } | ||||
902 | |||||
903 | if (!diagnosed) { | ||||
904 | S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) | ||||
905 | << typeArg << typeArg.getQualifiers().getAsString() | ||||
906 | << FixItHint::CreateRemoval(rangeToRemove); | ||||
907 | } | ||||
908 | } | ||||
909 | |||||
910 | // Remove qualifiers even if they're non-local. | ||||
911 | typeArg = typeArg.getUnqualifiedType(); | ||||
912 | |||||
913 | finalTypeArgs.push_back(typeArg); | ||||
914 | |||||
915 | if (typeArg->getAs<PackExpansionType>()) | ||||
916 | anyPackExpansions = true; | ||||
917 | |||||
918 | // Find the corresponding type parameter, if there is one. | ||||
919 | ObjCTypeParamDecl *typeParam = nullptr; | ||||
920 | if (!anyPackExpansions) { | ||||
921 | if (i < numTypeParams) { | ||||
922 | typeParam = typeParams->begin()[i]; | ||||
923 | } else { | ||||
924 | // Too many arguments. | ||||
925 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | ||||
926 | << false | ||||
927 | << objcClass->getDeclName() | ||||
928 | << (unsigned)typeArgs.size() | ||||
929 | << numTypeParams; | ||||
930 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | ||||
931 | << objcClass; | ||||
932 | |||||
933 | if (failOnError) | ||||
934 | return QualType(); | ||||
935 | |||||
936 | return type; | ||||
937 | } | ||||
938 | } | ||||
939 | |||||
940 | // Objective-C object pointer types must be substitutable for the bounds. | ||||
941 | if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { | ||||
942 | // If we don't have a type parameter to match against, assume | ||||
943 | // everything is fine. There was a prior pack expansion that | ||||
944 | // means we won't be able to match anything. | ||||
945 | if (!typeParam) { | ||||
946 | assert(anyPackExpansions && "Too many arguments?")((anyPackExpansions && "Too many arguments?") ? static_cast <void> (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 946, __PRETTY_FUNCTION__)); | ||||
947 | continue; | ||||
948 | } | ||||
949 | |||||
950 | // Retrieve the bound. | ||||
951 | QualType bound = typeParam->getUnderlyingType(); | ||||
952 | const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); | ||||
953 | |||||
954 | // Determine whether the type argument is substitutable for the bound. | ||||
955 | if (typeArgObjC->isObjCIdType()) { | ||||
956 | // When the type argument is 'id', the only acceptable type | ||||
957 | // parameter bound is 'id'. | ||||
958 | if (boundObjC->isObjCIdType()) | ||||
959 | continue; | ||||
960 | } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { | ||||
961 | // Otherwise, we follow the assignability rules. | ||||
962 | continue; | ||||
963 | } | ||||
964 | |||||
965 | // Diagnose the mismatch. | ||||
966 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | ||||
967 | diag::err_objc_type_arg_does_not_match_bound) | ||||
968 | << typeArg << bound << typeParam->getDeclName(); | ||||
969 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | ||||
970 | << typeParam->getDeclName(); | ||||
971 | |||||
972 | if (failOnError) | ||||
973 | return QualType(); | ||||
974 | |||||
975 | return type; | ||||
976 | } | ||||
977 | |||||
978 | // Block pointer types are permitted for unqualified 'id' bounds. | ||||
979 | if (typeArg->isBlockPointerType()) { | ||||
980 | // If we don't have a type parameter to match against, assume | ||||
981 | // everything is fine. There was a prior pack expansion that | ||||
982 | // means we won't be able to match anything. | ||||
983 | if (!typeParam) { | ||||
984 | assert(anyPackExpansions && "Too many arguments?")((anyPackExpansions && "Too many arguments?") ? static_cast <void> (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 984, __PRETTY_FUNCTION__)); | ||||
985 | continue; | ||||
986 | } | ||||
987 | |||||
988 | // Retrieve the bound. | ||||
989 | QualType bound = typeParam->getUnderlyingType(); | ||||
990 | if (bound->isBlockCompatibleObjCPointerType(S.Context)) | ||||
991 | continue; | ||||
992 | |||||
993 | // Diagnose the mismatch. | ||||
994 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | ||||
995 | diag::err_objc_type_arg_does_not_match_bound) | ||||
996 | << typeArg << bound << typeParam->getDeclName(); | ||||
997 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | ||||
998 | << typeParam->getDeclName(); | ||||
999 | |||||
1000 | if (failOnError) | ||||
1001 | return QualType(); | ||||
1002 | |||||
1003 | return type; | ||||
1004 | } | ||||
1005 | |||||
1006 | // Dependent types will be checked at instantiation time. | ||||
1007 | if (typeArg->isDependentType()) { | ||||
1008 | continue; | ||||
1009 | } | ||||
1010 | |||||
1011 | // Diagnose non-id-compatible type arguments. | ||||
1012 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | ||||
1013 | diag::err_objc_type_arg_not_id_compatible) | ||||
1014 | << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); | ||||
1015 | |||||
1016 | if (failOnError) | ||||
1017 | return QualType(); | ||||
1018 | |||||
1019 | return type; | ||||
1020 | } | ||||
1021 | |||||
1022 | // Make sure we didn't have the wrong number of arguments. | ||||
1023 | if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { | ||||
1024 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | ||||
1025 | << (typeArgs.size() < typeParams->size()) | ||||
1026 | << objcClass->getDeclName() | ||||
1027 | << (unsigned)finalTypeArgs.size() | ||||
1028 | << (unsigned)numTypeParams; | ||||
1029 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | ||||
1030 | << objcClass; | ||||
1031 | |||||
1032 | if (failOnError) | ||||
1033 | return QualType(); | ||||
1034 | |||||
1035 | return type; | ||||
1036 | } | ||||
1037 | |||||
1038 | // Success. Form the specialized type. | ||||
1039 | return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); | ||||
1040 | } | ||||
1041 | |||||
1042 | QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, | ||||
1043 | SourceLocation ProtocolLAngleLoc, | ||||
1044 | ArrayRef<ObjCProtocolDecl *> Protocols, | ||||
1045 | ArrayRef<SourceLocation> ProtocolLocs, | ||||
1046 | SourceLocation ProtocolRAngleLoc, | ||||
1047 | bool FailOnError) { | ||||
1048 | QualType Result = QualType(Decl->getTypeForDecl(), 0); | ||||
1049 | if (!Protocols.empty()) { | ||||
1050 | bool HasError; | ||||
1051 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | ||||
1052 | HasError); | ||||
1053 | if (HasError) { | ||||
1054 | Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) | ||||
1055 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | ||||
1056 | if (FailOnError) Result = QualType(); | ||||
1057 | } | ||||
1058 | if (FailOnError && Result.isNull()) | ||||
1059 | return QualType(); | ||||
1060 | } | ||||
1061 | |||||
1062 | return Result; | ||||
1063 | } | ||||
1064 | |||||
1065 | QualType Sema::BuildObjCObjectType(QualType BaseType, | ||||
1066 | SourceLocation Loc, | ||||
1067 | SourceLocation TypeArgsLAngleLoc, | ||||
1068 | ArrayRef<TypeSourceInfo *> TypeArgs, | ||||
1069 | SourceLocation TypeArgsRAngleLoc, | ||||
1070 | SourceLocation ProtocolLAngleLoc, | ||||
1071 | ArrayRef<ObjCProtocolDecl *> Protocols, | ||||
1072 | ArrayRef<SourceLocation> ProtocolLocs, | ||||
1073 | SourceLocation ProtocolRAngleLoc, | ||||
1074 | bool FailOnError) { | ||||
1075 | QualType Result = BaseType; | ||||
1076 | if (!TypeArgs.empty()) { | ||||
1077 | Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, | ||||
1078 | SourceRange(TypeArgsLAngleLoc, | ||||
1079 | TypeArgsRAngleLoc), | ||||
1080 | FailOnError); | ||||
1081 | if (FailOnError && Result.isNull()) | ||||
1082 | return QualType(); | ||||
1083 | } | ||||
1084 | |||||
1085 | if (!Protocols.empty()) { | ||||
1086 | bool HasError; | ||||
1087 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | ||||
1088 | HasError); | ||||
1089 | if (HasError) { | ||||
1090 | Diag(Loc, diag::err_invalid_protocol_qualifiers) | ||||
1091 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | ||||
1092 | if (FailOnError) Result = QualType(); | ||||
1093 | } | ||||
1094 | if (FailOnError && Result.isNull()) | ||||
1095 | return QualType(); | ||||
1096 | } | ||||
1097 | |||||
1098 | return Result; | ||||
1099 | } | ||||
1100 | |||||
1101 | TypeResult Sema::actOnObjCProtocolQualifierType( | ||||
1102 | SourceLocation lAngleLoc, | ||||
1103 | ArrayRef<Decl *> protocols, | ||||
1104 | ArrayRef<SourceLocation> protocolLocs, | ||||
1105 | SourceLocation rAngleLoc) { | ||||
1106 | // Form id<protocol-list>. | ||||
1107 | QualType Result = Context.getObjCObjectType( | ||||
1108 | Context.ObjCBuiltinIdTy, { }, | ||||
1109 | llvm::makeArrayRef( | ||||
1110 | (ObjCProtocolDecl * const *)protocols.data(), | ||||
1111 | protocols.size()), | ||||
1112 | false); | ||||
1113 | Result = Context.getObjCObjectPointerType(Result); | ||||
1114 | |||||
1115 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | ||||
1116 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | ||||
1117 | |||||
1118 | auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); | ||||
1119 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit | ||||
1120 | |||||
1121 | auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() | ||||
1122 | .castAs<ObjCObjectTypeLoc>(); | ||||
1123 | ObjCObjectTL.setHasBaseTypeAsWritten(false); | ||||
1124 | ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); | ||||
1125 | |||||
1126 | // No type arguments. | ||||
1127 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | ||||
1128 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | ||||
1129 | |||||
1130 | // Fill in protocol qualifiers. | ||||
1131 | ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); | ||||
1132 | ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); | ||||
1133 | for (unsigned i = 0, n = protocols.size(); i != n; ++i) | ||||
1134 | ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); | ||||
1135 | |||||
1136 | // We're done. Return the completed type to the parser. | ||||
1137 | return CreateParsedType(Result, ResultTInfo); | ||||
1138 | } | ||||
1139 | |||||
1140 | TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( | ||||
1141 | Scope *S, | ||||
1142 | SourceLocation Loc, | ||||
1143 | ParsedType BaseType, | ||||
1144 | SourceLocation TypeArgsLAngleLoc, | ||||
1145 | ArrayRef<ParsedType> TypeArgs, | ||||
1146 | SourceLocation TypeArgsRAngleLoc, | ||||
1147 | SourceLocation ProtocolLAngleLoc, | ||||
1148 | ArrayRef<Decl *> Protocols, | ||||
1149 | ArrayRef<SourceLocation> ProtocolLocs, | ||||
1150 | SourceLocation ProtocolRAngleLoc) { | ||||
1151 | TypeSourceInfo *BaseTypeInfo = nullptr; | ||||
1152 | QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); | ||||
1153 | if (T.isNull()) | ||||
1154 | return true; | ||||
1155 | |||||
1156 | // Handle missing type-source info. | ||||
1157 | if (!BaseTypeInfo) | ||||
1158 | BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); | ||||
1159 | |||||
1160 | // Extract type arguments. | ||||
1161 | SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; | ||||
1162 | for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { | ||||
1163 | TypeSourceInfo *TypeArgInfo = nullptr; | ||||
1164 | QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); | ||||
1165 | if (TypeArg.isNull()) { | ||||
1166 | ActualTypeArgInfos.clear(); | ||||
1167 | break; | ||||
1168 | } | ||||
1169 | |||||
1170 | assert(TypeArgInfo && "No type source info?")((TypeArgInfo && "No type source info?") ? static_cast <void> (0) : __assert_fail ("TypeArgInfo && \"No type source info?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1170, __PRETTY_FUNCTION__)); | ||||
1171 | ActualTypeArgInfos.push_back(TypeArgInfo); | ||||
1172 | } | ||||
1173 | |||||
1174 | // Build the object type. | ||||
1175 | QualType Result = BuildObjCObjectType( | ||||
1176 | T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), | ||||
1177 | TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, | ||||
1178 | ProtocolLAngleLoc, | ||||
1179 | llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), | ||||
1180 | Protocols.size()), | ||||
1181 | ProtocolLocs, ProtocolRAngleLoc, | ||||
1182 | /*FailOnError=*/false); | ||||
1183 | |||||
1184 | if (Result == T) | ||||
1185 | return BaseType; | ||||
1186 | |||||
1187 | // Create source information for this type. | ||||
1188 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | ||||
1189 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | ||||
1190 | |||||
1191 | // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an | ||||
1192 | // object pointer type. Fill in source information for it. | ||||
1193 | if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { | ||||
1194 | // The '*' is implicit. | ||||
1195 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); | ||||
1196 | ResultTL = ObjCObjectPointerTL.getPointeeLoc(); | ||||
1197 | } | ||||
1198 | |||||
1199 | if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { | ||||
1200 | // Protocol qualifier information. | ||||
1201 | if (OTPTL.getNumProtocols() > 0) { | ||||
1202 | assert(OTPTL.getNumProtocols() == Protocols.size())((OTPTL.getNumProtocols() == Protocols.size()) ? static_cast< void> (0) : __assert_fail ("OTPTL.getNumProtocols() == Protocols.size()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1202, __PRETTY_FUNCTION__)); | ||||
1203 | OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | ||||
1204 | OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | ||||
1205 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | ||||
1206 | OTPTL.setProtocolLoc(i, ProtocolLocs[i]); | ||||
1207 | } | ||||
1208 | |||||
1209 | // We're done. Return the completed type to the parser. | ||||
1210 | return CreateParsedType(Result, ResultTInfo); | ||||
1211 | } | ||||
1212 | |||||
1213 | auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); | ||||
1214 | |||||
1215 | // Type argument information. | ||||
1216 | if (ObjCObjectTL.getNumTypeArgs() > 0) { | ||||
1217 | assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size())((ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()) ? static_cast<void> (0) : __assert_fail ("ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1217, __PRETTY_FUNCTION__)); | ||||
1218 | ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); | ||||
1219 | ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); | ||||
1220 | for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) | ||||
1221 | ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); | ||||
1222 | } else { | ||||
1223 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | ||||
1224 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | ||||
1225 | } | ||||
1226 | |||||
1227 | // Protocol qualifier information. | ||||
1228 | if (ObjCObjectTL.getNumProtocols() > 0) { | ||||
1229 | assert(ObjCObjectTL.getNumProtocols() == Protocols.size())((ObjCObjectTL.getNumProtocols() == Protocols.size()) ? static_cast <void> (0) : __assert_fail ("ObjCObjectTL.getNumProtocols() == Protocols.size()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1229, __PRETTY_FUNCTION__)); | ||||
1230 | ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | ||||
1231 | ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | ||||
1232 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | ||||
1233 | ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); | ||||
1234 | } else { | ||||
1235 | ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); | ||||
1236 | ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); | ||||
1237 | } | ||||
1238 | |||||
1239 | // Base type. | ||||
1240 | ObjCObjectTL.setHasBaseTypeAsWritten(true); | ||||
1241 | if (ObjCObjectTL.getType() == T) | ||||
1242 | ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); | ||||
1243 | else | ||||
1244 | ObjCObjectTL.getBaseLoc().initialize(Context, Loc); | ||||
1245 | |||||
1246 | // We're done. Return the completed type to the parser. | ||||
1247 | return CreateParsedType(Result, ResultTInfo); | ||||
1248 | } | ||||
1249 | |||||
1250 | static OpenCLAccessAttr::Spelling | ||||
1251 | getImageAccess(const ParsedAttributesView &Attrs) { | ||||
1252 | for (const ParsedAttr &AL : Attrs) | ||||
1253 | if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) | ||||
1254 | return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); | ||||
1255 | return OpenCLAccessAttr::Keyword_read_only; | ||||
1256 | } | ||||
1257 | |||||
1258 | static QualType ConvertConstrainedAutoDeclSpecToType(Sema &S, DeclSpec &DS, | ||||
1259 | AutoTypeKeyword AutoKW) { | ||||
1260 | assert(DS.isConstrainedAuto())((DS.isConstrainedAuto()) ? static_cast<void> (0) : __assert_fail ("DS.isConstrainedAuto()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1260, __PRETTY_FUNCTION__)); | ||||
1261 | TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); | ||||
1262 | TemplateArgumentListInfo TemplateArgsInfo; | ||||
1263 | TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc); | ||||
1264 | TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc); | ||||
1265 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | ||||
1266 | TemplateId->NumArgs); | ||||
1267 | S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | ||||
1268 | llvm::SmallVector<TemplateArgument, 8> TemplateArgs; | ||||
1269 | for (auto &ArgLoc : TemplateArgsInfo.arguments()) | ||||
1270 | TemplateArgs.push_back(ArgLoc.getArgument()); | ||||
1271 | return S.Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false, | ||||
1272 | /*IsPack=*/false, | ||||
1273 | cast<ConceptDecl>(TemplateId->Template.get() | ||||
1274 | .getAsTemplateDecl()), | ||||
1275 | TemplateArgs); | ||||
1276 | } | ||||
1277 | |||||
1278 | /// Convert the specified declspec to the appropriate type | ||||
1279 | /// object. | ||||
1280 | /// \param state Specifies the declarator containing the declaration specifier | ||||
1281 | /// to be converted, along with other associated processing state. | ||||
1282 | /// \returns The type described by the declaration specifiers. This function | ||||
1283 | /// never returns null. | ||||
1284 | static QualType ConvertDeclSpecToType(TypeProcessingState &state) { | ||||
1285 | // FIXME: Should move the logic from DeclSpec::Finish to here for validity | ||||
1286 | // checking. | ||||
1287 | |||||
1288 | Sema &S = state.getSema(); | ||||
1289 | Declarator &declarator = state.getDeclarator(); | ||||
1290 | DeclSpec &DS = declarator.getMutableDeclSpec(); | ||||
1291 | SourceLocation DeclLoc = declarator.getIdentifierLoc(); | ||||
1292 | if (DeclLoc.isInvalid()) | ||||
1293 | DeclLoc = DS.getBeginLoc(); | ||||
1294 | |||||
1295 | ASTContext &Context = S.Context; | ||||
1296 | |||||
1297 | QualType Result; | ||||
1298 | switch (DS.getTypeSpecType()) { | ||||
1299 | case DeclSpec::TST_void: | ||||
1300 | Result = Context.VoidTy; | ||||
1301 | break; | ||||
1302 | case DeclSpec::TST_char: | ||||
1303 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) | ||||
1304 | Result = Context.CharTy; | ||||
1305 | else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) | ||||
1306 | Result = Context.SignedCharTy; | ||||
1307 | else { | ||||
1308 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&((DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1309, __PRETTY_FUNCTION__)) | ||||
1309 | "Unknown TSS value")((DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1309, __PRETTY_FUNCTION__)); | ||||
1310 | Result = Context.UnsignedCharTy; | ||||
1311 | } | ||||
1312 | break; | ||||
1313 | case DeclSpec::TST_wchar: | ||||
1314 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) | ||||
1315 | Result = Context.WCharTy; | ||||
1316 | else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) { | ||||
1317 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) | ||||
1318 | << DS.getSpecifierName(DS.getTypeSpecType(), | ||||
1319 | Context.getPrintingPolicy()); | ||||
1320 | Result = Context.getSignedWCharType(); | ||||
1321 | } else { | ||||
1322 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&((DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1323, __PRETTY_FUNCTION__)) | ||||
1323 | "Unknown TSS value")((DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1323, __PRETTY_FUNCTION__)); | ||||
1324 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) | ||||
1325 | << DS.getSpecifierName(DS.getTypeSpecType(), | ||||
1326 | Context.getPrintingPolicy()); | ||||
1327 | Result = Context.getUnsignedWCharType(); | ||||
1328 | } | ||||
1329 | break; | ||||
1330 | case DeclSpec::TST_char8: | ||||
1331 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1332, __PRETTY_FUNCTION__)) | ||||
1332 | "Unknown TSS value")((DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1332, __PRETTY_FUNCTION__)); | ||||
1333 | Result = Context.Char8Ty; | ||||
1334 | break; | ||||
1335 | case DeclSpec::TST_char16: | ||||
1336 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1337, __PRETTY_FUNCTION__)) | ||||
1337 | "Unknown TSS value")((DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1337, __PRETTY_FUNCTION__)); | ||||
1338 | Result = Context.Char16Ty; | ||||
1339 | break; | ||||
1340 | case DeclSpec::TST_char32: | ||||
1341 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1342, __PRETTY_FUNCTION__)) | ||||
1342 | "Unknown TSS value")((DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1342, __PRETTY_FUNCTION__)); | ||||
1343 | Result = Context.Char32Ty; | ||||
1344 | break; | ||||
1345 | case DeclSpec::TST_unspecified: | ||||
1346 | // If this is a missing declspec in a block literal return context, then it | ||||
1347 | // is inferred from the return statements inside the block. | ||||
1348 | // The declspec is always missing in a lambda expr context; it is either | ||||
1349 | // specified with a trailing return type or inferred. | ||||
1350 | if (S.getLangOpts().CPlusPlus14 && | ||||
1351 | declarator.getContext() == DeclaratorContext::LambdaExpr) { | ||||
1352 | // In C++1y, a lambda's implicit return type is 'auto'. | ||||
1353 | Result = Context.getAutoDeductType(); | ||||
1354 | break; | ||||
1355 | } else if (declarator.getContext() == DeclaratorContext::LambdaExpr || | ||||
1356 | checkOmittedBlockReturnType(S, declarator, | ||||
1357 | Context.DependentTy)) { | ||||
1358 | Result = Context.DependentTy; | ||||
1359 | break; | ||||
1360 | } | ||||
1361 | |||||
1362 | // Unspecified typespec defaults to int in C90. However, the C90 grammar | ||||
1363 | // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, | ||||
1364 | // type-qualifier, or storage-class-specifier. If not, emit an extwarn. | ||||
1365 | // Note that the one exception to this is function definitions, which are | ||||
1366 | // allowed to be completely missing a declspec. This is handled in the | ||||
1367 | // parser already though by it pretending to have seen an 'int' in this | ||||
1368 | // case. | ||||
1369 | if (S.getLangOpts().ImplicitInt) { | ||||
1370 | // In C89 mode, we only warn if there is a completely missing declspec | ||||
1371 | // when one is not allowed. | ||||
1372 | if (DS.isEmpty()) { | ||||
1373 | S.Diag(DeclLoc, diag::ext_missing_declspec) | ||||
1374 | << DS.getSourceRange() | ||||
1375 | << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); | ||||
1376 | } | ||||
1377 | } else if (!DS.hasTypeSpecifier()) { | ||||
1378 | // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: | ||||
1379 | // "At least one type specifier shall be given in the declaration | ||||
1380 | // specifiers in each declaration, and in the specifier-qualifier list in | ||||
1381 | // each struct declaration and type name." | ||||
1382 | if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) { | ||||
1383 | S.Diag(DeclLoc, diag::err_missing_type_specifier) | ||||
1384 | << DS.getSourceRange(); | ||||
1385 | |||||
1386 | // When this occurs in C++ code, often something is very broken with the | ||||
1387 | // value being declared, poison it as invalid so we don't get chains of | ||||
1388 | // errors. | ||||
1389 | declarator.setInvalidType(true); | ||||
1390 | } else if ((S.getLangOpts().OpenCLVersion >= 200 || | ||||
1391 | S.getLangOpts().OpenCLCPlusPlus) && | ||||
1392 | DS.isTypeSpecPipe()) { | ||||
1393 | S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) | ||||
1394 | << DS.getSourceRange(); | ||||
1395 | declarator.setInvalidType(true); | ||||
1396 | } else { | ||||
1397 | S.Diag(DeclLoc, diag::ext_missing_type_specifier) | ||||
1398 | << DS.getSourceRange(); | ||||
1399 | } | ||||
1400 | } | ||||
1401 | |||||
1402 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
1403 | case DeclSpec::TST_int: { | ||||
1404 | if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) { | ||||
1405 | switch (DS.getTypeSpecWidth()) { | ||||
1406 | case TypeSpecifierWidth::Unspecified: | ||||
1407 | Result = Context.IntTy; | ||||
1408 | break; | ||||
1409 | case TypeSpecifierWidth::Short: | ||||
1410 | Result = Context.ShortTy; | ||||
1411 | break; | ||||
1412 | case TypeSpecifierWidth::Long: | ||||
1413 | Result = Context.LongTy; | ||||
1414 | break; | ||||
1415 | case TypeSpecifierWidth::LongLong: | ||||
1416 | Result = Context.LongLongTy; | ||||
1417 | |||||
1418 | // 'long long' is a C99 or C++11 feature. | ||||
1419 | if (!S.getLangOpts().C99) { | ||||
1420 | if (S.getLangOpts().CPlusPlus) | ||||
1421 | S.Diag(DS.getTypeSpecWidthLoc(), | ||||
1422 | S.getLangOpts().CPlusPlus11 ? | ||||
1423 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | ||||
1424 | else | ||||
1425 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | ||||
1426 | } | ||||
1427 | break; | ||||
1428 | } | ||||
1429 | } else { | ||||
1430 | switch (DS.getTypeSpecWidth()) { | ||||
1431 | case TypeSpecifierWidth::Unspecified: | ||||
1432 | Result = Context.UnsignedIntTy; | ||||
1433 | break; | ||||
1434 | case TypeSpecifierWidth::Short: | ||||
1435 | Result = Context.UnsignedShortTy; | ||||
1436 | break; | ||||
1437 | case TypeSpecifierWidth::Long: | ||||
1438 | Result = Context.UnsignedLongTy; | ||||
1439 | break; | ||||
1440 | case TypeSpecifierWidth::LongLong: | ||||
1441 | Result = Context.UnsignedLongLongTy; | ||||
1442 | |||||
1443 | // 'long long' is a C99 or C++11 feature. | ||||
1444 | if (!S.getLangOpts().C99) { | ||||
1445 | if (S.getLangOpts().CPlusPlus) | ||||
1446 | S.Diag(DS.getTypeSpecWidthLoc(), | ||||
1447 | S.getLangOpts().CPlusPlus11 ? | ||||
1448 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | ||||
1449 | else | ||||
1450 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | ||||
1451 | } | ||||
1452 | break; | ||||
1453 | } | ||||
1454 | } | ||||
1455 | break; | ||||
1456 | } | ||||
1457 | case DeclSpec::TST_extint: { | ||||
1458 | if (!S.Context.getTargetInfo().hasExtIntType()) | ||||
1459 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | ||||
1460 | << "_ExtInt"; | ||||
1461 | Result = | ||||
1462 | S.BuildExtIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned, | ||||
1463 | DS.getRepAsExpr(), 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")::llvm::llvm_unreachable_internal("Unable to specify long long as _Accum width" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1482); | ||||
1483 | } | ||||
1484 | |||||
1485 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | ||||
1486 | Result = Context.getCorrespondingUnsignedType(Result); | ||||
1487 | |||||
1488 | if (DS.isTypeSpecSat()) | ||||
1489 | Result = Context.getCorrespondingSaturatedType(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")::llvm::llvm_unreachable_internal("Unable to specify long long as _Fract width" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1505); | ||||
1506 | } | ||||
1507 | |||||
1508 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | ||||
1509 | Result = Context.getCorrespondingUnsignedType(Result); | ||||
1510 | |||||
1511 | if (DS.isTypeSpecSat()) | ||||
1512 | Result = Context.getCorrespondingSaturatedType(Result); | ||||
1513 | |||||
1514 | break; | ||||
1515 | } | ||||
1516 | case DeclSpec::TST_int128: | ||||
1517 | if (!S.Context.getTargetInfo().hasInt128Type() && | ||||
1518 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | ||||
1519 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | ||||
1520 | << "__int128"; | ||||
1521 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | ||||
1522 | Result = Context.UnsignedInt128Ty; | ||||
1523 | else | ||||
1524 | Result = Context.Int128Ty; | ||||
1525 | break; | ||||
1526 | case DeclSpec::TST_float16: | ||||
1527 | // CUDA host and device may have different _Float16 support, therefore | ||||
1528 | // do not diagnose _Float16 usage to avoid false alarm. | ||||
1529 | // ToDo: more precise diagnostics for CUDA. | ||||
1530 | if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA && | ||||
1531 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | ||||
1532 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | ||||
1533 | << "_Float16"; | ||||
1534 | Result = Context.Float16Ty; | ||||
1535 | break; | ||||
1536 | case DeclSpec::TST_half: Result = Context.HalfTy; break; | ||||
1537 | case DeclSpec::TST_BFloat16: | ||||
1538 | if (!S.Context.getTargetInfo().hasBFloat16Type()) | ||||
1539 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | ||||
1540 | << "__bf16"; | ||||
1541 | Result = Context.BFloat16Ty; | ||||
1542 | break; | ||||
1543 | case DeclSpec::TST_float: Result = Context.FloatTy; break; | ||||
1544 | case DeclSpec::TST_double: | ||||
1545 | if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long) | ||||
1546 | Result = Context.LongDoubleTy; | ||||
1547 | else | ||||
1548 | Result = Context.DoubleTy; | ||||
1549 | break; | ||||
1550 | case DeclSpec::TST_float128: | ||||
1551 | if (!S.Context.getTargetInfo().hasFloat128Type() && | ||||
1552 | !S.getLangOpts().SYCLIsDevice && | ||||
1553 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | ||||
1554 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | ||||
1555 | << "__float128"; | ||||
1556 | Result = Context.Float128Ty; | ||||
1557 | break; | ||||
1558 | case DeclSpec::TST_bool: | ||||
1559 | Result = Context.BoolTy; // _Bool or bool | ||||
1560 | break; | ||||
1561 | case DeclSpec::TST_decimal32: // _Decimal32 | ||||
1562 | case DeclSpec::TST_decimal64: // _Decimal64 | ||||
1563 | case DeclSpec::TST_decimal128: // _Decimal128 | ||||
1564 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); | ||||
1565 | Result = Context.IntTy; | ||||
1566 | declarator.setInvalidType(true); | ||||
1567 | break; | ||||
1568 | case DeclSpec::TST_class: | ||||
1569 | case DeclSpec::TST_enum: | ||||
1570 | case DeclSpec::TST_union: | ||||
1571 | case DeclSpec::TST_struct: | ||||
1572 | case DeclSpec::TST_interface: { | ||||
1573 | TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()); | ||||
1574 | if (!D) { | ||||
1575 | // This can happen in C++ with ambiguous lookups. | ||||
1576 | Result = Context.IntTy; | ||||
1577 | declarator.setInvalidType(true); | ||||
1578 | break; | ||||
1579 | } | ||||
1580 | |||||
1581 | // If the type is deprecated or unavailable, diagnose it. | ||||
1582 | S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); | ||||
1583 | |||||
1584 | assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&((DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1587, __PRETTY_FUNCTION__)) | ||||
1585 | DS.getTypeSpecComplex() == 0 &&((DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1587, __PRETTY_FUNCTION__)) | ||||
1586 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1587, __PRETTY_FUNCTION__)) | ||||
1587 | "No qualifiers on tag names!")((DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1587, __PRETTY_FUNCTION__)); | ||||
1588 | |||||
1589 | // TypeQuals handled by caller. | ||||
1590 | Result = Context.getTypeDeclType(D); | ||||
1591 | |||||
1592 | // In both C and C++, make an ElaboratedType. | ||||
1593 | ElaboratedTypeKeyword Keyword | ||||
1594 | = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); | ||||
1595 | Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result, | ||||
1596 | DS.isTypeSpecOwned() ? D : nullptr); | ||||
1597 | break; | ||||
1598 | } | ||||
1599 | case DeclSpec::TST_typename: { | ||||
1600 | assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&((DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1603, __PRETTY_FUNCTION__)) | ||||
1601 | DS.getTypeSpecComplex() == 0 &&((DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1603, __PRETTY_FUNCTION__)) | ||||
1602 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1603, __PRETTY_FUNCTION__)) | ||||
1603 | "Can't handle qualifiers on typedef names yet!")((DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1603, __PRETTY_FUNCTION__)); | ||||
1604 | Result = S.GetTypeFromParser(DS.getRepAsType()); | ||||
1605 | if (Result.isNull()) { | ||||
1606 | declarator.setInvalidType(true); | ||||
1607 | } | ||||
1608 | |||||
1609 | // TypeQuals handled by caller. | ||||
1610 | break; | ||||
1611 | } | ||||
1612 | case DeclSpec::TST_typeofType: | ||||
1613 | // FIXME: Preserve type source info. | ||||
1614 | Result = S.GetTypeFromParser(DS.getRepAsType()); | ||||
1615 | assert(!Result.isNull() && "Didn't get a type for typeof?")((!Result.isNull() && "Didn't get a type for typeof?" ) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for typeof?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1615, __PRETTY_FUNCTION__)); | ||||
1616 | if (!Result->isDependentType()) | ||||
1617 | if (const TagType *TT = Result->getAs<TagType>()) | ||||
1618 | S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); | ||||
1619 | // TypeQuals handled by caller. | ||||
1620 | Result = Context.getTypeOfType(Result); | ||||
1621 | break; | ||||
1622 | case DeclSpec::TST_typeofExpr: { | ||||
1623 | Expr *E = DS.getRepAsExpr(); | ||||
1624 | assert(E && "Didn't get an expression for typeof?")((E && "Didn't get an expression for typeof?") ? static_cast <void> (0) : __assert_fail ("E && \"Didn't get an expression for typeof?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1624, __PRETTY_FUNCTION__)); | ||||
1625 | // TypeQuals handled by caller. | ||||
1626 | Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); | ||||
1627 | if (Result.isNull()) { | ||||
1628 | Result = Context.IntTy; | ||||
1629 | declarator.setInvalidType(true); | ||||
1630 | } | ||||
1631 | break; | ||||
1632 | } | ||||
1633 | case DeclSpec::TST_decltype: { | ||||
1634 | Expr *E = DS.getRepAsExpr(); | ||||
1635 | assert(E && "Didn't get an expression for decltype?")((E && "Didn't get an expression for decltype?") ? static_cast <void> (0) : __assert_fail ("E && \"Didn't get an expression for decltype?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1635, __PRETTY_FUNCTION__)); | ||||
1636 | // TypeQuals handled by caller. | ||||
1637 | Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); | ||||
1638 | if (Result.isNull()) { | ||||
1639 | Result = Context.IntTy; | ||||
1640 | declarator.setInvalidType(true); | ||||
1641 | } | ||||
1642 | break; | ||||
1643 | } | ||||
1644 | case DeclSpec::TST_underlyingType: | ||||
1645 | Result = S.GetTypeFromParser(DS.getRepAsType()); | ||||
1646 | assert(!Result.isNull() && "Didn't get a type for __underlying_type?")((!Result.isNull() && "Didn't get a type for __underlying_type?" ) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for __underlying_type?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1646, __PRETTY_FUNCTION__)); | ||||
1647 | Result = S.BuildUnaryTransformType(Result, | ||||
1648 | UnaryTransformType::EnumUnderlyingType, | ||||
1649 | DS.getTypeSpecTypeLoc()); | ||||
1650 | if (Result.isNull()) { | ||||
1651 | Result = Context.IntTy; | ||||
1652 | declarator.setInvalidType(true); | ||||
1653 | } | ||||
1654 | break; | ||||
1655 | |||||
1656 | case DeclSpec::TST_auto: | ||||
1657 | if (DS.isConstrainedAuto()) { | ||||
1658 | Result = ConvertConstrainedAutoDeclSpecToType(S, DS, | ||||
1659 | AutoTypeKeyword::Auto); | ||||
1660 | break; | ||||
1661 | } | ||||
1662 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false); | ||||
1663 | break; | ||||
1664 | |||||
1665 | case DeclSpec::TST_auto_type: | ||||
1666 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); | ||||
1667 | break; | ||||
1668 | |||||
1669 | case DeclSpec::TST_decltype_auto: | ||||
1670 | if (DS.isConstrainedAuto()) { | ||||
1671 | Result = | ||||
1672 | ConvertConstrainedAutoDeclSpecToType(S, DS, | ||||
1673 | AutoTypeKeyword::DecltypeAuto); | ||||
1674 | break; | ||||
1675 | } | ||||
1676 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto, | ||||
1677 | /*IsDependent*/ false); | ||||
1678 | break; | ||||
1679 | |||||
1680 | case DeclSpec::TST_unknown_anytype: | ||||
1681 | Result = Context.UnknownAnyTy; | ||||
1682 | break; | ||||
1683 | |||||
1684 | case DeclSpec::TST_atomic: | ||||
1685 | Result = S.GetTypeFromParser(DS.getRepAsType()); | ||||
1686 | assert(!Result.isNull() && "Didn't get a type for _Atomic?")((!Result.isNull() && "Didn't get a type for _Atomic?" ) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for _Atomic?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1686, __PRETTY_FUNCTION__)); | ||||
1687 | Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); | ||||
1688 | if (Result.isNull()) { | ||||
1689 | Result = Context.IntTy; | ||||
1690 | declarator.setInvalidType(true); | ||||
1691 | } | ||||
1692 | break; | ||||
1693 | |||||
1694 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ | ||||
1695 | case DeclSpec::TST_##ImgType##_t: \ | ||||
1696 | switch (getImageAccess(DS.getAttributes())) { \ | ||||
1697 | case OpenCLAccessAttr::Keyword_write_only: \ | ||||
1698 | Result = Context.Id##WOTy; \ | ||||
1699 | break; \ | ||||
1700 | case OpenCLAccessAttr::Keyword_read_write: \ | ||||
1701 | Result = Context.Id##RWTy; \ | ||||
1702 | break; \ | ||||
1703 | case OpenCLAccessAttr::Keyword_read_only: \ | ||||
1704 | Result = Context.Id##ROTy; \ | ||||
1705 | break; \ | ||||
1706 | case OpenCLAccessAttr::SpellingNotCalculated: \ | ||||
1707 | llvm_unreachable("Spelling not yet calculated")::llvm::llvm_unreachable_internal("Spelling not yet calculated" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1707); \ | ||||
1708 | } \ | ||||
1709 | break; | ||||
1710 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
1711 | |||||
1712 | case DeclSpec::TST_error: | ||||
1713 | Result = Context.IntTy; | ||||
1714 | declarator.setInvalidType(true); | ||||
1715 | break; | ||||
1716 | } | ||||
1717 | |||||
1718 | // FIXME: we want resulting declarations to be marked invalid, but claiming | ||||
1719 | // the type is invalid is too strong - e.g. it causes ActOnTypeName to return | ||||
1720 | // a null type. | ||||
1721 | if (Result->containsErrors()) | ||||
1722 | declarator.setInvalidType(); | ||||
1723 | |||||
1724 | if (S.getLangOpts().OpenCL && | ||||
1725 | S.checkOpenCLDisabledTypeDeclSpec(DS, Result)) | ||||
1726 | declarator.setInvalidType(true); | ||||
1727 | |||||
1728 | bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || | ||||
1729 | DS.getTypeSpecType() == DeclSpec::TST_fract; | ||||
1730 | |||||
1731 | // Only fixed point types can be saturated | ||||
1732 | if (DS.isTypeSpecSat() && !IsFixedPointType) | ||||
1733 | S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) | ||||
1734 | << DS.getSpecifierName(DS.getTypeSpecType(), | ||||
1735 | Context.getPrintingPolicy()); | ||||
1736 | |||||
1737 | // Handle complex types. | ||||
1738 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { | ||||
1739 | if (S.getLangOpts().Freestanding) | ||||
1740 | S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); | ||||
1741 | Result = Context.getComplexType(Result); | ||||
1742 | } else if (DS.isTypeAltiVecVector()) { | ||||
1743 | unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); | ||||
1744 | assert(typeSize > 0 && "type size for vector must be greater than 0 bits")((typeSize > 0 && "type size for vector must be greater than 0 bits" ) ? static_cast<void> (0) : __assert_fail ("typeSize > 0 && \"type size for vector must be greater than 0 bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1744, __PRETTY_FUNCTION__)); | ||||
1745 | VectorType::VectorKind VecKind = VectorType::AltiVecVector; | ||||
1746 | if (DS.isTypeAltiVecPixel()) | ||||
1747 | VecKind = VectorType::AltiVecPixel; | ||||
1748 | else if (DS.isTypeAltiVecBool()) | ||||
1749 | VecKind = VectorType::AltiVecBool; | ||||
1750 | Result = Context.getVectorType(Result, 128/typeSize, VecKind); | ||||
1751 | } | ||||
1752 | |||||
1753 | // FIXME: Imaginary. | ||||
1754 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) | ||||
1755 | S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); | ||||
1756 | |||||
1757 | // Before we process any type attributes, synthesize a block literal | ||||
1758 | // function declarator if necessary. | ||||
1759 | if (declarator.getContext() == DeclaratorContext::BlockLiteral) | ||||
1760 | maybeSynthesizeBlockSignature(state, Result); | ||||
1761 | |||||
1762 | // Apply any type attributes from the decl spec. This may cause the | ||||
1763 | // list of type attributes to be temporarily saved while the type | ||||
1764 | // attributes are pushed around. | ||||
1765 | // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) | ||||
1766 | if (!DS.isTypeSpecPipe()) | ||||
1767 | processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes()); | ||||
1768 | |||||
1769 | // Apply const/volatile/restrict qualifiers to T. | ||||
1770 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | ||||
1771 | // Warn about CV qualifiers on function types. | ||||
1772 | // C99 6.7.3p8: | ||||
1773 | // If the specification of a function type includes any type qualifiers, | ||||
1774 | // the behavior is undefined. | ||||
1775 | // C++11 [dcl.fct]p7: | ||||
1776 | // The effect of a cv-qualifier-seq in a function declarator is not the | ||||
1777 | // same as adding cv-qualification on top of the function type. In the | ||||
1778 | // latter case, the cv-qualifiers are ignored. | ||||
1779 | if (Result->isFunctionType()) { | ||||
1780 | diagnoseAndRemoveTypeQualifiers( | ||||
1781 | S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, | ||||
1782 | S.getLangOpts().CPlusPlus | ||||
1783 | ? diag::warn_typecheck_function_qualifiers_ignored | ||||
1784 | : diag::warn_typecheck_function_qualifiers_unspecified); | ||||
1785 | // No diagnostic for 'restrict' or '_Atomic' applied to a | ||||
1786 | // function type; we'll diagnose those later, in BuildQualifiedType. | ||||
1787 | } | ||||
1788 | |||||
1789 | // C++11 [dcl.ref]p1: | ||||
1790 | // Cv-qualified references are ill-formed except when the | ||||
1791 | // cv-qualifiers are introduced through the use of a typedef-name | ||||
1792 | // or decltype-specifier, in which case the cv-qualifiers are ignored. | ||||
1793 | // | ||||
1794 | // There don't appear to be any other contexts in which a cv-qualified | ||||
1795 | // reference type could be formed, so the 'ill-formed' clause here appears | ||||
1796 | // to never happen. | ||||
1797 | if (TypeQuals && Result->isReferenceType()) { | ||||
1798 | diagnoseAndRemoveTypeQualifiers( | ||||
1799 | S, DS, TypeQuals, Result, | ||||
1800 | DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, | ||||
1801 | diag::warn_typecheck_reference_qualifiers); | ||||
1802 | } | ||||
1803 | |||||
1804 | // C90 6.5.3 constraints: "The same type qualifier shall not appear more | ||||
1805 | // than once in the same specifier-list or qualifier-list, either directly | ||||
1806 | // or via one or more typedefs." | ||||
1807 | if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus | ||||
1808 | && TypeQuals & Result.getCVRQualifiers()) { | ||||
1809 | if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { | ||||
1810 | S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) | ||||
1811 | << "const"; | ||||
1812 | } | ||||
1813 | |||||
1814 | if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { | ||||
1815 | S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) | ||||
1816 | << "volatile"; | ||||
1817 | } | ||||
1818 | |||||
1819 | // C90 doesn't have restrict nor _Atomic, so it doesn't force us to | ||||
1820 | // produce a warning in this case. | ||||
1821 | } | ||||
1822 | |||||
1823 | QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); | ||||
1824 | |||||
1825 | // If adding qualifiers fails, just use the unqualified type. | ||||
1826 | if (Qualified.isNull()) | ||||
1827 | declarator.setInvalidType(true); | ||||
1828 | else | ||||
1829 | Result = Qualified; | ||||
1830 | } | ||||
1831 | |||||
1832 | assert(!Result.isNull() && "This function should not return a null type")((!Result.isNull() && "This function should not return a null type" ) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"This function should not return a null type\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1832, __PRETTY_FUNCTION__)); | ||||
1833 | return Result; | ||||
1834 | } | ||||
1835 | |||||
1836 | static std::string getPrintableNameForEntity(DeclarationName Entity) { | ||||
1837 | if (Entity) | ||||
1838 | return Entity.getAsString(); | ||||
1839 | |||||
1840 | return "type name"; | ||||
1841 | } | ||||
1842 | |||||
1843 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | ||||
1844 | Qualifiers Qs, const DeclSpec *DS) { | ||||
1845 | if (T.isNull()) | ||||
1846 | return QualType(); | ||||
1847 | |||||
1848 | // Ignore any attempt to form a cv-qualified reference. | ||||
1849 | if (T->isReferenceType()) { | ||||
1850 | Qs.removeConst(); | ||||
1851 | Qs.removeVolatile(); | ||||
1852 | } | ||||
1853 | |||||
1854 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from | ||||
1855 | // object or incomplete types shall not be restrict-qualified." | ||||
1856 | if (Qs.hasRestrict()) { | ||||
1857 | unsigned DiagID = 0; | ||||
1858 | QualType ProblemTy; | ||||
1859 | |||||
1860 | if (T->isAnyPointerType() || T->isReferenceType() || | ||||
1861 | T->isMemberPointerType()) { | ||||
1862 | QualType EltTy; | ||||
1863 | if (T->isObjCObjectPointerType()) | ||||
1864 | EltTy = T; | ||||
1865 | else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) | ||||
1866 | EltTy = PTy->getPointeeType(); | ||||
1867 | else | ||||
1868 | EltTy = T->getPointeeType(); | ||||
1869 | |||||
1870 | // If we have a pointer or reference, the pointee must have an object | ||||
1871 | // incomplete type. | ||||
1872 | if (!EltTy->isIncompleteOrObjectType()) { | ||||
1873 | DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; | ||||
1874 | ProblemTy = EltTy; | ||||
1875 | } | ||||
1876 | } else if (!T->isDependentType()) { | ||||
1877 | DiagID = diag::err_typecheck_invalid_restrict_not_pointer; | ||||
1878 | ProblemTy = T; | ||||
1879 | } | ||||
1880 | |||||
1881 | if (DiagID) { | ||||
1882 | Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; | ||||
1883 | Qs.removeRestrict(); | ||||
1884 | } | ||||
1885 | } | ||||
1886 | |||||
1887 | return Context.getQualifiedType(T, Qs); | ||||
1888 | } | ||||
1889 | |||||
1890 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | ||||
1891 | unsigned CVRAU, const DeclSpec *DS) { | ||||
1892 | if (T.isNull()) | ||||
1893 | return QualType(); | ||||
1894 | |||||
1895 | // Ignore any attempt to form a cv-qualified reference. | ||||
1896 | if (T->isReferenceType()) | ||||
1897 | CVRAU &= | ||||
1898 | ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); | ||||
1899 | |||||
1900 | // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and | ||||
1901 | // TQ_unaligned; | ||||
1902 | unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); | ||||
1903 | |||||
1904 | // C11 6.7.3/5: | ||||
1905 | // If the same qualifier appears more than once in the same | ||||
1906 | // specifier-qualifier-list, either directly or via one or more typedefs, | ||||
1907 | // the behavior is the same as if it appeared only once. | ||||
1908 | // | ||||
1909 | // It's not specified what happens when the _Atomic qualifier is applied to | ||||
1910 | // a type specified with the _Atomic specifier, but we assume that this | ||||
1911 | // should be treated as if the _Atomic qualifier appeared multiple times. | ||||
1912 | if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { | ||||
1913 | // C11 6.7.3/5: | ||||
1914 | // If other qualifiers appear along with the _Atomic qualifier in a | ||||
1915 | // specifier-qualifier-list, the resulting type is the so-qualified | ||||
1916 | // atomic type. | ||||
1917 | // | ||||
1918 | // Don't need to worry about array types here, since _Atomic can't be | ||||
1919 | // applied to such types. | ||||
1920 | SplitQualType Split = T.getSplitUnqualifiedType(); | ||||
1921 | T = BuildAtomicType(QualType(Split.Ty, 0), | ||||
1922 | DS ? DS->getAtomicSpecLoc() : Loc); | ||||
1923 | if (T.isNull()) | ||||
1924 | return T; | ||||
1925 | Split.Quals.addCVRQualifiers(CVR); | ||||
1926 | return BuildQualifiedType(T, Loc, Split.Quals); | ||||
1927 | } | ||||
1928 | |||||
1929 | Qualifiers Q = Qualifiers::fromCVRMask(CVR); | ||||
1930 | Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); | ||||
1931 | return BuildQualifiedType(T, Loc, Q, DS); | ||||
1932 | } | ||||
1933 | |||||
1934 | /// Build a paren type including \p T. | ||||
1935 | QualType Sema::BuildParenType(QualType T) { | ||||
1936 | return Context.getParenType(T); | ||||
1937 | } | ||||
1938 | |||||
1939 | /// Given that we're building a pointer or reference to the given | ||||
1940 | static QualType inferARCLifetimeForPointee(Sema &S, QualType type, | ||||
1941 | SourceLocation loc, | ||||
1942 | bool isReference) { | ||||
1943 | // Bail out if retention is unrequired or already specified. | ||||
1944 | if (!type->isObjCLifetimeType() || | ||||
1945 | type.getObjCLifetime() != Qualifiers::OCL_None) | ||||
1946 | return type; | ||||
1947 | |||||
1948 | Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; | ||||
1949 | |||||
1950 | // If the object type is const-qualified, we can safely use | ||||
1951 | // __unsafe_unretained. This is safe (because there are no read | ||||
1952 | // barriers), and it'll be safe to coerce anything but __weak* to | ||||
1953 | // the resulting type. | ||||
1954 | if (type.isConstQualified()) { | ||||
1955 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | ||||
1956 | |||||
1957 | // Otherwise, check whether the static type does not require | ||||
1958 | // retaining. This currently only triggers for Class (possibly | ||||
1959 | // protocol-qualifed, and arrays thereof). | ||||
1960 | } else if (type->isObjCARCImplicitlyUnretainedType()) { | ||||
1961 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | ||||
1962 | |||||
1963 | // If we are in an unevaluated context, like sizeof, skip adding a | ||||
1964 | // qualification. | ||||
1965 | } else if (S.isUnevaluatedContext()) { | ||||
1966 | return type; | ||||
1967 | |||||
1968 | // If that failed, give an error and recover using __strong. __strong | ||||
1969 | // is the option most likely to prevent spurious second-order diagnostics, | ||||
1970 | // like when binding a reference to a field. | ||||
1971 | } else { | ||||
1972 | // These types can show up in private ivars in system headers, so | ||||
1973 | // we need this to not be an error in those cases. Instead we | ||||
1974 | // want to delay. | ||||
1975 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | ||||
1976 | S.DelayedDiagnostics.add( | ||||
1977 | sema::DelayedDiagnostic::makeForbiddenType(loc, | ||||
1978 | diag::err_arc_indirect_no_ownership, type, isReference)); | ||||
1979 | } else { | ||||
1980 | S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; | ||||
1981 | } | ||||
1982 | implicitLifetime = Qualifiers::OCL_Strong; | ||||
1983 | } | ||||
1984 | assert(implicitLifetime && "didn't infer any lifetime!")((implicitLifetime && "didn't infer any lifetime!") ? static_cast<void> (0) : __assert_fail ("implicitLifetime && \"didn't infer any lifetime!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 1984, __PRETTY_FUNCTION__)); | ||||
1985 | |||||
1986 | Qualifiers qs; | ||||
1987 | qs.addObjCLifetime(implicitLifetime); | ||||
1988 | return S.Context.getQualifiedType(type, qs); | ||||
1989 | } | ||||
1990 | |||||
1991 | static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ | ||||
1992 | std::string Quals = FnTy->getMethodQuals().getAsString(); | ||||
1993 | |||||
1994 | switch (FnTy->getRefQualifier()) { | ||||
1995 | case RQ_None: | ||||
1996 | break; | ||||
1997 | |||||
1998 | case RQ_LValue: | ||||
1999 | if (!Quals.empty()) | ||||
2000 | Quals += ' '; | ||||
2001 | Quals += '&'; | ||||
2002 | break; | ||||
2003 | |||||
2004 | case RQ_RValue: | ||||
2005 | if (!Quals.empty()) | ||||
2006 | Quals += ' '; | ||||
2007 | Quals += "&&"; | ||||
2008 | break; | ||||
2009 | } | ||||
2010 | |||||
2011 | return Quals; | ||||
2012 | } | ||||
2013 | |||||
2014 | namespace { | ||||
2015 | /// Kinds of declarator that cannot contain a qualified function type. | ||||
2016 | /// | ||||
2017 | /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: | ||||
2018 | /// a function type with a cv-qualifier or a ref-qualifier can only appear | ||||
2019 | /// at the topmost level of a type. | ||||
2020 | /// | ||||
2021 | /// Parens and member pointers are permitted. We don't diagnose array and | ||||
2022 | /// function declarators, because they don't allow function types at all. | ||||
2023 | /// | ||||
2024 | /// The values of this enum are used in diagnostics. | ||||
2025 | enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; | ||||
2026 | } // end anonymous namespace | ||||
2027 | |||||
2028 | /// Check whether the type T is a qualified function type, and if it is, | ||||
2029 | /// diagnose that it cannot be contained within the given kind of declarator. | ||||
2030 | static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, | ||||
2031 | QualifiedFunctionKind QFK) { | ||||
2032 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | ||||
2033 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); | ||||
2034 | if (!FPT || | ||||
2035 | (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) | ||||
2036 | return false; | ||||
2037 | |||||
2038 | S.Diag(Loc, diag::err_compound_qualified_function_type) | ||||
2039 | << QFK << isa<FunctionType>(T.IgnoreParens()) << T | ||||
2040 | << getFunctionQualifiersAsString(FPT); | ||||
2041 | return true; | ||||
2042 | } | ||||
2043 | |||||
2044 | bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) { | ||||
2045 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); | ||||
2046 | if (!FPT || | ||||
2047 | (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) | ||||
2048 | return false; | ||||
2049 | |||||
2050 | Diag(Loc, diag::err_qualified_function_typeid) | ||||
2051 | << T << getFunctionQualifiersAsString(FPT); | ||||
2052 | return true; | ||||
2053 | } | ||||
2054 | |||||
2055 | // Helper to deduce addr space of a pointee type in OpenCL mode. | ||||
2056 | static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) { | ||||
2057 | if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() && | ||||
2058 | !PointeeType->isSamplerT() && | ||||
2059 | !PointeeType.hasAddressSpace()) | ||||
2060 | PointeeType = S.getASTContext().getAddrSpaceQualType( | ||||
2061 | PointeeType, | ||||
2062 | S.getLangOpts().OpenCLCPlusPlus || S.getLangOpts().OpenCLVersion == 200 | ||||
2063 | ? LangAS::opencl_generic | ||||
2064 | : LangAS::opencl_private); | ||||
2065 | return PointeeType; | ||||
2066 | } | ||||
2067 | |||||
2068 | /// Build a pointer type. | ||||
2069 | /// | ||||
2070 | /// \param T The type to which we'll be building a pointer. | ||||
2071 | /// | ||||
2072 | /// \param Loc The location of the entity whose type involves this | ||||
2073 | /// pointer type or, if there is no such entity, the location of the | ||||
2074 | /// type that will have pointer type. | ||||
2075 | /// | ||||
2076 | /// \param Entity The name of the entity that involves the pointer | ||||
2077 | /// type, if known. | ||||
2078 | /// | ||||
2079 | /// \returns A suitable pointer type, if there are no | ||||
2080 | /// errors. Otherwise, returns a NULL type. | ||||
2081 | QualType Sema::BuildPointerType(QualType T, | ||||
2082 | SourceLocation Loc, DeclarationName Entity) { | ||||
2083 | if (T->isReferenceType()) { | ||||
2084 | // C++ 8.3.2p4: There shall be no ... pointers to references ... | ||||
2085 | Diag(Loc, diag::err_illegal_decl_pointer_to_reference) | ||||
2086 | << getPrintableNameForEntity(Entity) << T; | ||||
2087 | return QualType(); | ||||
2088 | } | ||||
2089 | |||||
2090 | if (T->isFunctionType() && getLangOpts().OpenCL) { | ||||
2091 | Diag(Loc, diag::err_opencl_function_pointer); | ||||
2092 | return QualType(); | ||||
2093 | } | ||||
2094 | |||||
2095 | if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) | ||||
2096 | return QualType(); | ||||
2097 | |||||
2098 | assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType")((!T->isObjCObjectType() && "Should build ObjCObjectPointerType" ) ? static_cast<void> (0) : __assert_fail ("!T->isObjCObjectType() && \"Should build ObjCObjectPointerType\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 2098, __PRETTY_FUNCTION__)); | ||||
2099 | |||||
2100 | // In ARC, it is forbidden to build pointers to unqualified pointers. | ||||
2101 | if (getLangOpts().ObjCAutoRefCount) | ||||
2102 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); | ||||
2103 | |||||
2104 | if (getLangOpts().OpenCL) | ||||
2105 | T = deduceOpenCLPointeeAddrSpace(*this, T); | ||||
2106 | |||||
2107 | // Build the pointer type. | ||||
2108 | return Context.getPointerType(T); | ||||
2109 | } | ||||
2110 | |||||
2111 | /// Build a reference type. | ||||
2112 | /// | ||||
2113 | /// \param T The type to which we'll be building a reference. | ||||
2114 | /// | ||||
2115 | /// \param Loc The location of the entity whose type involves this | ||||
2116 | /// reference type or, if there is no such entity, the location of the | ||||
2117 | /// type that will have reference type. | ||||
2118 | /// | ||||
2119 | /// \param Entity The name of the entity that involves the reference | ||||
2120 | /// type, if known. | ||||
2121 | /// | ||||
2122 | /// \returns A suitable reference type, if there are no | ||||
2123 | /// errors. Otherwise, returns a NULL type. | ||||
2124 | QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, | ||||
2125 | SourceLocation Loc, | ||||
2126 | DeclarationName Entity) { | ||||
2127 | assert(Context.getCanonicalType(T) != Context.OverloadTy &&((Context.getCanonicalType(T) != Context.OverloadTy && "Unresolved overloaded function type") ? static_cast<void > (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 2128, __PRETTY_FUNCTION__)) | ||||
2128 | "Unresolved overloaded function type")((Context.getCanonicalType(T) != Context.OverloadTy && "Unresolved overloaded function type") ? static_cast<void > (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 2128, __PRETTY_FUNCTION__)); | ||||
2129 | |||||
2130 | // C++0x [dcl.ref]p6: | ||||
2131 | // If a typedef (7.1.3), a type template-parameter (14.3.1), or a | ||||
2132 | // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a | ||||
2133 | // type T, an attempt to create the type "lvalue reference to cv TR" creates | ||||
2134 | // the type "lvalue reference to T", while an attempt to create the type | ||||
2135 | // "rvalue reference to cv TR" creates the type TR. | ||||
2136 | bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); | ||||
2137 | |||||
2138 | // C++ [dcl.ref]p4: There shall be no references to references. | ||||
2139 | // | ||||
2140 | // According to C++ DR 106, references to references are only | ||||
2141 | // diagnosed when they are written directly (e.g., "int & &"), | ||||
2142 | // but not when they happen via a typedef: | ||||
2143 | // | ||||
2144 | // typedef int& intref; | ||||
2145 | // typedef intref& intref2; | ||||
2146 | // | ||||
2147 | // Parser::ParseDeclaratorInternal diagnoses the case where | ||||
2148 | // references are written directly; here, we handle the | ||||
2149 | // collapsing of references-to-references as described in C++0x. | ||||
2150 | // DR 106 and 540 introduce reference-collapsing into C++98/03. | ||||
2151 | |||||
2152 | // C++ [dcl.ref]p1: | ||||
2153 | // A declarator that specifies the type "reference to cv void" | ||||
2154 | // is ill-formed. | ||||
2155 | if (T->isVoidType()) { | ||||
2156 | Diag(Loc, diag::err_reference_to_void); | ||||
2157 | return QualType(); | ||||
2158 | } | ||||
2159 | |||||
2160 | if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) | ||||
2161 | return QualType(); | ||||
2162 | |||||
2163 | // In ARC, it is forbidden to build references to unqualified pointers. | ||||
2164 | if (getLangOpts().ObjCAutoRefCount) | ||||
2165 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); | ||||
2166 | |||||
2167 | if (getLangOpts().OpenCL) | ||||
2168 | T = deduceOpenCLPointeeAddrSpace(*this, T); | ||||
2169 | |||||
2170 | // Handle restrict on references. | ||||
2171 | if (LValueRef) | ||||
2172 | return Context.getLValueReferenceType(T, SpelledAsLValue); | ||||
2173 | return Context.getRValueReferenceType(T); | ||||
2174 | } | ||||
2175 | |||||
2176 | /// Build a Read-only Pipe type. | ||||
2177 | /// | ||||
2178 | /// \param T The type to which we'll be building a Pipe. | ||||
2179 | /// | ||||
2180 | /// \param Loc We do not use it for now. | ||||
2181 | /// | ||||
2182 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | ||||
2183 | /// NULL type. | ||||
2184 | QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { | ||||
2185 | return Context.getReadPipeType(T); | ||||
2186 | } | ||||
2187 | |||||
2188 | /// Build a Write-only Pipe type. | ||||
2189 | /// | ||||
2190 | /// \param T The type to which we'll be building a Pipe. | ||||
2191 | /// | ||||
2192 | /// \param Loc We do not use it for now. | ||||
2193 | /// | ||||
2194 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | ||||
2195 | /// NULL type. | ||||
2196 | QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { | ||||
2197 | return Context.getWritePipeType(T); | ||||
2198 | } | ||||
2199 | |||||
2200 | /// Build a extended int type. | ||||
2201 | /// | ||||
2202 | /// \param IsUnsigned Boolean representing the signedness of the type. | ||||
2203 | /// | ||||
2204 | /// \param BitWidth Size of this int type in bits, or an expression representing | ||||
2205 | /// that. | ||||
2206 | /// | ||||
2207 | /// \param Loc Location of the keyword. | ||||
2208 | QualType Sema::BuildExtIntType(bool IsUnsigned, Expr *BitWidth, | ||||
2209 | SourceLocation Loc) { | ||||
2210 | if (BitWidth->isInstantiationDependent()) | ||||
2211 | return Context.getDependentExtIntType(IsUnsigned, BitWidth); | ||||
2212 | |||||
2213 | llvm::APSInt Bits(32); | ||||
2214 | ExprResult ICE = | ||||
2215 | VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold); | ||||
2216 | |||||
2217 | if (ICE.isInvalid()) | ||||
2218 | return QualType(); | ||||
2219 | |||||
2220 | int64_t NumBits = Bits.getSExtValue(); | ||||
2221 | if (!IsUnsigned && NumBits < 2) { | ||||
2222 | Diag(Loc, diag::err_ext_int_bad_size) << 0; | ||||
2223 | return QualType(); | ||||
2224 | } | ||||
2225 | |||||
2226 | if (IsUnsigned && NumBits < 1) { | ||||
2227 | Diag(Loc, diag::err_ext_int_bad_size) << 1; | ||||
2228 | return QualType(); | ||||
2229 | } | ||||
2230 | |||||
2231 | if (NumBits > llvm::IntegerType::MAX_INT_BITS) { | ||||
2232 | Diag(Loc, diag::err_ext_int_max_size) << IsUnsigned | ||||
2233 | << llvm::IntegerType::MAX_INT_BITS; | ||||
2234 | return QualType(); | ||||
2235 | } | ||||
2236 | |||||
2237 | return Context.getExtIntType(IsUnsigned, NumBits); | ||||
2238 | } | ||||
2239 | |||||
2240 | /// Check whether the specified array bound can be evaluated using the relevant | ||||
2241 | /// language rules. If so, returns the possibly-converted expression and sets | ||||
2242 | /// SizeVal to the size. If not, but the expression might be a VLA bound, | ||||
2243 | /// returns ExprResult(). Otherwise, produces a diagnostic and returns | ||||
2244 | /// ExprError(). | ||||
2245 | static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, | ||||
2246 | llvm::APSInt &SizeVal, unsigned VLADiag, | ||||
2247 | bool VLAIsError) { | ||||
2248 | if (S.getLangOpts().CPlusPlus14 && | ||||
2249 | (VLAIsError || | ||||
2250 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) { | ||||
2251 | // C++14 [dcl.array]p1: | ||||
2252 | // The constant-expression shall be a converted constant expression of | ||||
2253 | // type std::size_t. | ||||
2254 | // | ||||
2255 | // Don't apply this rule if we might be forming a VLA: in that case, we | ||||
2256 | // allow non-constant expressions and constant-folding. We only need to use | ||||
2257 | // the converted constant expression rules (to properly convert the source) | ||||
2258 | // when the source expression is of class type. | ||||
2259 | return S.CheckConvertedConstantExpression( | ||||
2260 | ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound); | ||||
2261 | } | ||||
2262 | |||||
2263 | // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode | ||||
2264 | // (like gnu99, but not c99) accept any evaluatable value as an extension. | ||||
2265 | class VLADiagnoser : public Sema::VerifyICEDiagnoser { | ||||
2266 | public: | ||||
2267 | unsigned VLADiag; | ||||
2268 | bool VLAIsError; | ||||
2269 | bool IsVLA = false; | ||||
2270 | |||||
2271 | VLADiagnoser(unsigned VLADiag, bool VLAIsError) | ||||
2272 | : VLADiag(VLADiag), VLAIsError(VLAIsError) {} | ||||
2273 | |||||
2274 | Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | ||||
2275 | QualType T) override { | ||||
2276 | return S.Diag(Loc, diag::err_array_size_non_int) << T; | ||||
2277 | } | ||||
2278 | |||||
2279 | Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, | ||||
2280 | SourceLocation Loc) override { | ||||
2281 | IsVLA = !VLAIsError; | ||||
2282 | return S.Diag(Loc, VLADiag); | ||||
2283 | } | ||||
2284 | |||||
2285 | Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S, | ||||
2286 | SourceLocation Loc) override { | ||||
2287 | return S.Diag(Loc, diag::ext_vla_folded_to_constant); | ||||
2288 | } | ||||
2289 | } Diagnoser(VLADiag, VLAIsError); | ||||
2290 | |||||
2291 | ExprResult R = | ||||
2292 | S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser); | ||||
2293 | if (Diagnoser.IsVLA) | ||||
2294 | return ExprResult(); | ||||
2295 | return R; | ||||
2296 | } | ||||
2297 | |||||
2298 | /// Build an array type. | ||||
2299 | /// | ||||
2300 | /// \param T The type of each element in the array. | ||||
2301 | /// | ||||
2302 | /// \param ASM C99 array size modifier (e.g., '*', 'static'). | ||||
2303 | /// | ||||
2304 | /// \param ArraySize Expression describing the size of the array. | ||||
2305 | /// | ||||
2306 | /// \param Brackets The range from the opening '[' to the closing ']'. | ||||
2307 | /// | ||||
2308 | /// \param Entity The name of the entity that involves the array | ||||
2309 | /// type, if known. | ||||
2310 | /// | ||||
2311 | /// \returns A suitable array type, if there are no errors. Otherwise, | ||||
2312 | /// returns a NULL type. | ||||
2313 | QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, | ||||
2314 | Expr *ArraySize, unsigned Quals, | ||||
2315 | SourceRange Brackets, DeclarationName Entity) { | ||||
2316 | |||||
2317 | SourceLocation Loc = Brackets.getBegin(); | ||||
2318 | if (getLangOpts().CPlusPlus) { | ||||
2319 | // C++ [dcl.array]p1: | ||||
2320 | // T is called the array element type; this type shall not be a reference | ||||
2321 | // type, the (possibly cv-qualified) type void, a function type or an | ||||
2322 | // abstract class type. | ||||
2323 | // | ||||
2324 | // C++ [dcl.array]p3: | ||||
2325 | // When several "array of" specifications are adjacent, [...] only the | ||||
2326 | // first of the constant expressions that specify the bounds of the arrays | ||||
2327 | // may be omitted. | ||||
2328 | // | ||||
2329 | // Note: function types are handled in the common path with C. | ||||
2330 | if (T->isReferenceType()) { | ||||
2331 | Diag(Loc, diag::err_illegal_decl_array_of_references) | ||||
2332 | << getPrintableNameForEntity(Entity) << T; | ||||
2333 | return QualType(); | ||||
2334 | } | ||||
2335 | |||||
2336 | if (T->isVoidType() || T->isIncompleteArrayType()) { | ||||
2337 | Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T; | ||||
2338 | return QualType(); | ||||
2339 | } | ||||
2340 | |||||
2341 | if (RequireNonAbstractType(Brackets.getBegin(), T, | ||||
2342 | diag::err_array_of_abstract_type)) | ||||
2343 | return QualType(); | ||||
2344 | |||||
2345 | // Mentioning a member pointer type for an array type causes us to lock in | ||||
2346 | // an inheritance model, even if it's inside an unused typedef. | ||||
2347 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
2348 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) | ||||
2349 | if (!MPTy->getClass()->isDependentType()) | ||||
2350 | (void)isCompleteType(Loc, T); | ||||
2351 | |||||
2352 | } else { | ||||
2353 | // C99 6.7.5.2p1: If the element type is an incomplete or function type, | ||||
2354 | // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) | ||||
2355 | if (RequireCompleteSizedType(Loc, T, | ||||
2356 | diag::err_array_incomplete_or_sizeless_type)) | ||||
2357 | return QualType(); | ||||
2358 | } | ||||
2359 | |||||
2360 | if (T->isSizelessType()) { | ||||
2361 | Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T; | ||||
2362 | return QualType(); | ||||
2363 | } | ||||
2364 | |||||
2365 | if (T->isFunctionType()) { | ||||
2366 | Diag(Loc, diag::err_illegal_decl_array_of_functions) | ||||
2367 | << getPrintableNameForEntity(Entity) << T; | ||||
2368 | return QualType(); | ||||
2369 | } | ||||
2370 | |||||
2371 | if (const RecordType *EltTy = T->getAs<RecordType>()) { | ||||
2372 | // If the element type is a struct or union that contains a variadic | ||||
2373 | // array, accept it as a GNU extension: C99 6.7.2.1p2. | ||||
2374 | if (EltTy->getDecl()->hasFlexibleArrayMember()) | ||||
2375 | Diag(Loc, diag::ext_flexible_array_in_array) << T; | ||||
2376 | } else if (T->isObjCObjectType()) { | ||||
2377 | Diag(Loc, diag::err_objc_array_of_interfaces) << T; | ||||
2378 | return QualType(); | ||||
2379 | } | ||||
2380 | |||||
2381 | // Do placeholder conversions on the array size expression. | ||||
2382 | if (ArraySize && ArraySize->hasPlaceholderType()) { | ||||
2383 | ExprResult Result = CheckPlaceholderExpr(ArraySize); | ||||
2384 | if (Result.isInvalid()) return QualType(); | ||||
2385 | ArraySize = Result.get(); | ||||
2386 | } | ||||
2387 | |||||
2388 | // Do lvalue-to-rvalue conversions on the array size expression. | ||||
2389 | if (ArraySize && !ArraySize->isRValue()) { | ||||
2390 | ExprResult Result = DefaultLvalueConversion(ArraySize); | ||||
2391 | if (Result.isInvalid()) | ||||
2392 | return QualType(); | ||||
2393 | |||||
2394 | ArraySize = Result.get(); | ||||
2395 | } | ||||
2396 | |||||
2397 | // C99 6.7.5.2p1: The size expression shall have integer type. | ||||
2398 | // C++11 allows contextual conversions to such types. | ||||
2399 | if (!getLangOpts().CPlusPlus11 && | ||||
2400 | ArraySize && !ArraySize->isTypeDependent() && | ||||
2401 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||
2402 | Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) | ||||
2403 | << ArraySize->getType() << ArraySize->getSourceRange(); | ||||
2404 | return QualType(); | ||||
2405 | } | ||||
2406 | |||||
2407 | // VLAs always produce at least a -Wvla diagnostic, sometimes an error. | ||||
2408 | unsigned VLADiag; | ||||
2409 | bool VLAIsError; | ||||
2410 | if (getLangOpts().OpenCL) { | ||||
2411 | // OpenCL v1.2 s6.9.d: variable length arrays are not supported. | ||||
2412 | VLADiag = diag::err_opencl_vla; | ||||
2413 | VLAIsError = true; | ||||
2414 | } else if (getLangOpts().C99) { | ||||
2415 | VLADiag = diag::warn_vla_used; | ||||
2416 | VLAIsError = false; | ||||
2417 | } else if (isSFINAEContext()) { | ||||
2418 | VLADiag = diag::err_vla_in_sfinae; | ||||
2419 | VLAIsError = true; | ||||
2420 | } else { | ||||
2421 | VLADiag = diag::ext_vla; | ||||
2422 | VLAIsError = false; | ||||
2423 | } | ||||
2424 | |||||
2425 | llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); | ||||
2426 | if (!ArraySize) { | ||||
2427 | if (ASM == ArrayType::Star) { | ||||
2428 | Diag(Loc, VLADiag); | ||||
2429 | if (VLAIsError) | ||||
2430 | return QualType(); | ||||
2431 | |||||
2432 | T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); | ||||
2433 | } else { | ||||
2434 | T = Context.getIncompleteArrayType(T, ASM, Quals); | ||||
2435 | } | ||||
2436 | } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { | ||||
2437 | T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); | ||||
2438 | } else { | ||||
2439 | ExprResult R = | ||||
2440 | checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError); | ||||
2441 | if (R.isInvalid()) | ||||
2442 | return QualType(); | ||||
2443 | |||||
2444 | if (!R.isUsable()) { | ||||
2445 | // C99: an array with a non-ICE size is a VLA. We accept any expression | ||||
2446 | // that we can fold to a non-zero positive value as a non-VLA as an | ||||
2447 | // extension. | ||||
2448 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); | ||||
2449 | } else if (!T->isDependentType() && !T->isIncompleteType() && | ||||
2450 | !T->isConstantSizeType()) { | ||||
2451 | // C99: an array with an element type that has a non-constant-size is a | ||||
2452 | // VLA. | ||||
2453 | // FIXME: Add a note to explain why this isn't a VLA. | ||||
2454 | Diag(Loc, VLADiag); | ||||
2455 | if (VLAIsError) | ||||
2456 | return QualType(); | ||||
2457 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); | ||||
2458 | } else { | ||||
2459 | // C99 6.7.5.2p1: If the expression is a constant expression, it shall | ||||
2460 | // have a value greater than zero. | ||||
2461 | // In C++, this follows from narrowing conversions being disallowed. | ||||
2462 | if (ConstVal.isSigned() && ConstVal.isNegative()) { | ||||
2463 | if (Entity) | ||||
2464 | Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) | ||||
2465 | << getPrintableNameForEntity(Entity) | ||||
2466 | << ArraySize->getSourceRange(); | ||||
2467 | else | ||||
2468 | Diag(ArraySize->getBeginLoc(), | ||||
2469 | diag::err_typecheck_negative_array_size) | ||||
2470 | << ArraySize->getSourceRange(); | ||||
2471 | return QualType(); | ||||
2472 | } | ||||
2473 | if (ConstVal == 0) { | ||||
2474 | // GCC accepts zero sized static arrays. We allow them when | ||||
2475 | // we're not in a SFINAE context. | ||||
2476 | Diag(ArraySize->getBeginLoc(), | ||||
2477 | isSFINAEContext() ? diag::err_typecheck_zero_array_size | ||||
2478 | : diag::ext_typecheck_zero_array_size) | ||||
2479 | << ArraySize->getSourceRange(); | ||||
2480 | } | ||||
2481 | |||||
2482 | // Is the array too large? | ||||
2483 | unsigned ActiveSizeBits = | ||||
2484 | (!T->isDependentType() && !T->isVariablyModifiedType() && | ||||
2485 | !T->isIncompleteType() && !T->isUndeducedType()) | ||||
2486 | ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal) | ||||
2487 | : ConstVal.getActiveBits(); | ||||
2488 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | ||||
2489 | Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) | ||||
2490 | << ConstVal.toString(10) << ArraySize->getSourceRange(); | ||||
2491 | return QualType(); | ||||
2492 | } | ||||
2493 | |||||
2494 | T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals); | ||||
2495 | } | ||||
2496 | } | ||||
2497 | |||||
2498 | if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) { | ||||
2499 | // CUDA device code and some other targets don't support VLAs. | ||||
2500 | targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) | ||||
2501 | ? diag::err_cuda_vla | ||||
2502 | : diag::err_vla_unsupported) | ||||
2503 | << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice) | ||||
2504 | ? CurrentCUDATarget() | ||||
2505 | : CFT_InvalidTarget); | ||||
2506 | } | ||||
2507 | |||||
2508 | // If this is not C99, diagnose array size modifiers on non-VLAs. | ||||
2509 | if (!getLangOpts().C99 && !T->isVariableArrayType() && | ||||
2510 | (ASM != ArrayType::Normal || Quals != 0)) { | ||||
2511 | Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx | ||||
2512 | : diag::ext_c99_array_usage) | ||||
2513 | << ASM; | ||||
2514 | } | ||||
2515 | |||||
2516 | // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. | ||||
2517 | // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. | ||||
2518 | // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. | ||||
2519 | if (getLangOpts().OpenCL) { | ||||
2520 | const QualType ArrType = Context.getBaseElementType(T); | ||||
2521 | if (ArrType->isBlockPointerType() || ArrType->isPipeType() || | ||||
2522 | ArrType->isSamplerT() || ArrType->isImageType()) { | ||||
2523 | Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; | ||||
2524 | return QualType(); | ||||
2525 | } | ||||
2526 | } | ||||
2527 | |||||
2528 | return T; | ||||
2529 | } | ||||
2530 | |||||
2531 | QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, | ||||
2532 | SourceLocation AttrLoc) { | ||||
2533 | // The base type must be integer (not Boolean or enumeration) or float, and | ||||
2534 | // can't already be a vector. | ||||
2535 | if ((!CurType->isDependentType() && | ||||
2536 | (!CurType->isBuiltinType() || CurType->isBooleanType() || | ||||
2537 | (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) || | ||||
2538 | CurType->isArrayType()) { | ||||
2539 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; | ||||
2540 | return QualType(); | ||||
2541 | } | ||||
2542 | |||||
2543 | if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) | ||||
2544 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, | ||||
2545 | VectorType::GenericVector); | ||||
2546 | |||||
2547 | Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context); | ||||
2548 | if (!VecSize) { | ||||
2549 | Diag(AttrLoc, diag::err_attribute_argument_type) | ||||
2550 | << "vector_size" << AANT_ArgumentIntegerConstant | ||||
2551 | << SizeExpr->getSourceRange(); | ||||
2552 | return QualType(); | ||||
2553 | } | ||||
2554 | |||||
2555 | if (CurType->isDependentType()) | ||||
2556 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, | ||||
2557 | VectorType::GenericVector); | ||||
2558 | |||||
2559 | // vecSize is specified in bytes - convert to bits. | ||||
2560 | if (!VecSize->isIntN(61)) { | ||||
2561 | // Bit size will overflow uint64. | ||||
2562 | Diag(AttrLoc, diag::err_attribute_size_too_large) | ||||
2563 | << SizeExpr->getSourceRange() << "vector"; | ||||
2564 | return QualType(); | ||||
2565 | } | ||||
2566 | uint64_t VectorSizeBits = VecSize->getZExtValue() * 8; | ||||
2567 | unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType)); | ||||
2568 | |||||
2569 | if (VectorSizeBits == 0) { | ||||
2570 | Diag(AttrLoc, diag::err_attribute_zero_size) | ||||
2571 | << SizeExpr->getSourceRange() << "vector"; | ||||
2572 | return QualType(); | ||||
2573 | } | ||||
2574 | |||||
2575 | if (VectorSizeBits % TypeSize) { | ||||
2576 | Diag(AttrLoc, diag::err_attribute_invalid_size) | ||||
2577 | << SizeExpr->getSourceRange(); | ||||
2578 | return QualType(); | ||||
2579 | } | ||||
2580 | |||||
2581 | if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) { | ||||
2582 | Diag(AttrLoc, diag::err_attribute_size_too_large) | ||||
2583 | << SizeExpr->getSourceRange() << "vector"; | ||||
2584 | return QualType(); | ||||
2585 | } | ||||
2586 | |||||
2587 | return Context.getVectorType(CurType, VectorSizeBits / TypeSize, | ||||
2588 | VectorType::GenericVector); | ||||
2589 | } | ||||
2590 | |||||
2591 | /// Build an ext-vector type. | ||||
2592 | /// | ||||
2593 | /// Run the required checks for the extended vector type. | ||||
2594 | QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, | ||||
2595 | SourceLocation AttrLoc) { | ||||
2596 | // Unlike gcc's vector_size attribute, we do not allow vectors to be defined | ||||
2597 | // in conjunction with complex types (pointers, arrays, functions, etc.). | ||||
2598 | // | ||||
2599 | // Additionally, OpenCL prohibits vectors of booleans (they're considered a | ||||
2600 | // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects | ||||
2601 | // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors | ||||
2602 | // of bool aren't allowed. | ||||
2603 | if ((!T->isDependentType() && !T->isIntegerType() && | ||||
2604 | !T->isRealFloatingType()) || | ||||
2605 | T->isBooleanType()) { | ||||
2606 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; | ||||
2607 | return QualType(); | ||||
2608 | } | ||||
2609 | |||||
2610 | if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { | ||||
2611 | Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context); | ||||
2612 | if (!vecSize) { | ||||
2613 | Diag(AttrLoc, diag::err_attribute_argument_type) | ||||
2614 | << "ext_vector_type" << AANT_ArgumentIntegerConstant | ||||
2615 | << ArraySize->getSourceRange(); | ||||
2616 | return QualType(); | ||||
2617 | } | ||||
2618 | |||||
2619 | if (!vecSize->isIntN(32)) { | ||||
2620 | Diag(AttrLoc, diag::err_attribute_size_too_large) | ||||
2621 | << ArraySize->getSourceRange() << "vector"; | ||||
2622 | return QualType(); | ||||
2623 | } | ||||
2624 | // Unlike gcc's vector_size attribute, the size is specified as the | ||||
2625 | // number of elements, not the number of bytes. | ||||
2626 | unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue()); | ||||
2627 | |||||
2628 | if (vectorSize == 0) { | ||||
2629 | Diag(AttrLoc, diag::err_attribute_zero_size) | ||||
2630 | << ArraySize->getSourceRange() << "vector"; | ||||
2631 | return QualType(); | ||||
2632 | } | ||||
2633 | |||||
2634 | return Context.getExtVectorType(T, vectorSize); | ||||
2635 | } | ||||
2636 | |||||
2637 | return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); | ||||
2638 | } | ||||
2639 | |||||
2640 | QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols, | ||||
2641 | SourceLocation AttrLoc) { | ||||
2642 | assert(Context.getLangOpts().MatrixTypes &&((Context.getLangOpts().MatrixTypes && "Should never build a matrix type when it is disabled" ) ? static_cast<void> (0) : __assert_fail ("Context.getLangOpts().MatrixTypes && \"Should never build a matrix type when it is disabled\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 2643, __PRETTY_FUNCTION__)) | ||||
2643 | "Should never build a matrix type when it is disabled")((Context.getLangOpts().MatrixTypes && "Should never build a matrix type when it is disabled" ) ? static_cast<void> (0) : __assert_fail ("Context.getLangOpts().MatrixTypes && \"Should never build a matrix type when it is disabled\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 2643, __PRETTY_FUNCTION__)); | ||||
2644 | |||||
2645 | // Check element type, if it is not dependent. | ||||
2646 | if (!ElementTy->isDependentType() && | ||||
2647 | !MatrixType::isValidElementType(ElementTy)) { | ||||
2648 | Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy; | ||||
2649 | return QualType(); | ||||
2650 | } | ||||
2651 | |||||
2652 | if (NumRows->isTypeDependent() || NumCols->isTypeDependent() || | ||||
2653 | NumRows->isValueDependent() || NumCols->isValueDependent()) | ||||
2654 | return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols, | ||||
2655 | AttrLoc); | ||||
2656 | |||||
2657 | Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context); | ||||
2658 | Optional<llvm::APSInt> ValueColumns = | ||||
2659 | NumCols->getIntegerConstantExpr(Context); | ||||
2660 | |||||
2661 | auto const RowRange = NumRows->getSourceRange(); | ||||
2662 | auto const ColRange = NumCols->getSourceRange(); | ||||
2663 | |||||
2664 | // Both are row and column expressions are invalid. | ||||
2665 | if (!ValueRows && !ValueColumns) { | ||||
2666 | Diag(AttrLoc, diag::err_attribute_argument_type) | ||||
2667 | << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange | ||||
2668 | << ColRange; | ||||
2669 | return QualType(); | ||||
2670 | } | ||||
2671 | |||||
2672 | // Only the row expression is invalid. | ||||
2673 | if (!ValueRows) { | ||||
2674 | Diag(AttrLoc, diag::err_attribute_argument_type) | ||||
2675 | << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange; | ||||
2676 | return QualType(); | ||||
2677 | } | ||||
2678 | |||||
2679 | // Only the column expression is invalid. | ||||
2680 | if (!ValueColumns) { | ||||
2681 | Diag(AttrLoc, diag::err_attribute_argument_type) | ||||
2682 | << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange; | ||||
2683 | return QualType(); | ||||
2684 | } | ||||
2685 | |||||
2686 | // Check the matrix dimensions. | ||||
2687 | unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue()); | ||||
2688 | unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue()); | ||||
2689 | if (MatrixRows == 0 && MatrixColumns == 0) { | ||||
2690 | Diag(AttrLoc, diag::err_attribute_zero_size) | ||||
2691 | << "matrix" << RowRange << ColRange; | ||||
2692 | return QualType(); | ||||
2693 | } | ||||
2694 | if (MatrixRows == 0) { | ||||
2695 | Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange; | ||||
2696 | return QualType(); | ||||
2697 | } | ||||
2698 | if (MatrixColumns == 0) { | ||||
2699 | Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange; | ||||
2700 | return QualType(); | ||||
2701 | } | ||||
2702 | if (!ConstantMatrixType::isDimensionValid(MatrixRows)) { | ||||
2703 | Diag(AttrLoc, diag::err_attribute_size_too_large) | ||||
2704 | << RowRange << "matrix row"; | ||||
2705 | return QualType(); | ||||
2706 | } | ||||
2707 | if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) { | ||||
2708 | Diag(AttrLoc, diag::err_attribute_size_too_large) | ||||
2709 | << ColRange << "matrix column"; | ||||
2710 | return QualType(); | ||||
2711 | } | ||||
2712 | return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns); | ||||
2713 | } | ||||
2714 | |||||
2715 | bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { | ||||
2716 | if (T->isArrayType() || T->isFunctionType()) { | ||||
2717 | Diag(Loc, diag::err_func_returning_array_function) | ||||
2718 | << T->isFunctionType() << T; | ||||
2719 | return true; | ||||
2720 | } | ||||
2721 | |||||
2722 | // Functions cannot return half FP. | ||||
2723 | if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { | ||||
2724 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << | ||||
2725 | FixItHint::CreateInsertion(Loc, "*"); | ||||
2726 | return true; | ||||
2727 | } | ||||
2728 | |||||
2729 | // Methods cannot return interface types. All ObjC objects are | ||||
2730 | // passed by reference. | ||||
2731 | if (T->isObjCObjectType()) { | ||||
2732 | Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) | ||||
2733 | << 0 << T << FixItHint::CreateInsertion(Loc, "*"); | ||||
2734 | return true; | ||||
2735 | } | ||||
2736 | |||||
2737 | if (T.hasNonTrivialToPrimitiveDestructCUnion() || | ||||
2738 | T.hasNonTrivialToPrimitiveCopyCUnion()) | ||||
2739 | checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn, | ||||
2740 | NTCUK_Destruct|NTCUK_Copy); | ||||
2741 | |||||
2742 | // C++2a [dcl.fct]p12: | ||||
2743 | // A volatile-qualified return type is deprecated | ||||
2744 | if (T.isVolatileQualified() && getLangOpts().CPlusPlus20) | ||||
2745 | Diag(Loc, diag::warn_deprecated_volatile_return) << T; | ||||
2746 | |||||
2747 | return false; | ||||
2748 | } | ||||
2749 | |||||
2750 | /// Check the extended parameter information. Most of the necessary | ||||
2751 | /// checking should occur when applying the parameter attribute; the | ||||
2752 | /// only other checks required are positional restrictions. | ||||
2753 | static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, | ||||
2754 | const FunctionProtoType::ExtProtoInfo &EPI, | ||||
2755 | llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { | ||||
2756 | assert(EPI.ExtParameterInfos && "shouldn't get here without param infos")((EPI.ExtParameterInfos && "shouldn't get here without param infos" ) ? static_cast<void> (0) : __assert_fail ("EPI.ExtParameterInfos && \"shouldn't get here without param infos\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 2756, __PRETTY_FUNCTION__)); | ||||
2757 | |||||
2758 | bool hasCheckedSwiftCall = false; | ||||
2759 | auto checkForSwiftCC = [&](unsigned paramIndex) { | ||||
2760 | // Only do this once. | ||||
2761 | if (hasCheckedSwiftCall) return; | ||||
2762 | hasCheckedSwiftCall = true; | ||||
2763 | if (EPI.ExtInfo.getCC() == CC_Swift) return; | ||||
2764 | S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) | ||||
2765 | << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()); | ||||
2766 | }; | ||||
2767 | |||||
2768 | for (size_t paramIndex = 0, numParams = paramTypes.size(); | ||||
2769 | paramIndex != numParams; ++paramIndex) { | ||||
2770 | switch (EPI.ExtParameterInfos[paramIndex].getABI()) { | ||||
2771 | // Nothing interesting to check for orindary-ABI parameters. | ||||
2772 | case ParameterABI::Ordinary: | ||||
2773 | continue; | ||||
2774 | |||||
2775 | // swift_indirect_result parameters must be a prefix of the function | ||||
2776 | // arguments. | ||||
2777 | case ParameterABI::SwiftIndirectResult: | ||||
2778 | checkForSwiftCC(paramIndex); | ||||
2779 | if (paramIndex != 0 && | ||||
2780 | EPI.ExtParameterInfos[paramIndex - 1].getABI() | ||||
2781 | != ParameterABI::SwiftIndirectResult) { | ||||
2782 | S.Diag(getParamLoc(paramIndex), | ||||
2783 | diag::err_swift_indirect_result_not_first); | ||||
2784 | } | ||||
2785 | continue; | ||||
2786 | |||||
2787 | case ParameterABI::SwiftContext: | ||||
2788 | checkForSwiftCC(paramIndex); | ||||
2789 | continue; | ||||
2790 | |||||
2791 | // swift_error parameters must be preceded by a swift_context parameter. | ||||
2792 | case ParameterABI::SwiftErrorResult: | ||||
2793 | checkForSwiftCC(paramIndex); | ||||
2794 | if (paramIndex == 0 || | ||||
2795 | EPI.ExtParameterInfos[paramIndex - 1].getABI() != | ||||
2796 | ParameterABI::SwiftContext) { | ||||
2797 | S.Diag(getParamLoc(paramIndex), | ||||
2798 | diag::err_swift_error_result_not_after_swift_context); | ||||
2799 | } | ||||
2800 | continue; | ||||
2801 | } | ||||
2802 | llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 2802); | ||||
2803 | } | ||||
2804 | } | ||||
2805 | |||||
2806 | QualType Sema::BuildFunctionType(QualType T, | ||||
2807 | MutableArrayRef<QualType> ParamTypes, | ||||
2808 | SourceLocation Loc, DeclarationName Entity, | ||||
2809 | const FunctionProtoType::ExtProtoInfo &EPI) { | ||||
2810 | bool Invalid = false; | ||||
2811 | |||||
2812 | Invalid |= CheckFunctionReturnType(T, Loc); | ||||
2813 | |||||
2814 | for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { | ||||
2815 | // FIXME: Loc is too inprecise here, should use proper locations for args. | ||||
2816 | QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); | ||||
2817 | if (ParamType->isVoidType()) { | ||||
2818 | Diag(Loc, diag::err_param_with_void_type); | ||||
2819 | Invalid = true; | ||||
2820 | } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { | ||||
2821 | // Disallow half FP arguments. | ||||
2822 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << | ||||
2823 | FixItHint::CreateInsertion(Loc, "*"); | ||||
2824 | Invalid = true; | ||||
2825 | } | ||||
2826 | |||||
2827 | // C++2a [dcl.fct]p4: | ||||
2828 | // A parameter with volatile-qualified type is deprecated | ||||
2829 | if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20) | ||||
2830 | Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType; | ||||
2831 | |||||
2832 | ParamTypes[Idx] = ParamType; | ||||
2833 | } | ||||
2834 | |||||
2835 | if (EPI.ExtParameterInfos) { | ||||
2836 | checkExtParameterInfos(*this, ParamTypes, EPI, | ||||
2837 | [=](unsigned i) { return Loc; }); | ||||
2838 | } | ||||
2839 | |||||
2840 | if (EPI.ExtInfo.getProducesResult()) { | ||||
2841 | // This is just a warning, so we can't fail to build if we see it. | ||||
2842 | checkNSReturnsRetainedReturnType(Loc, T); | ||||
2843 | } | ||||
2844 | |||||
2845 | if (Invalid) | ||||
2846 | return QualType(); | ||||
2847 | |||||
2848 | return Context.getFunctionType(T, ParamTypes, EPI); | ||||
2849 | } | ||||
2850 | |||||
2851 | /// Build a member pointer type \c T Class::*. | ||||
2852 | /// | ||||
2853 | /// \param T the type to which the member pointer refers. | ||||
2854 | /// \param Class the class type into which the member pointer points. | ||||
2855 | /// \param Loc the location where this type begins | ||||
2856 | /// \param Entity the name of the entity that will have this member pointer type | ||||
2857 | /// | ||||
2858 | /// \returns a member pointer type, if successful, or a NULL type if there was | ||||
2859 | /// an error. | ||||
2860 | QualType Sema::BuildMemberPointerType(QualType T, QualType Class, | ||||
2861 | SourceLocation Loc, | ||||
2862 | DeclarationName Entity) { | ||||
2863 | // Verify that we're not building a pointer to pointer to function with | ||||
2864 | // exception specification. | ||||
2865 | if (CheckDistantExceptionSpec(T)) { | ||||
2866 | Diag(Loc, diag::err_distant_exception_spec); | ||||
2867 | return QualType(); | ||||
2868 | } | ||||
2869 | |||||
2870 | // C++ 8.3.3p3: A pointer to member shall not point to ... a member | ||||
2871 | // with reference type, or "cv void." | ||||
2872 | if (T->isReferenceType()) { | ||||
2873 | Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) | ||||
2874 | << getPrintableNameForEntity(Entity) << T; | ||||
2875 | return QualType(); | ||||
2876 | } | ||||
2877 | |||||
2878 | if (T->isVoidType()) { | ||||
2879 | Diag(Loc, diag::err_illegal_decl_mempointer_to_void) | ||||
2880 | << getPrintableNameForEntity(Entity); | ||||
2881 | return QualType(); | ||||
2882 | } | ||||
2883 | |||||
2884 | if (!Class->isDependentType() && !Class->isRecordType()) { | ||||
2885 | Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; | ||||
2886 | return QualType(); | ||||
2887 | } | ||||
2888 | |||||
2889 | // Adjust the default free function calling convention to the default method | ||||
2890 | // calling convention. | ||||
2891 | bool IsCtorOrDtor = | ||||
2892 | (Entity.getNameKind() == DeclarationName::CXXConstructorName) || | ||||
2893 | (Entity.getNameKind() == DeclarationName::CXXDestructorName); | ||||
2894 | if (T->isFunctionType()) | ||||
2895 | adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); | ||||
2896 | |||||
2897 | return Context.getMemberPointerType(T, Class.getTypePtr()); | ||||
2898 | } | ||||
2899 | |||||
2900 | /// Build a block pointer type. | ||||
2901 | /// | ||||
2902 | /// \param T The type to which we'll be building a block pointer. | ||||
2903 | /// | ||||
2904 | /// \param Loc The source location, used for diagnostics. | ||||
2905 | /// | ||||
2906 | /// \param Entity The name of the entity that involves the block pointer | ||||
2907 | /// type, if known. | ||||
2908 | /// | ||||
2909 | /// \returns A suitable block pointer type, if there are no | ||||
2910 | /// errors. Otherwise, returns a NULL type. | ||||
2911 | QualType Sema::BuildBlockPointerType(QualType T, | ||||
2912 | SourceLocation Loc, | ||||
2913 | DeclarationName Entity) { | ||||
2914 | if (!T->isFunctionType()) { | ||||
2915 | Diag(Loc, diag::err_nonfunction_block_type); | ||||
2916 | return QualType(); | ||||
2917 | } | ||||
2918 | |||||
2919 | if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) | ||||
2920 | return QualType(); | ||||
2921 | |||||
2922 | if (getLangOpts().OpenCL) | ||||
2923 | T = deduceOpenCLPointeeAddrSpace(*this, T); | ||||
2924 | |||||
2925 | return Context.getBlockPointerType(T); | ||||
2926 | } | ||||
2927 | |||||
2928 | QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { | ||||
2929 | QualType QT = Ty.get(); | ||||
2930 | if (QT.isNull()) { | ||||
2931 | if (TInfo) *TInfo = nullptr; | ||||
2932 | return QualType(); | ||||
2933 | } | ||||
2934 | |||||
2935 | TypeSourceInfo *DI = nullptr; | ||||
2936 | if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { | ||||
2937 | QT = LIT->getType(); | ||||
2938 | DI = LIT->getTypeSourceInfo(); | ||||
2939 | } | ||||
2940 | |||||
2941 | if (TInfo) *TInfo = DI; | ||||
2942 | return QT; | ||||
2943 | } | ||||
2944 | |||||
2945 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | ||||
2946 | Qualifiers::ObjCLifetime ownership, | ||||
2947 | unsigned chunkIndex); | ||||
2948 | |||||
2949 | /// Given that this is the declaration of a parameter under ARC, | ||||
2950 | /// attempt to infer attributes and such for pointer-to-whatever | ||||
2951 | /// types. | ||||
2952 | static void inferARCWriteback(TypeProcessingState &state, | ||||
2953 | QualType &declSpecType) { | ||||
2954 | Sema &S = state.getSema(); | ||||
2955 | Declarator &declarator = state.getDeclarator(); | ||||
2956 | |||||
2957 | // TODO: should we care about decl qualifiers? | ||||
2958 | |||||
2959 | // Check whether the declarator has the expected form. We walk | ||||
2960 | // from the inside out in order to make the block logic work. | ||||
2961 | unsigned outermostPointerIndex = 0; | ||||
2962 | bool isBlockPointer = false; | ||||
2963 | unsigned numPointers = 0; | ||||
2964 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | ||||
2965 | unsigned chunkIndex = i; | ||||
2966 | DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); | ||||
2967 | switch (chunk.Kind) { | ||||
2968 | case DeclaratorChunk::Paren: | ||||
2969 | // Ignore parens. | ||||
2970 | break; | ||||
2971 | |||||
2972 | case DeclaratorChunk::Reference: | ||||
2973 | case DeclaratorChunk::Pointer: | ||||
2974 | // Count the number of pointers. Treat references | ||||
2975 | // interchangeably as pointers; if they're mis-ordered, normal | ||||
2976 | // type building will discover that. | ||||
2977 | outermostPointerIndex = chunkIndex; | ||||
2978 | numPointers++; | ||||
2979 | break; | ||||
2980 | |||||
2981 | case DeclaratorChunk::BlockPointer: | ||||
2982 | // If we have a pointer to block pointer, that's an acceptable | ||||
2983 | // indirect reference; anything else is not an application of | ||||
2984 | // the rules. | ||||
2985 | if (numPointers != 1) return; | ||||
2986 | numPointers++; | ||||
2987 | outermostPointerIndex = chunkIndex; | ||||
2988 | isBlockPointer = true; | ||||
2989 | |||||
2990 | // We don't care about pointer structure in return values here. | ||||
2991 | goto done; | ||||
2992 | |||||
2993 | case DeclaratorChunk::Array: // suppress if written (id[])? | ||||
2994 | case DeclaratorChunk::Function: | ||||
2995 | case DeclaratorChunk::MemberPointer: | ||||
2996 | case DeclaratorChunk::Pipe: | ||||
2997 | return; | ||||
2998 | } | ||||
2999 | } | ||||
3000 | done: | ||||
3001 | |||||
3002 | // If we have *one* pointer, then we want to throw the qualifier on | ||||
3003 | // the declaration-specifiers, which means that it needs to be a | ||||
3004 | // retainable object type. | ||||
3005 | if (numPointers == 1) { | ||||
3006 | // If it's not a retainable object type, the rule doesn't apply. | ||||
3007 | if (!declSpecType->isObjCRetainableType()) return; | ||||
3008 | |||||
3009 | // If it already has lifetime, don't do anything. | ||||
3010 | if (declSpecType.getObjCLifetime()) return; | ||||
3011 | |||||
3012 | // Otherwise, modify the type in-place. | ||||
3013 | Qualifiers qs; | ||||
3014 | |||||
3015 | if (declSpecType->isObjCARCImplicitlyUnretainedType()) | ||||
3016 | qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); | ||||
3017 | else | ||||
3018 | qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); | ||||
3019 | declSpecType = S.Context.getQualifiedType(declSpecType, qs); | ||||
3020 | |||||
3021 | // If we have *two* pointers, then we want to throw the qualifier on | ||||
3022 | // the outermost pointer. | ||||
3023 | } else if (numPointers == 2) { | ||||
3024 | // If we don't have a block pointer, we need to check whether the | ||||
3025 | // declaration-specifiers gave us something that will turn into a | ||||
3026 | // retainable object pointer after we slap the first pointer on it. | ||||
3027 | if (!isBlockPointer && !declSpecType->isObjCObjectType()) | ||||
3028 | return; | ||||
3029 | |||||
3030 | // Look for an explicit lifetime attribute there. | ||||
3031 | DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); | ||||
3032 | if (chunk.Kind != DeclaratorChunk::Pointer && | ||||
3033 | chunk.Kind != DeclaratorChunk::BlockPointer) | ||||
3034 | return; | ||||
3035 | for (const ParsedAttr &AL : chunk.getAttrs()) | ||||
3036 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) | ||||
3037 | return; | ||||
3038 | |||||
3039 | transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, | ||||
3040 | outermostPointerIndex); | ||||
3041 | |||||
3042 | // Any other number of pointers/references does not trigger the rule. | ||||
3043 | } else return; | ||||
3044 | |||||
3045 | // TODO: mark whether we did this inference? | ||||
3046 | } | ||||
3047 | |||||
3048 | void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, | ||||
3049 | SourceLocation FallbackLoc, | ||||
3050 | SourceLocation ConstQualLoc, | ||||
3051 | SourceLocation VolatileQualLoc, | ||||
3052 | SourceLocation RestrictQualLoc, | ||||
3053 | SourceLocation AtomicQualLoc, | ||||
3054 | SourceLocation UnalignedQualLoc) { | ||||
3055 | if (!Quals) | ||||
3056 | return; | ||||
3057 | |||||
3058 | struct Qual { | ||||
3059 | const char *Name; | ||||
3060 | unsigned Mask; | ||||
3061 | SourceLocation Loc; | ||||
3062 | } const QualKinds[5] = { | ||||
3063 | { "const", DeclSpec::TQ_const, ConstQualLoc }, | ||||
3064 | { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, | ||||
3065 | { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, | ||||
3066 | { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, | ||||
3067 | { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } | ||||
3068 | }; | ||||
3069 | |||||
3070 | SmallString<32> QualStr; | ||||
3071 | unsigned NumQuals = 0; | ||||
3072 | SourceLocation Loc; | ||||
3073 | FixItHint FixIts[5]; | ||||
3074 | |||||
3075 | // Build a string naming the redundant qualifiers. | ||||
3076 | for (auto &E : QualKinds) { | ||||
3077 | if (Quals & E.Mask) { | ||||
3078 | if (!QualStr.empty()) QualStr += ' '; | ||||
3079 | QualStr += E.Name; | ||||
3080 | |||||
3081 | // If we have a location for the qualifier, offer a fixit. | ||||
3082 | SourceLocation QualLoc = E.Loc; | ||||
3083 | if (QualLoc.isValid()) { | ||||
3084 | FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); | ||||
3085 | if (Loc.isInvalid() || | ||||
3086 | getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) | ||||
3087 | Loc = QualLoc; | ||||
3088 | } | ||||
3089 | |||||
3090 | ++NumQuals; | ||||
3091 | } | ||||
3092 | } | ||||
3093 | |||||
3094 | Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) | ||||
3095 | << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; | ||||
3096 | } | ||||
3097 | |||||
3098 | // Diagnose pointless type qualifiers on the return type of a function. | ||||
3099 | static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, | ||||
3100 | Declarator &D, | ||||
3101 | unsigned FunctionChunkIndex) { | ||||
3102 | const DeclaratorChunk::FunctionTypeInfo &FTI = | ||||
3103 | D.getTypeObject(FunctionChunkIndex).Fun; | ||||
3104 | if (FTI.hasTrailingReturnType()) { | ||||
3105 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | ||||
3106 | RetTy.getLocalCVRQualifiers(), | ||||
3107 | FTI.getTrailingReturnTypeLoc()); | ||||
3108 | return; | ||||
3109 | } | ||||
3110 | |||||
3111 | for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, | ||||
3112 | End = D.getNumTypeObjects(); | ||||
3113 | OuterChunkIndex != End; ++OuterChunkIndex) { | ||||
3114 | DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); | ||||
3115 | switch (OuterChunk.Kind) { | ||||
3116 | case DeclaratorChunk::Paren: | ||||
3117 | continue; | ||||
3118 | |||||
3119 | case DeclaratorChunk::Pointer: { | ||||
3120 | DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; | ||||
3121 | S.diagnoseIgnoredQualifiers( | ||||
3122 | diag::warn_qual_return_type, | ||||
3123 | PTI.TypeQuals, | ||||
3124 | SourceLocation(), | ||||
3125 | SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), | ||||
3126 | SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), | ||||
3127 | SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), | ||||
3128 | SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc), | ||||
3129 | SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc)); | ||||
3130 | return; | ||||
3131 | } | ||||
3132 | |||||
3133 | case DeclaratorChunk::Function: | ||||
3134 | case DeclaratorChunk::BlockPointer: | ||||
3135 | case DeclaratorChunk::Reference: | ||||
3136 | case DeclaratorChunk::Array: | ||||
3137 | case DeclaratorChunk::MemberPointer: | ||||
3138 | case DeclaratorChunk::Pipe: | ||||
3139 | // FIXME: We can't currently provide an accurate source location and a | ||||
3140 | // fix-it hint for these. | ||||
3141 | unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; | ||||
3142 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | ||||
3143 | RetTy.getCVRQualifiers() | AtomicQual, | ||||
3144 | D.getIdentifierLoc()); | ||||
3145 | return; | ||||
3146 | } | ||||
3147 | |||||
3148 | llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3148); | ||||
3149 | } | ||||
3150 | |||||
3151 | // If the qualifiers come from a conversion function type, don't diagnose | ||||
3152 | // them -- they're not necessarily redundant, since such a conversion | ||||
3153 | // operator can be explicitly called as "x.operator const int()". | ||||
3154 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | ||||
3155 | return; | ||||
3156 | |||||
3157 | // Just parens all the way out to the decl specifiers. Diagnose any qualifiers | ||||
3158 | // which are present there. | ||||
3159 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | ||||
3160 | D.getDeclSpec().getTypeQualifiers(), | ||||
3161 | D.getIdentifierLoc(), | ||||
3162 | D.getDeclSpec().getConstSpecLoc(), | ||||
3163 | D.getDeclSpec().getVolatileSpecLoc(), | ||||
3164 | D.getDeclSpec().getRestrictSpecLoc(), | ||||
3165 | D.getDeclSpec().getAtomicSpecLoc(), | ||||
3166 | D.getDeclSpec().getUnalignedSpecLoc()); | ||||
3167 | } | ||||
3168 | |||||
3169 | static std::pair<QualType, TypeSourceInfo *> | ||||
3170 | InventTemplateParameter(TypeProcessingState &state, QualType T, | ||||
3171 | TypeSourceInfo *TrailingTSI, AutoType *Auto, | ||||
3172 | InventedTemplateParameterInfo &Info) { | ||||
3173 | Sema &S = state.getSema(); | ||||
3174 | Declarator &D = state.getDeclarator(); | ||||
3175 | |||||
3176 | const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth; | ||||
3177 | const unsigned AutoParameterPosition = Info.TemplateParams.size(); | ||||
3178 | const bool IsParameterPack = D.hasEllipsis(); | ||||
3179 | |||||
3180 | // If auto is mentioned in a lambda parameter or abbreviated function | ||||
3181 | // template context, convert it to a template parameter type. | ||||
3182 | |||||
3183 | // Create the TemplateTypeParmDecl here to retrieve the corresponding | ||||
3184 | // template parameter type. Template parameters are temporarily added | ||||
3185 | // to the TU until the associated TemplateDecl is created. | ||||
3186 | TemplateTypeParmDecl *InventedTemplateParam = | ||||
3187 | TemplateTypeParmDecl::Create( | ||||
3188 | S.Context, S.Context.getTranslationUnitDecl(), | ||||
3189 | /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(), | ||||
3190 | /*NameLoc=*/D.getIdentifierLoc(), | ||||
3191 | TemplateParameterDepth, AutoParameterPosition, | ||||
3192 | S.InventAbbreviatedTemplateParameterTypeName( | ||||
3193 | D.getIdentifier(), AutoParameterPosition), false, | ||||
3194 | IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained()); | ||||
3195 | InventedTemplateParam->setImplicit(); | ||||
3196 | Info.TemplateParams.push_back(InventedTemplateParam); | ||||
3197 | |||||
3198 | // Attach type constraints to the new parameter. | ||||
3199 | if (Auto->isConstrained()) { | ||||
3200 | if (TrailingTSI) { | ||||
3201 | // The 'auto' appears in a trailing return type we've already built; | ||||
3202 | // extract its type constraints to attach to the template parameter. | ||||
3203 | AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc(); | ||||
3204 | TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc()); | ||||
3205 | for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) | ||||
3206 | TAL.addArgument(AutoLoc.getArgLoc(Idx)); | ||||
3207 | |||||
3208 | S.AttachTypeConstraint(AutoLoc.getNestedNameSpecifierLoc(), | ||||
3209 | AutoLoc.getConceptNameInfo(), | ||||
3210 | AutoLoc.getNamedConcept(), | ||||
3211 | AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr, | ||||
3212 | InventedTemplateParam, D.getEllipsisLoc()); | ||||
3213 | } else { | ||||
3214 | // The 'auto' appears in the decl-specifiers; we've not finished forming | ||||
3215 | // TypeSourceInfo for it yet. | ||||
3216 | TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId(); | ||||
3217 | TemplateArgumentListInfo TemplateArgsInfo; | ||||
3218 | if (TemplateId->LAngleLoc.isValid()) { | ||||
3219 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | ||||
3220 | TemplateId->NumArgs); | ||||
3221 | S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | ||||
3222 | } | ||||
3223 | S.AttachTypeConstraint( | ||||
3224 | D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context), | ||||
3225 | DeclarationNameInfo(DeclarationName(TemplateId->Name), | ||||
3226 | TemplateId->TemplateNameLoc), | ||||
3227 | cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()), | ||||
3228 | TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr, | ||||
3229 | InventedTemplateParam, D.getEllipsisLoc()); | ||||
3230 | } | ||||
3231 | } | ||||
3232 | |||||
3233 | // Replace the 'auto' in the function parameter with this invented | ||||
3234 | // template type parameter. | ||||
3235 | // FIXME: Retain some type sugar to indicate that this was written | ||||
3236 | // as 'auto'? | ||||
3237 | QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0); | ||||
3238 | QualType NewT = state.ReplaceAutoType(T, Replacement); | ||||
3239 | TypeSourceInfo *NewTSI = | ||||
3240 | TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement) | ||||
3241 | : nullptr; | ||||
3242 | return {NewT, NewTSI}; | ||||
3243 | } | ||||
3244 | |||||
3245 | static TypeSourceInfo * | ||||
3246 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, | ||||
3247 | QualType T, TypeSourceInfo *ReturnTypeInfo); | ||||
3248 | |||||
3249 | static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, | ||||
3250 | TypeSourceInfo *&ReturnTypeInfo) { | ||||
3251 | Sema &SemaRef = state.getSema(); | ||||
3252 | Declarator &D = state.getDeclarator(); | ||||
3253 | QualType T; | ||||
3254 | ReturnTypeInfo = nullptr; | ||||
3255 | |||||
3256 | // The TagDecl owned by the DeclSpec. | ||||
3257 | TagDecl *OwnedTagDecl = nullptr; | ||||
3258 | |||||
3259 | switch (D.getName().getKind()) { | ||||
3260 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||
3261 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||
3262 | case UnqualifiedIdKind::IK_Identifier: | ||||
3263 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||
3264 | case UnqualifiedIdKind::IK_TemplateId: | ||||
3265 | T = ConvertDeclSpecToType(state); | ||||
3266 | |||||
3267 | if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { | ||||
3268 | OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | ||||
3269 | // Owned declaration is embedded in declarator. | ||||
3270 | OwnedTagDecl->setEmbeddedInDeclarator(true); | ||||
3271 | } | ||||
3272 | break; | ||||
3273 | |||||
3274 | case UnqualifiedIdKind::IK_ConstructorName: | ||||
3275 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | ||||
3276 | case UnqualifiedIdKind::IK_DestructorName: | ||||
3277 | // Constructors and destructors don't have return types. Use | ||||
3278 | // "void" instead. | ||||
3279 | T = SemaRef.Context.VoidTy; | ||||
3280 | processTypeAttrs(state, T, TAL_DeclSpec, | ||||
3281 | D.getMutableDeclSpec().getAttributes()); | ||||
3282 | break; | ||||
3283 | |||||
3284 | case UnqualifiedIdKind::IK_DeductionGuideName: | ||||
3285 | // Deduction guides have a trailing return type and no type in their | ||||
3286 | // decl-specifier sequence. Use a placeholder return type for now. | ||||
3287 | T = SemaRef.Context.DependentTy; | ||||
3288 | break; | ||||
3289 | |||||
3290 | case UnqualifiedIdKind::IK_ConversionFunctionId: | ||||
3291 | // The result type of a conversion function is the type that it | ||||
3292 | // converts to. | ||||
3293 | T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, | ||||
3294 | &ReturnTypeInfo); | ||||
3295 | break; | ||||
3296 | } | ||||
3297 | |||||
3298 | if (!D.getAttributes().empty()) | ||||
3299 | distributeTypeAttrsFromDeclarator(state, T); | ||||
3300 | |||||
3301 | // Find the deduced type in this type. Look in the trailing return type if we | ||||
3302 | // have one, otherwise in the DeclSpec type. | ||||
3303 | // FIXME: The standard wording doesn't currently describe this. | ||||
3304 | DeducedType *Deduced = T->getContainedDeducedType(); | ||||
3305 | bool DeducedIsTrailingReturnType = false; | ||||
3306 | if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) { | ||||
3307 | QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType()); | ||||
3308 | Deduced = T.isNull() ? nullptr : T->getContainedDeducedType(); | ||||
3309 | DeducedIsTrailingReturnType = true; | ||||
3310 | } | ||||
3311 | |||||
3312 | // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. | ||||
3313 | if (Deduced) { | ||||
3314 | AutoType *Auto = dyn_cast<AutoType>(Deduced); | ||||
3315 | int Error = -1; | ||||
3316 | |||||
3317 | // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or | ||||
3318 | // class template argument deduction)? | ||||
3319 | bool IsCXXAutoType = | ||||
3320 | (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); | ||||
3321 | bool IsDeducedReturnType = false; | ||||
3322 | |||||
3323 | switch (D.getContext()) { | ||||
3324 | case DeclaratorContext::LambdaExpr: | ||||
3325 | // Declared return type of a lambda-declarator is implicit and is always | ||||
3326 | // 'auto'. | ||||
3327 | break; | ||||
3328 | case DeclaratorContext::ObjCParameter: | ||||
3329 | case DeclaratorContext::ObjCResult: | ||||
3330 | Error = 0; | ||||
3331 | break; | ||||
3332 | case DeclaratorContext::RequiresExpr: | ||||
3333 | Error = 22; | ||||
3334 | break; | ||||
3335 | case DeclaratorContext::Prototype: | ||||
3336 | case DeclaratorContext::LambdaExprParameter: { | ||||
3337 | InventedTemplateParameterInfo *Info = nullptr; | ||||
3338 | if (D.getContext() == DeclaratorContext::Prototype) { | ||||
3339 | // With concepts we allow 'auto' in function parameters. | ||||
3340 | if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto || | ||||
3341 | Auto->getKeyword() != AutoTypeKeyword::Auto) { | ||||
3342 | Error = 0; | ||||
3343 | break; | ||||
3344 | } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) { | ||||
3345 | Error = 21; | ||||
3346 | break; | ||||
3347 | } | ||||
3348 | |||||
3349 | Info = &SemaRef.InventedParameterInfos.back(); | ||||
3350 | } else { | ||||
3351 | // In C++14, generic lambdas allow 'auto' in their parameters. | ||||
3352 | if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto || | ||||
3353 | Auto->getKeyword() != AutoTypeKeyword::Auto) { | ||||
3354 | Error = 16; | ||||
3355 | break; | ||||
3356 | } | ||||
3357 | Info = SemaRef.getCurLambda(); | ||||
3358 | assert(Info && "No LambdaScopeInfo on the stack!")((Info && "No LambdaScopeInfo on the stack!") ? static_cast <void> (0) : __assert_fail ("Info && \"No LambdaScopeInfo on the stack!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3358, __PRETTY_FUNCTION__)); | ||||
3359 | } | ||||
3360 | |||||
3361 | // We'll deal with inventing template parameters for 'auto' in trailing | ||||
3362 | // return types when we pick up the trailing return type when processing | ||||
3363 | // the function chunk. | ||||
3364 | if (!DeducedIsTrailingReturnType) | ||||
3365 | T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first; | ||||
3366 | break; | ||||
3367 | } | ||||
3368 | case DeclaratorContext::Member: { | ||||
3369 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || | ||||
3370 | D.isFunctionDeclarator()) | ||||
3371 | break; | ||||
3372 | bool Cxx = SemaRef.getLangOpts().CPlusPlus; | ||||
3373 | if (isa<ObjCContainerDecl>(SemaRef.CurContext)) { | ||||
3374 | Error = 6; // Interface member. | ||||
3375 | } else { | ||||
3376 | switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { | ||||
3377 | case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3377); | ||||
3378 | case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; | ||||
3379 | case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; | ||||
3380 | case TTK_Class: Error = 5; /* Class member */ break; | ||||
3381 | case TTK_Interface: Error = 6; /* Interface member */ break; | ||||
3382 | } | ||||
3383 | } | ||||
3384 | if (D.getDeclSpec().isFriendSpecified()) | ||||
3385 | Error = 20; // Friend type | ||||
3386 | break; | ||||
3387 | } | ||||
3388 | case DeclaratorContext::CXXCatch: | ||||
3389 | case DeclaratorContext::ObjCCatch: | ||||
3390 | Error = 7; // Exception declaration | ||||
3391 | break; | ||||
3392 | case DeclaratorContext::TemplateParam: | ||||
3393 | if (isa<DeducedTemplateSpecializationType>(Deduced) && | ||||
3394 | !SemaRef.getLangOpts().CPlusPlus20) | ||||
3395 | Error = 19; // Template parameter (until C++20) | ||||
3396 | else if (!SemaRef.getLangOpts().CPlusPlus17) | ||||
3397 | Error = 8; // Template parameter (until C++17) | ||||
3398 | break; | ||||
3399 | case DeclaratorContext::BlockLiteral: | ||||
3400 | Error = 9; // Block literal | ||||
3401 | break; | ||||
3402 | case DeclaratorContext::TemplateArg: | ||||
3403 | // Within a template argument list, a deduced template specialization | ||||
3404 | // type will be reinterpreted as a template template argument. | ||||
3405 | if (isa<DeducedTemplateSpecializationType>(Deduced) && | ||||
3406 | !D.getNumTypeObjects() && | ||||
3407 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) | ||||
3408 | break; | ||||
3409 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3410 | case DeclaratorContext::TemplateTypeArg: | ||||
3411 | Error = 10; // Template type argument | ||||
3412 | break; | ||||
3413 | case DeclaratorContext::AliasDecl: | ||||
3414 | case DeclaratorContext::AliasTemplate: | ||||
3415 | Error = 12; // Type alias | ||||
3416 | break; | ||||
3417 | case DeclaratorContext::TrailingReturn: | ||||
3418 | case DeclaratorContext::TrailingReturnVar: | ||||
3419 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | ||||
3420 | Error = 13; // Function return type | ||||
3421 | IsDeducedReturnType = true; | ||||
3422 | break; | ||||
3423 | case DeclaratorContext::ConversionId: | ||||
3424 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | ||||
3425 | Error = 14; // conversion-type-id | ||||
3426 | IsDeducedReturnType = true; | ||||
3427 | break; | ||||
3428 | case DeclaratorContext::FunctionalCast: | ||||
3429 | if (isa<DeducedTemplateSpecializationType>(Deduced)) | ||||
3430 | break; | ||||
3431 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3432 | case DeclaratorContext::TypeName: | ||||
3433 | Error = 15; // Generic | ||||
3434 | break; | ||||
3435 | case DeclaratorContext::File: | ||||
3436 | case DeclaratorContext::Block: | ||||
3437 | case DeclaratorContext::ForInit: | ||||
3438 | case DeclaratorContext::SelectionInit: | ||||
3439 | case DeclaratorContext::Condition: | ||||
3440 | // FIXME: P0091R3 (erroneously) does not permit class template argument | ||||
3441 | // deduction in conditions, for-init-statements, and other declarations | ||||
3442 | // that are not simple-declarations. | ||||
3443 | break; | ||||
3444 | case DeclaratorContext::CXXNew: | ||||
3445 | // FIXME: P0091R3 does not permit class template argument deduction here, | ||||
3446 | // but we follow GCC and allow it anyway. | ||||
3447 | if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) | ||||
3448 | Error = 17; // 'new' type | ||||
3449 | break; | ||||
3450 | case DeclaratorContext::KNRTypeList: | ||||
3451 | Error = 18; // K&R function parameter | ||||
3452 | break; | ||||
3453 | } | ||||
3454 | |||||
3455 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||
3456 | Error = 11; | ||||
3457 | |||||
3458 | // In Objective-C it is an error to use 'auto' on a function declarator | ||||
3459 | // (and everywhere for '__auto_type'). | ||||
3460 | if (D.isFunctionDeclarator() && | ||||
3461 | (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) | ||||
3462 | Error = 13; | ||||
3463 | |||||
3464 | SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); | ||||
3465 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | ||||
3466 | AutoRange = D.getName().getSourceRange(); | ||||
3467 | |||||
3468 | if (Error != -1) { | ||||
3469 | unsigned Kind; | ||||
3470 | if (Auto) { | ||||
3471 | switch (Auto->getKeyword()) { | ||||
3472 | case AutoTypeKeyword::Auto: Kind = 0; break; | ||||
3473 | case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; | ||||
3474 | case AutoTypeKeyword::GNUAutoType: Kind = 2; break; | ||||
3475 | } | ||||
3476 | } else { | ||||
3477 | assert(isa<DeducedTemplateSpecializationType>(Deduced) &&((isa<DeducedTemplateSpecializationType>(Deduced) && "unknown auto type") ? static_cast<void> (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3478, __PRETTY_FUNCTION__)) | ||||
3478 | "unknown auto type")((isa<DeducedTemplateSpecializationType>(Deduced) && "unknown auto type") ? static_cast<void> (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3478, __PRETTY_FUNCTION__)); | ||||
3479 | Kind = 3; | ||||
3480 | } | ||||
3481 | |||||
3482 | auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); | ||||
3483 | TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); | ||||
3484 | |||||
3485 | SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) | ||||
3486 | << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) | ||||
3487 | << QualType(Deduced, 0) << AutoRange; | ||||
3488 | if (auto *TD = TN.getAsTemplateDecl()) | ||||
3489 | SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); | ||||
3490 | |||||
3491 | T = SemaRef.Context.IntTy; | ||||
3492 | D.setInvalidType(true); | ||||
3493 | } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) { | ||||
3494 | // If there was a trailing return type, we already got | ||||
3495 | // warn_cxx98_compat_trailing_return_type in the parser. | ||||
3496 | SemaRef.Diag(AutoRange.getBegin(), | ||||
3497 | D.getContext() == DeclaratorContext::LambdaExprParameter | ||||
3498 | ? diag::warn_cxx11_compat_generic_lambda | ||||
3499 | : IsDeducedReturnType | ||||
3500 | ? diag::warn_cxx11_compat_deduced_return_type | ||||
3501 | : diag::warn_cxx98_compat_auto_type_specifier) | ||||
3502 | << AutoRange; | ||||
3503 | } | ||||
3504 | } | ||||
3505 | |||||
3506 | if (SemaRef.getLangOpts().CPlusPlus && | ||||
3507 | OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { | ||||
3508 | // Check the contexts where C++ forbids the declaration of a new class | ||||
3509 | // or enumeration in a type-specifier-seq. | ||||
3510 | unsigned DiagID = 0; | ||||
3511 | switch (D.getContext()) { | ||||
3512 | case DeclaratorContext::TrailingReturn: | ||||
3513 | case DeclaratorContext::TrailingReturnVar: | ||||
3514 | // Class and enumeration definitions are syntactically not allowed in | ||||
3515 | // trailing return types. | ||||
3516 | llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3516); | ||||
3517 | break; | ||||
3518 | case DeclaratorContext::File: | ||||
3519 | case DeclaratorContext::Member: | ||||
3520 | case DeclaratorContext::Block: | ||||
3521 | case DeclaratorContext::ForInit: | ||||
3522 | case DeclaratorContext::SelectionInit: | ||||
3523 | case DeclaratorContext::BlockLiteral: | ||||
3524 | case DeclaratorContext::LambdaExpr: | ||||
3525 | // C++11 [dcl.type]p3: | ||||
3526 | // A type-specifier-seq shall not define a class or enumeration unless | ||||
3527 | // it appears in the type-id of an alias-declaration (7.1.3) that is not | ||||
3528 | // the declaration of a template-declaration. | ||||
3529 | case DeclaratorContext::AliasDecl: | ||||
3530 | break; | ||||
3531 | case DeclaratorContext::AliasTemplate: | ||||
3532 | DiagID = diag::err_type_defined_in_alias_template; | ||||
3533 | break; | ||||
3534 | case DeclaratorContext::TypeName: | ||||
3535 | case DeclaratorContext::FunctionalCast: | ||||
3536 | case DeclaratorContext::ConversionId: | ||||
3537 | case DeclaratorContext::TemplateParam: | ||||
3538 | case DeclaratorContext::CXXNew: | ||||
3539 | case DeclaratorContext::CXXCatch: | ||||
3540 | case DeclaratorContext::ObjCCatch: | ||||
3541 | case DeclaratorContext::TemplateArg: | ||||
3542 | case DeclaratorContext::TemplateTypeArg: | ||||
3543 | DiagID = diag::err_type_defined_in_type_specifier; | ||||
3544 | break; | ||||
3545 | case DeclaratorContext::Prototype: | ||||
3546 | case DeclaratorContext::LambdaExprParameter: | ||||
3547 | case DeclaratorContext::ObjCParameter: | ||||
3548 | case DeclaratorContext::ObjCResult: | ||||
3549 | case DeclaratorContext::KNRTypeList: | ||||
3550 | case DeclaratorContext::RequiresExpr: | ||||
3551 | // C++ [dcl.fct]p6: | ||||
3552 | // Types shall not be defined in return or parameter types. | ||||
3553 | DiagID = diag::err_type_defined_in_param_type; | ||||
3554 | break; | ||||
3555 | case DeclaratorContext::Condition: | ||||
3556 | // C++ 6.4p2: | ||||
3557 | // The type-specifier-seq shall not contain typedef and shall not declare | ||||
3558 | // a new class or enumeration. | ||||
3559 | DiagID = diag::err_type_defined_in_condition; | ||||
3560 | break; | ||||
3561 | } | ||||
3562 | |||||
3563 | if (DiagID != 0) { | ||||
3564 | SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) | ||||
3565 | << SemaRef.Context.getTypeDeclType(OwnedTagDecl); | ||||
3566 | D.setInvalidType(true); | ||||
3567 | } | ||||
3568 | } | ||||
3569 | |||||
3570 | assert(!T.isNull() && "This function should not return a null type")((!T.isNull() && "This function should not return a null type" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"This function should not return a null type\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3570, __PRETTY_FUNCTION__)); | ||||
3571 | return T; | ||||
3572 | } | ||||
3573 | |||||
3574 | /// Produce an appropriate diagnostic for an ambiguity between a function | ||||
3575 | /// declarator and a C++ direct-initializer. | ||||
3576 | static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, | ||||
3577 | DeclaratorChunk &DeclType, QualType RT) { | ||||
3578 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | ||||
3579 | assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity")((FTI.isAmbiguous && "no direct-initializer / function ambiguity" ) ? static_cast<void> (0) : __assert_fail ("FTI.isAmbiguous && \"no direct-initializer / function ambiguity\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3579, __PRETTY_FUNCTION__)); | ||||
3580 | |||||
3581 | // If the return type is void there is no ambiguity. | ||||
3582 | if (RT->isVoidType()) | ||||
3583 | return; | ||||
3584 | |||||
3585 | // An initializer for a non-class type can have at most one argument. | ||||
3586 | if (!RT->isRecordType() && FTI.NumParams > 1) | ||||
3587 | return; | ||||
3588 | |||||
3589 | // An initializer for a reference must have exactly one argument. | ||||
3590 | if (RT->isReferenceType() && FTI.NumParams != 1) | ||||
3591 | return; | ||||
3592 | |||||
3593 | // Only warn if this declarator is declaring a function at block scope, and | ||||
3594 | // doesn't have a storage class (such as 'extern') specified. | ||||
3595 | if (!D.isFunctionDeclarator() || | ||||
3596 | D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration || | ||||
3597 | !S.CurContext->isFunctionOrMethod() || | ||||
3598 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified) | ||||
3599 | return; | ||||
3600 | |||||
3601 | // Inside a condition, a direct initializer is not permitted. We allow one to | ||||
3602 | // be parsed in order to give better diagnostics in condition parsing. | ||||
3603 | if (D.getContext() == DeclaratorContext::Condition) | ||||
3604 | return; | ||||
3605 | |||||
3606 | SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); | ||||
3607 | |||||
3608 | S.Diag(DeclType.Loc, | ||||
3609 | FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration | ||||
3610 | : diag::warn_empty_parens_are_function_decl) | ||||
3611 | << ParenRange; | ||||
3612 | |||||
3613 | // If the declaration looks like: | ||||
3614 | // T var1, | ||||
3615 | // f(); | ||||
3616 | // and name lookup finds a function named 'f', then the ',' was | ||||
3617 | // probably intended to be a ';'. | ||||
3618 | if (!D.isFirstDeclarator() && D.getIdentifier()) { | ||||
3619 | FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); | ||||
3620 | FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); | ||||
3621 | if (Comma.getFileID() != Name.getFileID() || | ||||
3622 | Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { | ||||
3623 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | ||||
3624 | Sema::LookupOrdinaryName); | ||||
3625 | if (S.LookupName(Result, S.getCurScope())) | ||||
3626 | S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) | ||||
3627 | << FixItHint::CreateReplacement(D.getCommaLoc(), ";") | ||||
3628 | << D.getIdentifier(); | ||||
3629 | Result.suppressDiagnostics(); | ||||
3630 | } | ||||
3631 | } | ||||
3632 | |||||
3633 | if (FTI.NumParams > 0) { | ||||
3634 | // For a declaration with parameters, eg. "T var(T());", suggest adding | ||||
3635 | // parens around the first parameter to turn the declaration into a | ||||
3636 | // variable declaration. | ||||
3637 | SourceRange Range = FTI.Params[0].Param->getSourceRange(); | ||||
3638 | SourceLocation B = Range.getBegin(); | ||||
3639 | SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); | ||||
3640 | // FIXME: Maybe we should suggest adding braces instead of parens | ||||
3641 | // in C++11 for classes that don't have an initializer_list constructor. | ||||
3642 | S.Diag(B, diag::note_additional_parens_for_variable_declaration) | ||||
3643 | << FixItHint::CreateInsertion(B, "(") | ||||
3644 | << FixItHint::CreateInsertion(E, ")"); | ||||
3645 | } else { | ||||
3646 | // For a declaration without parameters, eg. "T var();", suggest replacing | ||||
3647 | // the parens with an initializer to turn the declaration into a variable | ||||
3648 | // declaration. | ||||
3649 | const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); | ||||
3650 | |||||
3651 | // Empty parens mean value-initialization, and no parens mean | ||||
3652 | // default initialization. These are equivalent if the default | ||||
3653 | // constructor is user-provided or if zero-initialization is a | ||||
3654 | // no-op. | ||||
3655 | if (RD && RD->hasDefinition() && | ||||
3656 | (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) | ||||
3657 | S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) | ||||
3658 | << FixItHint::CreateRemoval(ParenRange); | ||||
3659 | else { | ||||
3660 | std::string Init = | ||||
3661 | S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); | ||||
3662 | if (Init.empty() && S.LangOpts.CPlusPlus11) | ||||
3663 | Init = "{}"; | ||||
3664 | if (!Init.empty()) | ||||
3665 | S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) | ||||
3666 | << FixItHint::CreateReplacement(ParenRange, Init); | ||||
3667 | } | ||||
3668 | } | ||||
3669 | } | ||||
3670 | |||||
3671 | /// Produce an appropriate diagnostic for a declarator with top-level | ||||
3672 | /// parentheses. | ||||
3673 | static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { | ||||
3674 | DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); | ||||
3675 | assert(Paren.Kind == DeclaratorChunk::Paren &&((Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses" ) ? static_cast<void> (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3676, __PRETTY_FUNCTION__)) | ||||
3676 | "do not have redundant top-level parentheses")((Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses" ) ? static_cast<void> (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3676, __PRETTY_FUNCTION__)); | ||||
3677 | |||||
3678 | // This is a syntactic check; we're not interested in cases that arise | ||||
3679 | // during template instantiation. | ||||
3680 | if (S.inTemplateInstantiation()) | ||||
3681 | return; | ||||
3682 | |||||
3683 | // Check whether this could be intended to be a construction of a temporary | ||||
3684 | // object in C++ via a function-style cast. | ||||
3685 | bool CouldBeTemporaryObject = | ||||
3686 | S.getLangOpts().CPlusPlus && D.isExpressionContext() && | ||||
3687 | !D.isInvalidType() && D.getIdentifier() && | ||||
3688 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && | ||||
3689 | (T->isRecordType() || T->isDependentType()) && | ||||
3690 | D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); | ||||
3691 | |||||
3692 | bool StartsWithDeclaratorId = true; | ||||
3693 | for (auto &C : D.type_objects()) { | ||||
3694 | switch (C.Kind) { | ||||
3695 | case DeclaratorChunk::Paren: | ||||
3696 | if (&C == &Paren) | ||||
3697 | continue; | ||||
3698 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
3699 | case DeclaratorChunk::Pointer: | ||||
3700 | StartsWithDeclaratorId = false; | ||||
3701 | continue; | ||||
3702 | |||||
3703 | case DeclaratorChunk::Array: | ||||
3704 | if (!C.Arr.NumElts) | ||||
3705 | CouldBeTemporaryObject = false; | ||||
3706 | continue; | ||||
3707 | |||||
3708 | case DeclaratorChunk::Reference: | ||||
3709 | // FIXME: Suppress the warning here if there is no initializer; we're | ||||
3710 | // going to give an error anyway. | ||||
3711 | // We assume that something like 'T (&x) = y;' is highly likely to not | ||||
3712 | // be intended to be a temporary object. | ||||
3713 | CouldBeTemporaryObject = false; | ||||
3714 | StartsWithDeclaratorId = false; | ||||
3715 | continue; | ||||
3716 | |||||
3717 | case DeclaratorChunk::Function: | ||||
3718 | // In a new-type-id, function chunks require parentheses. | ||||
3719 | if (D.getContext() == DeclaratorContext::CXXNew) | ||||
3720 | return; | ||||
3721 | // FIXME: "A(f())" deserves a vexing-parse warning, not just a | ||||
3722 | // redundant-parens warning, but we don't know whether the function | ||||
3723 | // chunk was syntactically valid as an expression here. | ||||
3724 | CouldBeTemporaryObject = false; | ||||
3725 | continue; | ||||
3726 | |||||
3727 | case DeclaratorChunk::BlockPointer: | ||||
3728 | case DeclaratorChunk::MemberPointer: | ||||
3729 | case DeclaratorChunk::Pipe: | ||||
3730 | // These cannot appear in expressions. | ||||
3731 | CouldBeTemporaryObject = false; | ||||
3732 | StartsWithDeclaratorId = false; | ||||
3733 | continue; | ||||
3734 | } | ||||
3735 | } | ||||
3736 | |||||
3737 | // FIXME: If there is an initializer, assume that this is not intended to be | ||||
3738 | // a construction of a temporary object. | ||||
3739 | |||||
3740 | // Check whether the name has already been declared; if not, this is not a | ||||
3741 | // function-style cast. | ||||
3742 | if (CouldBeTemporaryObject) { | ||||
3743 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | ||||
3744 | Sema::LookupOrdinaryName); | ||||
3745 | if (!S.LookupName(Result, S.getCurScope())) | ||||
3746 | CouldBeTemporaryObject = false; | ||||
3747 | Result.suppressDiagnostics(); | ||||
3748 | } | ||||
3749 | |||||
3750 | SourceRange ParenRange(Paren.Loc, Paren.EndLoc); | ||||
3751 | |||||
3752 | if (!CouldBeTemporaryObject) { | ||||
3753 | // If we have A (::B), the parentheses affect the meaning of the program. | ||||
3754 | // Suppress the warning in that case. Don't bother looking at the DeclSpec | ||||
3755 | // here: even (e.g.) "int ::x" is visually ambiguous even though it's | ||||
3756 | // formally unambiguous. | ||||
3757 | if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { | ||||
3758 | for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; | ||||
3759 | NNS = NNS->getPrefix()) { | ||||
3760 | if (NNS->getKind() == NestedNameSpecifier::Global) | ||||
3761 | return; | ||||
3762 | } | ||||
3763 | } | ||||
3764 | |||||
3765 | S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) | ||||
3766 | << ParenRange << FixItHint::CreateRemoval(Paren.Loc) | ||||
3767 | << FixItHint::CreateRemoval(Paren.EndLoc); | ||||
3768 | return; | ||||
3769 | } | ||||
3770 | |||||
3771 | S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) | ||||
3772 | << ParenRange << D.getIdentifier(); | ||||
3773 | auto *RD = T->getAsCXXRecordDecl(); | ||||
3774 | if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) | ||||
3775 | S.Diag(Paren.Loc, diag::note_raii_guard_add_name) | ||||
3776 | << FixItHint::CreateInsertion(Paren.Loc, " varname") << T | ||||
3777 | << D.getIdentifier(); | ||||
3778 | // FIXME: A cast to void is probably a better suggestion in cases where it's | ||||
3779 | // valid (when there is no initializer and we're not in a condition). | ||||
3780 | S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) | ||||
3781 | << FixItHint::CreateInsertion(D.getBeginLoc(), "(") | ||||
3782 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); | ||||
3783 | S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) | ||||
3784 | << FixItHint::CreateRemoval(Paren.Loc) | ||||
3785 | << FixItHint::CreateRemoval(Paren.EndLoc); | ||||
3786 | } | ||||
3787 | |||||
3788 | /// Helper for figuring out the default CC for a function declarator type. If | ||||
3789 | /// this is the outermost chunk, then we can determine the CC from the | ||||
3790 | /// declarator context. If not, then this could be either a member function | ||||
3791 | /// type or normal function type. | ||||
3792 | static CallingConv getCCForDeclaratorChunk( | ||||
3793 | Sema &S, Declarator &D, const ParsedAttributesView &AttrList, | ||||
3794 | const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { | ||||
3795 | assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function)((D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function ) ? static_cast<void> (0) : __assert_fail ("D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3795, __PRETTY_FUNCTION__)); | ||||
3796 | |||||
3797 | // Check for an explicit CC attribute. | ||||
3798 | for (const ParsedAttr &AL : AttrList) { | ||||
3799 | switch (AL.getKind()) { | ||||
3800 | CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll : { | ||||
3801 | // Ignore attributes that don't validate or can't apply to the | ||||
3802 | // function type. We'll diagnose the failure to apply them in | ||||
3803 | // handleFunctionTypeAttr. | ||||
3804 | CallingConv CC; | ||||
3805 | if (!S.CheckCallingConvAttr(AL, CC) && | ||||
3806 | (!FTI.isVariadic || supportsVariadicCall(CC))) { | ||||
3807 | return CC; | ||||
3808 | } | ||||
3809 | break; | ||||
3810 | } | ||||
3811 | |||||
3812 | default: | ||||
3813 | break; | ||||
3814 | } | ||||
3815 | } | ||||
3816 | |||||
3817 | bool IsCXXInstanceMethod = false; | ||||
3818 | |||||
3819 | if (S.getLangOpts().CPlusPlus) { | ||||
3820 | // Look inwards through parentheses to see if this chunk will form a | ||||
3821 | // member pointer type or if we're the declarator. Any type attributes | ||||
3822 | // between here and there will override the CC we choose here. | ||||
3823 | unsigned I = ChunkIndex; | ||||
3824 | bool FoundNonParen = false; | ||||
3825 | while (I && !FoundNonParen) { | ||||
3826 | --I; | ||||
3827 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) | ||||
3828 | FoundNonParen = true; | ||||
3829 | } | ||||
3830 | |||||
3831 | if (FoundNonParen) { | ||||
3832 | // If we're not the declarator, we're a regular function type unless we're | ||||
3833 | // in a member pointer. | ||||
3834 | IsCXXInstanceMethod = | ||||
3835 | D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; | ||||
3836 | } else if (D.getContext() == DeclaratorContext::LambdaExpr) { | ||||
3837 | // This can only be a call operator for a lambda, which is an instance | ||||
3838 | // method. | ||||
3839 | IsCXXInstanceMethod = true; | ||||
3840 | } else { | ||||
3841 | // We're the innermost decl chunk, so must be a function declarator. | ||||
3842 | assert(D.isFunctionDeclarator())((D.isFunctionDeclarator()) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3842, __PRETTY_FUNCTION__)); | ||||
3843 | |||||
3844 | // If we're inside a record, we're declaring a method, but it could be | ||||
3845 | // explicitly or implicitly static. | ||||
3846 | IsCXXInstanceMethod = | ||||
3847 | D.isFirstDeclarationOfMember() && | ||||
3848 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | ||||
3849 | !D.isStaticMember(); | ||||
3850 | } | ||||
3851 | } | ||||
3852 | |||||
3853 | CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, | ||||
3854 | IsCXXInstanceMethod); | ||||
3855 | |||||
3856 | // Attribute AT_OpenCLKernel affects the calling convention for SPIR | ||||
3857 | // and AMDGPU targets, hence it cannot be treated as a calling | ||||
3858 | // convention attribute. This is the simplest place to infer | ||||
3859 | // calling convention for OpenCL kernels. | ||||
3860 | if (S.getLangOpts().OpenCL) { | ||||
3861 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | ||||
3862 | if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { | ||||
3863 | CC = CC_OpenCLKernel; | ||||
3864 | break; | ||||
3865 | } | ||||
3866 | } | ||||
3867 | } | ||||
3868 | |||||
3869 | return CC; | ||||
3870 | } | ||||
3871 | |||||
3872 | namespace { | ||||
3873 | /// A simple notion of pointer kinds, which matches up with the various | ||||
3874 | /// pointer declarators. | ||||
3875 | enum class SimplePointerKind { | ||||
3876 | Pointer, | ||||
3877 | BlockPointer, | ||||
3878 | MemberPointer, | ||||
3879 | Array, | ||||
3880 | }; | ||||
3881 | } // end anonymous namespace | ||||
3882 | |||||
3883 | IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { | ||||
3884 | switch (nullability) { | ||||
3885 | case NullabilityKind::NonNull: | ||||
3886 | if (!Ident__Nonnull) | ||||
3887 | Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); | ||||
3888 | return Ident__Nonnull; | ||||
3889 | |||||
3890 | case NullabilityKind::Nullable: | ||||
3891 | if (!Ident__Nullable) | ||||
3892 | Ident__Nullable = PP.getIdentifierInfo("_Nullable"); | ||||
3893 | return Ident__Nullable; | ||||
3894 | |||||
3895 | case NullabilityKind::Unspecified: | ||||
3896 | if (!Ident__Null_unspecified) | ||||
3897 | Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); | ||||
3898 | return Ident__Null_unspecified; | ||||
3899 | } | ||||
3900 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 3900); | ||||
3901 | } | ||||
3902 | |||||
3903 | /// Retrieve the identifier "NSError". | ||||
3904 | IdentifierInfo *Sema::getNSErrorIdent() { | ||||
3905 | if (!Ident_NSError) | ||||
3906 | Ident_NSError = PP.getIdentifierInfo("NSError"); | ||||
3907 | |||||
3908 | return Ident_NSError; | ||||
3909 | } | ||||
3910 | |||||
3911 | /// Check whether there is a nullability attribute of any kind in the given | ||||
3912 | /// attribute list. | ||||
3913 | static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { | ||||
3914 | for (const ParsedAttr &AL : attrs) { | ||||
3915 | if (AL.getKind() == ParsedAttr::AT_TypeNonNull || | ||||
3916 | AL.getKind() == ParsedAttr::AT_TypeNullable || | ||||
3917 | AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) | ||||
3918 | return true; | ||||
3919 | } | ||||
3920 | |||||
3921 | return false; | ||||
3922 | } | ||||
3923 | |||||
3924 | namespace { | ||||
3925 | /// Describes the kind of a pointer a declarator describes. | ||||
3926 | enum class PointerDeclaratorKind { | ||||
3927 | // Not a pointer. | ||||
3928 | NonPointer, | ||||
3929 | // Single-level pointer. | ||||
3930 | SingleLevelPointer, | ||||
3931 | // Multi-level pointer (of any pointer kind). | ||||
3932 | MultiLevelPointer, | ||||
3933 | // CFFooRef* | ||||
3934 | MaybePointerToCFRef, | ||||
3935 | // CFErrorRef* | ||||
3936 | CFErrorRefPointer, | ||||
3937 | // NSError** | ||||
3938 | NSErrorPointerPointer, | ||||
3939 | }; | ||||
3940 | |||||
3941 | /// Describes a declarator chunk wrapping a pointer that marks inference as | ||||
3942 | /// unexpected. | ||||
3943 | // These values must be kept in sync with diagnostics. | ||||
3944 | enum class PointerWrappingDeclaratorKind { | ||||
3945 | /// Pointer is top-level. | ||||
3946 | None = -1, | ||||
3947 | /// Pointer is an array element. | ||||
3948 | Array = 0, | ||||
3949 | /// Pointer is the referent type of a C++ reference. | ||||
3950 | Reference = 1 | ||||
3951 | }; | ||||
3952 | } // end anonymous namespace | ||||
3953 | |||||
3954 | /// Classify the given declarator, whose type-specified is \c type, based on | ||||
3955 | /// what kind of pointer it refers to. | ||||
3956 | /// | ||||
3957 | /// This is used to determine the default nullability. | ||||
3958 | static PointerDeclaratorKind | ||||
3959 | classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, | ||||
3960 | PointerWrappingDeclaratorKind &wrappingKind) { | ||||
3961 | unsigned numNormalPointers = 0; | ||||
3962 | |||||
3963 | // For any dependent type, we consider it a non-pointer. | ||||
3964 | if (type->isDependentType()) | ||||
3965 | return PointerDeclaratorKind::NonPointer; | ||||
3966 | |||||
3967 | // Look through the declarator chunks to identify pointers. | ||||
3968 | for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { | ||||
3969 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | ||||
3970 | switch (chunk.Kind) { | ||||
3971 | case DeclaratorChunk::Array: | ||||
3972 | if (numNormalPointers == 0) | ||||
3973 | wrappingKind = PointerWrappingDeclaratorKind::Array; | ||||
3974 | break; | ||||
3975 | |||||
3976 | case DeclaratorChunk::Function: | ||||
3977 | case DeclaratorChunk::Pipe: | ||||
3978 | break; | ||||
3979 | |||||
3980 | case DeclaratorChunk::BlockPointer: | ||||
3981 | case DeclaratorChunk::MemberPointer: | ||||
3982 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | ||||
3983 | : PointerDeclaratorKind::SingleLevelPointer; | ||||
3984 | |||||
3985 | case DeclaratorChunk::Paren: | ||||
3986 | break; | ||||
3987 | |||||
3988 | case DeclaratorChunk::Reference: | ||||
3989 | if (numNormalPointers == 0) | ||||
3990 | wrappingKind = PointerWrappingDeclaratorKind::Reference; | ||||
3991 | break; | ||||
3992 | |||||
3993 | case DeclaratorChunk::Pointer: | ||||
3994 | ++numNormalPointers; | ||||
3995 | if (numNormalPointers > 2) | ||||
3996 | return PointerDeclaratorKind::MultiLevelPointer; | ||||
3997 | break; | ||||
3998 | } | ||||
3999 | } | ||||
4000 | |||||
4001 | // Then, dig into the type specifier itself. | ||||
4002 | unsigned numTypeSpecifierPointers = 0; | ||||
4003 | do { | ||||
4004 | // Decompose normal pointers. | ||||
4005 | if (auto ptrType = type->getAs<PointerType>()) { | ||||
4006 | ++numNormalPointers; | ||||
4007 | |||||
4008 | if (numNormalPointers > 2) | ||||
4009 | return PointerDeclaratorKind::MultiLevelPointer; | ||||
4010 | |||||
4011 | type = ptrType->getPointeeType(); | ||||
4012 | ++numTypeSpecifierPointers; | ||||
4013 | continue; | ||||
4014 | } | ||||
4015 | |||||
4016 | // Decompose block pointers. | ||||
4017 | if (type->getAs<BlockPointerType>()) { | ||||
4018 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | ||||
4019 | : PointerDeclaratorKind::SingleLevelPointer; | ||||
4020 | } | ||||
4021 | |||||
4022 | // Decompose member pointers. | ||||
4023 | if (type->getAs<MemberPointerType>()) { | ||||
4024 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | ||||
4025 | : PointerDeclaratorKind::SingleLevelPointer; | ||||
4026 | } | ||||
4027 | |||||
4028 | // Look at Objective-C object pointers. | ||||
4029 | if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { | ||||
4030 | ++numNormalPointers; | ||||
4031 | ++numTypeSpecifierPointers; | ||||
4032 | |||||
4033 | // If this is NSError**, report that. | ||||
4034 | if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { | ||||
4035 | if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && | ||||
4036 | numNormalPointers == 2 && numTypeSpecifierPointers < 2) { | ||||
4037 | return PointerDeclaratorKind::NSErrorPointerPointer; | ||||
4038 | } | ||||
4039 | } | ||||
4040 | |||||
4041 | break; | ||||
4042 | } | ||||
4043 | |||||
4044 | // Look at Objective-C class types. | ||||
4045 | if (auto objcClass = type->getAs<ObjCInterfaceType>()) { | ||||
4046 | if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { | ||||
4047 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) | ||||
4048 | return PointerDeclaratorKind::NSErrorPointerPointer; | ||||
4049 | } | ||||
4050 | |||||
4051 | break; | ||||
4052 | } | ||||
4053 | |||||
4054 | // If at this point we haven't seen a pointer, we won't see one. | ||||
4055 | if (numNormalPointers == 0) | ||||
4056 | return PointerDeclaratorKind::NonPointer; | ||||
4057 | |||||
4058 | if (auto recordType = type->getAs<RecordType>()) { | ||||
4059 | RecordDecl *recordDecl = recordType->getDecl(); | ||||
4060 | |||||
4061 | // If this is CFErrorRef*, report it as such. | ||||
4062 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 && | ||||
4063 | S.isCFError(recordDecl)) { | ||||
4064 | return PointerDeclaratorKind::CFErrorRefPointer; | ||||
4065 | } | ||||
4066 | break; | ||||
4067 | } | ||||
4068 | |||||
4069 | break; | ||||
4070 | } while (true); | ||||
4071 | |||||
4072 | switch (numNormalPointers) { | ||||
4073 | case 0: | ||||
4074 | return PointerDeclaratorKind::NonPointer; | ||||
4075 | |||||
4076 | case 1: | ||||
4077 | return PointerDeclaratorKind::SingleLevelPointer; | ||||
4078 | |||||
4079 | case 2: | ||||
4080 | return PointerDeclaratorKind::MaybePointerToCFRef; | ||||
4081 | |||||
4082 | default: | ||||
4083 | return PointerDeclaratorKind::MultiLevelPointer; | ||||
4084 | } | ||||
4085 | } | ||||
4086 | |||||
4087 | bool Sema::isCFError(RecordDecl *RD) { | ||||
4088 | // If we already know about CFError, test it directly. | ||||
4089 | if (CFError) | ||||
4090 | return CFError == RD; | ||||
4091 | |||||
4092 | // Check whether this is CFError, which we identify based on its bridge to | ||||
4093 | // NSError. CFErrorRef used to be declared with "objc_bridge" but is now | ||||
4094 | // declared with "objc_bridge_mutable", so look for either one of the two | ||||
4095 | // attributes. | ||||
4096 | if (RD->getTagKind() == TTK_Struct) { | ||||
4097 | IdentifierInfo *bridgedType = nullptr; | ||||
4098 | if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>()) | ||||
4099 | bridgedType = bridgeAttr->getBridgedType(); | ||||
4100 | else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>()) | ||||
4101 | bridgedType = bridgeAttr->getBridgedType(); | ||||
4102 | |||||
4103 | if (bridgedType == getNSErrorIdent()) { | ||||
4104 | CFError = RD; | ||||
4105 | return true; | ||||
4106 | } | ||||
4107 | } | ||||
4108 | |||||
4109 | return false; | ||||
4110 | } | ||||
4111 | |||||
4112 | static FileID getNullabilityCompletenessCheckFileID(Sema &S, | ||||
4113 | SourceLocation loc) { | ||||
4114 | // If we're anywhere in a function, method, or closure context, don't perform | ||||
4115 | // completeness checks. | ||||
4116 | for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { | ||||
4117 | if (ctx->isFunctionOrMethod()) | ||||
4118 | return FileID(); | ||||
4119 | |||||
4120 | if (ctx->isFileContext()) | ||||
4121 | break; | ||||
4122 | } | ||||
4123 | |||||
4124 | // We only care about the expansion location. | ||||
4125 | loc = S.SourceMgr.getExpansionLoc(loc); | ||||
4126 | FileID file = S.SourceMgr.getFileID(loc); | ||||
4127 | if (file.isInvalid()) | ||||
4128 | return FileID(); | ||||
4129 | |||||
4130 | // Retrieve file information. | ||||
4131 | bool invalid = false; | ||||
4132 | const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); | ||||
4133 | if (invalid || !sloc.isFile()) | ||||
4134 | return FileID(); | ||||
4135 | |||||
4136 | // We don't want to perform completeness checks on the main file or in | ||||
4137 | // system headers. | ||||
4138 | const SrcMgr::FileInfo &fileInfo = sloc.getFile(); | ||||
4139 | if (fileInfo.getIncludeLoc().isInvalid()) | ||||
4140 | return FileID(); | ||||
4141 | if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && | ||||
4142 | S.Diags.getSuppressSystemWarnings()) { | ||||
4143 | return FileID(); | ||||
4144 | } | ||||
4145 | |||||
4146 | return file; | ||||
4147 | } | ||||
4148 | |||||
4149 | /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, | ||||
4150 | /// taking into account whitespace before and after. | ||||
4151 | template <typename DiagBuilderT> | ||||
4152 | static void fixItNullability(Sema &S, DiagBuilderT &Diag, | ||||
4153 | SourceLocation PointerLoc, | ||||
4154 | NullabilityKind Nullability) { | ||||
4155 | assert(PointerLoc.isValid())((PointerLoc.isValid()) ? static_cast<void> (0) : __assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 4155, __PRETTY_FUNCTION__)); | ||||
4156 | if (PointerLoc.isMacroID()) | ||||
4157 | return; | ||||
4158 | |||||
4159 | SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); | ||||
4160 | if (!FixItLoc.isValid() || FixItLoc == PointerLoc) | ||||
4161 | return; | ||||
4162 | |||||
4163 | const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); | ||||
4164 | if (!NextChar) | ||||
4165 | return; | ||||
4166 | |||||
4167 | SmallString<32> InsertionTextBuf{" "}; | ||||
4168 | InsertionTextBuf += getNullabilitySpelling(Nullability); | ||||
4169 | InsertionTextBuf += " "; | ||||
4170 | StringRef InsertionText = InsertionTextBuf.str(); | ||||
4171 | |||||
4172 | if (isWhitespace(*NextChar)) { | ||||
4173 | InsertionText = InsertionText.drop_back(); | ||||
4174 | } else if (NextChar[-1] == '[') { | ||||
4175 | if (NextChar[0] == ']') | ||||
4176 | InsertionText = InsertionText.drop_back().drop_front(); | ||||
4177 | else | ||||
4178 | InsertionText = InsertionText.drop_front(); | ||||
4179 | } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) && | ||||
4180 | !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) { | ||||
4181 | InsertionText = InsertionText.drop_back().drop_front(); | ||||
4182 | } | ||||
4183 | |||||
4184 | Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); | ||||
4185 | } | ||||
4186 | |||||
4187 | static void emitNullabilityConsistencyWarning(Sema &S, | ||||
4188 | SimplePointerKind PointerKind, | ||||
4189 | SourceLocation PointerLoc, | ||||
4190 | SourceLocation PointerEndLoc) { | ||||
4191 | assert(PointerLoc.isValid())((PointerLoc.isValid()) ? static_cast<void> (0) : __assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 4191, __PRETTY_FUNCTION__)); | ||||
4192 | |||||
4193 | if (PointerKind == SimplePointerKind::Array) { | ||||
4194 | S.Diag(PointerLoc, diag::warn_nullability_missing_array); | ||||
4195 | } else { | ||||
4196 | S.Diag(PointerLoc, diag::warn_nullability_missing) | ||||
4197 | << static_cast<unsigned>(PointerKind); | ||||
4198 | } | ||||
4199 | |||||
4200 | auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; | ||||
4201 | if (FixItLoc.isMacroID()) | ||||
4202 | return; | ||||
4203 | |||||
4204 | auto addFixIt = [&](NullabilityKind Nullability) { | ||||
4205 | auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); | ||||
4206 | Diag << static_cast<unsigned>(Nullability); | ||||
4207 | Diag << static_cast<unsigned>(PointerKind); | ||||
4208 | fixItNullability(S, Diag, FixItLoc, Nullability); | ||||
4209 | }; | ||||
4210 | addFixIt(NullabilityKind::Nullable); | ||||
4211 | addFixIt(NullabilityKind::NonNull); | ||||
4212 | } | ||||
4213 | |||||
4214 | /// Complains about missing nullability if the file containing \p pointerLoc | ||||
4215 | /// has other uses of nullability (either the keywords or the \c assume_nonnull | ||||
4216 | /// pragma). | ||||
4217 | /// | ||||
4218 | /// If the file has \e not seen other uses of nullability, this particular | ||||
4219 | /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). | ||||
4220 | static void | ||||
4221 | checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, | ||||
4222 | SourceLocation pointerLoc, | ||||
4223 | SourceLocation pointerEndLoc = SourceLocation()) { | ||||
4224 | // Determine which file we're performing consistency checking for. | ||||
4225 | FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); | ||||
4226 | if (file.isInvalid()) | ||||
4227 | return; | ||||
4228 | |||||
4229 | // If we haven't seen any type nullability in this file, we won't warn now | ||||
4230 | // about anything. | ||||
4231 | FileNullability &fileNullability = S.NullabilityMap[file]; | ||||
4232 | if (!fileNullability.SawTypeNullability) { | ||||
4233 | // If this is the first pointer declarator in the file, and the appropriate | ||||
4234 | // warning is on, record it in case we need to diagnose it retroactively. | ||||
4235 | diag::kind diagKind; | ||||
4236 | if (pointerKind == SimplePointerKind::Array) | ||||
4237 | diagKind = diag::warn_nullability_missing_array; | ||||
4238 | else | ||||
4239 | diagKind = diag::warn_nullability_missing; | ||||
4240 | |||||
4241 | if (fileNullability.PointerLoc.isInvalid() && | ||||
4242 | !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { | ||||
4243 | fileNullability.PointerLoc = pointerLoc; | ||||
4244 | fileNullability.PointerEndLoc = pointerEndLoc; | ||||
4245 | fileNullability.PointerKind = static_cast<unsigned>(pointerKind); | ||||
4246 | } | ||||
4247 | |||||
4248 | return; | ||||
4249 | } | ||||
4250 | |||||
4251 | // Complain about missing nullability. | ||||
4252 | emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); | ||||
4253 | } | ||||
4254 | |||||
4255 | /// Marks that a nullability feature has been used in the file containing | ||||
4256 | /// \p loc. | ||||
4257 | /// | ||||
4258 | /// If this file already had pointer types in it that were missing nullability, | ||||
4259 | /// the first such instance is retroactively diagnosed. | ||||
4260 | /// | ||||
4261 | /// \sa checkNullabilityConsistency | ||||
4262 | static void recordNullabilitySeen(Sema &S, SourceLocation loc) { | ||||
4263 | FileID file = getNullabilityCompletenessCheckFileID(S, loc); | ||||
4264 | if (file.isInvalid()) | ||||
4265 | return; | ||||
4266 | |||||
4267 | FileNullability &fileNullability = S.NullabilityMap[file]; | ||||
4268 | if (fileNullability.SawTypeNullability) | ||||
4269 | return; | ||||
4270 | fileNullability.SawTypeNullability = true; | ||||
4271 | |||||
4272 | // If we haven't seen any type nullability before, now we have. Retroactively | ||||
4273 | // diagnose the first unannotated pointer, if there was one. | ||||
4274 | if (fileNullability.PointerLoc.isInvalid()) | ||||
4275 | return; | ||||
4276 | |||||
4277 | auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); | ||||
4278 | emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, | ||||
4279 | fileNullability.PointerEndLoc); | ||||
4280 | } | ||||
4281 | |||||
4282 | /// Returns true if any of the declarator chunks before \p endIndex include a | ||||
4283 | /// level of indirection: array, pointer, reference, or pointer-to-member. | ||||
4284 | /// | ||||
4285 | /// Because declarator chunks are stored in outer-to-inner order, testing | ||||
4286 | /// every chunk before \p endIndex is testing all chunks that embed the current | ||||
4287 | /// chunk as part of their type. | ||||
4288 | /// | ||||
4289 | /// It is legal to pass the result of Declarator::getNumTypeObjects() as the | ||||
4290 | /// end index, in which case all chunks are tested. | ||||
4291 | static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { | ||||
4292 | unsigned i = endIndex; | ||||
4293 | while (i != 0) { | ||||
4294 | // Walk outwards along the declarator chunks. | ||||
4295 | --i; | ||||
4296 | const DeclaratorChunk &DC = D.getTypeObject(i); | ||||
4297 | switch (DC.Kind) { | ||||
4298 | case DeclaratorChunk::Paren: | ||||
4299 | break; | ||||
4300 | case DeclaratorChunk::Array: | ||||
4301 | case DeclaratorChunk::Pointer: | ||||
4302 | case DeclaratorChunk::Reference: | ||||
4303 | case DeclaratorChunk::MemberPointer: | ||||
4304 | return true; | ||||
4305 | case DeclaratorChunk::Function: | ||||
4306 | case DeclaratorChunk::BlockPointer: | ||||
4307 | case DeclaratorChunk::Pipe: | ||||
4308 | // These are invalid anyway, so just ignore. | ||||
4309 | break; | ||||
4310 | } | ||||
4311 | } | ||||
4312 | return false; | ||||
4313 | } | ||||
4314 | |||||
4315 | static bool IsNoDerefableChunk(DeclaratorChunk Chunk) { | ||||
4316 | return (Chunk.Kind == DeclaratorChunk::Pointer || | ||||
4317 | Chunk.Kind == DeclaratorChunk::Array); | ||||
4318 | } | ||||
4319 | |||||
4320 | template<typename AttrT> | ||||
4321 | static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) { | ||||
4322 | AL.setUsedAsTypeAttr(); | ||||
4323 | return ::new (Ctx) AttrT(Ctx, AL); | ||||
4324 | } | ||||
4325 | |||||
4326 | static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, | ||||
4327 | NullabilityKind NK) { | ||||
4328 | switch (NK) { | ||||
4329 | case NullabilityKind::NonNull: | ||||
4330 | return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); | ||||
4331 | |||||
4332 | case NullabilityKind::Nullable: | ||||
4333 | return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); | ||||
4334 | |||||
4335 | case NullabilityKind::Unspecified: | ||||
4336 | return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); | ||||
4337 | } | ||||
4338 | llvm_unreachable("unknown NullabilityKind")::llvm::llvm_unreachable_internal("unknown NullabilityKind", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 4338); | ||||
4339 | } | ||||
4340 | |||||
4341 | // Diagnose whether this is a case with the multiple addr spaces. | ||||
4342 | // Returns true if this is an invalid case. | ||||
4343 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified | ||||
4344 | // by qualifiers for two or more different address spaces." | ||||
4345 | static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, | ||||
4346 | LangAS ASNew, | ||||
4347 | SourceLocation AttrLoc) { | ||||
4348 | if (ASOld != LangAS::Default) { | ||||
4349 | if (ASOld != ASNew) { | ||||
4350 | S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | ||||
4351 | return true; | ||||
4352 | } | ||||
4353 | // Emit a warning if they are identical; it's likely unintended. | ||||
4354 | S.Diag(AttrLoc, | ||||
4355 | diag::warn_attribute_address_multiple_identical_qualifiers); | ||||
4356 | } | ||||
4357 | return false; | ||||
4358 | } | ||||
4359 | |||||
4360 | static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, | ||||
4361 | QualType declSpecType, | ||||
4362 | TypeSourceInfo *TInfo) { | ||||
4363 | // The TypeSourceInfo that this function returns will not be a null type. | ||||
4364 | // If there is an error, this function will fill in a dummy type as fallback. | ||||
4365 | QualType T = declSpecType; | ||||
4366 | Declarator &D = state.getDeclarator(); | ||||
4367 | Sema &S = state.getSema(); | ||||
4368 | ASTContext &Context = S.Context; | ||||
4369 | const LangOptions &LangOpts = S.getLangOpts(); | ||||
4370 | |||||
4371 | // The name we're declaring, if any. | ||||
4372 | DeclarationName Name; | ||||
4373 | if (D.getIdentifier()) | ||||
4374 | Name = D.getIdentifier(); | ||||
4375 | |||||
4376 | // Does this declaration declare a typedef-name? | ||||
4377 | bool IsTypedefName = | ||||
4378 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || | ||||
4379 | D.getContext() == DeclaratorContext::AliasDecl || | ||||
4380 | D.getContext() == DeclaratorContext::AliasTemplate; | ||||
4381 | |||||
4382 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | ||||
4383 | bool IsQualifiedFunction = T->isFunctionProtoType() && | ||||
4384 | (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || | ||||
4385 | T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); | ||||
4386 | |||||
4387 | // If T is 'decltype(auto)', the only declarators we can have are parens | ||||
4388 | // and at most one function declarator if this is a function declaration. | ||||
4389 | // If T is a deduced class template specialization type, we can have no | ||||
4390 | // declarator chunks at all. | ||||
4391 | if (auto *DT = T->getAs<DeducedType>()) { | ||||
4392 | const AutoType *AT = T->getAs<AutoType>(); | ||||
4393 | bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); | ||||
4394 | if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { | ||||
4395 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | ||||
4396 | unsigned Index = E - I - 1; | ||||
4397 | DeclaratorChunk &DeclChunk = D.getTypeObject(Index); | ||||
4398 | unsigned DiagId = IsClassTemplateDeduction | ||||
4399 | ? diag::err_deduced_class_template_compound_type | ||||
4400 | : diag::err_decltype_auto_compound_type; | ||||
4401 | unsigned DiagKind = 0; | ||||
4402 | switch (DeclChunk.Kind) { | ||||
4403 | case DeclaratorChunk::Paren: | ||||
4404 | // FIXME: Rejecting this is a little silly. | ||||
4405 | if (IsClassTemplateDeduction) { | ||||
4406 | DiagKind = 4; | ||||
4407 | break; | ||||
4408 | } | ||||
4409 | continue; | ||||
4410 | case DeclaratorChunk::Function: { | ||||
4411 | if (IsClassTemplateDeduction) { | ||||
4412 | DiagKind = 3; | ||||
4413 | break; | ||||
4414 | } | ||||
4415 | unsigned FnIndex; | ||||
4416 | if (D.isFunctionDeclarationContext() && | ||||
4417 | D.isFunctionDeclarator(FnIndex) && FnIndex == Index) | ||||
4418 | continue; | ||||
4419 | DiagId = diag::err_decltype_auto_function_declarator_not_declaration; | ||||
4420 | break; | ||||
4421 | } | ||||
4422 | case DeclaratorChunk::Pointer: | ||||
4423 | case DeclaratorChunk::BlockPointer: | ||||
4424 | case DeclaratorChunk::MemberPointer: | ||||
4425 | DiagKind = 0; | ||||
4426 | break; | ||||
4427 | case DeclaratorChunk::Reference: | ||||
4428 | DiagKind = 1; | ||||
4429 | break; | ||||
4430 | case DeclaratorChunk::Array: | ||||
4431 | DiagKind = 2; | ||||
4432 | break; | ||||
4433 | case DeclaratorChunk::Pipe: | ||||
4434 | break; | ||||
4435 | } | ||||
4436 | |||||
4437 | S.Diag(DeclChunk.Loc, DiagId) << DiagKind; | ||||
4438 | D.setInvalidType(true); | ||||
4439 | break; | ||||
4440 | } | ||||
4441 | } | ||||
4442 | } | ||||
4443 | |||||
4444 | // Determine whether we should infer _Nonnull on pointer types. | ||||
4445 | Optional<NullabilityKind> inferNullability; | ||||
4446 | bool inferNullabilityCS = false; | ||||
4447 | bool inferNullabilityInnerOnly = false; | ||||
4448 | bool inferNullabilityInnerOnlyComplete = false; | ||||
4449 | |||||
4450 | // Are we in an assume-nonnull region? | ||||
4451 | bool inAssumeNonNullRegion = false; | ||||
4452 | SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); | ||||
4453 | if (assumeNonNullLoc.isValid()) { | ||||
4454 | inAssumeNonNullRegion = true; | ||||
4455 | recordNullabilitySeen(S, assumeNonNullLoc); | ||||
4456 | } | ||||
4457 | |||||
4458 | // Whether to complain about missing nullability specifiers or not. | ||||
4459 | enum { | ||||
4460 | /// Never complain. | ||||
4461 | CAMN_No, | ||||
4462 | /// Complain on the inner pointers (but not the outermost | ||||
4463 | /// pointer). | ||||
4464 | CAMN_InnerPointers, | ||||
4465 | /// Complain about any pointers that don't have nullability | ||||
4466 | /// specified or inferred. | ||||
4467 | CAMN_Yes | ||||
4468 | } complainAboutMissingNullability = CAMN_No; | ||||
4469 | unsigned NumPointersRemaining = 0; | ||||
4470 | auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; | ||||
4471 | |||||
4472 | if (IsTypedefName) { | ||||
4473 | // For typedefs, we do not infer any nullability (the default), | ||||
4474 | // and we only complain about missing nullability specifiers on | ||||
4475 | // inner pointers. | ||||
4476 | complainAboutMissingNullability = CAMN_InnerPointers; | ||||
4477 | |||||
4478 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | ||||
4479 | !T->getNullability(S.Context)) { | ||||
4480 | // Note that we allow but don't require nullability on dependent types. | ||||
4481 | ++NumPointersRemaining; | ||||
4482 | } | ||||
4483 | |||||
4484 | for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { | ||||
4485 | DeclaratorChunk &chunk = D.getTypeObject(i); | ||||
4486 | switch (chunk.Kind) { | ||||
4487 | case DeclaratorChunk::Array: | ||||
4488 | case DeclaratorChunk::Function: | ||||
4489 | case DeclaratorChunk::Pipe: | ||||
4490 | break; | ||||
4491 | |||||
4492 | case DeclaratorChunk::BlockPointer: | ||||
4493 | case DeclaratorChunk::MemberPointer: | ||||
4494 | ++NumPointersRemaining; | ||||
4495 | break; | ||||
4496 | |||||
4497 | case DeclaratorChunk::Paren: | ||||
4498 | case DeclaratorChunk::Reference: | ||||
4499 | continue; | ||||
4500 | |||||
4501 | case DeclaratorChunk::Pointer: | ||||
4502 | ++NumPointersRemaining; | ||||
4503 | continue; | ||||
4504 | } | ||||
4505 | } | ||||
4506 | } else { | ||||
4507 | bool isFunctionOrMethod = false; | ||||
4508 | switch (auto context = state.getDeclarator().getContext()) { | ||||
4509 | case DeclaratorContext::ObjCParameter: | ||||
4510 | case DeclaratorContext::ObjCResult: | ||||
4511 | case DeclaratorContext::Prototype: | ||||
4512 | case DeclaratorContext::TrailingReturn: | ||||
4513 | case DeclaratorContext::TrailingReturnVar: | ||||
4514 | isFunctionOrMethod = true; | ||||
4515 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
4516 | |||||
4517 | case DeclaratorContext::Member: | ||||
4518 | if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { | ||||
4519 | complainAboutMissingNullability = CAMN_No; | ||||
4520 | break; | ||||
4521 | } | ||||
4522 | |||||
4523 | // Weak properties are inferred to be nullable. | ||||
4524 | if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { | ||||
4525 | inferNullability = NullabilityKind::Nullable; | ||||
4526 | break; | ||||
4527 | } | ||||
4528 | |||||
4529 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
4530 | |||||
4531 | case DeclaratorContext::File: | ||||
4532 | case DeclaratorContext::KNRTypeList: { | ||||
4533 | complainAboutMissingNullability = CAMN_Yes; | ||||
4534 | |||||
4535 | // Nullability inference depends on the type and declarator. | ||||
4536 | auto wrappingKind = PointerWrappingDeclaratorKind::None; | ||||
4537 | switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { | ||||
4538 | case PointerDeclaratorKind::NonPointer: | ||||
4539 | case PointerDeclaratorKind::MultiLevelPointer: | ||||
4540 | // Cannot infer nullability. | ||||
4541 | break; | ||||
4542 | |||||
4543 | case PointerDeclaratorKind::SingleLevelPointer: | ||||
4544 | // Infer _Nonnull if we are in an assumes-nonnull region. | ||||
4545 | if (inAssumeNonNullRegion) { | ||||
4546 | complainAboutInferringWithinChunk = wrappingKind; | ||||
4547 | inferNullability = NullabilityKind::NonNull; | ||||
4548 | inferNullabilityCS = (context == DeclaratorContext::ObjCParameter || | ||||
4549 | context == DeclaratorContext::ObjCResult); | ||||
4550 | } | ||||
4551 | break; | ||||
4552 | |||||
4553 | case PointerDeclaratorKind::CFErrorRefPointer: | ||||
4554 | case PointerDeclaratorKind::NSErrorPointerPointer: | ||||
4555 | // Within a function or method signature, infer _Nullable at both | ||||
4556 | // levels. | ||||
4557 | if (isFunctionOrMethod && inAssumeNonNullRegion) | ||||
4558 | inferNullability = NullabilityKind::Nullable; | ||||
4559 | break; | ||||
4560 | |||||
4561 | case PointerDeclaratorKind::MaybePointerToCFRef: | ||||
4562 | if (isFunctionOrMethod) { | ||||
4563 | // On pointer-to-pointer parameters marked cf_returns_retained or | ||||
4564 | // cf_returns_not_retained, if the outer pointer is explicit then | ||||
4565 | // infer the inner pointer as _Nullable. | ||||
4566 | auto hasCFReturnsAttr = | ||||
4567 | [](const ParsedAttributesView &AttrList) -> bool { | ||||
4568 | return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || | ||||
4569 | AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); | ||||
4570 | }; | ||||
4571 | if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { | ||||
4572 | if (hasCFReturnsAttr(D.getAttributes()) || | ||||
4573 | hasCFReturnsAttr(InnermostChunk->getAttrs()) || | ||||
4574 | hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { | ||||
4575 | inferNullability = NullabilityKind::Nullable; | ||||
4576 | inferNullabilityInnerOnly = true; | ||||
4577 | } | ||||
4578 | } | ||||
4579 | } | ||||
4580 | break; | ||||
4581 | } | ||||
4582 | break; | ||||
4583 | } | ||||
4584 | |||||
4585 | case DeclaratorContext::ConversionId: | ||||
4586 | complainAboutMissingNullability = CAMN_Yes; | ||||
4587 | break; | ||||
4588 | |||||
4589 | case DeclaratorContext::AliasDecl: | ||||
4590 | case DeclaratorContext::AliasTemplate: | ||||
4591 | case DeclaratorContext::Block: | ||||
4592 | case DeclaratorContext::BlockLiteral: | ||||
4593 | case DeclaratorContext::Condition: | ||||
4594 | case DeclaratorContext::CXXCatch: | ||||
4595 | case DeclaratorContext::CXXNew: | ||||
4596 | case DeclaratorContext::ForInit: | ||||
4597 | case DeclaratorContext::SelectionInit: | ||||
4598 | case DeclaratorContext::LambdaExpr: | ||||
4599 | case DeclaratorContext::LambdaExprParameter: | ||||
4600 | case DeclaratorContext::ObjCCatch: | ||||
4601 | case DeclaratorContext::TemplateParam: | ||||
4602 | case DeclaratorContext::TemplateArg: | ||||
4603 | case DeclaratorContext::TemplateTypeArg: | ||||
4604 | case DeclaratorContext::TypeName: | ||||
4605 | case DeclaratorContext::FunctionalCast: | ||||
4606 | case DeclaratorContext::RequiresExpr: | ||||
4607 | // Don't infer in these contexts. | ||||
4608 | break; | ||||
4609 | } | ||||
4610 | } | ||||
4611 | |||||
4612 | // Local function that returns true if its argument looks like a va_list. | ||||
4613 | auto isVaList = [&S](QualType T) -> bool { | ||||
4614 | auto *typedefTy = T->getAs<TypedefType>(); | ||||
4615 | if (!typedefTy) | ||||
4616 | return false; | ||||
4617 | TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); | ||||
4618 | do { | ||||
4619 | if (typedefTy->getDecl() == vaListTypedef) | ||||
4620 | return true; | ||||
4621 | if (auto *name = typedefTy->getDecl()->getIdentifier()) | ||||
4622 | if (name->isStr("va_list")) | ||||
4623 | return true; | ||||
4624 | typedefTy = typedefTy->desugar()->getAs<TypedefType>(); | ||||
4625 | } while (typedefTy); | ||||
4626 | return false; | ||||
4627 | }; | ||||
4628 | |||||
4629 | // Local function that checks the nullability for a given pointer declarator. | ||||
4630 | // Returns true if _Nonnull was inferred. | ||||
4631 | auto inferPointerNullability = | ||||
4632 | [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, | ||||
4633 | SourceLocation pointerEndLoc, | ||||
4634 | ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { | ||||
4635 | // We've seen a pointer. | ||||
4636 | if (NumPointersRemaining > 0) | ||||
4637 | --NumPointersRemaining; | ||||
4638 | |||||
4639 | // If a nullability attribute is present, there's nothing to do. | ||||
4640 | if (hasNullabilityAttr(attrs)) | ||||
4641 | return nullptr; | ||||
4642 | |||||
4643 | // If we're supposed to infer nullability, do so now. | ||||
4644 | if (inferNullability && !inferNullabilityInnerOnlyComplete) { | ||||
4645 | ParsedAttr::Syntax syntax = inferNullabilityCS | ||||
4646 | ? ParsedAttr::AS_ContextSensitiveKeyword | ||||
4647 | : ParsedAttr::AS_Keyword; | ||||
4648 | ParsedAttr *nullabilityAttr = Pool.create( | ||||
4649 | S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc), | ||||
4650 | nullptr, SourceLocation(), nullptr, 0, syntax); | ||||
4651 | |||||
4652 | attrs.addAtEnd(nullabilityAttr); | ||||
4653 | |||||
4654 | if (inferNullabilityCS) { | ||||
4655 | state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() | ||||
4656 | ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); | ||||
4657 | } | ||||
4658 | |||||
4659 | if (pointerLoc.isValid() && | ||||
4660 | complainAboutInferringWithinChunk != | ||||
4661 | PointerWrappingDeclaratorKind::None) { | ||||
4662 | auto Diag = | ||||
4663 | S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); | ||||
4664 | Diag << static_cast<int>(complainAboutInferringWithinChunk); | ||||
4665 | fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); | ||||
4666 | } | ||||
4667 | |||||
4668 | if (inferNullabilityInnerOnly) | ||||
4669 | inferNullabilityInnerOnlyComplete = true; | ||||
4670 | return nullabilityAttr; | ||||
4671 | } | ||||
4672 | |||||
4673 | // If we're supposed to complain about missing nullability, do so | ||||
4674 | // now if it's truly missing. | ||||
4675 | switch (complainAboutMissingNullability) { | ||||
4676 | case CAMN_No: | ||||
4677 | break; | ||||
4678 | |||||
4679 | case CAMN_InnerPointers: | ||||
4680 | if (NumPointersRemaining == 0) | ||||
4681 | break; | ||||
4682 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
4683 | |||||
4684 | case CAMN_Yes: | ||||
4685 | checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); | ||||
4686 | } | ||||
4687 | return nullptr; | ||||
4688 | }; | ||||
4689 | |||||
4690 | // If the type itself could have nullability but does not, infer pointer | ||||
4691 | // nullability and perform consistency checking. | ||||
4692 | if (S.CodeSynthesisContexts.empty()) { | ||||
4693 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | ||||
4694 | !T->getNullability(S.Context)) { | ||||
4695 | if (isVaList(T)) { | ||||
4696 | // Record that we've seen a pointer, but do nothing else. | ||||
4697 | if (NumPointersRemaining > 0) | ||||
4698 | --NumPointersRemaining; | ||||
4699 | } else { | ||||
4700 | SimplePointerKind pointerKind = SimplePointerKind::Pointer; | ||||
4701 | if (T->isBlockPointerType()) | ||||
4702 | pointerKind = SimplePointerKind::BlockPointer; | ||||
4703 | else if (T->isMemberPointerType()) | ||||
4704 | pointerKind = SimplePointerKind::MemberPointer; | ||||
4705 | |||||
4706 | if (auto *attr = inferPointerNullability( | ||||
4707 | pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), | ||||
4708 | D.getDeclSpec().getEndLoc(), | ||||
4709 | D.getMutableDeclSpec().getAttributes(), | ||||
4710 | D.getMutableDeclSpec().getAttributePool())) { | ||||
4711 | T = state.getAttributedType( | ||||
4712 | createNullabilityAttr(Context, *attr, *inferNullability), T, T); | ||||
4713 | } | ||||
4714 | } | ||||
4715 | } | ||||
4716 | |||||
4717 | if (complainAboutMissingNullability == CAMN_Yes && | ||||
4718 | T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && | ||||
4719 | D.isPrototypeContext() && | ||||
4720 | !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { | ||||
4721 | checkNullabilityConsistency(S, SimplePointerKind::Array, | ||||
4722 | D.getDeclSpec().getTypeSpecTypeLoc()); | ||||
4723 | } | ||||
4724 | } | ||||
4725 | |||||
4726 | bool ExpectNoDerefChunk = | ||||
4727 | state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); | ||||
4728 | |||||
4729 | // Walk the DeclTypeInfo, building the recursive type as we go. | ||||
4730 | // DeclTypeInfos are ordered from the identifier out, which is | ||||
4731 | // opposite of what we want :). | ||||
4732 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | ||||
4733 | unsigned chunkIndex = e - i - 1; | ||||
4734 | state.setCurrentChunkIndex(chunkIndex); | ||||
4735 | DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); | ||||
4736 | IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; | ||||
4737 | switch (DeclType.Kind) { | ||||
4738 | case DeclaratorChunk::Paren: | ||||
4739 | if (i == 0) | ||||
4740 | warnAboutRedundantParens(S, D, T); | ||||
4741 | T = S.BuildParenType(T); | ||||
4742 | break; | ||||
4743 | case DeclaratorChunk::BlockPointer: | ||||
4744 | // If blocks are disabled, emit an error. | ||||
4745 | if (!LangOpts.Blocks) | ||||
4746 | S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; | ||||
4747 | |||||
4748 | // Handle pointer nullability. | ||||
4749 | inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, | ||||
4750 | DeclType.EndLoc, DeclType.getAttrs(), | ||||
4751 | state.getDeclarator().getAttributePool()); | ||||
4752 | |||||
4753 | T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); | ||||
4754 | if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { | ||||
4755 | // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly | ||||
4756 | // qualified with const. | ||||
4757 | if (LangOpts.OpenCL) | ||||
4758 | DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; | ||||
4759 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); | ||||
4760 | } | ||||
4761 | break; | ||||
4762 | case DeclaratorChunk::Pointer: | ||||
4763 | // Verify that we're not building a pointer to pointer to function with | ||||
4764 | // exception specification. | ||||
4765 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | ||||
4766 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | ||||
4767 | D.setInvalidType(true); | ||||
4768 | // Build the type anyway. | ||||
4769 | } | ||||
4770 | |||||
4771 | // Handle pointer nullability | ||||
4772 | inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, | ||||
4773 | DeclType.EndLoc, DeclType.getAttrs(), | ||||
4774 | state.getDeclarator().getAttributePool()); | ||||
4775 | |||||
4776 | if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { | ||||
4777 | T = Context.getObjCObjectPointerType(T); | ||||
4778 | if (DeclType.Ptr.TypeQuals) | ||||
4779 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | ||||
4780 | break; | ||||
4781 | } | ||||
4782 | |||||
4783 | // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. | ||||
4784 | // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. | ||||
4785 | // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. | ||||
4786 | if (LangOpts.OpenCL) { | ||||
4787 | if (T->isImageType() || T->isSamplerT() || T->isPipeType() || | ||||
4788 | T->isBlockPointerType()) { | ||||
4789 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; | ||||
4790 | D.setInvalidType(true); | ||||
4791 | } | ||||
4792 | } | ||||
4793 | |||||
4794 | T = S.BuildPointerType(T, DeclType.Loc, Name); | ||||
4795 | if (DeclType.Ptr.TypeQuals) | ||||
4796 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | ||||
4797 | break; | ||||
4798 | case DeclaratorChunk::Reference: { | ||||
4799 | // Verify that we're not building a reference to pointer to function with | ||||
4800 | // exception specification. | ||||
4801 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | ||||
4802 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | ||||
4803 | D.setInvalidType(true); | ||||
4804 | // Build the type anyway. | ||||
4805 | } | ||||
4806 | T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); | ||||
4807 | |||||
4808 | if (DeclType.Ref.HasRestrict) | ||||
4809 | T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); | ||||
4810 | break; | ||||
4811 | } | ||||
4812 | case DeclaratorChunk::Array: { | ||||
4813 | // Verify that we're not building an array of pointers to function with | ||||
4814 | // exception specification. | ||||
4815 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | ||||
4816 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | ||||
4817 | D.setInvalidType(true); | ||||
4818 | // Build the type anyway. | ||||
4819 | } | ||||
4820 | DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; | ||||
4821 | Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); | ||||
4822 | ArrayType::ArraySizeModifier ASM; | ||||
4823 | if (ATI.isStar) | ||||
4824 | ASM = ArrayType::Star; | ||||
4825 | else if (ATI.hasStatic) | ||||
4826 | ASM = ArrayType::Static; | ||||
4827 | else | ||||
4828 | ASM = ArrayType::Normal; | ||||
4829 | if (ASM == ArrayType::Star && !D.isPrototypeContext()) { | ||||
4830 | // FIXME: This check isn't quite right: it allows star in prototypes | ||||
4831 | // for function definitions, and disallows some edge cases detailed | ||||
4832 | // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html | ||||
4833 | S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); | ||||
4834 | ASM = ArrayType::Normal; | ||||
4835 | D.setInvalidType(true); | ||||
4836 | } | ||||
4837 | |||||
4838 | // C99 6.7.5.2p1: The optional type qualifiers and the keyword static | ||||
4839 | // shall appear only in a declaration of a function parameter with an | ||||
4840 | // array type, ... | ||||
4841 | if (ASM == ArrayType::Static || ATI.TypeQuals) { | ||||
4842 | if (!(D.isPrototypeContext() || | ||||
4843 | D.getContext() == DeclaratorContext::KNRTypeList)) { | ||||
4844 | S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << | ||||
4845 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | ||||
4846 | // Remove the 'static' and the type qualifiers. | ||||
4847 | if (ASM == ArrayType::Static) | ||||
4848 | ASM = ArrayType::Normal; | ||||
4849 | ATI.TypeQuals = 0; | ||||
4850 | D.setInvalidType(true); | ||||
4851 | } | ||||
4852 | |||||
4853 | // C99 6.7.5.2p1: ... and then only in the outermost array type | ||||
4854 | // derivation. | ||||
4855 | if (hasOuterPointerLikeChunk(D, chunkIndex)) { | ||||
4856 | S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << | ||||
4857 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | ||||
4858 | if (ASM == ArrayType::Static) | ||||
4859 | ASM = ArrayType::Normal; | ||||
4860 | ATI.TypeQuals = 0; | ||||
4861 | D.setInvalidType(true); | ||||
4862 | } | ||||
4863 | } | ||||
4864 | const AutoType *AT = T->getContainedAutoType(); | ||||
4865 | // Allow arrays of auto if we are a generic lambda parameter. | ||||
4866 | // i.e. [](auto (&array)[5]) { return array[0]; }; OK | ||||
4867 | if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) { | ||||
4868 | // We've already diagnosed this for decltype(auto). | ||||
4869 | if (!AT->isDecltypeAuto()) | ||||
4870 | S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) | ||||
4871 | << getPrintableNameForEntity(Name) << T; | ||||
4872 | T = QualType(); | ||||
4873 | break; | ||||
4874 | } | ||||
4875 | |||||
4876 | // Array parameters can be marked nullable as well, although it's not | ||||
4877 | // necessary if they're marked 'static'. | ||||
4878 | if (complainAboutMissingNullability == CAMN_Yes && | ||||
4879 | !hasNullabilityAttr(DeclType.getAttrs()) && | ||||
4880 | ASM != ArrayType::Static && | ||||
4881 | D.isPrototypeContext() && | ||||
4882 | !hasOuterPointerLikeChunk(D, chunkIndex)) { | ||||
4883 | checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); | ||||
4884 | } | ||||
4885 | |||||
4886 | T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, | ||||
4887 | SourceRange(DeclType.Loc, DeclType.EndLoc), Name); | ||||
4888 | break; | ||||
4889 | } | ||||
4890 | case DeclaratorChunk::Function: { | ||||
4891 | // If the function declarator has a prototype (i.e. it is not () and | ||||
4892 | // does not have a K&R-style identifier list), then the arguments are part | ||||
4893 | // of the type, otherwise the argument list is (). | ||||
4894 | DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | ||||
4895 | IsQualifiedFunction = | ||||
4896 | FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); | ||||
4897 | |||||
4898 | // Check for auto functions and trailing return type and adjust the | ||||
4899 | // return type accordingly. | ||||
4900 | if (!D.isInvalidType()) { | ||||
4901 | // trailing-return-type is only required if we're declaring a function, | ||||
4902 | // and not, for instance, a pointer to a function. | ||||
4903 | if (D.getDeclSpec().hasAutoTypeSpec() && | ||||
4904 | !FTI.hasTrailingReturnType() && chunkIndex == 0) { | ||||
4905 | if (!S.getLangOpts().CPlusPlus14) { | ||||
4906 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | ||||
4907 | D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto | ||||
4908 | ? diag::err_auto_missing_trailing_return | ||||
4909 | : diag::err_deduced_return_type); | ||||
4910 | T = Context.IntTy; | ||||
4911 | D.setInvalidType(true); | ||||
4912 | } else { | ||||
4913 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | ||||
4914 | diag::warn_cxx11_compat_deduced_return_type); | ||||
4915 | } | ||||
4916 | } else if (FTI.hasTrailingReturnType()) { | ||||
4917 | // T must be exactly 'auto' at this point. See CWG issue 681. | ||||
4918 | if (isa<ParenType>(T)) { | ||||
4919 | S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) | ||||
4920 | << T << D.getSourceRange(); | ||||
4921 | D.setInvalidType(true); | ||||
4922 | } else if (D.getName().getKind() == | ||||
4923 | UnqualifiedIdKind::IK_DeductionGuideName) { | ||||
4924 | if (T != Context.DependentTy) { | ||||
4925 | S.Diag(D.getDeclSpec().getBeginLoc(), | ||||
4926 | diag::err_deduction_guide_with_complex_decl) | ||||
4927 | << D.getSourceRange(); | ||||
4928 | D.setInvalidType(true); | ||||
4929 | } | ||||
4930 | } else if (D.getContext() != DeclaratorContext::LambdaExpr && | ||||
4931 | (T.hasQualifiers() || !isa<AutoType>(T) || | ||||
4932 | cast<AutoType>(T)->getKeyword() != | ||||
4933 | AutoTypeKeyword::Auto || | ||||
4934 | cast<AutoType>(T)->isConstrained())) { | ||||
4935 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | ||||
4936 | diag::err_trailing_return_without_auto) | ||||
4937 | << T << D.getDeclSpec().getSourceRange(); | ||||
4938 | D.setInvalidType(true); | ||||
4939 | } | ||||
4940 | T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); | ||||
4941 | if (T.isNull()) { | ||||
4942 | // An error occurred parsing the trailing return type. | ||||
4943 | T = Context.IntTy; | ||||
4944 | D.setInvalidType(true); | ||||
4945 | } else if (AutoType *Auto = T->getContainedAutoType()) { | ||||
4946 | // If the trailing return type contains an `auto`, we may need to | ||||
4947 | // invent a template parameter for it, for cases like | ||||
4948 | // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`. | ||||
4949 | InventedTemplateParameterInfo *InventedParamInfo = nullptr; | ||||
4950 | if (D.getContext() == DeclaratorContext::Prototype) | ||||
4951 | InventedParamInfo = &S.InventedParameterInfos.back(); | ||||
4952 | else if (D.getContext() == DeclaratorContext::LambdaExprParameter) | ||||
4953 | InventedParamInfo = S.getCurLambda(); | ||||
4954 | if (InventedParamInfo) { | ||||
4955 | std::tie(T, TInfo) = InventTemplateParameter( | ||||
4956 | state, T, TInfo, Auto, *InventedParamInfo); | ||||
4957 | } | ||||
4958 | } | ||||
4959 | } else { | ||||
4960 | // This function type is not the type of the entity being declared, | ||||
4961 | // so checking the 'auto' is not the responsibility of this chunk. | ||||
4962 | } | ||||
4963 | } | ||||
4964 | |||||
4965 | // C99 6.7.5.3p1: The return type may not be a function or array type. | ||||
4966 | // For conversion functions, we'll diagnose this particular error later. | ||||
4967 | if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && | ||||
4968 | (D.getName().getKind() != | ||||
4969 | UnqualifiedIdKind::IK_ConversionFunctionId)) { | ||||
4970 | unsigned diagID = diag::err_func_returning_array_function; | ||||
4971 | // Last processing chunk in block context means this function chunk | ||||
4972 | // represents the block. | ||||
4973 | if (chunkIndex == 0 && | ||||
4974 | D.getContext() == DeclaratorContext::BlockLiteral) | ||||
4975 | diagID = diag::err_block_returning_array_function; | ||||
4976 | S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; | ||||
4977 | T = Context.IntTy; | ||||
4978 | D.setInvalidType(true); | ||||
4979 | } | ||||
4980 | |||||
4981 | // Do not allow returning half FP value. | ||||
4982 | // FIXME: This really should be in BuildFunctionType. | ||||
4983 | if (T->isHalfType()) { | ||||
4984 | if (S.getLangOpts().OpenCL) { | ||||
4985 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | ||||
4986 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | ||||
4987 | << T << 0 /*pointer hint*/; | ||||
4988 | D.setInvalidType(true); | ||||
4989 | } | ||||
4990 | } else if (!S.getLangOpts().HalfArgsAndReturns) { | ||||
4991 | S.Diag(D.getIdentifierLoc(), | ||||
4992 | diag::err_parameters_retval_cannot_have_fp16_type) << 1; | ||||
4993 | D.setInvalidType(true); | ||||
4994 | } | ||||
4995 | } | ||||
4996 | |||||
4997 | if (LangOpts.OpenCL) { | ||||
4998 | // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a | ||||
4999 | // function. | ||||
5000 | if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || | ||||
5001 | T->isPipeType()) { | ||||
5002 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | ||||
5003 | << T << 1 /*hint off*/; | ||||
5004 | D.setInvalidType(true); | ||||
5005 | } | ||||
5006 | // OpenCL doesn't support variadic functions and blocks | ||||
5007 | // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. | ||||
5008 | // We also allow here any toolchain reserved identifiers. | ||||
5009 | if (FTI.isVariadic && | ||||
5010 | !(D.getIdentifier() && | ||||
5011 | ((D.getIdentifier()->getName() == "printf" && | ||||
5012 | (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) || | ||||
5013 | D.getIdentifier()->getName().startswith("__")))) { | ||||
5014 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); | ||||
5015 | D.setInvalidType(true); | ||||
5016 | } | ||||
5017 | } | ||||
5018 | |||||
5019 | // Methods cannot return interface types. All ObjC objects are | ||||
5020 | // passed by reference. | ||||
5021 | if (T->isObjCObjectType()) { | ||||
5022 | SourceLocation DiagLoc, FixitLoc; | ||||
5023 | if (TInfo) { | ||||
5024 | DiagLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||
5025 | FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); | ||||
5026 | } else { | ||||
5027 | DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); | ||||
5028 | FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); | ||||
5029 | } | ||||
5030 | S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) | ||||
5031 | << 0 << T | ||||
5032 | << FixItHint::CreateInsertion(FixitLoc, "*"); | ||||
5033 | |||||
5034 | T = Context.getObjCObjectPointerType(T); | ||||
5035 | if (TInfo) { | ||||
5036 | TypeLocBuilder TLB; | ||||
5037 | TLB.pushFullCopy(TInfo->getTypeLoc()); | ||||
5038 | ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); | ||||
5039 | TLoc.setStarLoc(FixitLoc); | ||||
5040 | TInfo = TLB.getTypeSourceInfo(Context, T); | ||||
5041 | } | ||||
5042 | |||||
5043 | D.setInvalidType(true); | ||||
5044 | } | ||||
5045 | |||||
5046 | // cv-qualifiers on return types are pointless except when the type is a | ||||
5047 | // class type in C++. | ||||
5048 | if ((T.getCVRQualifiers() || T->isAtomicType()) && | ||||
5049 | !(S.getLangOpts().CPlusPlus && | ||||
5050 | (T->isDependentType() || T->isRecordType()))) { | ||||
5051 | if (T->isVoidType() && !S.getLangOpts().CPlusPlus && | ||||
5052 | D.getFunctionDefinitionKind() == | ||||
5053 | FunctionDefinitionKind::Definition) { | ||||
5054 | // [6.9.1/3] qualified void return is invalid on a C | ||||
5055 | // function definition. Apparently ok on declarations and | ||||
5056 | // in C++ though (!) | ||||
5057 | S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; | ||||
5058 | } else | ||||
5059 | diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); | ||||
5060 | |||||
5061 | // C++2a [dcl.fct]p12: | ||||
5062 | // A volatile-qualified return type is deprecated | ||||
5063 | if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20) | ||||
5064 | S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T; | ||||
5065 | } | ||||
5066 | |||||
5067 | // Objective-C ARC ownership qualifiers are ignored on the function | ||||
5068 | // return type (by type canonicalization). Complain if this attribute | ||||
5069 | // was written here. | ||||
5070 | if (T.getQualifiers().hasObjCLifetime()) { | ||||
5071 | SourceLocation AttrLoc; | ||||
5072 | if (chunkIndex + 1 < D.getNumTypeObjects()) { | ||||
5073 | DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); | ||||
5074 | for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { | ||||
5075 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { | ||||
5076 | AttrLoc = AL.getLoc(); | ||||
5077 | break; | ||||
5078 | } | ||||
5079 | } | ||||
5080 | } | ||||
5081 | if (AttrLoc.isInvalid()) { | ||||
5082 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | ||||
5083 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { | ||||
5084 | AttrLoc = AL.getLoc(); | ||||
5085 | break; | ||||
5086 | } | ||||
5087 | } | ||||
5088 | } | ||||
5089 | |||||
5090 | if (AttrLoc.isValid()) { | ||||
5091 | // The ownership attributes are almost always written via | ||||
5092 | // the predefined | ||||
5093 | // __strong/__weak/__autoreleasing/__unsafe_unretained. | ||||
5094 | if (AttrLoc.isMacroID()) | ||||
5095 | AttrLoc = | ||||
5096 | S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); | ||||
5097 | |||||
5098 | S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) | ||||
5099 | << T.getQualifiers().getObjCLifetime(); | ||||
5100 | } | ||||
5101 | } | ||||
5102 | |||||
5103 | if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { | ||||
5104 | // C++ [dcl.fct]p6: | ||||
5105 | // Types shall not be defined in return or parameter types. | ||||
5106 | TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | ||||
5107 | S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) | ||||
5108 | << Context.getTypeDeclType(Tag); | ||||
5109 | } | ||||
5110 | |||||
5111 | // Exception specs are not allowed in typedefs. Complain, but add it | ||||
5112 | // anyway. | ||||
5113 | if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) | ||||
5114 | S.Diag(FTI.getExceptionSpecLocBeg(), | ||||
5115 | diag::err_exception_spec_in_typedef) | ||||
5116 | << (D.getContext() == DeclaratorContext::AliasDecl || | ||||
5117 | D.getContext() == DeclaratorContext::AliasTemplate); | ||||
5118 | |||||
5119 | // If we see "T var();" or "T var(T());" at block scope, it is probably | ||||
5120 | // an attempt to initialize a variable, not a function declaration. | ||||
5121 | if (FTI.isAmbiguous) | ||||
5122 | warnAboutAmbiguousFunction(S, D, DeclType, T); | ||||
5123 | |||||
5124 | FunctionType::ExtInfo EI( | ||||
5125 | getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); | ||||
5126 | |||||
5127 | if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus | ||||
5128 | && !LangOpts.OpenCL) { | ||||
5129 | // Simple void foo(), where the incoming T is the result type. | ||||
5130 | T = Context.getFunctionNoProtoType(T, EI); | ||||
5131 | } else { | ||||
5132 | // We allow a zero-parameter variadic function in C if the | ||||
5133 | // function is marked with the "overloadable" attribute. Scan | ||||
5134 | // for this attribute now. | ||||
5135 | if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) | ||||
5136 | if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable)) | ||||
5137 | S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); | ||||
5138 | |||||
5139 | if (FTI.NumParams && FTI.Params[0].Param == nullptr) { | ||||
5140 | // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function | ||||
5141 | // definition. | ||||
5142 | S.Diag(FTI.Params[0].IdentLoc, | ||||
5143 | diag::err_ident_list_in_fn_declaration); | ||||
5144 | D.setInvalidType(true); | ||||
5145 | // Recover by creating a K&R-style function type. | ||||
5146 | T = Context.getFunctionNoProtoType(T, EI); | ||||
5147 | break; | ||||
5148 | } | ||||
5149 | |||||
5150 | FunctionProtoType::ExtProtoInfo EPI; | ||||
5151 | EPI.ExtInfo = EI; | ||||
5152 | EPI.Variadic = FTI.isVariadic; | ||||
5153 | EPI.EllipsisLoc = FTI.getEllipsisLoc(); | ||||
5154 | EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); | ||||
5155 | EPI.TypeQuals.addCVRUQualifiers( | ||||
5156 | FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() | ||||
5157 | : 0); | ||||
5158 | EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None | ||||
5159 | : FTI.RefQualifierIsLValueRef? RQ_LValue | ||||
5160 | : RQ_RValue; | ||||
5161 | |||||
5162 | // Otherwise, we have a function with a parameter list that is | ||||
5163 | // potentially variadic. | ||||
5164 | SmallVector<QualType, 16> ParamTys; | ||||
5165 | ParamTys.reserve(FTI.NumParams); | ||||
5166 | |||||
5167 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> | ||||
5168 | ExtParameterInfos(FTI.NumParams); | ||||
5169 | bool HasAnyInterestingExtParameterInfos = false; | ||||
5170 | |||||
5171 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | ||||
5172 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | ||||
5173 | QualType ParamTy = Param->getType(); | ||||
5174 | assert(!ParamTy.isNull() && "Couldn't parse type?")((!ParamTy.isNull() && "Couldn't parse type?") ? static_cast <void> (0) : __assert_fail ("!ParamTy.isNull() && \"Couldn't parse type?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5174, __PRETTY_FUNCTION__)); | ||||
5175 | |||||
5176 | // Look for 'void'. void is allowed only as a single parameter to a | ||||
5177 | // function with no other parameters (C99 6.7.5.3p10). We record | ||||
5178 | // int(void) as a FunctionProtoType with an empty parameter list. | ||||
5179 | if (ParamTy->isVoidType()) { | ||||
5180 | // If this is something like 'float(int, void)', reject it. 'void' | ||||
5181 | // is an incomplete type (C99 6.2.5p19) and function decls cannot | ||||
5182 | // have parameters of incomplete type. | ||||
5183 | if (FTI.NumParams != 1 || FTI.isVariadic) { | ||||
5184 | S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param); | ||||
5185 | ParamTy = Context.IntTy; | ||||
5186 | Param->setType(ParamTy); | ||||
5187 | } else if (FTI.Params[i].Ident) { | ||||
5188 | // Reject, but continue to parse 'int(void abc)'. | ||||
5189 | S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); | ||||
5190 | ParamTy = Context.IntTy; | ||||
5191 | Param->setType(ParamTy); | ||||
5192 | } else { | ||||
5193 | // Reject, but continue to parse 'float(const void)'. | ||||
5194 | if (ParamTy.hasQualifiers()) | ||||
5195 | S.Diag(DeclType.Loc, diag::err_void_param_qualified); | ||||
5196 | |||||
5197 | // Do not add 'void' to the list. | ||||
5198 | break; | ||||
5199 | } | ||||
5200 | } else if (ParamTy->isHalfType()) { | ||||
5201 | // Disallow half FP parameters. | ||||
5202 | // FIXME: This really should be in BuildFunctionType. | ||||
5203 | if (S.getLangOpts().OpenCL) { | ||||
5204 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | ||||
5205 | S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) | ||||
5206 | << ParamTy << 0; | ||||
5207 | D.setInvalidType(); | ||||
5208 | Param->setInvalidDecl(); | ||||
5209 | } | ||||
5210 | } else if (!S.getLangOpts().HalfArgsAndReturns) { | ||||
5211 | S.Diag(Param->getLocation(), | ||||
5212 | diag::err_parameters_retval_cannot_have_fp16_type) << 0; | ||||
5213 | D.setInvalidType(); | ||||
5214 | } | ||||
5215 | } else if (!FTI.hasPrototype) { | ||||
5216 | if (ParamTy->isPromotableIntegerType()) { | ||||
5217 | ParamTy = Context.getPromotedIntegerType(ParamTy); | ||||
5218 | Param->setKNRPromoted(true); | ||||
5219 | } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { | ||||
5220 | if (BTy->getKind() == BuiltinType::Float) { | ||||
5221 | ParamTy = Context.DoubleTy; | ||||
5222 | Param->setKNRPromoted(true); | ||||
5223 | } | ||||
5224 | } | ||||
5225 | } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) { | ||||
5226 | // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function. | ||||
5227 | S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) | ||||
5228 | << ParamTy << 1 /*hint off*/; | ||||
5229 | D.setInvalidType(); | ||||
5230 | } | ||||
5231 | |||||
5232 | if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { | ||||
5233 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); | ||||
5234 | HasAnyInterestingExtParameterInfos = true; | ||||
5235 | } | ||||
5236 | |||||
5237 | if (auto attr = Param->getAttr<ParameterABIAttr>()) { | ||||
5238 | ExtParameterInfos[i] = | ||||
5239 | ExtParameterInfos[i].withABI(attr->getABI()); | ||||
5240 | HasAnyInterestingExtParameterInfos = true; | ||||
5241 | } | ||||
5242 | |||||
5243 | if (Param->hasAttr<PassObjectSizeAttr>()) { | ||||
5244 | ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); | ||||
5245 | HasAnyInterestingExtParameterInfos = true; | ||||
5246 | } | ||||
5247 | |||||
5248 | if (Param->hasAttr<NoEscapeAttr>()) { | ||||
5249 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); | ||||
5250 | HasAnyInterestingExtParameterInfos = true; | ||||
5251 | } | ||||
5252 | |||||
5253 | ParamTys.push_back(ParamTy); | ||||
5254 | } | ||||
5255 | |||||
5256 | if (HasAnyInterestingExtParameterInfos) { | ||||
5257 | EPI.ExtParameterInfos = ExtParameterInfos.data(); | ||||
5258 | checkExtParameterInfos(S, ParamTys, EPI, | ||||
5259 | [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); | ||||
5260 | } | ||||
5261 | |||||
5262 | SmallVector<QualType, 4> Exceptions; | ||||
5263 | SmallVector<ParsedType, 2> DynamicExceptions; | ||||
5264 | SmallVector<SourceRange, 2> DynamicExceptionRanges; | ||||
5265 | Expr *NoexceptExpr = nullptr; | ||||
5266 | |||||
5267 | if (FTI.getExceptionSpecType() == EST_Dynamic) { | ||||
5268 | // FIXME: It's rather inefficient to have to split into two vectors | ||||
5269 | // here. | ||||
5270 | unsigned N = FTI.getNumExceptions(); | ||||
5271 | DynamicExceptions.reserve(N); | ||||
5272 | DynamicExceptionRanges.reserve(N); | ||||
5273 | for (unsigned I = 0; I != N; ++I) { | ||||
5274 | DynamicExceptions.push_back(FTI.Exceptions[I].Ty); | ||||
5275 | DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); | ||||
5276 | } | ||||
5277 | } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { | ||||
5278 | NoexceptExpr = FTI.NoexceptExpr; | ||||
5279 | } | ||||
5280 | |||||
5281 | S.checkExceptionSpecification(D.isFunctionDeclarationContext(), | ||||
5282 | FTI.getExceptionSpecType(), | ||||
5283 | DynamicExceptions, | ||||
5284 | DynamicExceptionRanges, | ||||
5285 | NoexceptExpr, | ||||
5286 | Exceptions, | ||||
5287 | EPI.ExceptionSpec); | ||||
5288 | |||||
5289 | // FIXME: Set address space from attrs for C++ mode here. | ||||
5290 | // OpenCLCPlusPlus: A class member function has an address space. | ||||
5291 | auto IsClassMember = [&]() { | ||||
5292 | return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && | ||||
5293 | state.getDeclarator() | ||||
5294 | .getCXXScopeSpec() | ||||
5295 | .getScopeRep() | ||||
5296 | ->getKind() == NestedNameSpecifier::TypeSpec) || | ||||
5297 | state.getDeclarator().getContext() == | ||||
5298 | DeclaratorContext::Member || | ||||
5299 | state.getDeclarator().getContext() == | ||||
5300 | DeclaratorContext::LambdaExpr; | ||||
5301 | }; | ||||
5302 | |||||
5303 | if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { | ||||
5304 | LangAS ASIdx = LangAS::Default; | ||||
5305 | // Take address space attr if any and mark as invalid to avoid adding | ||||
5306 | // them later while creating QualType. | ||||
5307 | if (FTI.MethodQualifiers) | ||||
5308 | for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { | ||||
5309 | LangAS ASIdxNew = attr.asOpenCLLangAS(); | ||||
5310 | if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, | ||||
5311 | attr.getLoc())) | ||||
5312 | D.setInvalidType(true); | ||||
5313 | else | ||||
5314 | ASIdx = ASIdxNew; | ||||
5315 | } | ||||
5316 | // If a class member function's address space is not set, set it to | ||||
5317 | // __generic. | ||||
5318 | LangAS AS = | ||||
5319 | (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace() | ||||
5320 | : ASIdx); | ||||
5321 | EPI.TypeQuals.addAddressSpace(AS); | ||||
5322 | } | ||||
5323 | T = Context.getFunctionType(T, ParamTys, EPI); | ||||
5324 | } | ||||
5325 | break; | ||||
5326 | } | ||||
5327 | case DeclaratorChunk::MemberPointer: { | ||||
5328 | // The scope spec must refer to a class, or be dependent. | ||||
5329 | CXXScopeSpec &SS = DeclType.Mem.Scope(); | ||||
5330 | QualType ClsType; | ||||
5331 | |||||
5332 | // Handle pointer nullability. | ||||
5333 | inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, | ||||
5334 | DeclType.EndLoc, DeclType.getAttrs(), | ||||
5335 | state.getDeclarator().getAttributePool()); | ||||
5336 | |||||
5337 | if (SS.isInvalid()) { | ||||
5338 | // Avoid emitting extra errors if we already errored on the scope. | ||||
5339 | D.setInvalidType(true); | ||||
5340 | } else if (S.isDependentScopeSpecifier(SS) || | ||||
5341 | dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { | ||||
5342 | NestedNameSpecifier *NNS = SS.getScopeRep(); | ||||
5343 | NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); | ||||
5344 | switch (NNS->getKind()) { | ||||
5345 | case NestedNameSpecifier::Identifier: | ||||
5346 | ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, | ||||
5347 | NNS->getAsIdentifier()); | ||||
5348 | break; | ||||
5349 | |||||
5350 | case NestedNameSpecifier::Namespace: | ||||
5351 | case NestedNameSpecifier::NamespaceAlias: | ||||
5352 | case NestedNameSpecifier::Global: | ||||
5353 | case NestedNameSpecifier::Super: | ||||
5354 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5354); | ||||
5355 | |||||
5356 | case NestedNameSpecifier::TypeSpec: | ||||
5357 | case NestedNameSpecifier::TypeSpecWithTemplate: | ||||
5358 | ClsType = QualType(NNS->getAsType(), 0); | ||||
5359 | // Note: if the NNS has a prefix and ClsType is a nondependent | ||||
5360 | // TemplateSpecializationType, then the NNS prefix is NOT included | ||||
5361 | // in ClsType; hence we wrap ClsType into an ElaboratedType. | ||||
5362 | // NOTE: in particular, no wrap occurs if ClsType already is an | ||||
5363 | // Elaborated, DependentName, or DependentTemplateSpecialization. | ||||
5364 | if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) | ||||
5365 | ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); | ||||
5366 | break; | ||||
5367 | } | ||||
5368 | } else { | ||||
5369 | S.Diag(DeclType.Mem.Scope().getBeginLoc(), | ||||
5370 | diag::err_illegal_decl_mempointer_in_nonclass) | ||||
5371 | << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") | ||||
5372 | << DeclType.Mem.Scope().getRange(); | ||||
5373 | D.setInvalidType(true); | ||||
5374 | } | ||||
5375 | |||||
5376 | if (!ClsType.isNull()) | ||||
5377 | T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, | ||||
5378 | D.getIdentifier()); | ||||
5379 | if (T.isNull()) { | ||||
5380 | T = Context.IntTy; | ||||
5381 | D.setInvalidType(true); | ||||
5382 | } else if (DeclType.Mem.TypeQuals) { | ||||
5383 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); | ||||
5384 | } | ||||
5385 | break; | ||||
5386 | } | ||||
5387 | |||||
5388 | case DeclaratorChunk::Pipe: { | ||||
5389 | T = S.BuildReadPipeType(T, DeclType.Loc); | ||||
5390 | processTypeAttrs(state, T, TAL_DeclSpec, | ||||
5391 | D.getMutableDeclSpec().getAttributes()); | ||||
5392 | break; | ||||
5393 | } | ||||
5394 | } | ||||
5395 | |||||
5396 | if (T.isNull()) { | ||||
5397 | D.setInvalidType(true); | ||||
5398 | T = Context.IntTy; | ||||
5399 | } | ||||
5400 | |||||
5401 | // See if there are any attributes on this declarator chunk. | ||||
5402 | processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); | ||||
5403 | |||||
5404 | if (DeclType.Kind != DeclaratorChunk::Paren) { | ||||
5405 | if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) | ||||
5406 | S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); | ||||
5407 | |||||
5408 | ExpectNoDerefChunk = state.didParseNoDeref(); | ||||
5409 | } | ||||
5410 | } | ||||
5411 | |||||
5412 | if (ExpectNoDerefChunk) | ||||
5413 | S.Diag(state.getDeclarator().getBeginLoc(), | ||||
5414 | diag::warn_noderef_on_non_pointer_or_array); | ||||
5415 | |||||
5416 | // GNU warning -Wstrict-prototypes | ||||
5417 | // Warn if a function declaration is without a prototype. | ||||
5418 | // This warning is issued for all kinds of unprototyped function | ||||
5419 | // declarations (i.e. function type typedef, function pointer etc.) | ||||
5420 | // C99 6.7.5.3p14: | ||||
5421 | // The empty list in a function declarator that is not part of a definition | ||||
5422 | // of that function specifies that no information about the number or types | ||||
5423 | // of the parameters is supplied. | ||||
5424 | if (!LangOpts.CPlusPlus && | ||||
5425 | D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration) { | ||||
5426 | bool IsBlock = false; | ||||
5427 | for (const DeclaratorChunk &DeclType : D.type_objects()) { | ||||
5428 | switch (DeclType.Kind) { | ||||
5429 | case DeclaratorChunk::BlockPointer: | ||||
5430 | IsBlock = true; | ||||
5431 | break; | ||||
5432 | case DeclaratorChunk::Function: { | ||||
5433 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | ||||
5434 | // We supress the warning when there's no LParen location, as this | ||||
5435 | // indicates the declaration was an implicit declaration, which gets | ||||
5436 | // warned about separately via -Wimplicit-function-declaration. | ||||
5437 | if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid()) | ||||
5438 | S.Diag(DeclType.Loc, diag::warn_strict_prototypes) | ||||
5439 | << IsBlock | ||||
5440 | << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); | ||||
5441 | IsBlock = false; | ||||
5442 | break; | ||||
5443 | } | ||||
5444 | default: | ||||
5445 | break; | ||||
5446 | } | ||||
5447 | } | ||||
5448 | } | ||||
5449 | |||||
5450 | assert(!T.isNull() && "T must not be null after this point")((!T.isNull() && "T must not be null after this point" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"T must not be null after this point\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5450, __PRETTY_FUNCTION__)); | ||||
5451 | |||||
5452 | if (LangOpts.CPlusPlus && T->isFunctionType()) { | ||||
5453 | const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); | ||||
5454 | assert(FnTy && "Why oh why is there not a FunctionProtoType here?")((FnTy && "Why oh why is there not a FunctionProtoType here?" ) ? static_cast<void> (0) : __assert_fail ("FnTy && \"Why oh why is there not a FunctionProtoType here?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5454, __PRETTY_FUNCTION__)); | ||||
5455 | |||||
5456 | // C++ 8.3.5p4: | ||||
5457 | // A cv-qualifier-seq shall only be part of the function type | ||||
5458 | // for a nonstatic member function, the function type to which a pointer | ||||
5459 | // to member refers, or the top-level function type of a function typedef | ||||
5460 | // declaration. | ||||
5461 | // | ||||
5462 | // Core issue 547 also allows cv-qualifiers on function types that are | ||||
5463 | // top-level template type arguments. | ||||
5464 | enum { NonMember, Member, DeductionGuide } Kind = NonMember; | ||||
5465 | if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) | ||||
5466 | Kind = DeductionGuide; | ||||
5467 | else if (!D.getCXXScopeSpec().isSet()) { | ||||
5468 | if ((D.getContext() == DeclaratorContext::Member || | ||||
5469 | D.getContext() == DeclaratorContext::LambdaExpr) && | ||||
5470 | !D.getDeclSpec().isFriendSpecified()) | ||||
5471 | Kind = Member; | ||||
5472 | } else { | ||||
5473 | DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); | ||||
5474 | if (!DC || DC->isRecord()) | ||||
5475 | Kind = Member; | ||||
5476 | } | ||||
5477 | |||||
5478 | // C++11 [dcl.fct]p6 (w/DR1417): | ||||
5479 | // An attempt to specify a function type with a cv-qualifier-seq or a | ||||
5480 | // ref-qualifier (including by typedef-name) is ill-formed unless it is: | ||||
5481 | // - the function type for a non-static member function, | ||||
5482 | // - the function type to which a pointer to member refers, | ||||
5483 | // - the top-level function type of a function typedef declaration or | ||||
5484 | // alias-declaration, | ||||
5485 | // - the type-id in the default argument of a type-parameter, or | ||||
5486 | // - the type-id of a template-argument for a type-parameter | ||||
5487 | // | ||||
5488 | // FIXME: Checking this here is insufficient. We accept-invalid on: | ||||
5489 | // | ||||
5490 | // template<typename T> struct S { void f(T); }; | ||||
5491 | // S<int() const> s; | ||||
5492 | // | ||||
5493 | // ... for instance. | ||||
5494 | if (IsQualifiedFunction && | ||||
5495 | !(Kind == Member && | ||||
5496 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && | ||||
5497 | !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg && | ||||
5498 | D.getContext() != DeclaratorContext::TemplateTypeArg) { | ||||
5499 | SourceLocation Loc = D.getBeginLoc(); | ||||
5500 | SourceRange RemovalRange; | ||||
5501 | unsigned I; | ||||
5502 | if (D.isFunctionDeclarator(I)) { | ||||
5503 | SmallVector<SourceLocation, 4> RemovalLocs; | ||||
5504 | const DeclaratorChunk &Chunk = D.getTypeObject(I); | ||||
5505 | assert(Chunk.Kind == DeclaratorChunk::Function)((Chunk.Kind == DeclaratorChunk::Function) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5505, __PRETTY_FUNCTION__)); | ||||
5506 | |||||
5507 | if (Chunk.Fun.hasRefQualifier()) | ||||
5508 | RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); | ||||
5509 | |||||
5510 | if (Chunk.Fun.hasMethodTypeQualifiers()) | ||||
5511 | Chunk.Fun.MethodQualifiers->forEachQualifier( | ||||
5512 | [&](DeclSpec::TQ TypeQual, StringRef QualName, | ||||
5513 | SourceLocation SL) { RemovalLocs.push_back(SL); }); | ||||
5514 | |||||
5515 | if (!RemovalLocs.empty()) { | ||||
5516 | llvm::sort(RemovalLocs, | ||||
5517 | BeforeThanCompare<SourceLocation>(S.getSourceManager())); | ||||
5518 | RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); | ||||
5519 | Loc = RemovalLocs.front(); | ||||
5520 | } | ||||
5521 | } | ||||
5522 | |||||
5523 | S.Diag(Loc, diag::err_invalid_qualified_function_type) | ||||
5524 | << Kind << D.isFunctionDeclarator() << T | ||||
5525 | << getFunctionQualifiersAsString(FnTy) | ||||
5526 | << FixItHint::CreateRemoval(RemovalRange); | ||||
5527 | |||||
5528 | // Strip the cv-qualifiers and ref-qualifiers from the type. | ||||
5529 | FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); | ||||
5530 | EPI.TypeQuals.removeCVRQualifiers(); | ||||
5531 | EPI.RefQualifier = RQ_None; | ||||
5532 | |||||
5533 | T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), | ||||
5534 | EPI); | ||||
5535 | // Rebuild any parens around the identifier in the function type. | ||||
5536 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | ||||
5537 | if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) | ||||
5538 | break; | ||||
5539 | T = S.BuildParenType(T); | ||||
5540 | } | ||||
5541 | } | ||||
5542 | } | ||||
5543 | |||||
5544 | // Apply any undistributed attributes from the declarator. | ||||
5545 | processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); | ||||
5546 | |||||
5547 | // Diagnose any ignored type attributes. | ||||
5548 | state.diagnoseIgnoredTypeAttrs(T); | ||||
5549 | |||||
5550 | // C++0x [dcl.constexpr]p9: | ||||
5551 | // A constexpr specifier used in an object declaration declares the object | ||||
5552 | // as const. | ||||
5553 | if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr && | ||||
5554 | T->isObjectType()) | ||||
5555 | T.addConst(); | ||||
5556 | |||||
5557 | // C++2a [dcl.fct]p4: | ||||
5558 | // A parameter with volatile-qualified type is deprecated | ||||
5559 | if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 && | ||||
5560 | (D.getContext() == DeclaratorContext::Prototype || | ||||
5561 | D.getContext() == DeclaratorContext::LambdaExprParameter)) | ||||
5562 | S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; | ||||
5563 | |||||
5564 | // If there was an ellipsis in the declarator, the declaration declares a | ||||
5565 | // parameter pack whose type may be a pack expansion type. | ||||
5566 | if (D.hasEllipsis()) { | ||||
5567 | // C++0x [dcl.fct]p13: | ||||
5568 | // A declarator-id or abstract-declarator containing an ellipsis shall | ||||
5569 | // only be used in a parameter-declaration. Such a parameter-declaration | ||||
5570 | // is a parameter pack (14.5.3). [...] | ||||
5571 | switch (D.getContext()) { | ||||
5572 | case DeclaratorContext::Prototype: | ||||
5573 | case DeclaratorContext::LambdaExprParameter: | ||||
5574 | case DeclaratorContext::RequiresExpr: | ||||
5575 | // C++0x [dcl.fct]p13: | ||||
5576 | // [...] When it is part of a parameter-declaration-clause, the | ||||
5577 | // parameter pack is a function parameter pack (14.5.3). The type T | ||||
5578 | // of the declarator-id of the function parameter pack shall contain | ||||
5579 | // a template parameter pack; each template parameter pack in T is | ||||
5580 | // expanded by the function parameter pack. | ||||
5581 | // | ||||
5582 | // We represent function parameter packs as function parameters whose | ||||
5583 | // type is a pack expansion. | ||||
5584 | if (!T->containsUnexpandedParameterPack() && | ||||
5585 | (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) { | ||||
5586 | S.Diag(D.getEllipsisLoc(), | ||||
5587 | diag::err_function_parameter_pack_without_parameter_packs) | ||||
5588 | << T << D.getSourceRange(); | ||||
5589 | D.setEllipsisLoc(SourceLocation()); | ||||
5590 | } else { | ||||
5591 | T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false); | ||||
5592 | } | ||||
5593 | break; | ||||
5594 | case DeclaratorContext::TemplateParam: | ||||
5595 | // C++0x [temp.param]p15: | ||||
5596 | // If a template-parameter is a [...] is a parameter-declaration that | ||||
5597 | // declares a parameter pack (8.3.5), then the template-parameter is a | ||||
5598 | // template parameter pack (14.5.3). | ||||
5599 | // | ||||
5600 | // Note: core issue 778 clarifies that, if there are any unexpanded | ||||
5601 | // parameter packs in the type of the non-type template parameter, then | ||||
5602 | // it expands those parameter packs. | ||||
5603 | if (T->containsUnexpandedParameterPack()) | ||||
5604 | T = Context.getPackExpansionType(T, None); | ||||
5605 | else | ||||
5606 | S.Diag(D.getEllipsisLoc(), | ||||
5607 | LangOpts.CPlusPlus11 | ||||
5608 | ? diag::warn_cxx98_compat_variadic_templates | ||||
5609 | : diag::ext_variadic_templates); | ||||
5610 | break; | ||||
5611 | |||||
5612 | case DeclaratorContext::File: | ||||
5613 | case DeclaratorContext::KNRTypeList: | ||||
5614 | case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here? | ||||
5615 | case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here? | ||||
5616 | case DeclaratorContext::TypeName: | ||||
5617 | case DeclaratorContext::FunctionalCast: | ||||
5618 | case DeclaratorContext::CXXNew: | ||||
5619 | case DeclaratorContext::AliasDecl: | ||||
5620 | case DeclaratorContext::AliasTemplate: | ||||
5621 | case DeclaratorContext::Member: | ||||
5622 | case DeclaratorContext::Block: | ||||
5623 | case DeclaratorContext::ForInit: | ||||
5624 | case DeclaratorContext::SelectionInit: | ||||
5625 | case DeclaratorContext::Condition: | ||||
5626 | case DeclaratorContext::CXXCatch: | ||||
5627 | case DeclaratorContext::ObjCCatch: | ||||
5628 | case DeclaratorContext::BlockLiteral: | ||||
5629 | case DeclaratorContext::LambdaExpr: | ||||
5630 | case DeclaratorContext::ConversionId: | ||||
5631 | case DeclaratorContext::TrailingReturn: | ||||
5632 | case DeclaratorContext::TrailingReturnVar: | ||||
5633 | case DeclaratorContext::TemplateArg: | ||||
5634 | case DeclaratorContext::TemplateTypeArg: | ||||
5635 | // FIXME: We may want to allow parameter packs in block-literal contexts | ||||
5636 | // in the future. | ||||
5637 | S.Diag(D.getEllipsisLoc(), | ||||
5638 | diag::err_ellipsis_in_declarator_not_parameter); | ||||
5639 | D.setEllipsisLoc(SourceLocation()); | ||||
5640 | break; | ||||
5641 | } | ||||
5642 | } | ||||
5643 | |||||
5644 | assert(!T.isNull() && "T must not be null at the end of this function")((!T.isNull() && "T must not be null at the end of this function" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"T must not be null at the end of this function\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5644, __PRETTY_FUNCTION__)); | ||||
5645 | if (D.isInvalidType()) | ||||
5646 | return Context.getTrivialTypeSourceInfo(T); | ||||
5647 | |||||
5648 | return GetTypeSourceInfoForDeclarator(state, T, TInfo); | ||||
5649 | } | ||||
5650 | |||||
5651 | /// GetTypeForDeclarator - Convert the type for the specified | ||||
5652 | /// declarator to Type instances. | ||||
5653 | /// | ||||
5654 | /// The result of this call will never be null, but the associated | ||||
5655 | /// type may be a null type if there's an unrecoverable error. | ||||
5656 | TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { | ||||
5657 | // Determine the type of the declarator. Not all forms of declarator | ||||
5658 | // have a type. | ||||
5659 | |||||
5660 | TypeProcessingState state(*this, D); | ||||
5661 | |||||
5662 | TypeSourceInfo *ReturnTypeInfo = nullptr; | ||||
5663 | QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | ||||
5664 | if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) | ||||
5665 | inferARCWriteback(state, T); | ||||
5666 | |||||
5667 | return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); | ||||
5668 | } | ||||
5669 | |||||
5670 | static void transferARCOwnershipToDeclSpec(Sema &S, | ||||
5671 | QualType &declSpecTy, | ||||
5672 | Qualifiers::ObjCLifetime ownership) { | ||||
5673 | if (declSpecTy->isObjCRetainableType() && | ||||
5674 | declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { | ||||
5675 | Qualifiers qs; | ||||
5676 | qs.addObjCLifetime(ownership); | ||||
5677 | declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); | ||||
5678 | } | ||||
5679 | } | ||||
5680 | |||||
5681 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | ||||
5682 | Qualifiers::ObjCLifetime ownership, | ||||
5683 | unsigned chunkIndex) { | ||||
5684 | Sema &S = state.getSema(); | ||||
5685 | Declarator &D = state.getDeclarator(); | ||||
5686 | |||||
5687 | // Look for an explicit lifetime attribute. | ||||
5688 | DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); | ||||
5689 | if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) | ||||
5690 | return; | ||||
5691 | |||||
5692 | const char *attrStr = nullptr; | ||||
5693 | switch (ownership) { | ||||
5694 | case Qualifiers::OCL_None: llvm_unreachable("no ownership!")::llvm::llvm_unreachable_internal("no ownership!", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5694); | ||||
5695 | case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; | ||||
5696 | case Qualifiers::OCL_Strong: attrStr = "strong"; break; | ||||
5697 | case Qualifiers::OCL_Weak: attrStr = "weak"; break; | ||||
5698 | case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; | ||||
5699 | } | ||||
5700 | |||||
5701 | IdentifierLoc *Arg = new (S.Context) IdentifierLoc; | ||||
5702 | Arg->Ident = &S.Context.Idents.get(attrStr); | ||||
5703 | Arg->Loc = SourceLocation(); | ||||
5704 | |||||
5705 | ArgsUnion Args(Arg); | ||||
5706 | |||||
5707 | // If there wasn't one, add one (with an invalid source location | ||||
5708 | // so that we don't make an AttributedType for it). | ||||
5709 | ParsedAttr *attr = D.getAttributePool().create( | ||||
5710 | &S.Context.Idents.get("objc_ownership"), SourceLocation(), | ||||
5711 | /*scope*/ nullptr, SourceLocation(), | ||||
5712 | /*args*/ &Args, 1, ParsedAttr::AS_GNU); | ||||
5713 | chunk.getAttrs().addAtEnd(attr); | ||||
5714 | // TODO: mark whether we did this inference? | ||||
5715 | } | ||||
5716 | |||||
5717 | /// Used for transferring ownership in casts resulting in l-values. | ||||
5718 | static void transferARCOwnership(TypeProcessingState &state, | ||||
5719 | QualType &declSpecTy, | ||||
5720 | Qualifiers::ObjCLifetime ownership) { | ||||
5721 | Sema &S = state.getSema(); | ||||
5722 | Declarator &D = state.getDeclarator(); | ||||
5723 | |||||
5724 | int inner = -1; | ||||
5725 | bool hasIndirection = false; | ||||
5726 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | ||||
5727 | DeclaratorChunk &chunk = D.getTypeObject(i); | ||||
5728 | switch (chunk.Kind) { | ||||
5729 | case DeclaratorChunk::Paren: | ||||
5730 | // Ignore parens. | ||||
5731 | break; | ||||
5732 | |||||
5733 | case DeclaratorChunk::Array: | ||||
5734 | case DeclaratorChunk::Reference: | ||||
5735 | case DeclaratorChunk::Pointer: | ||||
5736 | if (inner != -1) | ||||
5737 | hasIndirection = true; | ||||
5738 | inner = i; | ||||
5739 | break; | ||||
5740 | |||||
5741 | case DeclaratorChunk::BlockPointer: | ||||
5742 | if (inner != -1) | ||||
5743 | transferARCOwnershipToDeclaratorChunk(state, ownership, i); | ||||
5744 | return; | ||||
5745 | |||||
5746 | case DeclaratorChunk::Function: | ||||
5747 | case DeclaratorChunk::MemberPointer: | ||||
5748 | case DeclaratorChunk::Pipe: | ||||
5749 | return; | ||||
5750 | } | ||||
5751 | } | ||||
5752 | |||||
5753 | if (inner == -1) | ||||
5754 | return; | ||||
5755 | |||||
5756 | DeclaratorChunk &chunk = D.getTypeObject(inner); | ||||
5757 | if (chunk.Kind == DeclaratorChunk::Pointer) { | ||||
5758 | if (declSpecTy->isObjCRetainableType()) | ||||
5759 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | ||||
5760 | if (declSpecTy->isObjCObjectType() && hasIndirection) | ||||
5761 | return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); | ||||
5762 | } else { | ||||
5763 | assert(chunk.Kind == DeclaratorChunk::Array ||((chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk ::Reference) ? static_cast<void> (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5764, __PRETTY_FUNCTION__)) | ||||
5764 | chunk.Kind == DeclaratorChunk::Reference)((chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk ::Reference) ? static_cast<void> (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5764, __PRETTY_FUNCTION__)); | ||||
5765 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | ||||
5766 | } | ||||
5767 | } | ||||
5768 | |||||
5769 | TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { | ||||
5770 | TypeProcessingState state(*this, D); | ||||
5771 | |||||
5772 | TypeSourceInfo *ReturnTypeInfo = nullptr; | ||||
5773 | QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | ||||
5774 | |||||
5775 | if (getLangOpts().ObjC) { | ||||
5776 | Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); | ||||
5777 | if (ownership != Qualifiers::OCL_None) | ||||
5778 | transferARCOwnership(state, declSpecTy, ownership); | ||||
5779 | } | ||||
5780 | |||||
5781 | return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); | ||||
5782 | } | ||||
5783 | |||||
5784 | static void fillAttributedTypeLoc(AttributedTypeLoc TL, | ||||
5785 | TypeProcessingState &State) { | ||||
5786 | TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); | ||||
5787 | } | ||||
5788 | |||||
5789 | namespace { | ||||
5790 | class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { | ||||
5791 | Sema &SemaRef; | ||||
5792 | ASTContext &Context; | ||||
5793 | TypeProcessingState &State; | ||||
5794 | const DeclSpec &DS; | ||||
5795 | |||||
5796 | public: | ||||
5797 | TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State, | ||||
5798 | const DeclSpec &DS) | ||||
5799 | : SemaRef(S), Context(Context), State(State), DS(DS) {} | ||||
5800 | |||||
5801 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | ||||
5802 | Visit(TL.getModifiedLoc()); | ||||
5803 | fillAttributedTypeLoc(TL, State); | ||||
5804 | } | ||||
5805 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { | ||||
5806 | Visit(TL.getInnerLoc()); | ||||
5807 | TL.setExpansionLoc( | ||||
5808 | State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); | ||||
5809 | } | ||||
5810 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | ||||
5811 | Visit(TL.getUnqualifiedLoc()); | ||||
5812 | } | ||||
5813 | void VisitTypedefTypeLoc(TypedefTypeLoc TL) { | ||||
5814 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | ||||
5815 | } | ||||
5816 | void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { | ||||
5817 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | ||||
5818 | // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires | ||||
5819 | // addition field. What we have is good enough for dispay of location | ||||
5820 | // of 'fixit' on interface name. | ||||
5821 | TL.setNameEndLoc(DS.getEndLoc()); | ||||
5822 | } | ||||
5823 | void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { | ||||
5824 | TypeSourceInfo *RepTInfo = nullptr; | ||||
5825 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | ||||
5826 | TL.copy(RepTInfo->getTypeLoc()); | ||||
5827 | } | ||||
5828 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | ||||
5829 | TypeSourceInfo *RepTInfo = nullptr; | ||||
5830 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | ||||
5831 | TL.copy(RepTInfo->getTypeLoc()); | ||||
5832 | } | ||||
5833 | void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { | ||||
5834 | TypeSourceInfo *TInfo = nullptr; | ||||
5835 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | ||||
5836 | |||||
5837 | // If we got no declarator info from previous Sema routines, | ||||
5838 | // just fill with the typespec loc. | ||||
5839 | if (!TInfo) { | ||||
5840 | TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); | ||||
5841 | return; | ||||
5842 | } | ||||
5843 | |||||
5844 | TypeLoc OldTL = TInfo->getTypeLoc(); | ||||
5845 | if (TInfo->getType()->getAs<ElaboratedType>()) { | ||||
5846 | ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); | ||||
5847 | TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() | ||||
5848 | .castAs<TemplateSpecializationTypeLoc>(); | ||||
5849 | TL.copy(NamedTL); | ||||
5850 | } else { | ||||
5851 | TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); | ||||
5852 | assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc())((TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc >().getRAngleLoc()) ? static_cast<void> (0) : __assert_fail ("TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5852, __PRETTY_FUNCTION__)); | ||||
5853 | } | ||||
5854 | |||||
5855 | } | ||||
5856 | void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { | ||||
5857 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr)((DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) ? static_cast <void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofExpr" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5857, __PRETTY_FUNCTION__)); | ||||
5858 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | ||||
5859 | TL.setParensRange(DS.getTypeofParensRange()); | ||||
5860 | } | ||||
5861 | void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { | ||||
5862 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType)((DS.getTypeSpecType() == DeclSpec::TST_typeofType) ? static_cast <void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofType" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5862, __PRETTY_FUNCTION__)); | ||||
5863 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | ||||
5864 | TL.setParensRange(DS.getTypeofParensRange()); | ||||
5865 | assert(DS.getRepAsType())((DS.getRepAsType()) ? static_cast<void> (0) : __assert_fail ("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5865, __PRETTY_FUNCTION__)); | ||||
5866 | TypeSourceInfo *TInfo = nullptr; | ||||
5867 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | ||||
5868 | TL.setUnderlyingTInfo(TInfo); | ||||
5869 | } | ||||
5870 | void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { | ||||
5871 | // FIXME: This holds only because we only have one unary transform. | ||||
5872 | assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType)((DS.getTypeSpecType() == DeclSpec::TST_underlyingType) ? static_cast <void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_underlyingType" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5872, __PRETTY_FUNCTION__)); | ||||
5873 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | ||||
5874 | TL.setParensRange(DS.getTypeofParensRange()); | ||||
5875 | assert(DS.getRepAsType())((DS.getRepAsType()) ? static_cast<void> (0) : __assert_fail ("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5875, __PRETTY_FUNCTION__)); | ||||
5876 | TypeSourceInfo *TInfo = nullptr; | ||||
5877 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | ||||
5878 | TL.setUnderlyingTInfo(TInfo); | ||||
5879 | } | ||||
5880 | void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { | ||||
5881 | // By default, use the source location of the type specifier. | ||||
5882 | TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); | ||||
5883 | if (TL.needsExtraLocalData()) { | ||||
5884 | // Set info for the written builtin specifiers. | ||||
5885 | TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); | ||||
5886 | // Try to have a meaningful source location. | ||||
5887 | if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified) | ||||
5888 | TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); | ||||
5889 | if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified) | ||||
5890 | TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); | ||||
5891 | } | ||||
5892 | } | ||||
5893 | void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { | ||||
5894 | ElaboratedTypeKeyword Keyword | ||||
5895 | = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); | ||||
5896 | if (DS.getTypeSpecType() == TST_typename) { | ||||
5897 | TypeSourceInfo *TInfo = nullptr; | ||||
5898 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | ||||
5899 | if (TInfo) { | ||||
5900 | TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); | ||||
5901 | return; | ||||
5902 | } | ||||
5903 | } | ||||
5904 | TL.setElaboratedKeywordLoc(Keyword != ETK_None | ||||
5905 | ? DS.getTypeSpecTypeLoc() | ||||
5906 | : SourceLocation()); | ||||
5907 | const CXXScopeSpec& SS = DS.getTypeSpecScope(); | ||||
5908 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
5909 | Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); | ||||
5910 | } | ||||
5911 | void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { | ||||
5912 | assert(DS.getTypeSpecType() == TST_typename)((DS.getTypeSpecType() == TST_typename) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5912, __PRETTY_FUNCTION__)); | ||||
5913 | TypeSourceInfo *TInfo = nullptr; | ||||
5914 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | ||||
5915 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5915, __PRETTY_FUNCTION__)); | ||||
5916 | TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); | ||||
5917 | } | ||||
5918 | void VisitDependentTemplateSpecializationTypeLoc( | ||||
5919 | DependentTemplateSpecializationTypeLoc TL) { | ||||
5920 | assert(DS.getTypeSpecType() == TST_typename)((DS.getTypeSpecType() == TST_typename) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5920, __PRETTY_FUNCTION__)); | ||||
5921 | TypeSourceInfo *TInfo = nullptr; | ||||
5922 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | ||||
5923 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5923, __PRETTY_FUNCTION__)); | ||||
5924 | TL.copy( | ||||
5925 | TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); | ||||
5926 | } | ||||
5927 | void VisitAutoTypeLoc(AutoTypeLoc TL) { | ||||
5928 | assert(DS.getTypeSpecType() == TST_auto ||((DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5931, __PRETTY_FUNCTION__)) | ||||
5929 | DS.getTypeSpecType() == TST_decltype_auto ||((DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5931, __PRETTY_FUNCTION__)) | ||||
5930 | DS.getTypeSpecType() == TST_auto_type ||((DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5931, __PRETTY_FUNCTION__)) | ||||
5931 | DS.getTypeSpecType() == TST_unspecified)((DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5931, __PRETTY_FUNCTION__)); | ||||
5932 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | ||||
5933 | if (!DS.isConstrainedAuto()) | ||||
5934 | return; | ||||
5935 | TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); | ||||
5936 | if (DS.getTypeSpecScope().isNotEmpty()) | ||||
5937 | TL.setNestedNameSpecifierLoc( | ||||
5938 | DS.getTypeSpecScope().getWithLocInContext(Context)); | ||||
5939 | else | ||||
5940 | TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc()); | ||||
5941 | TL.setTemplateKWLoc(TemplateId->TemplateKWLoc); | ||||
5942 | TL.setConceptNameLoc(TemplateId->TemplateNameLoc); | ||||
5943 | TL.setFoundDecl(nullptr); | ||||
5944 | TL.setLAngleLoc(TemplateId->LAngleLoc); | ||||
5945 | TL.setRAngleLoc(TemplateId->RAngleLoc); | ||||
5946 | if (TemplateId->NumArgs == 0) | ||||
5947 | return; | ||||
5948 | TemplateArgumentListInfo TemplateArgsInfo; | ||||
5949 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | ||||
5950 | TemplateId->NumArgs); | ||||
5951 | SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | ||||
5952 | for (unsigned I = 0; I < TemplateId->NumArgs; ++I) | ||||
5953 | TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo()); | ||||
5954 | } | ||||
5955 | void VisitTagTypeLoc(TagTypeLoc TL) { | ||||
5956 | TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); | ||||
5957 | } | ||||
5958 | void VisitAtomicTypeLoc(AtomicTypeLoc TL) { | ||||
5959 | // An AtomicTypeLoc can come from either an _Atomic(...) type specifier | ||||
5960 | // or an _Atomic qualifier. | ||||
5961 | if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { | ||||
5962 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | ||||
5963 | TL.setParensRange(DS.getTypeofParensRange()); | ||||
5964 | |||||
5965 | TypeSourceInfo *TInfo = nullptr; | ||||
5966 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | ||||
5967 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 5967, __PRETTY_FUNCTION__)); | ||||
5968 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | ||||
5969 | } else { | ||||
5970 | TL.setKWLoc(DS.getAtomicSpecLoc()); | ||||
5971 | // No parens, to indicate this was spelled as an _Atomic qualifier. | ||||
5972 | TL.setParensRange(SourceRange()); | ||||
5973 | Visit(TL.getValueLoc()); | ||||
5974 | } | ||||
5975 | } | ||||
5976 | |||||
5977 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | ||||
5978 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | ||||
5979 | |||||
5980 | TypeSourceInfo *TInfo = nullptr; | ||||
5981 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | ||||
5982 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | ||||
5983 | } | ||||
5984 | |||||
5985 | void VisitExtIntTypeLoc(ExtIntTypeLoc TL) { | ||||
5986 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | ||||
5987 | } | ||||
5988 | |||||
5989 | void VisitDependentExtIntTypeLoc(DependentExtIntTypeLoc TL) { | ||||
5990 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | ||||
5991 | } | ||||
5992 | |||||
5993 | void VisitTypeLoc(TypeLoc TL) { | ||||
5994 | // FIXME: add other typespec types and change this to an assert. | ||||
5995 | TL.initialize(Context, DS.getTypeSpecTypeLoc()); | ||||
5996 | } | ||||
5997 | }; | ||||
5998 | |||||
5999 | class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { | ||||
6000 | ASTContext &Context; | ||||
6001 | TypeProcessingState &State; | ||||
6002 | const DeclaratorChunk &Chunk; | ||||
6003 | |||||
6004 | public: | ||||
6005 | DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, | ||||
6006 | const DeclaratorChunk &Chunk) | ||||
6007 | : Context(Context), State(State), Chunk(Chunk) {} | ||||
6008 | |||||
6009 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | ||||
6010 | llvm_unreachable("qualified type locs not expected here!")::llvm::llvm_unreachable_internal("qualified type locs not expected here!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6010); | ||||
6011 | } | ||||
6012 | void VisitDecayedTypeLoc(DecayedTypeLoc TL) { | ||||
6013 | llvm_unreachable("decayed type locs not expected here!")::llvm::llvm_unreachable_internal("decayed type locs not expected here!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6013); | ||||
6014 | } | ||||
6015 | |||||
6016 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | ||||
6017 | fillAttributedTypeLoc(TL, State); | ||||
6018 | } | ||||
6019 | void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { | ||||
6020 | // nothing | ||||
6021 | } | ||||
6022 | void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { | ||||
6023 | assert(Chunk.Kind == DeclaratorChunk::BlockPointer)((Chunk.Kind == DeclaratorChunk::BlockPointer) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::BlockPointer" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6023, __PRETTY_FUNCTION__)); | ||||
6024 | TL.setCaretLoc(Chunk.Loc); | ||||
6025 | } | ||||
6026 | void VisitPointerTypeLoc(PointerTypeLoc TL) { | ||||
6027 | assert(Chunk.Kind == DeclaratorChunk::Pointer)((Chunk.Kind == DeclaratorChunk::Pointer) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6027, __PRETTY_FUNCTION__)); | ||||
6028 | TL.setStarLoc(Chunk.Loc); | ||||
6029 | } | ||||
6030 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | ||||
6031 | assert(Chunk.Kind == DeclaratorChunk::Pointer)((Chunk.Kind == DeclaratorChunk::Pointer) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6031, __PRETTY_FUNCTION__)); | ||||
6032 | TL.setStarLoc(Chunk.Loc); | ||||
6033 | } | ||||
6034 | void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { | ||||
6035 | assert(Chunk.Kind == DeclaratorChunk::MemberPointer)((Chunk.Kind == DeclaratorChunk::MemberPointer) ? static_cast <void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::MemberPointer" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6035, __PRETTY_FUNCTION__)); | ||||
6036 | const CXXScopeSpec& SS = Chunk.Mem.Scope(); | ||||
6037 | NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); | ||||
6038 | |||||
6039 | const Type* ClsTy = TL.getClass(); | ||||
6040 | QualType ClsQT = QualType(ClsTy, 0); | ||||
6041 | TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); | ||||
6042 | // Now copy source location info into the type loc component. | ||||
6043 | TypeLoc ClsTL = ClsTInfo->getTypeLoc(); | ||||
6044 | switch (NNSLoc.getNestedNameSpecifier()->getKind()) { | ||||
6045 | case NestedNameSpecifier::Identifier: | ||||
6046 | assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc")((isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc" ) ? static_cast<void> (0) : __assert_fail ("isa<DependentNameType>(ClsTy) && \"Unexpected TypeLoc\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6046, __PRETTY_FUNCTION__)); | ||||
6047 | { | ||||
6048 | DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); | ||||
6049 | DNTLoc.setElaboratedKeywordLoc(SourceLocation()); | ||||
6050 | DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); | ||||
6051 | DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); | ||||
6052 | } | ||||
6053 | break; | ||||
6054 | |||||
6055 | case NestedNameSpecifier::TypeSpec: | ||||
6056 | case NestedNameSpecifier::TypeSpecWithTemplate: | ||||
6057 | if (isa<ElaboratedType>(ClsTy)) { | ||||
6058 | ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); | ||||
6059 | ETLoc.setElaboratedKeywordLoc(SourceLocation()); | ||||
6060 | ETLoc.setQualifierLoc(NNSLoc.getPrefix()); | ||||
6061 | TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); | ||||
6062 | NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); | ||||
6063 | } else { | ||||
6064 | ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); | ||||
6065 | } | ||||
6066 | break; | ||||
6067 | |||||
6068 | case NestedNameSpecifier::Namespace: | ||||
6069 | case NestedNameSpecifier::NamespaceAlias: | ||||
6070 | case NestedNameSpecifier::Global: | ||||
6071 | case NestedNameSpecifier::Super: | ||||
6072 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6072); | ||||
6073 | } | ||||
6074 | |||||
6075 | // Finally fill in MemberPointerLocInfo fields. | ||||
6076 | TL.setStarLoc(SourceLocation::getFromRawEncoding(Chunk.Mem.StarLoc)); | ||||
6077 | TL.setClassTInfo(ClsTInfo); | ||||
6078 | } | ||||
6079 | void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { | ||||
6080 | assert(Chunk.Kind == DeclaratorChunk::Reference)((Chunk.Kind == DeclaratorChunk::Reference) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6080, __PRETTY_FUNCTION__)); | ||||
6081 | // 'Amp' is misleading: this might have been originally | ||||
6082 | /// spelled with AmpAmp. | ||||
6083 | TL.setAmpLoc(Chunk.Loc); | ||||
6084 | } | ||||
6085 | void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { | ||||
6086 | assert(Chunk.Kind == DeclaratorChunk::Reference)((Chunk.Kind == DeclaratorChunk::Reference) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6086, __PRETTY_FUNCTION__)); | ||||
6087 | assert(!Chunk.Ref.LValueRef)((!Chunk.Ref.LValueRef) ? static_cast<void> (0) : __assert_fail ("!Chunk.Ref.LValueRef", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6087, __PRETTY_FUNCTION__)); | ||||
6088 | TL.setAmpAmpLoc(Chunk.Loc); | ||||
6089 | } | ||||
6090 | void VisitArrayTypeLoc(ArrayTypeLoc TL) { | ||||
6091 | assert(Chunk.Kind == DeclaratorChunk::Array)((Chunk.Kind == DeclaratorChunk::Array) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Array" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6091, __PRETTY_FUNCTION__)); | ||||
6092 | TL.setLBracketLoc(Chunk.Loc); | ||||
6093 | TL.setRBracketLoc(Chunk.EndLoc); | ||||
6094 | TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); | ||||
6095 | } | ||||
6096 | void VisitFunctionTypeLoc(FunctionTypeLoc TL) { | ||||
6097 | assert(Chunk.Kind == DeclaratorChunk::Function)((Chunk.Kind == DeclaratorChunk::Function) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6097, __PRETTY_FUNCTION__)); | ||||
6098 | TL.setLocalRangeBegin(Chunk.Loc); | ||||
6099 | TL.setLocalRangeEnd(Chunk.EndLoc); | ||||
6100 | |||||
6101 | const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; | ||||
6102 | TL.setLParenLoc(FTI.getLParenLoc()); | ||||
6103 | TL.setRParenLoc(FTI.getRParenLoc()); | ||||
6104 | for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { | ||||
6105 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | ||||
6106 | TL.setParam(tpi++, Param); | ||||
6107 | } | ||||
6108 | TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); | ||||
6109 | } | ||||
6110 | void VisitParenTypeLoc(ParenTypeLoc TL) { | ||||
6111 | assert(Chunk.Kind == DeclaratorChunk::Paren)((Chunk.Kind == DeclaratorChunk::Paren) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Paren" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6111, __PRETTY_FUNCTION__)); | ||||
6112 | TL.setLParenLoc(Chunk.Loc); | ||||
6113 | TL.setRParenLoc(Chunk.EndLoc); | ||||
6114 | } | ||||
6115 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | ||||
6116 | assert(Chunk.Kind == DeclaratorChunk::Pipe)((Chunk.Kind == DeclaratorChunk::Pipe) ? static_cast<void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pipe", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6116, __PRETTY_FUNCTION__)); | ||||
6117 | TL.setKWLoc(Chunk.Loc); | ||||
6118 | } | ||||
6119 | void VisitExtIntTypeLoc(ExtIntTypeLoc TL) { | ||||
6120 | TL.setNameLoc(Chunk.Loc); | ||||
6121 | } | ||||
6122 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { | ||||
6123 | TL.setExpansionLoc(Chunk.Loc); | ||||
6124 | } | ||||
6125 | |||||
6126 | void VisitTypeLoc(TypeLoc TL) { | ||||
6127 | llvm_unreachable("unsupported TypeLoc kind in declarator!")::llvm::llvm_unreachable_internal("unsupported TypeLoc kind in declarator!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6127); | ||||
6128 | } | ||||
6129 | }; | ||||
6130 | } // end anonymous namespace | ||||
6131 | |||||
6132 | static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { | ||||
6133 | SourceLocation Loc; | ||||
6134 | switch (Chunk.Kind) { | ||||
6135 | case DeclaratorChunk::Function: | ||||
6136 | case DeclaratorChunk::Array: | ||||
6137 | case DeclaratorChunk::Paren: | ||||
6138 | case DeclaratorChunk::Pipe: | ||||
6139 | llvm_unreachable("cannot be _Atomic qualified")::llvm::llvm_unreachable_internal("cannot be _Atomic qualified" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6139); | ||||
6140 | |||||
6141 | case DeclaratorChunk::Pointer: | ||||
6142 | Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); | ||||
6143 | break; | ||||
6144 | |||||
6145 | case DeclaratorChunk::BlockPointer: | ||||
6146 | case DeclaratorChunk::Reference: | ||||
6147 | case DeclaratorChunk::MemberPointer: | ||||
6148 | // FIXME: Provide a source location for the _Atomic keyword. | ||||
6149 | break; | ||||
6150 | } | ||||
6151 | |||||
6152 | ATL.setKWLoc(Loc); | ||||
6153 | ATL.setParensRange(SourceRange()); | ||||
6154 | } | ||||
6155 | |||||
6156 | static void | ||||
6157 | fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, | ||||
6158 | const ParsedAttributesView &Attrs) { | ||||
6159 | for (const ParsedAttr &AL : Attrs) { | ||||
6160 | if (AL.getKind() == ParsedAttr::AT_AddressSpace) { | ||||
6161 | DASTL.setAttrNameLoc(AL.getLoc()); | ||||
6162 | DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); | ||||
6163 | DASTL.setAttrOperandParensRange(SourceRange()); | ||||
6164 | return; | ||||
6165 | } | ||||
6166 | } | ||||
6167 | |||||
6168 | llvm_unreachable(::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6169) | ||||
6169 | "no address_space attribute found at the expected location!")::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6169); | ||||
6170 | } | ||||
6171 | |||||
6172 | static void fillMatrixTypeLoc(MatrixTypeLoc MTL, | ||||
6173 | const ParsedAttributesView &Attrs) { | ||||
6174 | for (const ParsedAttr &AL : Attrs) { | ||||
6175 | if (AL.getKind() == ParsedAttr::AT_MatrixType) { | ||||
6176 | MTL.setAttrNameLoc(AL.getLoc()); | ||||
6177 | MTL.setAttrRowOperand(AL.getArgAsExpr(0)); | ||||
6178 | MTL.setAttrColumnOperand(AL.getArgAsExpr(1)); | ||||
6179 | MTL.setAttrOperandParensRange(SourceRange()); | ||||
6180 | return; | ||||
6181 | } | ||||
6182 | } | ||||
6183 | |||||
6184 | llvm_unreachable("no matrix_type attribute found at the expected location!")::llvm::llvm_unreachable_internal("no matrix_type attribute found at the expected location!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6184); | ||||
6185 | } | ||||
6186 | |||||
6187 | /// Create and instantiate a TypeSourceInfo with type source information. | ||||
6188 | /// | ||||
6189 | /// \param T QualType referring to the type as written in source code. | ||||
6190 | /// | ||||
6191 | /// \param ReturnTypeInfo For declarators whose return type does not show | ||||
6192 | /// up in the normal place in the declaration specifiers (such as a C++ | ||||
6193 | /// conversion function), this pointer will refer to a type source information | ||||
6194 | /// for that return type. | ||||
6195 | static TypeSourceInfo * | ||||
6196 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, | ||||
6197 | QualType T, TypeSourceInfo *ReturnTypeInfo) { | ||||
6198 | Sema &S = State.getSema(); | ||||
6199 | Declarator &D = State.getDeclarator(); | ||||
6200 | |||||
6201 | TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); | ||||
6202 | UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); | ||||
6203 | |||||
6204 | // Handle parameter packs whose type is a pack expansion. | ||||
6205 | if (isa<PackExpansionType>(T)) { | ||||
6206 | CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); | ||||
6207 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | ||||
6208 | } | ||||
6209 | |||||
6210 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | ||||
6211 | // An AtomicTypeLoc might be produced by an atomic qualifier in this | ||||
6212 | // declarator chunk. | ||||
6213 | if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { | ||||
6214 | fillAtomicQualLoc(ATL, D.getTypeObject(i)); | ||||
6215 | CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); | ||||
6216 | } | ||||
6217 | |||||
6218 | while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) { | ||||
6219 | TL.setExpansionLoc( | ||||
6220 | State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); | ||||
6221 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | ||||
6222 | } | ||||
6223 | |||||
6224 | while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { | ||||
6225 | fillAttributedTypeLoc(TL, State); | ||||
6226 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | ||||
6227 | } | ||||
6228 | |||||
6229 | while (DependentAddressSpaceTypeLoc TL = | ||||
6230 | CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { | ||||
6231 | fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); | ||||
6232 | CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); | ||||
6233 | } | ||||
6234 | |||||
6235 | if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>()) | ||||
6236 | fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs()); | ||||
6237 | |||||
6238 | // FIXME: Ordering here? | ||||
6239 | while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) | ||||
6240 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | ||||
6241 | |||||
6242 | DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); | ||||
6243 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | ||||
6244 | } | ||||
6245 | |||||
6246 | // If we have different source information for the return type, use | ||||
6247 | // that. This really only applies to C++ conversion functions. | ||||
6248 | if (ReturnTypeInfo) { | ||||
6249 | TypeLoc TL = ReturnTypeInfo->getTypeLoc(); | ||||
6250 | assert(TL.getFullDataSize() == CurrTL.getFullDataSize())((TL.getFullDataSize() == CurrTL.getFullDataSize()) ? static_cast <void> (0) : __assert_fail ("TL.getFullDataSize() == CurrTL.getFullDataSize()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6250, __PRETTY_FUNCTION__)); | ||||
6251 | memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); | ||||
6252 | } else { | ||||
6253 | TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL); | ||||
6254 | } | ||||
6255 | |||||
6256 | return TInfo; | ||||
6257 | } | ||||
6258 | |||||
6259 | /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. | ||||
6260 | ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { | ||||
6261 | // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser | ||||
6262 | // and Sema during declaration parsing. Try deallocating/caching them when | ||||
6263 | // it's appropriate, instead of allocating them and keeping them around. | ||||
6264 | LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), | ||||
6265 | TypeAlignment); | ||||
6266 | new (LocT) LocInfoType(T, TInfo); | ||||
6267 | assert(LocT->getTypeClass() != T->getTypeClass() &&((LocT->getTypeClass() != T->getTypeClass() && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? static_cast<void> (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6268, __PRETTY_FUNCTION__)) | ||||
6268 | "LocInfoType's TypeClass conflicts with an existing Type class")((LocT->getTypeClass() != T->getTypeClass() && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? static_cast<void> (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6268, __PRETTY_FUNCTION__)); | ||||
6269 | return ParsedType::make(QualType(LocT, 0)); | ||||
6270 | } | ||||
6271 | |||||
6272 | void LocInfoType::getAsStringInternal(std::string &Str, | ||||
6273 | const PrintingPolicy &Policy) const { | ||||
6274 | llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6276) | ||||
6275 | " was used directly instead of getting the QualType through"::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6276) | ||||
6276 | " GetTypeFromParser")::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6276); | ||||
6277 | } | ||||
6278 | |||||
6279 | TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { | ||||
6280 | // C99 6.7.6: Type names have no identifier. This is already validated by | ||||
6281 | // the parser. | ||||
6282 | assert(D.getIdentifier() == nullptr &&((D.getIdentifier() == nullptr && "Type name should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6283, __PRETTY_FUNCTION__)) | ||||
6283 | "Type name should have no identifier!")((D.getIdentifier() == nullptr && "Type name should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6283, __PRETTY_FUNCTION__)); | ||||
6284 | |||||
6285 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
6286 | QualType T = TInfo->getType(); | ||||
6287 | if (D.isInvalidType()) | ||||
6288 | return true; | ||||
6289 | |||||
6290 | // Make sure there are no unused decl attributes on the declarator. | ||||
6291 | // We don't want to do this for ObjC parameters because we're going | ||||
6292 | // to apply them to the actual parameter declaration. | ||||
6293 | // Likewise, we don't want to do this for alias declarations, because | ||||
6294 | // we are actually going to build a declaration from this eventually. | ||||
6295 | if (D.getContext() != DeclaratorContext::ObjCParameter && | ||||
6296 | D.getContext() != DeclaratorContext::AliasDecl && | ||||
6297 | D.getContext() != DeclaratorContext::AliasTemplate) | ||||
6298 | checkUnusedDeclAttributes(D); | ||||
6299 | |||||
6300 | if (getLangOpts().CPlusPlus) { | ||||
6301 | // Check that there are no default arguments (C++ only). | ||||
6302 | CheckExtraCXXDefaultArguments(D); | ||||
6303 | } | ||||
6304 | |||||
6305 | return CreateParsedType(T, TInfo); | ||||
6306 | } | ||||
6307 | |||||
6308 | ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { | ||||
6309 | QualType T = Context.getObjCInstanceType(); | ||||
6310 | TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | ||||
6311 | return CreateParsedType(T, TInfo); | ||||
6312 | } | ||||
6313 | |||||
6314 | //===----------------------------------------------------------------------===// | ||||
6315 | // Type Attribute Processing | ||||
6316 | //===----------------------------------------------------------------------===// | ||||
6317 | |||||
6318 | /// Build an AddressSpace index from a constant expression and diagnose any | ||||
6319 | /// errors related to invalid address_spaces. Returns true on successfully | ||||
6320 | /// building an AddressSpace index. | ||||
6321 | static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, | ||||
6322 | const Expr *AddrSpace, | ||||
6323 | SourceLocation AttrLoc) { | ||||
6324 | if (!AddrSpace->isValueDependent()) { | ||||
6325 | Optional<llvm::APSInt> OptAddrSpace = | ||||
6326 | AddrSpace->getIntegerConstantExpr(S.Context); | ||||
6327 | if (!OptAddrSpace) { | ||||
6328 | S.Diag(AttrLoc, diag::err_attribute_argument_type) | ||||
6329 | << "'address_space'" << AANT_ArgumentIntegerConstant | ||||
6330 | << AddrSpace->getSourceRange(); | ||||
6331 | return false; | ||||
6332 | } | ||||
6333 | llvm::APSInt &addrSpace = *OptAddrSpace; | ||||
6334 | |||||
6335 | // Bounds checking. | ||||
6336 | if (addrSpace.isSigned()) { | ||||
6337 | if (addrSpace.isNegative()) { | ||||
6338 | S.Diag(AttrLoc, diag::err_attribute_address_space_negative) | ||||
6339 | << AddrSpace->getSourceRange(); | ||||
6340 | return false; | ||||
6341 | } | ||||
6342 | addrSpace.setIsSigned(false); | ||||
6343 | } | ||||
6344 | |||||
6345 | llvm::APSInt max(addrSpace.getBitWidth()); | ||||
6346 | max = | ||||
6347 | Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; | ||||
6348 | if (addrSpace > max) { | ||||
6349 | S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) | ||||
6350 | << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); | ||||
6351 | return false; | ||||
6352 | } | ||||
6353 | |||||
6354 | ASIdx = | ||||
6355 | getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); | ||||
6356 | return true; | ||||
6357 | } | ||||
6358 | |||||
6359 | // Default value for DependentAddressSpaceTypes | ||||
6360 | ASIdx = LangAS::Default; | ||||
6361 | return true; | ||||
6362 | } | ||||
6363 | |||||
6364 | /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression | ||||
6365 | /// is uninstantiated. If instantiated it will apply the appropriate address | ||||
6366 | /// space to the type. This function allows dependent template variables to be | ||||
6367 | /// used in conjunction with the address_space attribute | ||||
6368 | QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, | ||||
6369 | SourceLocation AttrLoc) { | ||||
6370 | if (!AddrSpace->isValueDependent()) { | ||||
6371 | if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, | ||||
6372 | AttrLoc)) | ||||
6373 | return QualType(); | ||||
6374 | |||||
6375 | return Context.getAddrSpaceQualType(T, ASIdx); | ||||
6376 | } | ||||
6377 | |||||
6378 | // A check with similar intentions as checking if a type already has an | ||||
6379 | // address space except for on a dependent types, basically if the | ||||
6380 | // current type is already a DependentAddressSpaceType then its already | ||||
6381 | // lined up to have another address space on it and we can't have | ||||
6382 | // multiple address spaces on the one pointer indirection | ||||
6383 | if (T->getAs<DependentAddressSpaceType>()) { | ||||
6384 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | ||||
6385 | return QualType(); | ||||
6386 | } | ||||
6387 | |||||
6388 | return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); | ||||
6389 | } | ||||
6390 | |||||
6391 | QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, | ||||
6392 | SourceLocation AttrLoc) { | ||||
6393 | LangAS ASIdx; | ||||
6394 | if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) | ||||
6395 | return QualType(); | ||||
6396 | return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); | ||||
6397 | } | ||||
6398 | |||||
6399 | /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the | ||||
6400 | /// specified type. The attribute contains 1 argument, the id of the address | ||||
6401 | /// space for the type. | ||||
6402 | static void HandleAddressSpaceTypeAttribute(QualType &Type, | ||||
6403 | const ParsedAttr &Attr, | ||||
6404 | TypeProcessingState &State) { | ||||
6405 | Sema &S = State.getSema(); | ||||
6406 | |||||
6407 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be | ||||
6408 | // qualified by an address-space qualifier." | ||||
6409 | if (Type->isFunctionType()) { | ||||
6410 | S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); | ||||
6411 | Attr.setInvalid(); | ||||
6412 | return; | ||||
6413 | } | ||||
6414 | |||||
6415 | LangAS ASIdx; | ||||
6416 | if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { | ||||
6417 | |||||
6418 | // Check the attribute arguments. | ||||
6419 | if (Attr.getNumArgs() != 1) { | ||||
6420 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | ||||
6421 | << 1; | ||||
6422 | Attr.setInvalid(); | ||||
6423 | return; | ||||
6424 | } | ||||
6425 | |||||
6426 | Expr *ASArgExpr; | ||||
6427 | if (Attr.isArgIdent(0)) { | ||||
6428 | // Special case where the argument is a template id. | ||||
6429 | CXXScopeSpec SS; | ||||
6430 | SourceLocation TemplateKWLoc; | ||||
6431 | UnqualifiedId id; | ||||
6432 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | ||||
6433 | |||||
6434 | ExprResult AddrSpace = S.ActOnIdExpression( | ||||
6435 | S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false, | ||||
6436 | /*IsAddressOfOperand=*/false); | ||||
6437 | if (AddrSpace.isInvalid()) | ||||
6438 | return; | ||||
6439 | |||||
6440 | ASArgExpr = static_cast<Expr *>(AddrSpace.get()); | ||||
6441 | } else { | ||||
6442 | ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); | ||||
6443 | } | ||||
6444 | |||||
6445 | LangAS ASIdx; | ||||
6446 | if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { | ||||
6447 | Attr.setInvalid(); | ||||
6448 | return; | ||||
6449 | } | ||||
6450 | |||||
6451 | ASTContext &Ctx = S.Context; | ||||
6452 | auto *ASAttr = | ||||
6453 | ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); | ||||
6454 | |||||
6455 | // If the expression is not value dependent (not templated), then we can | ||||
6456 | // apply the address space qualifiers just to the equivalent type. | ||||
6457 | // Otherwise, we make an AttributedType with the modified and equivalent | ||||
6458 | // type the same, and wrap it in a DependentAddressSpaceType. When this | ||||
6459 | // dependent type is resolved, the qualifier is added to the equivalent type | ||||
6460 | // later. | ||||
6461 | QualType T; | ||||
6462 | if (!ASArgExpr->isValueDependent()) { | ||||
6463 | QualType EquivType = | ||||
6464 | S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); | ||||
6465 | if (EquivType.isNull()) { | ||||
6466 | Attr.setInvalid(); | ||||
6467 | return; | ||||
6468 | } | ||||
6469 | T = State.getAttributedType(ASAttr, Type, EquivType); | ||||
6470 | } else { | ||||
6471 | T = State.getAttributedType(ASAttr, Type, Type); | ||||
6472 | T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); | ||||
6473 | } | ||||
6474 | |||||
6475 | if (!T.isNull()) | ||||
6476 | Type = T; | ||||
6477 | else | ||||
6478 | Attr.setInvalid(); | ||||
6479 | } else { | ||||
6480 | // The keyword-based type attributes imply which address space to use. | ||||
6481 | ASIdx = Attr.asOpenCLLangAS(); | ||||
6482 | if (ASIdx == LangAS::Default) | ||||
6483 | llvm_unreachable("Invalid address space")::llvm::llvm_unreachable_internal("Invalid address space", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6483); | ||||
6484 | |||||
6485 | if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, | ||||
6486 | Attr.getLoc())) { | ||||
6487 | Attr.setInvalid(); | ||||
6488 | return; | ||||
6489 | } | ||||
6490 | |||||
6491 | Type = S.Context.getAddrSpaceQualType(Type, ASIdx); | ||||
6492 | } | ||||
6493 | } | ||||
6494 | |||||
6495 | /// handleObjCOwnershipTypeAttr - Process an objc_ownership | ||||
6496 | /// attribute on the specified type. | ||||
6497 | /// | ||||
6498 | /// Returns 'true' if the attribute was handled. | ||||
6499 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | ||||
6500 | ParsedAttr &attr, QualType &type) { | ||||
6501 | bool NonObjCPointer = false; | ||||
6502 | |||||
6503 | if (!type->isDependentType() && !type->isUndeducedType()) { | ||||
6504 | if (const PointerType *ptr = type->getAs<PointerType>()) { | ||||
6505 | QualType pointee = ptr->getPointeeType(); | ||||
6506 | if (pointee->isObjCRetainableType() || pointee->isPointerType()) | ||||
6507 | return false; | ||||
6508 | // It is important not to lose the source info that there was an attribute | ||||
6509 | // applied to non-objc pointer. We will create an attributed type but | ||||
6510 | // its type will be the same as the original type. | ||||
6511 | NonObjCPointer = true; | ||||
6512 | } else if (!type->isObjCRetainableType()) { | ||||
6513 | return false; | ||||
6514 | } | ||||
6515 | |||||
6516 | // Don't accept an ownership attribute in the declspec if it would | ||||
6517 | // just be the return type of a block pointer. | ||||
6518 | if (state.isProcessingDeclSpec()) { | ||||
6519 | Declarator &D = state.getDeclarator(); | ||||
6520 | if (maybeMovePastReturnType(D, D.getNumTypeObjects(), | ||||
6521 | /*onlyBlockPointers=*/true)) | ||||
6522 | return false; | ||||
6523 | } | ||||
6524 | } | ||||
6525 | |||||
6526 | Sema &S = state.getSema(); | ||||
6527 | SourceLocation AttrLoc = attr.getLoc(); | ||||
6528 | if (AttrLoc.isMacroID()) | ||||
6529 | AttrLoc = | ||||
6530 | S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); | ||||
6531 | |||||
6532 | if (!attr.isArgIdent(0)) { | ||||
6533 | S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr | ||||
6534 | << AANT_ArgumentString; | ||||
6535 | attr.setInvalid(); | ||||
6536 | return true; | ||||
6537 | } | ||||
6538 | |||||
6539 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | ||||
6540 | Qualifiers::ObjCLifetime lifetime; | ||||
6541 | if (II->isStr("none")) | ||||
6542 | lifetime = Qualifiers::OCL_ExplicitNone; | ||||
6543 | else if (II->isStr("strong")) | ||||
6544 | lifetime = Qualifiers::OCL_Strong; | ||||
6545 | else if (II->isStr("weak")) | ||||
6546 | lifetime = Qualifiers::OCL_Weak; | ||||
6547 | else if (II->isStr("autoreleasing")) | ||||
6548 | lifetime = Qualifiers::OCL_Autoreleasing; | ||||
6549 | else { | ||||
6550 | S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; | ||||
6551 | attr.setInvalid(); | ||||
6552 | return true; | ||||
6553 | } | ||||
6554 | |||||
6555 | // Just ignore lifetime attributes other than __weak and __unsafe_unretained | ||||
6556 | // outside of ARC mode. | ||||
6557 | if (!S.getLangOpts().ObjCAutoRefCount && | ||||
6558 | lifetime != Qualifiers::OCL_Weak && | ||||
6559 | lifetime != Qualifiers::OCL_ExplicitNone) { | ||||
6560 | return true; | ||||
6561 | } | ||||
6562 | |||||
6563 | SplitQualType underlyingType = type.split(); | ||||
6564 | |||||
6565 | // Check for redundant/conflicting ownership qualifiers. | ||||
6566 | if (Qualifiers::ObjCLifetime previousLifetime | ||||
6567 | = type.getQualifiers().getObjCLifetime()) { | ||||
6568 | // If it's written directly, that's an error. | ||||
6569 | if (S.Context.hasDirectOwnershipQualifier(type)) { | ||||
6570 | S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) | ||||
6571 | << type; | ||||
6572 | return true; | ||||
6573 | } | ||||
6574 | |||||
6575 | // Otherwise, if the qualifiers actually conflict, pull sugar off | ||||
6576 | // and remove the ObjCLifetime qualifiers. | ||||
6577 | if (previousLifetime != lifetime) { | ||||
6578 | // It's possible to have multiple local ObjCLifetime qualifiers. We | ||||
6579 | // can't stop after we reach a type that is directly qualified. | ||||
6580 | const Type *prevTy = nullptr; | ||||
6581 | while (!prevTy || prevTy != underlyingType.Ty) { | ||||
6582 | prevTy = underlyingType.Ty; | ||||
6583 | underlyingType = underlyingType.getSingleStepDesugaredType(); | ||||
6584 | } | ||||
6585 | underlyingType.Quals.removeObjCLifetime(); | ||||
6586 | } | ||||
6587 | } | ||||
6588 | |||||
6589 | underlyingType.Quals.addObjCLifetime(lifetime); | ||||
6590 | |||||
6591 | if (NonObjCPointer) { | ||||
6592 | StringRef name = attr.getAttrName()->getName(); | ||||
6593 | switch (lifetime) { | ||||
6594 | case Qualifiers::OCL_None: | ||||
6595 | case Qualifiers::OCL_ExplicitNone: | ||||
6596 | break; | ||||
6597 | case Qualifiers::OCL_Strong: name = "__strong"; break; | ||||
6598 | case Qualifiers::OCL_Weak: name = "__weak"; break; | ||||
6599 | case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; | ||||
6600 | } | ||||
6601 | S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name | ||||
6602 | << TDS_ObjCObjOrBlock << type; | ||||
6603 | } | ||||
6604 | |||||
6605 | // Don't actually add the __unsafe_unretained qualifier in non-ARC files, | ||||
6606 | // because having both 'T' and '__unsafe_unretained T' exist in the type | ||||
6607 | // system causes unfortunate widespread consistency problems. (For example, | ||||
6608 | // they're not considered compatible types, and we mangle them identicially | ||||
6609 | // as template arguments.) These problems are all individually fixable, | ||||
6610 | // but it's easier to just not add the qualifier and instead sniff it out | ||||
6611 | // in specific places using isObjCInertUnsafeUnretainedType(). | ||||
6612 | // | ||||
6613 | // Doing this does means we miss some trivial consistency checks that | ||||
6614 | // would've triggered in ARC, but that's better than trying to solve all | ||||
6615 | // the coexistence problems with __unsafe_unretained. | ||||
6616 | if (!S.getLangOpts().ObjCAutoRefCount && | ||||
6617 | lifetime == Qualifiers::OCL_ExplicitNone) { | ||||
6618 | type = state.getAttributedType( | ||||
6619 | createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), | ||||
6620 | type, type); | ||||
6621 | return true; | ||||
6622 | } | ||||
6623 | |||||
6624 | QualType origType = type; | ||||
6625 | if (!NonObjCPointer) | ||||
6626 | type = S.Context.getQualifiedType(underlyingType); | ||||
6627 | |||||
6628 | // If we have a valid source location for the attribute, use an | ||||
6629 | // AttributedType instead. | ||||
6630 | if (AttrLoc.isValid()) { | ||||
6631 | type = state.getAttributedType(::new (S.Context) | ||||
6632 | ObjCOwnershipAttr(S.Context, attr, II), | ||||
6633 | origType, type); | ||||
6634 | } | ||||
6635 | |||||
6636 | auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, | ||||
6637 | unsigned diagnostic, QualType type) { | ||||
6638 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | ||||
6639 | S.DelayedDiagnostics.add( | ||||
6640 | sema::DelayedDiagnostic::makeForbiddenType( | ||||
6641 | S.getSourceManager().getExpansionLoc(loc), | ||||
6642 | diagnostic, type, /*ignored*/ 0)); | ||||
6643 | } else { | ||||
6644 | S.Diag(loc, diagnostic); | ||||
6645 | } | ||||
6646 | }; | ||||
6647 | |||||
6648 | // Sometimes, __weak isn't allowed. | ||||
6649 | if (lifetime == Qualifiers::OCL_Weak && | ||||
6650 | !S.getLangOpts().ObjCWeak && !NonObjCPointer) { | ||||
6651 | |||||
6652 | // Use a specialized diagnostic if the runtime just doesn't support them. | ||||
6653 | unsigned diagnostic = | ||||
6654 | (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled | ||||
6655 | : diag::err_arc_weak_no_runtime); | ||||
6656 | |||||
6657 | // In any case, delay the diagnostic until we know what we're parsing. | ||||
6658 | diagnoseOrDelay(S, AttrLoc, diagnostic, type); | ||||
6659 | |||||
6660 | attr.setInvalid(); | ||||
6661 | return true; | ||||
6662 | } | ||||
6663 | |||||
6664 | // Forbid __weak for class objects marked as | ||||
6665 | // objc_arc_weak_reference_unavailable | ||||
6666 | if (lifetime == Qualifiers::OCL_Weak) { | ||||
6667 | if (const ObjCObjectPointerType *ObjT = | ||||
6668 | type->getAs<ObjCObjectPointerType>()) { | ||||
6669 | if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { | ||||
6670 | if (Class->isArcWeakrefUnavailable()) { | ||||
6671 | S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); | ||||
6672 | S.Diag(ObjT->getInterfaceDecl()->getLocation(), | ||||
6673 | diag::note_class_declared); | ||||
6674 | } | ||||
6675 | } | ||||
6676 | } | ||||
6677 | } | ||||
6678 | |||||
6679 | return true; | ||||
6680 | } | ||||
6681 | |||||
6682 | /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type | ||||
6683 | /// attribute on the specified type. Returns true to indicate that | ||||
6684 | /// the attribute was handled, false to indicate that the type does | ||||
6685 | /// not permit the attribute. | ||||
6686 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | ||||
6687 | QualType &type) { | ||||
6688 | Sema &S = state.getSema(); | ||||
6689 | |||||
6690 | // Delay if this isn't some kind of pointer. | ||||
6691 | if (!type->isPointerType() && | ||||
6692 | !type->isObjCObjectPointerType() && | ||||
6693 | !type->isBlockPointerType()) | ||||
6694 | return false; | ||||
6695 | |||||
6696 | if (type.getObjCGCAttr() != Qualifiers::GCNone) { | ||||
6697 | S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); | ||||
6698 | attr.setInvalid(); | ||||
6699 | return true; | ||||
6700 | } | ||||
6701 | |||||
6702 | // Check the attribute arguments. | ||||
6703 | if (!attr.isArgIdent(0)) { | ||||
6704 | S.Diag(attr.getLoc(), diag::err_attribute_argument_type) | ||||
6705 | << attr << AANT_ArgumentString; | ||||
6706 | attr.setInvalid(); | ||||
6707 | return true; | ||||
6708 | } | ||||
6709 | Qualifiers::GC GCAttr; | ||||
6710 | if (attr.getNumArgs() > 1) { | ||||
6711 | S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr | ||||
6712 | << 1; | ||||
6713 | attr.setInvalid(); | ||||
6714 | return true; | ||||
6715 | } | ||||
6716 | |||||
6717 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | ||||
6718 | if (II->isStr("weak")) | ||||
6719 | GCAttr = Qualifiers::Weak; | ||||
6720 | else if (II->isStr("strong")) | ||||
6721 | GCAttr = Qualifiers::Strong; | ||||
6722 | else { | ||||
6723 | S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) | ||||
6724 | << attr << II; | ||||
6725 | attr.setInvalid(); | ||||
6726 | return true; | ||||
6727 | } | ||||
6728 | |||||
6729 | QualType origType = type; | ||||
6730 | type = S.Context.getObjCGCQualType(origType, GCAttr); | ||||
6731 | |||||
6732 | // Make an attributed type to preserve the source information. | ||||
6733 | if (attr.getLoc().isValid()) | ||||
6734 | type = state.getAttributedType( | ||||
6735 | ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); | ||||
6736 | |||||
6737 | return true; | ||||
6738 | } | ||||
6739 | |||||
6740 | namespace { | ||||
6741 | /// A helper class to unwrap a type down to a function for the | ||||
6742 | /// purposes of applying attributes there. | ||||
6743 | /// | ||||
6744 | /// Use: | ||||
6745 | /// FunctionTypeUnwrapper unwrapped(SemaRef, T); | ||||
6746 | /// if (unwrapped.isFunctionType()) { | ||||
6747 | /// const FunctionType *fn = unwrapped.get(); | ||||
6748 | /// // change fn somehow | ||||
6749 | /// T = unwrapped.wrap(fn); | ||||
6750 | /// } | ||||
6751 | struct FunctionTypeUnwrapper { | ||||
6752 | enum WrapKind { | ||||
6753 | Desugar, | ||||
6754 | Attributed, | ||||
6755 | Parens, | ||||
6756 | Array, | ||||
6757 | Pointer, | ||||
6758 | BlockPointer, | ||||
6759 | Reference, | ||||
6760 | MemberPointer, | ||||
6761 | MacroQualified, | ||||
6762 | }; | ||||
6763 | |||||
6764 | QualType Original; | ||||
6765 | const FunctionType *Fn; | ||||
6766 | SmallVector<unsigned char /*WrapKind*/, 8> Stack; | ||||
6767 | |||||
6768 | FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { | ||||
6769 | while (true) { | ||||
6770 | const Type *Ty = T.getTypePtr(); | ||||
6771 | if (isa<FunctionType>(Ty)) { | ||||
6772 | Fn = cast<FunctionType>(Ty); | ||||
6773 | return; | ||||
6774 | } else if (isa<ParenType>(Ty)) { | ||||
6775 | T = cast<ParenType>(Ty)->getInnerType(); | ||||
6776 | Stack.push_back(Parens); | ||||
6777 | } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) || | ||||
6778 | isa<IncompleteArrayType>(Ty)) { | ||||
6779 | T = cast<ArrayType>(Ty)->getElementType(); | ||||
6780 | Stack.push_back(Array); | ||||
6781 | } else if (isa<PointerType>(Ty)) { | ||||
6782 | T = cast<PointerType>(Ty)->getPointeeType(); | ||||
6783 | Stack.push_back(Pointer); | ||||
6784 | } else if (isa<BlockPointerType>(Ty)) { | ||||
6785 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | ||||
6786 | Stack.push_back(BlockPointer); | ||||
6787 | } else if (isa<MemberPointerType>(Ty)) { | ||||
6788 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | ||||
6789 | Stack.push_back(MemberPointer); | ||||
6790 | } else if (isa<ReferenceType>(Ty)) { | ||||
6791 | T = cast<ReferenceType>(Ty)->getPointeeType(); | ||||
6792 | Stack.push_back(Reference); | ||||
6793 | } else if (isa<AttributedType>(Ty)) { | ||||
6794 | T = cast<AttributedType>(Ty)->getEquivalentType(); | ||||
6795 | Stack.push_back(Attributed); | ||||
6796 | } else if (isa<MacroQualifiedType>(Ty)) { | ||||
6797 | T = cast<MacroQualifiedType>(Ty)->getUnderlyingType(); | ||||
6798 | Stack.push_back(MacroQualified); | ||||
6799 | } else { | ||||
6800 | const Type *DTy = Ty->getUnqualifiedDesugaredType(); | ||||
6801 | if (Ty == DTy) { | ||||
6802 | Fn = nullptr; | ||||
6803 | return; | ||||
6804 | } | ||||
6805 | |||||
6806 | T = QualType(DTy, 0); | ||||
6807 | Stack.push_back(Desugar); | ||||
6808 | } | ||||
6809 | } | ||||
6810 | } | ||||
6811 | |||||
6812 | bool isFunctionType() const { return (Fn != nullptr); } | ||||
6813 | const FunctionType *get() const { return Fn; } | ||||
6814 | |||||
6815 | QualType wrap(Sema &S, const FunctionType *New) { | ||||
6816 | // If T wasn't modified from the unwrapped type, do nothing. | ||||
6817 | if (New == get()) return Original; | ||||
6818 | |||||
6819 | Fn = New; | ||||
6820 | return wrap(S.Context, Original, 0); | ||||
6821 | } | ||||
6822 | |||||
6823 | private: | ||||
6824 | QualType wrap(ASTContext &C, QualType Old, unsigned I) { | ||||
6825 | if (I == Stack.size()) | ||||
6826 | return C.getQualifiedType(Fn, Old.getQualifiers()); | ||||
6827 | |||||
6828 | // Build up the inner type, applying the qualifiers from the old | ||||
6829 | // type to the new type. | ||||
6830 | SplitQualType SplitOld = Old.split(); | ||||
6831 | |||||
6832 | // As a special case, tail-recurse if there are no qualifiers. | ||||
6833 | if (SplitOld.Quals.empty()) | ||||
6834 | return wrap(C, SplitOld.Ty, I); | ||||
6835 | return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); | ||||
6836 | } | ||||
6837 | |||||
6838 | QualType wrap(ASTContext &C, const Type *Old, unsigned I) { | ||||
6839 | if (I == Stack.size()) return QualType(Fn, 0); | ||||
6840 | |||||
6841 | switch (static_cast<WrapKind>(Stack[I++])) { | ||||
6842 | case Desugar: | ||||
6843 | // This is the point at which we potentially lose source | ||||
6844 | // information. | ||||
6845 | return wrap(C, Old->getUnqualifiedDesugaredType(), I); | ||||
6846 | |||||
6847 | case Attributed: | ||||
6848 | return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); | ||||
6849 | |||||
6850 | case Parens: { | ||||
6851 | QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); | ||||
6852 | return C.getParenType(New); | ||||
6853 | } | ||||
6854 | |||||
6855 | case MacroQualified: | ||||
6856 | return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I); | ||||
6857 | |||||
6858 | case Array: { | ||||
6859 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) { | ||||
6860 | QualType New = wrap(C, CAT->getElementType(), I); | ||||
6861 | return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(), | ||||
6862 | CAT->getSizeModifier(), | ||||
6863 | CAT->getIndexTypeCVRQualifiers()); | ||||
6864 | } | ||||
6865 | |||||
6866 | if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) { | ||||
6867 | QualType New = wrap(C, VAT->getElementType(), I); | ||||
6868 | return C.getVariableArrayType( | ||||
6869 | New, VAT->getSizeExpr(), VAT->getSizeModifier(), | ||||
6870 | VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); | ||||
6871 | } | ||||
6872 | |||||
6873 | const auto *IAT = cast<IncompleteArrayType>(Old); | ||||
6874 | QualType New = wrap(C, IAT->getElementType(), I); | ||||
6875 | return C.getIncompleteArrayType(New, IAT->getSizeModifier(), | ||||
6876 | IAT->getIndexTypeCVRQualifiers()); | ||||
6877 | } | ||||
6878 | |||||
6879 | case Pointer: { | ||||
6880 | QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); | ||||
6881 | return C.getPointerType(New); | ||||
6882 | } | ||||
6883 | |||||
6884 | case BlockPointer: { | ||||
6885 | QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); | ||||
6886 | return C.getBlockPointerType(New); | ||||
6887 | } | ||||
6888 | |||||
6889 | case MemberPointer: { | ||||
6890 | const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); | ||||
6891 | QualType New = wrap(C, OldMPT->getPointeeType(), I); | ||||
6892 | return C.getMemberPointerType(New, OldMPT->getClass()); | ||||
6893 | } | ||||
6894 | |||||
6895 | case Reference: { | ||||
6896 | const ReferenceType *OldRef = cast<ReferenceType>(Old); | ||||
6897 | QualType New = wrap(C, OldRef->getPointeeType(), I); | ||||
6898 | if (isa<LValueReferenceType>(OldRef)) | ||||
6899 | return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); | ||||
6900 | else | ||||
6901 | return C.getRValueReferenceType(New); | ||||
6902 | } | ||||
6903 | } | ||||
6904 | |||||
6905 | llvm_unreachable("unknown wrapping kind")::llvm::llvm_unreachable_internal("unknown wrapping kind", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6905); | ||||
6906 | } | ||||
6907 | }; | ||||
6908 | } // end anonymous namespace | ||||
6909 | |||||
6910 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, | ||||
6911 | ParsedAttr &PAttr, QualType &Type) { | ||||
6912 | Sema &S = State.getSema(); | ||||
6913 | |||||
6914 | Attr *A; | ||||
6915 | switch (PAttr.getKind()) { | ||||
6916 | default: llvm_unreachable("Unknown attribute kind")::llvm::llvm_unreachable_internal("Unknown attribute kind", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 6916); | ||||
6917 | case ParsedAttr::AT_Ptr32: | ||||
6918 | A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); | ||||
6919 | break; | ||||
6920 | case ParsedAttr::AT_Ptr64: | ||||
6921 | A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); | ||||
6922 | break; | ||||
6923 | case ParsedAttr::AT_SPtr: | ||||
6924 | A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); | ||||
6925 | break; | ||||
6926 | case ParsedAttr::AT_UPtr: | ||||
6927 | A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); | ||||
6928 | break; | ||||
6929 | } | ||||
6930 | |||||
6931 | std::bitset<attr::LastAttr> Attrs; | ||||
6932 | attr::Kind NewAttrKind = A->getKind(); | ||||
6933 | QualType Desugared = Type; | ||||
6934 | const AttributedType *AT = dyn_cast<AttributedType>(Type); | ||||
6935 | while (AT) { | ||||
6936 | Attrs[AT->getAttrKind()] = true; | ||||
6937 | Desugared = AT->getModifiedType(); | ||||
6938 | AT = dyn_cast<AttributedType>(Desugared); | ||||
6939 | } | ||||
6940 | |||||
6941 | // You cannot specify duplicate type attributes, so if the attribute has | ||||
6942 | // already been applied, flag it. | ||||
6943 | if (Attrs[NewAttrKind]) { | ||||
6944 | S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; | ||||
6945 | return true; | ||||
6946 | } | ||||
6947 | Attrs[NewAttrKind] = true; | ||||
6948 | |||||
6949 | // You cannot have both __sptr and __uptr on the same type, nor can you | ||||
6950 | // have __ptr32 and __ptr64. | ||||
6951 | if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) { | ||||
6952 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) | ||||
6953 | << "'__ptr32'" | ||||
6954 | << "'__ptr64'"; | ||||
6955 | return true; | ||||
6956 | } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) { | ||||
6957 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) | ||||
6958 | << "'__sptr'" | ||||
6959 | << "'__uptr'"; | ||||
6960 | return true; | ||||
6961 | } | ||||
6962 | |||||
6963 | // Pointer type qualifiers can only operate on pointer types, but not | ||||
6964 | // pointer-to-member types. | ||||
6965 | // | ||||
6966 | // FIXME: Should we really be disallowing this attribute if there is any | ||||
6967 | // type sugar between it and the pointer (other than attributes)? Eg, this | ||||
6968 | // disallows the attribute on a parenthesized pointer. | ||||
6969 | // And if so, should we really allow *any* type attribute? | ||||
6970 | if (!isa<PointerType>(Desugared)) { | ||||
6971 | if (Type->isMemberPointerType()) | ||||
6972 | S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; | ||||
6973 | else | ||||
6974 | S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; | ||||
6975 | return true; | ||||
6976 | } | ||||
6977 | |||||
6978 | // Add address space to type based on its attributes. | ||||
6979 | LangAS ASIdx = LangAS::Default; | ||||
6980 | uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0); | ||||
6981 | if (PtrWidth == 32) { | ||||
6982 | if (Attrs[attr::Ptr64]) | ||||
6983 | ASIdx = LangAS::ptr64; | ||||
6984 | else if (Attrs[attr::UPtr]) | ||||
6985 | ASIdx = LangAS::ptr32_uptr; | ||||
6986 | } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) { | ||||
6987 | if (Attrs[attr::UPtr]) | ||||
6988 | ASIdx = LangAS::ptr32_uptr; | ||||
6989 | else | ||||
6990 | ASIdx = LangAS::ptr32_sptr; | ||||
6991 | } | ||||
6992 | |||||
6993 | QualType Pointee = Type->getPointeeType(); | ||||
6994 | if (ASIdx != LangAS::Default) | ||||
6995 | Pointee = S.Context.getAddrSpaceQualType( | ||||
6996 | S.Context.removeAddrSpaceQualType(Pointee), ASIdx); | ||||
6997 | Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee)); | ||||
6998 | return false; | ||||
6999 | } | ||||
7000 | |||||
7001 | /// Map a nullability attribute kind to a nullability kind. | ||||
7002 | static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { | ||||
7003 | switch (kind) { | ||||
7004 | case ParsedAttr::AT_TypeNonNull: | ||||
7005 | return NullabilityKind::NonNull; | ||||
7006 | |||||
7007 | case ParsedAttr::AT_TypeNullable: | ||||
7008 | return NullabilityKind::Nullable; | ||||
7009 | |||||
7010 | case ParsedAttr::AT_TypeNullUnspecified: | ||||
7011 | return NullabilityKind::Unspecified; | ||||
7012 | |||||
7013 | default: | ||||
7014 | llvm_unreachable("not a nullability attribute kind")::llvm::llvm_unreachable_internal("not a nullability attribute kind" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7014); | ||||
7015 | } | ||||
7016 | } | ||||
7017 | |||||
7018 | /// Applies a nullability type specifier to the given type, if possible. | ||||
7019 | /// | ||||
7020 | /// \param state The type processing state. | ||||
7021 | /// | ||||
7022 | /// \param type The type to which the nullability specifier will be | ||||
7023 | /// added. On success, this type will be updated appropriately. | ||||
7024 | /// | ||||
7025 | /// \param attr The attribute as written on the type. | ||||
7026 | /// | ||||
7027 | /// \param allowOnArrayType Whether to accept nullability specifiers on an | ||||
7028 | /// array type (e.g., because it will decay to a pointer). | ||||
7029 | /// | ||||
7030 | /// \returns true if a problem has been diagnosed, false on success. | ||||
7031 | static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, | ||||
7032 | QualType &type, | ||||
7033 | ParsedAttr &attr, | ||||
7034 | bool allowOnArrayType) { | ||||
7035 | Sema &S = state.getSema(); | ||||
7036 | |||||
7037 | NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); | ||||
7038 | SourceLocation nullabilityLoc = attr.getLoc(); | ||||
7039 | bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); | ||||
7040 | |||||
7041 | recordNullabilitySeen(S, nullabilityLoc); | ||||
7042 | |||||
7043 | // Check for existing nullability attributes on the type. | ||||
7044 | QualType desugared = type; | ||||
7045 | while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { | ||||
7046 | // Check whether there is already a null | ||||
7047 | if (auto existingNullability = attributed->getImmediateNullability()) { | ||||
7048 | // Duplicated nullability. | ||||
7049 | if (nullability == *existingNullability) { | ||||
7050 | S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) | ||||
7051 | << DiagNullabilityKind(nullability, isContextSensitive) | ||||
7052 | << FixItHint::CreateRemoval(nullabilityLoc); | ||||
7053 | |||||
7054 | break; | ||||
7055 | } | ||||
7056 | |||||
7057 | // Conflicting nullability. | ||||
7058 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) | ||||
7059 | << DiagNullabilityKind(nullability, isContextSensitive) | ||||
7060 | << DiagNullabilityKind(*existingNullability, false); | ||||
7061 | return true; | ||||
7062 | } | ||||
7063 | |||||
7064 | desugared = attributed->getModifiedType(); | ||||
7065 | } | ||||
7066 | |||||
7067 | // If there is already a different nullability specifier, complain. | ||||
7068 | // This (unlike the code above) looks through typedefs that might | ||||
7069 | // have nullability specifiers on them, which means we cannot | ||||
7070 | // provide a useful Fix-It. | ||||
7071 | if (auto existingNullability = desugared->getNullability(S.Context)) { | ||||
7072 | if (nullability != *existingNullability) { | ||||
7073 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) | ||||
7074 | << DiagNullabilityKind(nullability, isContextSensitive) | ||||
7075 | << DiagNullabilityKind(*existingNullability, false); | ||||
7076 | |||||
7077 | // Try to find the typedef with the existing nullability specifier. | ||||
7078 | if (auto typedefType = desugared->getAs<TypedefType>()) { | ||||
7079 | TypedefNameDecl *typedefDecl = typedefType->getDecl(); | ||||
7080 | QualType underlyingType = typedefDecl->getUnderlyingType(); | ||||
7081 | if (auto typedefNullability | ||||
7082 | = AttributedType::stripOuterNullability(underlyingType)) { | ||||
7083 | if (*typedefNullability == *existingNullability) { | ||||
7084 | S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) | ||||
7085 | << DiagNullabilityKind(*existingNullability, false); | ||||
7086 | } | ||||
7087 | } | ||||
7088 | } | ||||
7089 | |||||
7090 | return true; | ||||
7091 | } | ||||
7092 | } | ||||
7093 | |||||
7094 | // If this definitely isn't a pointer type, reject the specifier. | ||||
7095 | if (!desugared->canHaveNullability() && | ||||
7096 | !(allowOnArrayType && desugared->isArrayType())) { | ||||
7097 | S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) | ||||
7098 | << DiagNullabilityKind(nullability, isContextSensitive) << type; | ||||
7099 | return true; | ||||
7100 | } | ||||
7101 | |||||
7102 | // For the context-sensitive keywords/Objective-C property | ||||
7103 | // attributes, require that the type be a single-level pointer. | ||||
7104 | if (isContextSensitive) { | ||||
7105 | // Make sure that the pointee isn't itself a pointer type. | ||||
7106 | const Type *pointeeType = nullptr; | ||||
7107 | if (desugared->isArrayType()) | ||||
7108 | pointeeType = desugared->getArrayElementTypeNoTypeQual(); | ||||
7109 | else if (desugared->isAnyPointerType()) | ||||
7110 | pointeeType = desugared->getPointeeType().getTypePtr(); | ||||
7111 | |||||
7112 | if (pointeeType && (pointeeType->isAnyPointerType() || | ||||
7113 | pointeeType->isObjCObjectPointerType() || | ||||
7114 | pointeeType->isMemberPointerType())) { | ||||
7115 | S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) | ||||
7116 | << DiagNullabilityKind(nullability, true) | ||||
7117 | << type; | ||||
7118 | S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) | ||||
7119 | << DiagNullabilityKind(nullability, false) | ||||
7120 | << type | ||||
7121 | << FixItHint::CreateReplacement(nullabilityLoc, | ||||
7122 | getNullabilitySpelling(nullability)); | ||||
7123 | return true; | ||||
7124 | } | ||||
7125 | } | ||||
7126 | |||||
7127 | // Form the attributed type. | ||||
7128 | type = state.getAttributedType( | ||||
7129 | createNullabilityAttr(S.Context, attr, nullability), type, type); | ||||
7130 | return false; | ||||
7131 | } | ||||
7132 | |||||
7133 | /// Check the application of the Objective-C '__kindof' qualifier to | ||||
7134 | /// the given type. | ||||
7135 | static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, | ||||
7136 | ParsedAttr &attr) { | ||||
7137 | Sema &S = state.getSema(); | ||||
7138 | |||||
7139 | if (isa<ObjCTypeParamType>(type)) { | ||||
7140 | // Build the attributed type to record where __kindof occurred. | ||||
7141 | type = state.getAttributedType( | ||||
7142 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); | ||||
7143 | return false; | ||||
7144 | } | ||||
7145 | |||||
7146 | // Find out if it's an Objective-C object or object pointer type; | ||||
7147 | const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); | ||||
7148 | const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() | ||||
7149 | : type->getAs<ObjCObjectType>(); | ||||
7150 | |||||
7151 | // If not, we can't apply __kindof. | ||||
7152 | if (!objType) { | ||||
7153 | // FIXME: Handle dependent types that aren't yet object types. | ||||
7154 | S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) | ||||
7155 | << type; | ||||
7156 | return true; | ||||
7157 | } | ||||
7158 | |||||
7159 | // Rebuild the "equivalent" type, which pushes __kindof down into | ||||
7160 | // the object type. | ||||
7161 | // There is no need to apply kindof on an unqualified id type. | ||||
7162 | QualType equivType = S.Context.getObjCObjectType( | ||||
7163 | objType->getBaseType(), objType->getTypeArgsAsWritten(), | ||||
7164 | objType->getProtocols(), | ||||
7165 | /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); | ||||
7166 | |||||
7167 | // If we started with an object pointer type, rebuild it. | ||||
7168 | if (ptrType) { | ||||
7169 | equivType = S.Context.getObjCObjectPointerType(equivType); | ||||
7170 | if (auto nullability = type->getNullability(S.Context)) { | ||||
7171 | // We create a nullability attribute from the __kindof attribute. | ||||
7172 | // Make sure that will make sense. | ||||
7173 | assert(attr.getAttributeSpellingListIndex() == 0 &&((attr.getAttributeSpellingListIndex() == 0 && "multiple spellings for __kindof?" ) ? static_cast<void> (0) : __assert_fail ("attr.getAttributeSpellingListIndex() == 0 && \"multiple spellings for __kindof?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7174, __PRETTY_FUNCTION__)) | ||||
7174 | "multiple spellings for __kindof?")((attr.getAttributeSpellingListIndex() == 0 && "multiple spellings for __kindof?" ) ? static_cast<void> (0) : __assert_fail ("attr.getAttributeSpellingListIndex() == 0 && \"multiple spellings for __kindof?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7174, __PRETTY_FUNCTION__)); | ||||
7175 | Attr *A = createNullabilityAttr(S.Context, attr, *nullability); | ||||
7176 | A->setImplicit(true); | ||||
7177 | equivType = state.getAttributedType(A, equivType, equivType); | ||||
7178 | } | ||||
7179 | } | ||||
7180 | |||||
7181 | // Build the attributed type to record where __kindof occurred. | ||||
7182 | type = state.getAttributedType( | ||||
7183 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); | ||||
7184 | return false; | ||||
7185 | } | ||||
7186 | |||||
7187 | /// Distribute a nullability type attribute that cannot be applied to | ||||
7188 | /// the type specifier to a pointer, block pointer, or member pointer | ||||
7189 | /// declarator, complaining if necessary. | ||||
7190 | /// | ||||
7191 | /// \returns true if the nullability annotation was distributed, false | ||||
7192 | /// otherwise. | ||||
7193 | static bool distributeNullabilityTypeAttr(TypeProcessingState &state, | ||||
7194 | QualType type, ParsedAttr &attr) { | ||||
7195 | Declarator &declarator = state.getDeclarator(); | ||||
7196 | |||||
7197 | /// Attempt to move the attribute to the specified chunk. | ||||
7198 | auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { | ||||
7199 | // If there is already a nullability attribute there, don't add | ||||
7200 | // one. | ||||
7201 | if (hasNullabilityAttr(chunk.getAttrs())) | ||||
7202 | return false; | ||||
7203 | |||||
7204 | // Complain about the nullability qualifier being in the wrong | ||||
7205 | // place. | ||||
7206 | enum { | ||||
7207 | PK_Pointer, | ||||
7208 | PK_BlockPointer, | ||||
7209 | PK_MemberPointer, | ||||
7210 | PK_FunctionPointer, | ||||
7211 | PK_MemberFunctionPointer, | ||||
7212 | } pointerKind | ||||
7213 | = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer | ||||
7214 | : PK_Pointer) | ||||
7215 | : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer | ||||
7216 | : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; | ||||
7217 | |||||
7218 | auto diag = state.getSema().Diag(attr.getLoc(), | ||||
7219 | diag::warn_nullability_declspec) | ||||
7220 | << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), | ||||
7221 | attr.isContextSensitiveKeywordAttribute()) | ||||
7222 | << type | ||||
7223 | << static_cast<unsigned>(pointerKind); | ||||
7224 | |||||
7225 | // FIXME: MemberPointer chunks don't carry the location of the *. | ||||
7226 | if (chunk.Kind != DeclaratorChunk::MemberPointer) { | ||||
7227 | diag << FixItHint::CreateRemoval(attr.getLoc()) | ||||
7228 | << FixItHint::CreateInsertion( | ||||
7229 | state.getSema().getPreprocessor().getLocForEndOfToken( | ||||
7230 | chunk.Loc), | ||||
7231 | " " + attr.getAttrName()->getName().str() + " "); | ||||
7232 | } | ||||
7233 | |||||
7234 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | ||||
7235 | chunk.getAttrs()); | ||||
7236 | return true; | ||||
7237 | }; | ||||
7238 | |||||
7239 | // Move it to the outermost pointer, member pointer, or block | ||||
7240 | // pointer declarator. | ||||
7241 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | ||||
7242 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | ||||
7243 | switch (chunk.Kind) { | ||||
7244 | case DeclaratorChunk::Pointer: | ||||
7245 | case DeclaratorChunk::BlockPointer: | ||||
7246 | case DeclaratorChunk::MemberPointer: | ||||
7247 | return moveToChunk(chunk, false); | ||||
7248 | |||||
7249 | case DeclaratorChunk::Paren: | ||||
7250 | case DeclaratorChunk::Array: | ||||
7251 | continue; | ||||
7252 | |||||
7253 | case DeclaratorChunk::Function: | ||||
7254 | // Try to move past the return type to a function/block/member | ||||
7255 | // function pointer. | ||||
7256 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | ||||
7257 | declarator, i, | ||||
7258 | /*onlyBlockPointers=*/false)) { | ||||
7259 | return moveToChunk(*dest, true); | ||||
7260 | } | ||||
7261 | |||||
7262 | return false; | ||||
7263 | |||||
7264 | // Don't walk through these. | ||||
7265 | case DeclaratorChunk::Reference: | ||||
7266 | case DeclaratorChunk::Pipe: | ||||
7267 | return false; | ||||
7268 | } | ||||
7269 | } | ||||
7270 | |||||
7271 | return false; | ||||
7272 | } | ||||
7273 | |||||
7274 | static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { | ||||
7275 | assert(!Attr.isInvalid())((!Attr.isInvalid()) ? static_cast<void> (0) : __assert_fail ("!Attr.isInvalid()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7275, __PRETTY_FUNCTION__)); | ||||
7276 | switch (Attr.getKind()) { | ||||
7277 | default: | ||||
7278 | llvm_unreachable("not a calling convention attribute")::llvm::llvm_unreachable_internal("not a calling convention attribute" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7278); | ||||
7279 | case ParsedAttr::AT_CDecl: | ||||
7280 | return createSimpleAttr<CDeclAttr>(Ctx, Attr); | ||||
7281 | case ParsedAttr::AT_FastCall: | ||||
7282 | return createSimpleAttr<FastCallAttr>(Ctx, Attr); | ||||
7283 | case ParsedAttr::AT_StdCall: | ||||
7284 | return createSimpleAttr<StdCallAttr>(Ctx, Attr); | ||||
7285 | case ParsedAttr::AT_ThisCall: | ||||
7286 | return createSimpleAttr<ThisCallAttr>(Ctx, Attr); | ||||
7287 | case ParsedAttr::AT_RegCall: | ||||
7288 | return createSimpleAttr<RegCallAttr>(Ctx, Attr); | ||||
7289 | case ParsedAttr::AT_Pascal: | ||||
7290 | return createSimpleAttr<PascalAttr>(Ctx, Attr); | ||||
7291 | case ParsedAttr::AT_SwiftCall: | ||||
7292 | return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); | ||||
7293 | case ParsedAttr::AT_VectorCall: | ||||
7294 | return createSimpleAttr<VectorCallAttr>(Ctx, Attr); | ||||
7295 | case ParsedAttr::AT_AArch64VectorPcs: | ||||
7296 | return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); | ||||
7297 | case ParsedAttr::AT_Pcs: { | ||||
7298 | // The attribute may have had a fixit applied where we treated an | ||||
7299 | // identifier as a string literal. The contents of the string are valid, | ||||
7300 | // but the form may not be. | ||||
7301 | StringRef Str; | ||||
7302 | if (Attr.isArgExpr(0)) | ||||
7303 | Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); | ||||
7304 | else | ||||
7305 | Str = Attr.getArgAsIdent(0)->Ident->getName(); | ||||
7306 | PcsAttr::PCSType Type; | ||||
7307 | if (!PcsAttr::ConvertStrToPCSType(Str, Type)) | ||||
7308 | llvm_unreachable("already validated the attribute")::llvm::llvm_unreachable_internal("already validated the attribute" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7308); | ||||
7309 | return ::new (Ctx) PcsAttr(Ctx, Attr, Type); | ||||
7310 | } | ||||
7311 | case ParsedAttr::AT_IntelOclBicc: | ||||
7312 | return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); | ||||
7313 | case ParsedAttr::AT_MSABI: | ||||
7314 | return createSimpleAttr<MSABIAttr>(Ctx, Attr); | ||||
7315 | case ParsedAttr::AT_SysVABI: | ||||
7316 | return createSimpleAttr<SysVABIAttr>(Ctx, Attr); | ||||
7317 | case ParsedAttr::AT_PreserveMost: | ||||
7318 | return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); | ||||
7319 | case ParsedAttr::AT_PreserveAll: | ||||
7320 | return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); | ||||
7321 | } | ||||
7322 | llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7322); | ||||
7323 | } | ||||
7324 | |||||
7325 | /// Process an individual function attribute. Returns true to | ||||
7326 | /// indicate that the attribute was handled, false if it wasn't. | ||||
7327 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | ||||
7328 | QualType &type) { | ||||
7329 | Sema &S = state.getSema(); | ||||
7330 | |||||
7331 | FunctionTypeUnwrapper unwrapped(S, type); | ||||
7332 | |||||
7333 | if (attr.getKind() == ParsedAttr::AT_NoReturn) { | ||||
7334 | if (S.CheckAttrNoArgs(attr)) | ||||
7335 | return true; | ||||
7336 | |||||
7337 | // Delay if this is not a function type. | ||||
7338 | if (!unwrapped.isFunctionType()) | ||||
7339 | return false; | ||||
7340 | |||||
7341 | // Otherwise we can process right away. | ||||
7342 | FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); | ||||
7343 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | ||||
7344 | return true; | ||||
7345 | } | ||||
7346 | |||||
7347 | if (attr.getKind() == ParsedAttr::AT_CmseNSCall) { | ||||
7348 | // Delay if this is not a function type. | ||||
7349 | if (!unwrapped.isFunctionType()) | ||||
7350 | return false; | ||||
7351 | |||||
7352 | // Ignore if we don't have CMSE enabled. | ||||
7353 | if (!S.getLangOpts().Cmse) { | ||||
7354 | S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr; | ||||
7355 | attr.setInvalid(); | ||||
7356 | return true; | ||||
7357 | } | ||||
7358 | |||||
7359 | // Otherwise we can process right away. | ||||
7360 | FunctionType::ExtInfo EI = | ||||
7361 | unwrapped.get()->getExtInfo().withCmseNSCall(true); | ||||
7362 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | ||||
7363 | return true; | ||||
7364 | } | ||||
7365 | |||||
7366 | // ns_returns_retained is not always a type attribute, but if we got | ||||
7367 | // here, we're treating it as one right now. | ||||
7368 | if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { | ||||
7369 | if (attr.getNumArgs()) return true; | ||||
7370 | |||||
7371 | // Delay if this is not a function type. | ||||
7372 | if (!unwrapped.isFunctionType()) | ||||
7373 | return false; | ||||
7374 | |||||
7375 | // Check whether the return type is reasonable. | ||||
7376 | if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), | ||||
7377 | unwrapped.get()->getReturnType())) | ||||
7378 | return true; | ||||
7379 | |||||
7380 | // Only actually change the underlying type in ARC builds. | ||||
7381 | QualType origType = type; | ||||
7382 | if (state.getSema().getLangOpts().ObjCAutoRefCount) { | ||||
7383 | FunctionType::ExtInfo EI | ||||
7384 | = unwrapped.get()->getExtInfo().withProducesResult(true); | ||||
7385 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | ||||
7386 | } | ||||
7387 | type = state.getAttributedType( | ||||
7388 | createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), | ||||
7389 | origType, type); | ||||
7390 | return true; | ||||
7391 | } | ||||
7392 | |||||
7393 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { | ||||
7394 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) | ||||
7395 | return true; | ||||
7396 | |||||
7397 | // Delay if this is not a function type. | ||||
7398 | if (!unwrapped.isFunctionType()) | ||||
7399 | return false; | ||||
7400 | |||||
7401 | FunctionType::ExtInfo EI = | ||||
7402 | unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); | ||||
7403 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | ||||
7404 | return true; | ||||
7405 | } | ||||
7406 | |||||
7407 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { | ||||
7408 | if (!S.getLangOpts().CFProtectionBranch) { | ||||
7409 | S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); | ||||
7410 | attr.setInvalid(); | ||||
7411 | return true; | ||||
7412 | } | ||||
7413 | |||||
7414 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) | ||||
7415 | return true; | ||||
7416 | |||||
7417 | // If this is not a function type, warning will be asserted by subject | ||||
7418 | // check. | ||||
7419 | if (!unwrapped.isFunctionType()) | ||||
7420 | return true; | ||||
7421 | |||||
7422 | FunctionType::ExtInfo EI = | ||||
7423 | unwrapped.get()->getExtInfo().withNoCfCheck(true); | ||||
7424 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | ||||
7425 | return true; | ||||
7426 | } | ||||
7427 | |||||
7428 | if (attr.getKind() == ParsedAttr::AT_Regparm) { | ||||
7429 | unsigned value; | ||||
7430 | if (S.CheckRegparmAttr(attr, value)) | ||||
7431 | return true; | ||||
7432 | |||||
7433 | // Delay if this is not a function type. | ||||
7434 | if (!unwrapped.isFunctionType()) | ||||
7435 | return false; | ||||
7436 | |||||
7437 | // Diagnose regparm with fastcall. | ||||
7438 | const FunctionType *fn = unwrapped.get(); | ||||
7439 | CallingConv CC = fn->getCallConv(); | ||||
7440 | if (CC == CC_X86FastCall) { | ||||
7441 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | ||||
7442 | << FunctionType::getNameForCallConv(CC) | ||||
7443 | << "regparm"; | ||||
7444 | attr.setInvalid(); | ||||
7445 | return true; | ||||
7446 | } | ||||
7447 | |||||
7448 | FunctionType::ExtInfo EI = | ||||
7449 | unwrapped.get()->getExtInfo().withRegParm(value); | ||||
7450 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | ||||
7451 | return true; | ||||
7452 | } | ||||
7453 | |||||
7454 | if (attr.getKind() == ParsedAttr::AT_NoThrow) { | ||||
7455 | // Delay if this is not a function type. | ||||
7456 | if (!unwrapped.isFunctionType()) | ||||
7457 | return false; | ||||
7458 | |||||
7459 | if (S.CheckAttrNoArgs(attr)) { | ||||
7460 | attr.setInvalid(); | ||||
7461 | return true; | ||||
7462 | } | ||||
7463 | |||||
7464 | // Otherwise we can process right away. | ||||
7465 | auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); | ||||
7466 | |||||
7467 | // MSVC ignores nothrow if it is in conflict with an explicit exception | ||||
7468 | // specification. | ||||
7469 | if (Proto->hasExceptionSpec()) { | ||||
7470 | switch (Proto->getExceptionSpecType()) { | ||||
7471 | case EST_None: | ||||
7472 | llvm_unreachable("This doesn't have an exception spec!")::llvm::llvm_unreachable_internal("This doesn't have an exception spec!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7472); | ||||
7473 | |||||
7474 | case EST_DynamicNone: | ||||
7475 | case EST_BasicNoexcept: | ||||
7476 | case EST_NoexceptTrue: | ||||
7477 | case EST_NoThrow: | ||||
7478 | // Exception spec doesn't conflict with nothrow, so don't warn. | ||||
7479 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
7480 | case EST_Unparsed: | ||||
7481 | case EST_Uninstantiated: | ||||
7482 | case EST_DependentNoexcept: | ||||
7483 | case EST_Unevaluated: | ||||
7484 | // We don't have enough information to properly determine if there is a | ||||
7485 | // conflict, so suppress the warning. | ||||
7486 | break; | ||||
7487 | case EST_Dynamic: | ||||
7488 | case EST_MSAny: | ||||
7489 | case EST_NoexceptFalse: | ||||
7490 | S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); | ||||
7491 | break; | ||||
7492 | } | ||||
7493 | return true; | ||||
7494 | } | ||||
7495 | |||||
7496 | type = unwrapped.wrap( | ||||
7497 | S, S.Context | ||||
7498 | .getFunctionTypeWithExceptionSpec( | ||||
7499 | QualType{Proto, 0}, | ||||
7500 | FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) | ||||
7501 | ->getAs<FunctionType>()); | ||||
7502 | return true; | ||||
7503 | } | ||||
7504 | |||||
7505 | // Delay if the type didn't work out to a function. | ||||
7506 | if (!unwrapped.isFunctionType()) return false; | ||||
7507 | |||||
7508 | // Otherwise, a calling convention. | ||||
7509 | CallingConv CC; | ||||
7510 | if (S.CheckCallingConvAttr(attr, CC)) | ||||
7511 | return true; | ||||
7512 | |||||
7513 | const FunctionType *fn = unwrapped.get(); | ||||
7514 | CallingConv CCOld = fn->getCallConv(); | ||||
7515 | Attr *CCAttr = getCCTypeAttr(S.Context, attr); | ||||
7516 | |||||
7517 | if (CCOld != CC) { | ||||
7518 | // Error out on when there's already an attribute on the type | ||||
7519 | // and the CCs don't match. | ||||
7520 | if (S.getCallingConvAttributedType(type)) { | ||||
7521 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | ||||
7522 | << FunctionType::getNameForCallConv(CC) | ||||
7523 | << FunctionType::getNameForCallConv(CCOld); | ||||
7524 | attr.setInvalid(); | ||||
7525 | return true; | ||||
7526 | } | ||||
7527 | } | ||||
7528 | |||||
7529 | // Diagnose use of variadic functions with calling conventions that | ||||
7530 | // don't support them (e.g. because they're callee-cleanup). | ||||
7531 | // We delay warning about this on unprototyped function declarations | ||||
7532 | // until after redeclaration checking, just in case we pick up a | ||||
7533 | // prototype that way. And apparently we also "delay" warning about | ||||
7534 | // unprototyped function types in general, despite not necessarily having | ||||
7535 | // much ability to diagnose it later. | ||||
7536 | if (!supportsVariadicCall(CC)) { | ||||
7537 | const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); | ||||
7538 | if (FnP && FnP->isVariadic()) { | ||||
7539 | // stdcall and fastcall are ignored with a warning for GCC and MS | ||||
7540 | // compatibility. | ||||
7541 | if (CC == CC_X86StdCall || CC == CC_X86FastCall) | ||||
7542 | return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) | ||||
7543 | << FunctionType::getNameForCallConv(CC) | ||||
7544 | << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; | ||||
7545 | |||||
7546 | attr.setInvalid(); | ||||
7547 | return S.Diag(attr.getLoc(), diag::err_cconv_varargs) | ||||
7548 | << FunctionType::getNameForCallConv(CC); | ||||
7549 | } | ||||
7550 | } | ||||
7551 | |||||
7552 | // Also diagnose fastcall with regparm. | ||||
7553 | if (CC == CC_X86FastCall && fn->getHasRegParm()) { | ||||
7554 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | ||||
7555 | << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); | ||||
7556 | attr.setInvalid(); | ||||
7557 | return true; | ||||
7558 | } | ||||
7559 | |||||
7560 | // Modify the CC from the wrapped function type, wrap it all back, and then | ||||
7561 | // wrap the whole thing in an AttributedType as written. The modified type | ||||
7562 | // might have a different CC if we ignored the attribute. | ||||
7563 | QualType Equivalent; | ||||
7564 | if (CCOld == CC) { | ||||
7565 | Equivalent = type; | ||||
7566 | } else { | ||||
7567 | auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); | ||||
7568 | Equivalent = | ||||
7569 | unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | ||||
7570 | } | ||||
7571 | type = state.getAttributedType(CCAttr, type, Equivalent); | ||||
7572 | return true; | ||||
7573 | } | ||||
7574 | |||||
7575 | bool Sema::hasExplicitCallingConv(QualType T) { | ||||
7576 | const AttributedType *AT; | ||||
7577 | |||||
7578 | // Stop if we'd be stripping off a typedef sugar node to reach the | ||||
7579 | // AttributedType. | ||||
7580 | while ((AT = T->getAs<AttributedType>()) && | ||||
7581 | AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { | ||||
7582 | if (AT->isCallingConv()) | ||||
7583 | return true; | ||||
7584 | T = AT->getModifiedType(); | ||||
7585 | } | ||||
7586 | return false; | ||||
7587 | } | ||||
7588 | |||||
7589 | void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, | ||||
7590 | SourceLocation Loc) { | ||||
7591 | FunctionTypeUnwrapper Unwrapped(*this, T); | ||||
7592 | const FunctionType *FT = Unwrapped.get(); | ||||
7593 | bool IsVariadic = (isa<FunctionProtoType>(FT) && | ||||
7594 | cast<FunctionProtoType>(FT)->isVariadic()); | ||||
7595 | CallingConv CurCC = FT->getCallConv(); | ||||
7596 | CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); | ||||
7597 | |||||
7598 | if (CurCC == ToCC) | ||||
7599 | return; | ||||
7600 | |||||
7601 | // MS compiler ignores explicit calling convention attributes on structors. We | ||||
7602 | // should do the same. | ||||
7603 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { | ||||
7604 | // Issue a warning on ignored calling convention -- except of __stdcall. | ||||
7605 | // Again, this is what MS compiler does. | ||||
7606 | if (CurCC != CC_X86StdCall) | ||||
7607 | Diag(Loc, diag::warn_cconv_unsupported) | ||||
7608 | << FunctionType::getNameForCallConv(CurCC) | ||||
7609 | << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; | ||||
7610 | // Default adjustment. | ||||
7611 | } else { | ||||
7612 | // Only adjust types with the default convention. For example, on Windows | ||||
7613 | // we should adjust a __cdecl type to __thiscall for instance methods, and a | ||||
7614 | // __thiscall type to __cdecl for static methods. | ||||
7615 | CallingConv DefaultCC = | ||||
7616 | Context.getDefaultCallingConvention(IsVariadic, IsStatic); | ||||
7617 | |||||
7618 | if (CurCC != DefaultCC || DefaultCC == ToCC) | ||||
7619 | return; | ||||
7620 | |||||
7621 | if (hasExplicitCallingConv(T)) | ||||
7622 | return; | ||||
7623 | } | ||||
7624 | |||||
7625 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); | ||||
7626 | QualType Wrapped = Unwrapped.wrap(*this, FT); | ||||
7627 | T = Context.getAdjustedType(T, Wrapped); | ||||
7628 | } | ||||
7629 | |||||
7630 | /// HandleVectorSizeAttribute - this attribute is only applicable to integral | ||||
7631 | /// and float scalars, although arrays, pointers, and function return values are | ||||
7632 | /// allowed in conjunction with this construct. Aggregates with this attribute | ||||
7633 | /// are invalid, even if they are of the same size as a corresponding scalar. | ||||
7634 | /// The raw attribute should contain precisely 1 argument, the vector size for | ||||
7635 | /// the variable, measured in bytes. If curType and rawAttr are well formed, | ||||
7636 | /// this routine will return a new vector type. | ||||
7637 | static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, | ||||
7638 | Sema &S) { | ||||
7639 | // Check the attribute arguments. | ||||
7640 | if (Attr.getNumArgs() != 1) { | ||||
7641 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | ||||
7642 | << 1; | ||||
7643 | Attr.setInvalid(); | ||||
7644 | return; | ||||
7645 | } | ||||
7646 | |||||
7647 | Expr *SizeExpr; | ||||
7648 | // Special case where the argument is a template id. | ||||
7649 | if (Attr.isArgIdent(0)) { | ||||
7650 | CXXScopeSpec SS; | ||||
7651 | SourceLocation TemplateKWLoc; | ||||
7652 | UnqualifiedId Id; | ||||
7653 | Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | ||||
7654 | |||||
7655 | ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, | ||||
7656 | Id, /*HasTrailingLParen=*/false, | ||||
7657 | /*IsAddressOfOperand=*/false); | ||||
7658 | |||||
7659 | if (Size.isInvalid()) | ||||
7660 | return; | ||||
7661 | SizeExpr = Size.get(); | ||||
7662 | } else { | ||||
7663 | SizeExpr = Attr.getArgAsExpr(0); | ||||
7664 | } | ||||
7665 | |||||
7666 | QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); | ||||
7667 | if (!T.isNull()) | ||||
7668 | CurType = T; | ||||
7669 | else | ||||
7670 | Attr.setInvalid(); | ||||
7671 | } | ||||
7672 | |||||
7673 | /// Process the OpenCL-like ext_vector_type attribute when it occurs on | ||||
7674 | /// a type. | ||||
7675 | static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, | ||||
7676 | Sema &S) { | ||||
7677 | // check the attribute arguments. | ||||
7678 | if (Attr.getNumArgs() != 1) { | ||||
7679 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | ||||
7680 | << 1; | ||||
7681 | return; | ||||
7682 | } | ||||
7683 | |||||
7684 | Expr *sizeExpr; | ||||
7685 | |||||
7686 | // Special case where the argument is a template id. | ||||
7687 | if (Attr.isArgIdent(0)) { | ||||
7688 | CXXScopeSpec SS; | ||||
7689 | SourceLocation TemplateKWLoc; | ||||
7690 | UnqualifiedId id; | ||||
7691 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | ||||
7692 | |||||
7693 | ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, | ||||
7694 | id, /*HasTrailingLParen=*/false, | ||||
7695 | /*IsAddressOfOperand=*/false); | ||||
7696 | if (Size.isInvalid()) | ||||
7697 | return; | ||||
7698 | |||||
7699 | sizeExpr = Size.get(); | ||||
7700 | } else { | ||||
7701 | sizeExpr = Attr.getArgAsExpr(0); | ||||
7702 | } | ||||
7703 | |||||
7704 | // Create the vector type. | ||||
7705 | QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); | ||||
7706 | if (!T.isNull()) | ||||
7707 | CurType = T; | ||||
7708 | } | ||||
7709 | |||||
7710 | static bool isPermittedNeonBaseType(QualType &Ty, | ||||
7711 | VectorType::VectorKind VecKind, Sema &S) { | ||||
7712 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | ||||
7713 | if (!BTy) | ||||
7714 | return false; | ||||
7715 | |||||
7716 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); | ||||
7717 | |||||
7718 | // Signed poly is mathematically wrong, but has been baked into some ABIs by | ||||
7719 | // now. | ||||
7720 | bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || | ||||
7721 | Triple.getArch() == llvm::Triple::aarch64_32 || | ||||
7722 | Triple.getArch() == llvm::Triple::aarch64_be; | ||||
7723 | if (VecKind == VectorType::NeonPolyVector) { | ||||
7724 | if (IsPolyUnsigned) { | ||||
7725 | // AArch64 polynomial vectors are unsigned. | ||||
7726 | return BTy->getKind() == BuiltinType::UChar || | ||||
7727 | BTy->getKind() == BuiltinType::UShort || | ||||
7728 | BTy->getKind() == BuiltinType::ULong || | ||||
7729 | BTy->getKind() == BuiltinType::ULongLong; | ||||
7730 | } else { | ||||
7731 | // AArch32 polynomial vectors are signed. | ||||
7732 | return BTy->getKind() == BuiltinType::SChar || | ||||
7733 | BTy->getKind() == BuiltinType::Short || | ||||
7734 | BTy->getKind() == BuiltinType::LongLong; | ||||
7735 | } | ||||
7736 | } | ||||
7737 | |||||
7738 | // Non-polynomial vector types: the usual suspects are allowed, as well as | ||||
7739 | // float64_t on AArch64. | ||||
7740 | if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) && | ||||
7741 | BTy->getKind() == BuiltinType::Double) | ||||
7742 | return true; | ||||
7743 | |||||
7744 | return BTy->getKind() == BuiltinType::SChar || | ||||
7745 | BTy->getKind() == BuiltinType::UChar || | ||||
7746 | BTy->getKind() == BuiltinType::Short || | ||||
7747 | BTy->getKind() == BuiltinType::UShort || | ||||
7748 | BTy->getKind() == BuiltinType::Int || | ||||
7749 | BTy->getKind() == BuiltinType::UInt || | ||||
7750 | BTy->getKind() == BuiltinType::Long || | ||||
7751 | BTy->getKind() == BuiltinType::ULong || | ||||
7752 | BTy->getKind() == BuiltinType::LongLong || | ||||
7753 | BTy->getKind() == BuiltinType::ULongLong || | ||||
7754 | BTy->getKind() == BuiltinType::Float || | ||||
7755 | BTy->getKind() == BuiltinType::Half || | ||||
7756 | BTy->getKind() == BuiltinType::BFloat16; | ||||
7757 | } | ||||
7758 | |||||
7759 | static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, | ||||
7760 | llvm::APSInt &Result) { | ||||
7761 | const auto *AttrExpr = Attr.getArgAsExpr(0); | ||||
7762 | if (!AttrExpr->isTypeDependent() && !AttrExpr->isValueDependent()) { | ||||
7763 | if (Optional<llvm::APSInt> Res = | ||||
7764 | AttrExpr->getIntegerConstantExpr(S.Context)) { | ||||
7765 | Result = *Res; | ||||
7766 | return true; | ||||
7767 | } | ||||
7768 | } | ||||
7769 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) | ||||
7770 | << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange(); | ||||
7771 | Attr.setInvalid(); | ||||
7772 | return false; | ||||
7773 | } | ||||
7774 | |||||
7775 | /// HandleNeonVectorTypeAttr - The "neon_vector_type" and | ||||
7776 | /// "neon_polyvector_type" attributes are used to create vector types that | ||||
7777 | /// are mangled according to ARM's ABI. Otherwise, these types are identical | ||||
7778 | /// to those created with the "vector_size" attribute. Unlike "vector_size" | ||||
7779 | /// the argument to these Neon attributes is the number of vector elements, | ||||
7780 | /// not the vector size in bytes. The vector width and element type must | ||||
7781 | /// match one of the standard Neon vector types. | ||||
7782 | static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, | ||||
7783 | Sema &S, VectorType::VectorKind VecKind) { | ||||
7784 | // Target must have NEON (or MVE, whose vectors are similar enough | ||||
7785 | // not to need a separate attribute) | ||||
7786 | if (!S.Context.getTargetInfo().hasFeature("neon") && | ||||
7787 | !S.Context.getTargetInfo().hasFeature("mve")) { | ||||
7788 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr; | ||||
7789 | Attr.setInvalid(); | ||||
7790 | return; | ||||
7791 | } | ||||
7792 | // Check the attribute arguments. | ||||
7793 | if (Attr.getNumArgs() != 1) { | ||||
7794 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | ||||
7795 | << 1; | ||||
7796 | Attr.setInvalid(); | ||||
7797 | return; | ||||
7798 | } | ||||
7799 | // The number of elements must be an ICE. | ||||
7800 | llvm::APSInt numEltsInt(32); | ||||
7801 | if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt)) | ||||
7802 | return; | ||||
7803 | |||||
7804 | // Only certain element types are supported for Neon vectors. | ||||
7805 | if (!isPermittedNeonBaseType(CurType, VecKind, S)) { | ||||
7806 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; | ||||
7807 | Attr.setInvalid(); | ||||
7808 | return; | ||||
7809 | } | ||||
7810 | |||||
7811 | // The total size of the vector must be 64 or 128 bits. | ||||
7812 | unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); | ||||
7813 | unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); | ||||
7814 | unsigned vecSize = typeSize * numElts; | ||||
7815 | if (vecSize != 64 && vecSize != 128) { | ||||
7816 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; | ||||
7817 | Attr.setInvalid(); | ||||
7818 | return; | ||||
7819 | } | ||||
7820 | |||||
7821 | CurType = S.Context.getVectorType(CurType, numElts, VecKind); | ||||
7822 | } | ||||
7823 | |||||
7824 | /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is | ||||
7825 | /// used to create fixed-length versions of sizeless SVE types defined by | ||||
7826 | /// the ACLE, such as svint32_t and svbool_t. | ||||
7827 | static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, | ||||
7828 | Sema &S) { | ||||
7829 | // Target must have SVE. | ||||
7830 | if (!S.Context.getTargetInfo().hasFeature("sve")) { | ||||
7831 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr; | ||||
7832 | Attr.setInvalid(); | ||||
7833 | return; | ||||
7834 | } | ||||
7835 | |||||
7836 | // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified. | ||||
7837 | if (!S.getLangOpts().ArmSveVectorBits) { | ||||
7838 | S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported) | ||||
7839 | << Attr; | ||||
7840 | Attr.setInvalid(); | ||||
7841 | return; | ||||
7842 | } | ||||
7843 | |||||
7844 | // Check the attribute arguments. | ||||
7845 | if (Attr.getNumArgs() != 1) { | ||||
7846 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | ||||
7847 | << Attr << 1; | ||||
7848 | Attr.setInvalid(); | ||||
7849 | return; | ||||
7850 | } | ||||
7851 | |||||
7852 | // The vector size must be an integer constant expression. | ||||
7853 | llvm::APSInt SveVectorSizeInBits(32); | ||||
7854 | if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits)) | ||||
7855 | return; | ||||
7856 | |||||
7857 | unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue()); | ||||
7858 | |||||
7859 | // The attribute vector size must match -msve-vector-bits. | ||||
7860 | if (VecSize != S.getLangOpts().ArmSveVectorBits) { | ||||
7861 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size) | ||||
7862 | << VecSize << S.getLangOpts().ArmSveVectorBits; | ||||
7863 | Attr.setInvalid(); | ||||
7864 | return; | ||||
7865 | } | ||||
7866 | |||||
7867 | // Attribute can only be attached to a single SVE vector or predicate type. | ||||
7868 | if (!CurType->isVLSTBuiltinType()) { | ||||
7869 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type) | ||||
7870 | << Attr << CurType; | ||||
7871 | Attr.setInvalid(); | ||||
7872 | return; | ||||
7873 | } | ||||
7874 | |||||
7875 | const auto *BT = CurType->castAs<BuiltinType>(); | ||||
7876 | |||||
7877 | QualType EltType = CurType->getSveEltType(S.Context); | ||||
7878 | unsigned TypeSize = S.Context.getTypeSize(EltType); | ||||
7879 | VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector; | ||||
7880 | if (BT->getKind() == BuiltinType::SveBool) { | ||||
7881 | // Predicates are represented as i8. | ||||
7882 | VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth(); | ||||
7883 | VecKind = VectorType::SveFixedLengthPredicateVector; | ||||
7884 | } else | ||||
7885 | VecSize /= TypeSize; | ||||
7886 | CurType = S.Context.getVectorType(EltType, VecSize, VecKind); | ||||
7887 | } | ||||
7888 | |||||
7889 | static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, | ||||
7890 | QualType &CurType, | ||||
7891 | ParsedAttr &Attr) { | ||||
7892 | const VectorType *VT = dyn_cast<VectorType>(CurType); | ||||
7893 | if (!VT || VT->getVectorKind() != VectorType::NeonVector) { | ||||
7894 | State.getSema().Diag(Attr.getLoc(), | ||||
7895 | diag::err_attribute_arm_mve_polymorphism); | ||||
7896 | Attr.setInvalid(); | ||||
7897 | return; | ||||
7898 | } | ||||
7899 | |||||
7900 | CurType = | ||||
7901 | State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>( | ||||
7902 | State.getSema().Context, Attr), | ||||
7903 | CurType, CurType); | ||||
7904 | } | ||||
7905 | |||||
7906 | /// Handle OpenCL Access Qualifier Attribute. | ||||
7907 | static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, | ||||
7908 | Sema &S) { | ||||
7909 | // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. | ||||
7910 | if (!(CurType->isImageType() || CurType->isPipeType())) { | ||||
7911 | S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); | ||||
7912 | Attr.setInvalid(); | ||||
7913 | return; | ||||
7914 | } | ||||
7915 | |||||
7916 | if (const TypedefType* TypedefTy
| ||||
7917 | QualType BaseTy = TypedefTy->desugar(); | ||||
7918 | |||||
7919 | std::string PrevAccessQual; | ||||
7920 | if (BaseTy->isPipeType()) { | ||||
7921 | if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { | ||||
7922 | OpenCLAccessAttr *Attr = | ||||
7923 | TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); | ||||
7924 | PrevAccessQual = Attr->getSpelling(); | ||||
7925 | } else { | ||||
7926 | PrevAccessQual = "read_only"; | ||||
7927 | } | ||||
7928 | } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { | ||||
7929 | |||||
7930 | switch (ImgType->getKind()) { | ||||
7931 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
7932 | case BuiltinType::Id: \ | ||||
7933 | PrevAccessQual = #Access; \ | ||||
7934 | break; | ||||
7935 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
7936 | default: | ||||
7937 | llvm_unreachable("Unable to find corresponding image type.")::llvm::llvm_unreachable_internal("Unable to find corresponding image type." , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7937); | ||||
7938 | } | ||||
7939 | } else { | ||||
7940 | llvm_unreachable("unexpected type")::llvm::llvm_unreachable_internal("unexpected type", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7940); | ||||
7941 | } | ||||
7942 | StringRef AttrName = Attr.getAttrName()->getName(); | ||||
7943 | if (PrevAccessQual == AttrName.ltrim("_")) { | ||||
7944 | // Duplicated qualifiers | ||||
7945 | S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) | ||||
7946 | << AttrName << Attr.getRange(); | ||||
7947 | } else { | ||||
7948 | // Contradicting qualifiers | ||||
7949 | S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); | ||||
7950 | } | ||||
7951 | |||||
7952 | S.Diag(TypedefTy->getDecl()->getBeginLoc(), | ||||
7953 | diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; | ||||
7954 | } else if (CurType->isPipeType()) { | ||||
7955 | if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { | ||||
7956 | QualType ElemType = CurType->getAs<PipeType>()->getElementType(); | ||||
| |||||
7957 | CurType = S.Context.getWritePipeType(ElemType); | ||||
7958 | } | ||||
7959 | } | ||||
7960 | } | ||||
7961 | |||||
7962 | /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type | ||||
7963 | static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, | ||||
7964 | Sema &S) { | ||||
7965 | if (!S.getLangOpts().MatrixTypes) { | ||||
7966 | S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled); | ||||
7967 | return; | ||||
7968 | } | ||||
7969 | |||||
7970 | if (Attr.getNumArgs() != 2) { | ||||
7971 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | ||||
7972 | << Attr << 2; | ||||
7973 | return; | ||||
7974 | } | ||||
7975 | |||||
7976 | Expr *RowsExpr = nullptr; | ||||
7977 | Expr *ColsExpr = nullptr; | ||||
7978 | |||||
7979 | // TODO: Refactor parameter extraction into separate function | ||||
7980 | // Get the number of rows | ||||
7981 | if (Attr.isArgIdent(0)) { | ||||
7982 | CXXScopeSpec SS; | ||||
7983 | SourceLocation TemplateKeywordLoc; | ||||
7984 | UnqualifiedId id; | ||||
7985 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | ||||
7986 | ExprResult Rows = S.ActOnIdExpression(S.getCurScope(), SS, | ||||
7987 | TemplateKeywordLoc, id, false, false); | ||||
7988 | |||||
7989 | if (Rows.isInvalid()) | ||||
7990 | // TODO: maybe a good error message would be nice here | ||||
7991 | return; | ||||
7992 | RowsExpr = Rows.get(); | ||||
7993 | } else { | ||||
7994 | assert(Attr.isArgExpr(0) &&((Attr.isArgExpr(0) && "Argument to should either be an identity or expression" ) ? static_cast<void> (0) : __assert_fail ("Attr.isArgExpr(0) && \"Argument to should either be an identity or expression\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7995, __PRETTY_FUNCTION__)) | ||||
7995 | "Argument to should either be an identity or expression")((Attr.isArgExpr(0) && "Argument to should either be an identity or expression" ) ? static_cast<void> (0) : __assert_fail ("Attr.isArgExpr(0) && \"Argument to should either be an identity or expression\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 7995, __PRETTY_FUNCTION__)); | ||||
7996 | RowsExpr = Attr.getArgAsExpr(0); | ||||
7997 | } | ||||
7998 | |||||
7999 | // Get the number of columns | ||||
8000 | if (Attr.isArgIdent(1)) { | ||||
8001 | CXXScopeSpec SS; | ||||
8002 | SourceLocation TemplateKeywordLoc; | ||||
8003 | UnqualifiedId id; | ||||
8004 | id.setIdentifier(Attr.getArgAsIdent(1)->Ident, Attr.getLoc()); | ||||
8005 | ExprResult Columns = S.ActOnIdExpression( | ||||
8006 | S.getCurScope(), SS, TemplateKeywordLoc, id, false, false); | ||||
8007 | |||||
8008 | if (Columns.isInvalid()) | ||||
8009 | // TODO: a good error message would be nice here | ||||
8010 | return; | ||||
8011 | RowsExpr = Columns.get(); | ||||
8012 | } else { | ||||
8013 | assert(Attr.isArgExpr(1) &&((Attr.isArgExpr(1) && "Argument to should either be an identity or expression" ) ? static_cast<void> (0) : __assert_fail ("Attr.isArgExpr(1) && \"Argument to should either be an identity or expression\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8014, __PRETTY_FUNCTION__)) | ||||
8014 | "Argument to should either be an identity or expression")((Attr.isArgExpr(1) && "Argument to should either be an identity or expression" ) ? static_cast<void> (0) : __assert_fail ("Attr.isArgExpr(1) && \"Argument to should either be an identity or expression\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8014, __PRETTY_FUNCTION__)); | ||||
8015 | ColsExpr = Attr.getArgAsExpr(1); | ||||
8016 | } | ||||
8017 | |||||
8018 | // Create the matrix type. | ||||
8019 | QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc()); | ||||
8020 | if (!T.isNull()) | ||||
8021 | CurType = T; | ||||
8022 | } | ||||
8023 | |||||
8024 | static void HandleLifetimeBoundAttr(TypeProcessingState &State, | ||||
8025 | QualType &CurType, | ||||
8026 | ParsedAttr &Attr) { | ||||
8027 | if (State.getDeclarator().isDeclarationOfFunction()) { | ||||
8028 | CurType = State.getAttributedType( | ||||
8029 | createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), | ||||
8030 | CurType, CurType); | ||||
8031 | } else { | ||||
8032 | Attr.diagnoseAppertainsTo(State.getSema(), nullptr); | ||||
8033 | } | ||||
8034 | } | ||||
8035 | |||||
8036 | static bool isAddressSpaceKind(const ParsedAttr &attr) { | ||||
8037 | auto attrKind = attr.getKind(); | ||||
8038 | |||||
8039 | return attrKind == ParsedAttr::AT_AddressSpace || | ||||
8040 | attrKind == ParsedAttr::AT_OpenCLPrivateAddressSpace || | ||||
8041 | attrKind == ParsedAttr::AT_OpenCLGlobalAddressSpace || | ||||
8042 | attrKind == ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace || | ||||
8043 | attrKind == ParsedAttr::AT_OpenCLGlobalHostAddressSpace || | ||||
8044 | attrKind == ParsedAttr::AT_OpenCLLocalAddressSpace || | ||||
8045 | attrKind == ParsedAttr::AT_OpenCLConstantAddressSpace || | ||||
8046 | attrKind == ParsedAttr::AT_OpenCLGenericAddressSpace; | ||||
8047 | } | ||||
8048 | |||||
8049 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, | ||||
8050 | TypeAttrLocation TAL, | ||||
8051 | ParsedAttributesView &attrs) { | ||||
8052 | // Scan through and apply attributes to this type where it makes sense. Some | ||||
8053 | // attributes (such as __address_space__, __vector_size__, etc) apply to the | ||||
8054 | // type, but others can be present in the type specifiers even though they | ||||
8055 | // apply to the decl. Here we apply type attributes and ignore the rest. | ||||
8056 | |||||
8057 | // This loop modifies the list pretty frequently, but we still need to make | ||||
8058 | // sure we visit every element once. Copy the attributes list, and iterate | ||||
8059 | // over that. | ||||
8060 | ParsedAttributesView AttrsCopy{attrs}; | ||||
8061 | |||||
8062 | state.setParsedNoDeref(false); | ||||
8063 | |||||
8064 | for (ParsedAttr &attr : AttrsCopy) { | ||||
8065 | |||||
8066 | // Skip attributes that were marked to be invalid. | ||||
8067 | if (attr.isInvalid()) | ||||
| |||||
8068 | continue; | ||||
8069 | |||||
8070 | if (attr.isCXX11Attribute()) { | ||||
8071 | // [[gnu::...]] attributes are treated as declaration attributes, so may | ||||
8072 | // not appertain to a DeclaratorChunk. If we handle them as type | ||||
8073 | // attributes, accept them in that position and diagnose the GCC | ||||
8074 | // incompatibility. | ||||
8075 | if (attr.isGNUScope()) { | ||||
8076 | bool IsTypeAttr = attr.isTypeAttr(); | ||||
8077 | if (TAL == TAL_DeclChunk) { | ||||
8078 | state.getSema().Diag(attr.getLoc(), | ||||
8079 | IsTypeAttr | ||||
8080 | ? diag::warn_gcc_ignores_type_attr | ||||
8081 | : diag::warn_cxx11_gnu_attribute_on_type) | ||||
8082 | << attr; | ||||
8083 | if (!IsTypeAttr) | ||||
8084 | continue; | ||||
8085 | } | ||||
8086 | } else if (TAL != TAL_DeclChunk && !isAddressSpaceKind(attr)) { | ||||
8087 | // Otherwise, only consider type processing for a C++11 attribute if | ||||
8088 | // it's actually been applied to a type. | ||||
8089 | // We also allow C++11 address_space and | ||||
8090 | // OpenCL language address space attributes to pass through. | ||||
8091 | continue; | ||||
8092 | } | ||||
8093 | } | ||||
8094 | |||||
8095 | // If this is an attribute we can handle, do so now, | ||||
8096 | // otherwise, add it to the FnAttrs list for rechaining. | ||||
8097 | switch (attr.getKind()) { | ||||
8098 | default: | ||||
8099 | // A C++11 attribute on a declarator chunk must appertain to a type. | ||||
8100 | if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { | ||||
8101 | state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) | ||||
8102 | << attr; | ||||
8103 | attr.setUsedAsTypeAttr(); | ||||
8104 | } | ||||
8105 | break; | ||||
8106 | |||||
8107 | case ParsedAttr::UnknownAttribute: | ||||
8108 | if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) | ||||
8109 | state.getSema().Diag(attr.getLoc(), | ||||
8110 | diag::warn_unknown_attribute_ignored) | ||||
8111 | << attr << attr.getRange(); | ||||
8112 | break; | ||||
8113 | |||||
8114 | case ParsedAttr::IgnoredAttribute: | ||||
8115 | break; | ||||
8116 | |||||
8117 | case ParsedAttr::AT_MayAlias: | ||||
8118 | // FIXME: This attribute needs to actually be handled, but if we ignore | ||||
8119 | // it it breaks large amounts of Linux software. | ||||
8120 | attr.setUsedAsTypeAttr(); | ||||
8121 | break; | ||||
8122 | case ParsedAttr::AT_OpenCLPrivateAddressSpace: | ||||
8123 | case ParsedAttr::AT_OpenCLGlobalAddressSpace: | ||||
8124 | case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace: | ||||
8125 | case ParsedAttr::AT_OpenCLGlobalHostAddressSpace: | ||||
8126 | case ParsedAttr::AT_OpenCLLocalAddressSpace: | ||||
8127 | case ParsedAttr::AT_OpenCLConstantAddressSpace: | ||||
8128 | case ParsedAttr::AT_OpenCLGenericAddressSpace: | ||||
8129 | case ParsedAttr::AT_AddressSpace: | ||||
8130 | HandleAddressSpaceTypeAttribute(type, attr, state); | ||||
8131 | attr.setUsedAsTypeAttr(); | ||||
8132 | break; | ||||
8133 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: | ||||
8134 | if (!handleObjCPointerTypeAttr(state, attr, type)) | ||||
8135 | distributeObjCPointerTypeAttr(state, attr, type); | ||||
8136 | attr.setUsedAsTypeAttr(); | ||||
8137 | break; | ||||
8138 | case ParsedAttr::AT_VectorSize: | ||||
8139 | HandleVectorSizeAttr(type, attr, state.getSema()); | ||||
8140 | attr.setUsedAsTypeAttr(); | ||||
8141 | break; | ||||
8142 | case ParsedAttr::AT_ExtVectorType: | ||||
8143 | HandleExtVectorTypeAttr(type, attr, state.getSema()); | ||||
8144 | attr.setUsedAsTypeAttr(); | ||||
8145 | break; | ||||
8146 | case ParsedAttr::AT_NeonVectorType: | ||||
8147 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | ||||
8148 | VectorType::NeonVector); | ||||
8149 | attr.setUsedAsTypeAttr(); | ||||
8150 | break; | ||||
8151 | case ParsedAttr::AT_NeonPolyVectorType: | ||||
8152 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | ||||
8153 | VectorType::NeonPolyVector); | ||||
8154 | attr.setUsedAsTypeAttr(); | ||||
8155 | break; | ||||
8156 | case ParsedAttr::AT_ArmSveVectorBits: | ||||
8157 | HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema()); | ||||
8158 | attr.setUsedAsTypeAttr(); | ||||
8159 | break; | ||||
8160 | case ParsedAttr::AT_ArmMveStrictPolymorphism: { | ||||
8161 | HandleArmMveStrictPolymorphismAttr(state, type, attr); | ||||
8162 | attr.setUsedAsTypeAttr(); | ||||
8163 | break; | ||||
8164 | } | ||||
8165 | case ParsedAttr::AT_OpenCLAccess: | ||||
8166 | HandleOpenCLAccessAttr(type, attr, state.getSema()); | ||||
8167 | attr.setUsedAsTypeAttr(); | ||||
8168 | break; | ||||
8169 | case ParsedAttr::AT_LifetimeBound: | ||||
8170 | if (TAL == TAL_DeclChunk) | ||||
8171 | HandleLifetimeBoundAttr(state, type, attr); | ||||
8172 | break; | ||||
8173 | |||||
8174 | case ParsedAttr::AT_NoDeref: { | ||||
8175 | ASTContext &Ctx = state.getSema().Context; | ||||
8176 | type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), | ||||
8177 | type, type); | ||||
8178 | attr.setUsedAsTypeAttr(); | ||||
8179 | state.setParsedNoDeref(true); | ||||
8180 | break; | ||||
8181 | } | ||||
8182 | |||||
8183 | case ParsedAttr::AT_MatrixType: | ||||
8184 | HandleMatrixTypeAttr(type, attr, state.getSema()); | ||||
8185 | attr.setUsedAsTypeAttr(); | ||||
8186 | break; | ||||
8187 | |||||
8188 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: | ||||
8189 | if (!handleMSPointerTypeQualifierAttr(state, attr, type)) | ||||
8190 | attr.setUsedAsTypeAttr(); | ||||
8191 | break; | ||||
8192 | |||||
8193 | |||||
8194 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullUnspecified: | ||||
8195 | // Either add nullability here or try to distribute it. We | ||||
8196 | // don't want to distribute the nullability specifier past any | ||||
8197 | // dependent type, because that complicates the user model. | ||||
8198 | if (type->canHaveNullability() || type->isDependentType() || | ||||
8199 | type->isArrayType() || | ||||
8200 | !distributeNullabilityTypeAttr(state, type, attr)) { | ||||
8201 | unsigned endIndex; | ||||
8202 | if (TAL == TAL_DeclChunk) | ||||
8203 | endIndex = state.getCurrentChunkIndex(); | ||||
8204 | else | ||||
8205 | endIndex = state.getDeclarator().getNumTypeObjects(); | ||||
8206 | bool allowOnArrayType = | ||||
8207 | state.getDeclarator().isPrototypeContext() && | ||||
8208 | !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); | ||||
8209 | if (checkNullabilityTypeSpecifier( | ||||
8210 | state, | ||||
8211 | type, | ||||
8212 | attr, | ||||
8213 | allowOnArrayType)) { | ||||
8214 | attr.setInvalid(); | ||||
8215 | } | ||||
8216 | |||||
8217 | attr.setUsedAsTypeAttr(); | ||||
8218 | } | ||||
8219 | break; | ||||
8220 | |||||
8221 | case ParsedAttr::AT_ObjCKindOf: | ||||
8222 | // '__kindof' must be part of the decl-specifiers. | ||||
8223 | switch (TAL) { | ||||
8224 | case TAL_DeclSpec: | ||||
8225 | break; | ||||
8226 | |||||
8227 | case TAL_DeclChunk: | ||||
8228 | case TAL_DeclName: | ||||
8229 | state.getSema().Diag(attr.getLoc(), | ||||
8230 | diag::err_objc_kindof_wrong_position) | ||||
8231 | << FixItHint::CreateRemoval(attr.getLoc()) | ||||
8232 | << FixItHint::CreateInsertion( | ||||
8233 | state.getDeclarator().getDeclSpec().getBeginLoc(), | ||||
8234 | "__kindof "); | ||||
8235 | break; | ||||
8236 | } | ||||
8237 | |||||
8238 | // Apply it regardless. | ||||
8239 | if (checkObjCKindOfType(state, type, attr)) | ||||
8240 | attr.setInvalid(); | ||||
8241 | break; | ||||
8242 | |||||
8243 | case ParsedAttr::AT_NoThrow: | ||||
8244 | // Exception Specifications aren't generally supported in C mode throughout | ||||
8245 | // clang, so revert to attribute-based handling for C. | ||||
8246 | if (!state.getSema().getLangOpts().CPlusPlus) | ||||
8247 | break; | ||||
8248 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
8249 | FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll: | ||||
8250 | attr.setUsedAsTypeAttr(); | ||||
8251 | |||||
8252 | // Never process function type attributes as part of the | ||||
8253 | // declaration-specifiers. | ||||
8254 | if (TAL == TAL_DeclSpec) | ||||
8255 | distributeFunctionTypeAttrFromDeclSpec(state, attr, type); | ||||
8256 | |||||
8257 | // Otherwise, handle the possible delays. | ||||
8258 | else if (!handleFunctionTypeAttr(state, attr, type)) | ||||
8259 | distributeFunctionTypeAttr(state, attr, type); | ||||
8260 | break; | ||||
8261 | case ParsedAttr::AT_AcquireHandle: { | ||||
8262 | if (!type->isFunctionType()) | ||||
8263 | return; | ||||
8264 | |||||
8265 | if (attr.getNumArgs() != 1) { | ||||
8266 | state.getSema().Diag(attr.getLoc(), | ||||
8267 | diag::err_attribute_wrong_number_arguments) | ||||
8268 | << attr << 1; | ||||
8269 | attr.setInvalid(); | ||||
8270 | return; | ||||
8271 | } | ||||
8272 | |||||
8273 | StringRef HandleType; | ||||
8274 | if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType)) | ||||
8275 | return; | ||||
8276 | type = state.getAttributedType( | ||||
8277 | AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr), | ||||
8278 | type, type); | ||||
8279 | attr.setUsedAsTypeAttr(); | ||||
8280 | break; | ||||
8281 | } | ||||
8282 | } | ||||
8283 | |||||
8284 | // Handle attributes that are defined in a macro. We do not want this to be | ||||
8285 | // applied to ObjC builtin attributes. | ||||
8286 | if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && | ||||
8287 | !type.getQualifiers().hasObjCLifetime() && | ||||
8288 | !type.getQualifiers().hasObjCGCAttr() && | ||||
8289 | attr.getKind() != ParsedAttr::AT_ObjCGC && | ||||
8290 | attr.getKind() != ParsedAttr::AT_ObjCOwnership) { | ||||
8291 | const IdentifierInfo *MacroII = attr.getMacroIdentifier(); | ||||
8292 | type = state.getSema().Context.getMacroQualifiedType(type, MacroII); | ||||
8293 | state.setExpansionLocForMacroQualifiedType( | ||||
8294 | cast<MacroQualifiedType>(type.getTypePtr()), | ||||
8295 | attr.getMacroExpansionLoc()); | ||||
8296 | } | ||||
8297 | } | ||||
8298 | |||||
8299 | if (!state.getSema().getLangOpts().OpenCL || | ||||
8300 | type.getAddressSpace() != LangAS::Default) | ||||
8301 | return; | ||||
8302 | } | ||||
8303 | |||||
8304 | void Sema::completeExprArrayBound(Expr *E) { | ||||
8305 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||
8306 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | ||||
8307 | if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { | ||||
8308 | auto *Def = Var->getDefinition(); | ||||
8309 | if (!Def) { | ||||
8310 | SourceLocation PointOfInstantiation = E->getExprLoc(); | ||||
8311 | runWithSufficientStackSpace(PointOfInstantiation, [&] { | ||||
8312 | InstantiateVariableDefinition(PointOfInstantiation, Var); | ||||
8313 | }); | ||||
8314 | Def = Var->getDefinition(); | ||||
8315 | |||||
8316 | // If we don't already have a point of instantiation, and we managed | ||||
8317 | // to instantiate a definition, this is the point of instantiation. | ||||
8318 | // Otherwise, we don't request an end-of-TU instantiation, so this is | ||||
8319 | // not a point of instantiation. | ||||
8320 | // FIXME: Is this really the right behavior? | ||||
8321 | if (Var->getPointOfInstantiation().isInvalid() && Def) { | ||||
8322 | assert(Var->getTemplateSpecializationKind() ==((Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? static_cast<void> (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8324, __PRETTY_FUNCTION__)) | ||||
8323 | TSK_ImplicitInstantiation &&((Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? static_cast<void> (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8324, __PRETTY_FUNCTION__)) | ||||
8324 | "explicit instantiation with no point of instantiation")((Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? static_cast<void> (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8324, __PRETTY_FUNCTION__)); | ||||
8325 | Var->setTemplateSpecializationKind( | ||||
8326 | Var->getTemplateSpecializationKind(), PointOfInstantiation); | ||||
8327 | } | ||||
8328 | } | ||||
8329 | |||||
8330 | // Update the type to the definition's type both here and within the | ||||
8331 | // expression. | ||||
8332 | if (Def) { | ||||
8333 | DRE->setDecl(Def); | ||||
8334 | QualType T = Def->getType(); | ||||
8335 | DRE->setType(T); | ||||
8336 | // FIXME: Update the type on all intervening expressions. | ||||
8337 | E->setType(T); | ||||
8338 | } | ||||
8339 | |||||
8340 | // We still go on to try to complete the type independently, as it | ||||
8341 | // may also require instantiations or diagnostics if it remains | ||||
8342 | // incomplete. | ||||
8343 | } | ||||
8344 | } | ||||
8345 | } | ||||
8346 | } | ||||
8347 | |||||
8348 | /// Ensure that the type of the given expression is complete. | ||||
8349 | /// | ||||
8350 | /// This routine checks whether the expression \p E has a complete type. If the | ||||
8351 | /// expression refers to an instantiable construct, that instantiation is | ||||
8352 | /// performed as needed to complete its type. Furthermore | ||||
8353 | /// Sema::RequireCompleteType is called for the expression's type (or in the | ||||
8354 | /// case of a reference type, the referred-to type). | ||||
8355 | /// | ||||
8356 | /// \param E The expression whose type is required to be complete. | ||||
8357 | /// \param Kind Selects which completeness rules should be applied. | ||||
8358 | /// \param Diagnoser The object that will emit a diagnostic if the type is | ||||
8359 | /// incomplete. | ||||
8360 | /// | ||||
8361 | /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false | ||||
8362 | /// otherwise. | ||||
8363 | bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, | ||||
8364 | TypeDiagnoser &Diagnoser) { | ||||
8365 | QualType T = E->getType(); | ||||
8366 | |||||
8367 | // Incomplete array types may be completed by the initializer attached to | ||||
8368 | // their definitions. For static data members of class templates and for | ||||
8369 | // variable templates, we need to instantiate the definition to get this | ||||
8370 | // initializer and complete the type. | ||||
8371 | if (T->isIncompleteArrayType()) { | ||||
8372 | completeExprArrayBound(E); | ||||
8373 | T = E->getType(); | ||||
8374 | } | ||||
8375 | |||||
8376 | // FIXME: Are there other cases which require instantiating something other | ||||
8377 | // than the type to complete the type of an expression? | ||||
8378 | |||||
8379 | return RequireCompleteType(E->getExprLoc(), T, Kind, Diagnoser); | ||||
8380 | } | ||||
8381 | |||||
8382 | bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { | ||||
8383 | BoundTypeDiagnoser<> Diagnoser(DiagID); | ||||
8384 | return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); | ||||
8385 | } | ||||
8386 | |||||
8387 | /// Ensure that the type T is a complete type. | ||||
8388 | /// | ||||
8389 | /// This routine checks whether the type @p T is complete in any | ||||
8390 | /// context where a complete type is required. If @p T is a complete | ||||
8391 | /// type, returns false. If @p T is a class template specialization, | ||||
8392 | /// this routine then attempts to perform class template | ||||
8393 | /// instantiation. If instantiation fails, or if @p T is incomplete | ||||
8394 | /// and cannot be completed, issues the diagnostic @p diag (giving it | ||||
8395 | /// the type @p T) and returns true. | ||||
8396 | /// | ||||
8397 | /// @param Loc The location in the source that the incomplete type | ||||
8398 | /// diagnostic should refer to. | ||||
8399 | /// | ||||
8400 | /// @param T The type that this routine is examining for completeness. | ||||
8401 | /// | ||||
8402 | /// @param Kind Selects which completeness rules should be applied. | ||||
8403 | /// | ||||
8404 | /// @returns @c true if @p T is incomplete and a diagnostic was emitted, | ||||
8405 | /// @c false otherwise. | ||||
8406 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | ||||
8407 | CompleteTypeKind Kind, | ||||
8408 | TypeDiagnoser &Diagnoser) { | ||||
8409 | if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser)) | ||||
8410 | return true; | ||||
8411 | if (const TagType *Tag = T->getAs<TagType>()) { | ||||
8412 | if (!Tag->getDecl()->isCompleteDefinitionRequired()) { | ||||
8413 | Tag->getDecl()->setCompleteDefinitionRequired(); | ||||
8414 | Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); | ||||
8415 | } | ||||
8416 | } | ||||
8417 | return false; | ||||
8418 | } | ||||
8419 | |||||
8420 | bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { | ||||
8421 | llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; | ||||
8422 | if (!Suggested) | ||||
8423 | return false; | ||||
8424 | |||||
8425 | // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext | ||||
8426 | // and isolate from other C++ specific checks. | ||||
8427 | StructuralEquivalenceContext Ctx( | ||||
8428 | D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, | ||||
8429 | StructuralEquivalenceKind::Default, | ||||
8430 | false /*StrictTypeSpelling*/, true /*Complain*/, | ||||
8431 | true /*ErrorOnTagTypeMismatch*/); | ||||
8432 | return Ctx.IsEquivalent(D, Suggested); | ||||
8433 | } | ||||
8434 | |||||
8435 | /// Determine whether there is any declaration of \p D that was ever a | ||||
8436 | /// definition (perhaps before module merging) and is currently visible. | ||||
8437 | /// \param D The definition of the entity. | ||||
8438 | /// \param Suggested Filled in with the declaration that should be made visible | ||||
8439 | /// in order to provide a definition of this entity. | ||||
8440 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, | ||||
8441 | /// not defined. This only matters for enums with a fixed underlying | ||||
8442 | /// type, since in all other cases, a type is complete if and only if it | ||||
8443 | /// is defined. | ||||
8444 | bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, | ||||
8445 | bool OnlyNeedComplete) { | ||||
8446 | // Easy case: if we don't have modules, all declarations are visible. | ||||
8447 | if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) | ||||
8448 | return true; | ||||
8449 | |||||
8450 | // If this definition was instantiated from a template, map back to the | ||||
8451 | // pattern from which it was instantiated. | ||||
8452 | if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { | ||||
8453 | // We're in the middle of defining it; this definition should be treated | ||||
8454 | // as visible. | ||||
8455 | return true; | ||||
8456 | } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { | ||||
8457 | if (auto *Pattern = RD->getTemplateInstantiationPattern()) | ||||
8458 | RD = Pattern; | ||||
8459 | D = RD->getDefinition(); | ||||
8460 | } else if (auto *ED = dyn_cast<EnumDecl>(D)) { | ||||
8461 | if (auto *Pattern = ED->getTemplateInstantiationPattern()) | ||||
8462 | ED = Pattern; | ||||
8463 | if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) { | ||||
8464 | // If the enum has a fixed underlying type, it may have been forward | ||||
8465 | // declared. In -fms-compatibility, `enum Foo;` will also forward declare | ||||
8466 | // the enum and assign it the underlying type of `int`. Since we're only | ||||
8467 | // looking for a complete type (not a definition), any visible declaration | ||||
8468 | // of it will do. | ||||
8469 | *Suggested = nullptr; | ||||
8470 | for (auto *Redecl : ED->redecls()) { | ||||
8471 | if (isVisible(Redecl)) | ||||
8472 | return true; | ||||
8473 | if (Redecl->isThisDeclarationADefinition() || | ||||
8474 | (Redecl->isCanonicalDecl() && !*Suggested)) | ||||
8475 | *Suggested = Redecl; | ||||
8476 | } | ||||
8477 | return false; | ||||
8478 | } | ||||
8479 | D = ED->getDefinition(); | ||||
8480 | } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { | ||||
8481 | if (auto *Pattern = FD->getTemplateInstantiationPattern()) | ||||
8482 | FD = Pattern; | ||||
8483 | D = FD->getDefinition(); | ||||
8484 | } else if (auto *VD = dyn_cast<VarDecl>(D)) { | ||||
8485 | if (auto *Pattern = VD->getTemplateInstantiationPattern()) | ||||
8486 | VD = Pattern; | ||||
8487 | D = VD->getDefinition(); | ||||
8488 | } | ||||
8489 | assert(D && "missing definition for pattern of instantiated definition")((D && "missing definition for pattern of instantiated definition" ) ? static_cast<void> (0) : __assert_fail ("D && \"missing definition for pattern of instantiated definition\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8489, __PRETTY_FUNCTION__)); | ||||
8490 | |||||
8491 | *Suggested = D; | ||||
8492 | |||||
8493 | auto DefinitionIsVisible = [&] { | ||||
8494 | // The (primary) definition might be in a visible module. | ||||
8495 | if (isVisible(D)) | ||||
8496 | return true; | ||||
8497 | |||||
8498 | // A visible module might have a merged definition instead. | ||||
8499 | if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) | ||||
8500 | : hasVisibleMergedDefinition(D)) { | ||||
8501 | if (CodeSynthesisContexts.empty() && | ||||
8502 | !getLangOpts().ModulesLocalVisibility) { | ||||
8503 | // Cache the fact that this definition is implicitly visible because | ||||
8504 | // there is a visible merged definition. | ||||
8505 | D->setVisibleDespiteOwningModule(); | ||||
8506 | } | ||||
8507 | return true; | ||||
8508 | } | ||||
8509 | |||||
8510 | return false; | ||||
8511 | }; | ||||
8512 | |||||
8513 | if (DefinitionIsVisible()) | ||||
8514 | return true; | ||||
8515 | |||||
8516 | // The external source may have additional definitions of this entity that are | ||||
8517 | // visible, so complete the redeclaration chain now and ask again. | ||||
8518 | if (auto *Source = Context.getExternalSource()) { | ||||
8519 | Source->CompleteRedeclChain(D); | ||||
8520 | return DefinitionIsVisible(); | ||||
8521 | } | ||||
8522 | |||||
8523 | return false; | ||||
8524 | } | ||||
8525 | |||||
8526 | /// Locks in the inheritance model for the given class and all of its bases. | ||||
8527 | static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { | ||||
8528 | RD = RD->getMostRecentNonInjectedDecl(); | ||||
8529 | if (!RD->hasAttr<MSInheritanceAttr>()) { | ||||
8530 | MSInheritanceModel IM; | ||||
8531 | bool BestCase = false; | ||||
8532 | switch (S.MSPointerToMemberRepresentationMethod) { | ||||
8533 | case LangOptions::PPTMK_BestCase: | ||||
8534 | BestCase = true; | ||||
8535 | IM = RD->calculateInheritanceModel(); | ||||
8536 | break; | ||||
8537 | case LangOptions::PPTMK_FullGeneralitySingleInheritance: | ||||
8538 | IM = MSInheritanceModel::Single; | ||||
8539 | break; | ||||
8540 | case LangOptions::PPTMK_FullGeneralityMultipleInheritance: | ||||
8541 | IM = MSInheritanceModel::Multiple; | ||||
8542 | break; | ||||
8543 | case LangOptions::PPTMK_FullGeneralityVirtualInheritance: | ||||
8544 | IM = MSInheritanceModel::Unspecified; | ||||
8545 | break; | ||||
8546 | } | ||||
8547 | |||||
8548 | SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() | ||||
8549 | ? S.ImplicitMSInheritanceAttrLoc | ||||
8550 | : RD->getSourceRange(); | ||||
8551 | RD->addAttr(MSInheritanceAttr::CreateImplicit( | ||||
8552 | S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft, | ||||
8553 | MSInheritanceAttr::Spelling(IM))); | ||||
8554 | S.Consumer.AssignInheritanceModel(RD); | ||||
8555 | } | ||||
8556 | } | ||||
8557 | |||||
8558 | /// The implementation of RequireCompleteType | ||||
8559 | bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, | ||||
8560 | CompleteTypeKind Kind, | ||||
8561 | TypeDiagnoser *Diagnoser) { | ||||
8562 | // FIXME: Add this assertion to make sure we always get instantiation points. | ||||
8563 | // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); | ||||
8564 | // FIXME: Add this assertion to help us flush out problems with | ||||
8565 | // checking for dependent types and type-dependent expressions. | ||||
8566 | // | ||||
8567 | // assert(!T->isDependentType() && | ||||
8568 | // "Can't ask whether a dependent type is complete"); | ||||
8569 | |||||
8570 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { | ||||
8571 | if (!MPTy->getClass()->isDependentType()) { | ||||
8572 | if (getLangOpts().CompleteMemberPointers && | ||||
8573 | !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && | ||||
8574 | RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind, | ||||
8575 | diag::err_memptr_incomplete)) | ||||
8576 | return true; | ||||
8577 | |||||
8578 | // We lock in the inheritance model once somebody has asked us to ensure | ||||
8579 | // that a pointer-to-member type is complete. | ||||
8580 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
8581 | (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); | ||||
8582 | assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); | ||||
8583 | } | ||||
8584 | } | ||||
8585 | } | ||||
8586 | |||||
8587 | NamedDecl *Def = nullptr; | ||||
8588 | bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless); | ||||
8589 | bool Incomplete = (T->isIncompleteType(&Def) || | ||||
8590 | (!AcceptSizeless && T->isSizelessBuiltinType())); | ||||
8591 | |||||
8592 | // Check that any necessary explicit specializations are visible. For an | ||||
8593 | // enum, we just need the declaration, so don't check this. | ||||
8594 | if (Def && !isa<EnumDecl>(Def)) | ||||
8595 | checkSpecializationVisibility(Loc, Def); | ||||
8596 | |||||
8597 | // If we have a complete type, we're done. | ||||
8598 | if (!Incomplete) { | ||||
8599 | // If we know about the definition but it is not visible, complain. | ||||
8600 | NamedDecl *SuggestedDef = nullptr; | ||||
8601 | if (Def && | ||||
8602 | !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { | ||||
8603 | // If the user is going to see an error here, recover by making the | ||||
8604 | // definition visible. | ||||
8605 | bool TreatAsComplete = Diagnoser && !isSFINAEContext(); | ||||
8606 | if (Diagnoser && SuggestedDef) | ||||
8607 | diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, | ||||
8608 | /*Recover*/TreatAsComplete); | ||||
8609 | return !TreatAsComplete; | ||||
8610 | } else if (Def && !TemplateInstCallbacks.empty()) { | ||||
8611 | CodeSynthesisContext TempInst; | ||||
8612 | TempInst.Kind = CodeSynthesisContext::Memoization; | ||||
8613 | TempInst.Template = Def; | ||||
8614 | TempInst.Entity = Def; | ||||
8615 | TempInst.PointOfInstantiation = Loc; | ||||
8616 | atTemplateBegin(TemplateInstCallbacks, *this, TempInst); | ||||
8617 | atTemplateEnd(TemplateInstCallbacks, *this, TempInst); | ||||
8618 | } | ||||
8619 | |||||
8620 | return false; | ||||
8621 | } | ||||
8622 | |||||
8623 | TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); | ||||
8624 | ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); | ||||
8625 | |||||
8626 | // Give the external source a chance to provide a definition of the type. | ||||
8627 | // This is kept separate from completing the redeclaration chain so that | ||||
8628 | // external sources such as LLDB can avoid synthesizing a type definition | ||||
8629 | // unless it's actually needed. | ||||
8630 | if (Tag || IFace) { | ||||
8631 | // Avoid diagnosing invalid decls as incomplete. | ||||
8632 | if (Def->isInvalidDecl()) | ||||
8633 | return true; | ||||
8634 | |||||
8635 | // Give the external AST source a chance to complete the type. | ||||
8636 | if (auto *Source = Context.getExternalSource()) { | ||||
8637 | if (Tag && Tag->hasExternalLexicalStorage()) | ||||
8638 | Source->CompleteType(Tag); | ||||
8639 | if (IFace && IFace->hasExternalLexicalStorage()) | ||||
8640 | Source->CompleteType(IFace); | ||||
8641 | // If the external source completed the type, go through the motions | ||||
8642 | // again to ensure we're allowed to use the completed type. | ||||
8643 | if (!T->isIncompleteType()) | ||||
8644 | return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); | ||||
8645 | } | ||||
8646 | } | ||||
8647 | |||||
8648 | // If we have a class template specialization or a class member of a | ||||
8649 | // class template specialization, or an array with known size of such, | ||||
8650 | // try to instantiate it. | ||||
8651 | if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { | ||||
8652 | bool Instantiated = false; | ||||
8653 | bool Diagnosed = false; | ||||
8654 | if (RD->isDependentContext()) { | ||||
8655 | // Don't try to instantiate a dependent class (eg, a member template of | ||||
8656 | // an instantiated class template specialization). | ||||
8657 | // FIXME: Can this ever happen? | ||||
8658 | } else if (auto *ClassTemplateSpec = | ||||
8659 | dyn_cast<ClassTemplateSpecializationDecl>(RD)) { | ||||
8660 | if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { | ||||
8661 | runWithSufficientStackSpace(Loc, [&] { | ||||
8662 | Diagnosed = InstantiateClassTemplateSpecialization( | ||||
8663 | Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, | ||||
8664 | /*Complain=*/Diagnoser); | ||||
8665 | }); | ||||
8666 | Instantiated = true; | ||||
8667 | } | ||||
8668 | } else { | ||||
8669 | CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); | ||||
8670 | if (!RD->isBeingDefined() && Pattern) { | ||||
8671 | MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); | ||||
8672 | assert(MSI && "Missing member specialization information?")((MSI && "Missing member specialization information?" ) ? static_cast<void> (0) : __assert_fail ("MSI && \"Missing member specialization information?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8672, __PRETTY_FUNCTION__)); | ||||
8673 | // This record was instantiated from a class within a template. | ||||
8674 | if (MSI->getTemplateSpecializationKind() != | ||||
8675 | TSK_ExplicitSpecialization) { | ||||
8676 | runWithSufficientStackSpace(Loc, [&] { | ||||
8677 | Diagnosed = InstantiateClass(Loc, RD, Pattern, | ||||
8678 | getTemplateInstantiationArgs(RD), | ||||
8679 | TSK_ImplicitInstantiation, | ||||
8680 | /*Complain=*/Diagnoser); | ||||
8681 | }); | ||||
8682 | Instantiated = true; | ||||
8683 | } | ||||
8684 | } | ||||
8685 | } | ||||
8686 | |||||
8687 | if (Instantiated) { | ||||
8688 | // Instantiate* might have already complained that the template is not | ||||
8689 | // defined, if we asked it to. | ||||
8690 | if (Diagnoser && Diagnosed) | ||||
8691 | return true; | ||||
8692 | // If we instantiated a definition, check that it's usable, even if | ||||
8693 | // instantiation produced an error, so that repeated calls to this | ||||
8694 | // function give consistent answers. | ||||
8695 | if (!T->isIncompleteType()) | ||||
8696 | return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); | ||||
8697 | } | ||||
8698 | } | ||||
8699 | |||||
8700 | // FIXME: If we didn't instantiate a definition because of an explicit | ||||
8701 | // specialization declaration, check that it's visible. | ||||
8702 | |||||
8703 | if (!Diagnoser) | ||||
8704 | return true; | ||||
8705 | |||||
8706 | Diagnoser->diagnose(*this, Loc, T); | ||||
8707 | |||||
8708 | // If the type was a forward declaration of a class/struct/union | ||||
8709 | // type, produce a note. | ||||
8710 | if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid()) | ||||
8711 | Diag(Tag->getLocation(), | ||||
8712 | Tag->isBeingDefined() ? diag::note_type_being_defined | ||||
8713 | : diag::note_forward_declaration) | ||||
8714 | << Context.getTagDeclType(Tag); | ||||
8715 | |||||
8716 | // If the Objective-C class was a forward declaration, produce a note. | ||||
8717 | if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid()) | ||||
8718 | Diag(IFace->getLocation(), diag::note_forward_class); | ||||
8719 | |||||
8720 | // If we have external information that we can use to suggest a fix, | ||||
8721 | // produce a note. | ||||
8722 | if (ExternalSource) | ||||
8723 | ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); | ||||
8724 | |||||
8725 | return true; | ||||
8726 | } | ||||
8727 | |||||
8728 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | ||||
8729 | CompleteTypeKind Kind, unsigned DiagID) { | ||||
8730 | BoundTypeDiagnoser<> Diagnoser(DiagID); | ||||
8731 | return RequireCompleteType(Loc, T, Kind, Diagnoser); | ||||
8732 | } | ||||
8733 | |||||
8734 | /// Get diagnostic %select index for tag kind for | ||||
8735 | /// literal type diagnostic message. | ||||
8736 | /// WARNING: Indexes apply to particular diagnostics only! | ||||
8737 | /// | ||||
8738 | /// \returns diagnostic %select index. | ||||
8739 | static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { | ||||
8740 | switch (Tag) { | ||||
8741 | case TTK_Struct: return 0; | ||||
8742 | case TTK_Interface: return 1; | ||||
8743 | case TTK_Class: return 2; | ||||
8744 | default: llvm_unreachable("Invalid tag kind for literal type diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for literal type diagnostic!" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8744); | ||||
8745 | } | ||||
8746 | } | ||||
8747 | |||||
8748 | /// Ensure that the type T is a literal type. | ||||
8749 | /// | ||||
8750 | /// This routine checks whether the type @p T is a literal type. If @p T is an | ||||
8751 | /// incomplete type, an attempt is made to complete it. If @p T is a literal | ||||
8752 | /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, | ||||
8753 | /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving | ||||
8754 | /// it the type @p T), along with notes explaining why the type is not a | ||||
8755 | /// literal type, and returns true. | ||||
8756 | /// | ||||
8757 | /// @param Loc The location in the source that the non-literal type | ||||
8758 | /// diagnostic should refer to. | ||||
8759 | /// | ||||
8760 | /// @param T The type that this routine is examining for literalness. | ||||
8761 | /// | ||||
8762 | /// @param Diagnoser Emits a diagnostic if T is not a literal type. | ||||
8763 | /// | ||||
8764 | /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, | ||||
8765 | /// @c false otherwise. | ||||
8766 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, | ||||
8767 | TypeDiagnoser &Diagnoser) { | ||||
8768 | assert(!T->isDependentType() && "type should not be dependent")((!T->isDependentType() && "type should not be dependent" ) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"type should not be dependent\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8768, __PRETTY_FUNCTION__)); | ||||
8769 | |||||
8770 | QualType ElemType = Context.getBaseElementType(T); | ||||
8771 | if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && | ||||
8772 | T->isLiteralType(Context)) | ||||
8773 | return false; | ||||
8774 | |||||
8775 | Diagnoser.diagnose(*this, Loc, T); | ||||
8776 | |||||
8777 | if (T->isVariableArrayType()) | ||||
8778 | return true; | ||||
8779 | |||||
8780 | const RecordType *RT = ElemType->getAs<RecordType>(); | ||||
8781 | if (!RT) | ||||
8782 | return true; | ||||
8783 | |||||
8784 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | ||||
8785 | |||||
8786 | // A partially-defined class type can't be a literal type, because a literal | ||||
8787 | // class type must have a trivial destructor (which can't be checked until | ||||
8788 | // the class definition is complete). | ||||
8789 | if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) | ||||
8790 | return true; | ||||
8791 | |||||
8792 | // [expr.prim.lambda]p3: | ||||
8793 | // This class type is [not] a literal type. | ||||
8794 | if (RD->isLambda() && !getLangOpts().CPlusPlus17) { | ||||
8795 | Diag(RD->getLocation(), diag::note_non_literal_lambda); | ||||
8796 | return true; | ||||
8797 | } | ||||
8798 | |||||
8799 | // If the class has virtual base classes, then it's not an aggregate, and | ||||
8800 | // cannot have any constexpr constructors or a trivial default constructor, | ||||
8801 | // so is non-literal. This is better to diagnose than the resulting absence | ||||
8802 | // of constexpr constructors. | ||||
8803 | if (RD->getNumVBases()) { | ||||
8804 | Diag(RD->getLocation(), diag::note_non_literal_virtual_base) | ||||
8805 | << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); | ||||
8806 | for (const auto &I : RD->vbases()) | ||||
8807 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) | ||||
8808 | << I.getSourceRange(); | ||||
8809 | } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && | ||||
8810 | !RD->hasTrivialDefaultConstructor()) { | ||||
8811 | Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; | ||||
8812 | } else if (RD->hasNonLiteralTypeFieldsOrBases()) { | ||||
8813 | for (const auto &I : RD->bases()) { | ||||
8814 | if (!I.getType()->isLiteralType(Context)) { | ||||
8815 | Diag(I.getBeginLoc(), diag::note_non_literal_base_class) | ||||
8816 | << RD << I.getType() << I.getSourceRange(); | ||||
8817 | return true; | ||||
8818 | } | ||||
8819 | } | ||||
8820 | for (const auto *I : RD->fields()) { | ||||
8821 | if (!I->getType()->isLiteralType(Context) || | ||||
8822 | I->getType().isVolatileQualified()) { | ||||
8823 | Diag(I->getLocation(), diag::note_non_literal_field) | ||||
8824 | << RD << I << I->getType() | ||||
8825 | << I->getType().isVolatileQualified(); | ||||
8826 | return true; | ||||
8827 | } | ||||
8828 | } | ||||
8829 | } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor() | ||||
8830 | : !RD->hasTrivialDestructor()) { | ||||
8831 | // All fields and bases are of literal types, so have trivial or constexpr | ||||
8832 | // destructors. If this class's destructor is non-trivial / non-constexpr, | ||||
8833 | // it must be user-declared. | ||||
8834 | CXXDestructorDecl *Dtor = RD->getDestructor(); | ||||
8835 | assert(Dtor && "class has literal fields and bases but no dtor?")((Dtor && "class has literal fields and bases but no dtor?" ) ? static_cast<void> (0) : __assert_fail ("Dtor && \"class has literal fields and bases but no dtor?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8835, __PRETTY_FUNCTION__)); | ||||
8836 | if (!Dtor) | ||||
8837 | return true; | ||||
8838 | |||||
8839 | if (getLangOpts().CPlusPlus20) { | ||||
8840 | Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) | ||||
8841 | << RD; | ||||
8842 | } else { | ||||
8843 | Diag(Dtor->getLocation(), Dtor->isUserProvided() | ||||
8844 | ? diag::note_non_literal_user_provided_dtor | ||||
8845 | : diag::note_non_literal_nontrivial_dtor) | ||||
8846 | << RD; | ||||
8847 | if (!Dtor->isUserProvided()) | ||||
8848 | SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, | ||||
8849 | /*Diagnose*/ true); | ||||
8850 | } | ||||
8851 | } | ||||
8852 | |||||
8853 | return true; | ||||
8854 | } | ||||
8855 | |||||
8856 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { | ||||
8857 | BoundTypeDiagnoser<> Diagnoser(DiagID); | ||||
8858 | return RequireLiteralType(Loc, T, Diagnoser); | ||||
8859 | } | ||||
8860 | |||||
8861 | /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified | ||||
8862 | /// by the nested-name-specifier contained in SS, and that is (re)declared by | ||||
8863 | /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. | ||||
8864 | QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, | ||||
8865 | const CXXScopeSpec &SS, QualType T, | ||||
8866 | TagDecl *OwnedTagDecl) { | ||||
8867 | if (T.isNull()) | ||||
8868 | return T; | ||||
8869 | NestedNameSpecifier *NNS; | ||||
8870 | if (SS.isValid()) | ||||
8871 | NNS = SS.getScopeRep(); | ||||
8872 | else { | ||||
8873 | if (Keyword == ETK_None) | ||||
8874 | return T; | ||||
8875 | NNS = nullptr; | ||||
8876 | } | ||||
8877 | return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); | ||||
8878 | } | ||||
8879 | |||||
8880 | QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { | ||||
8881 | assert(!E->hasPlaceholderType() && "unexpected placeholder")((!E->hasPlaceholderType() && "unexpected placeholder" ) ? static_cast<void> (0) : __assert_fail ("!E->hasPlaceholderType() && \"unexpected placeholder\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8881, __PRETTY_FUNCTION__)); | ||||
8882 | |||||
8883 | if (!getLangOpts().CPlusPlus && E->refersToBitField()) | ||||
8884 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; | ||||
8885 | |||||
8886 | if (!E->isTypeDependent()) { | ||||
8887 | QualType T = E->getType(); | ||||
8888 | if (const TagType *TT = T->getAs<TagType>()) | ||||
8889 | DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); | ||||
8890 | } | ||||
8891 | return Context.getTypeOfExprType(E); | ||||
8892 | } | ||||
8893 | |||||
8894 | /// getDecltypeForExpr - Given an expr, will return the decltype for | ||||
8895 | /// that expression, according to the rules in C++11 | ||||
8896 | /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. | ||||
8897 | static QualType getDecltypeForExpr(Sema &S, Expr *E) { | ||||
8898 | if (E->isTypeDependent()) | ||||
8899 | return S.Context.DependentTy; | ||||
8900 | |||||
8901 | // C++11 [dcl.type.simple]p4: | ||||
8902 | // The type denoted by decltype(e) is defined as follows: | ||||
8903 | |||||
8904 | // C++20: | ||||
8905 | // - if E is an unparenthesized id-expression naming a non-type | ||||
8906 | // template-parameter (13.2), decltype(E) is the type of the | ||||
8907 | // template-parameter after performing any necessary type deduction | ||||
8908 | // Note that this does not pick up the implicit 'const' for a template | ||||
8909 | // parameter object. This rule makes no difference before C++20 so we apply | ||||
8910 | // it unconditionally. | ||||
8911 | if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) | ||||
8912 | return SNTTPE->getParameterType(S.Context); | ||||
8913 | |||||
8914 | // - if e is an unparenthesized id-expression or an unparenthesized class | ||||
8915 | // member access (5.2.5), decltype(e) is the type of the entity named | ||||
8916 | // by e. If there is no such entity, or if e names a set of overloaded | ||||
8917 | // functions, the program is ill-formed; | ||||
8918 | // | ||||
8919 | // We apply the same rules for Objective-C ivar and property references. | ||||
8920 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
8921 | const ValueDecl *VD = DRE->getDecl(); | ||||
8922 | if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(VD)) | ||||
8923 | return TPO->getType().getUnqualifiedType(); | ||||
8924 | return VD->getType(); | ||||
8925 | } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | ||||
8926 | if (const ValueDecl *VD = ME->getMemberDecl()) | ||||
8927 | if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) | ||||
8928 | return VD->getType(); | ||||
8929 | } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { | ||||
8930 | return IR->getDecl()->getType(); | ||||
8931 | } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { | ||||
8932 | if (PR->isExplicitProperty()) | ||||
8933 | return PR->getExplicitProperty()->getType(); | ||||
8934 | } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { | ||||
8935 | return PE->getType(); | ||||
8936 | } | ||||
8937 | |||||
8938 | // C++11 [expr.lambda.prim]p18: | ||||
8939 | // Every occurrence of decltype((x)) where x is a possibly | ||||
8940 | // parenthesized id-expression that names an entity of automatic | ||||
8941 | // storage duration is treated as if x were transformed into an | ||||
8942 | // access to a corresponding data member of the closure type that | ||||
8943 | // would have been declared if x were an odr-use of the denoted | ||||
8944 | // entity. | ||||
8945 | using namespace sema; | ||||
8946 | if (S.getCurLambda()) { | ||||
8947 | if (isa<ParenExpr>(E)) { | ||||
8948 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | ||||
8949 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | ||||
8950 | QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); | ||||
8951 | if (!T.isNull()) | ||||
8952 | return S.Context.getLValueReferenceType(T); | ||||
8953 | } | ||||
8954 | } | ||||
8955 | } | ||||
8956 | } | ||||
8957 | |||||
8958 | |||||
8959 | // C++11 [dcl.type.simple]p4: | ||||
8960 | // [...] | ||||
8961 | QualType T = E->getType(); | ||||
8962 | switch (E->getValueKind()) { | ||||
8963 | // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the | ||||
8964 | // type of e; | ||||
8965 | case VK_XValue: T = S.Context.getRValueReferenceType(T); break; | ||||
8966 | // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the | ||||
8967 | // type of e; | ||||
8968 | case VK_LValue: T = S.Context.getLValueReferenceType(T); break; | ||||
8969 | // - otherwise, decltype(e) is the type of e. | ||||
8970 | case VK_RValue: break; | ||||
8971 | } | ||||
8972 | |||||
8973 | return T; | ||||
8974 | } | ||||
8975 | |||||
8976 | QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, | ||||
8977 | bool AsUnevaluated) { | ||||
8978 | assert(!E->hasPlaceholderType() && "unexpected placeholder")((!E->hasPlaceholderType() && "unexpected placeholder" ) ? static_cast<void> (0) : __assert_fail ("!E->hasPlaceholderType() && \"unexpected placeholder\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 8978, __PRETTY_FUNCTION__)); | ||||
8979 | |||||
8980 | if (AsUnevaluated && CodeSynthesisContexts.empty() && | ||||
8981 | E->HasSideEffects(Context, false)) { | ||||
8982 | // The expression operand for decltype is in an unevaluated expression | ||||
8983 | // context, so side effects could result in unintended consequences. | ||||
8984 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | ||||
8985 | } | ||||
8986 | |||||
8987 | return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); | ||||
8988 | } | ||||
8989 | |||||
8990 | QualType Sema::BuildUnaryTransformType(QualType BaseType, | ||||
8991 | UnaryTransformType::UTTKind UKind, | ||||
8992 | SourceLocation Loc) { | ||||
8993 | switch (UKind) { | ||||
8994 | case UnaryTransformType::EnumUnderlyingType: | ||||
8995 | if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { | ||||
8996 | Diag(Loc, diag::err_only_enums_have_underlying_types); | ||||
8997 | return QualType(); | ||||
8998 | } else { | ||||
8999 | QualType Underlying = BaseType; | ||||
9000 | if (!BaseType->isDependentType()) { | ||||
9001 | // The enum could be incomplete if we're parsing its definition or | ||||
9002 | // recovering from an error. | ||||
9003 | NamedDecl *FwdDecl = nullptr; | ||||
9004 | if (BaseType->isIncompleteType(&FwdDecl)) { | ||||
9005 | Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; | ||||
9006 | Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; | ||||
9007 | return QualType(); | ||||
9008 | } | ||||
9009 | |||||
9010 | EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); | ||||
9011 | assert(ED && "EnumType has no EnumDecl")((ED && "EnumType has no EnumDecl") ? static_cast< void> (0) : __assert_fail ("ED && \"EnumType has no EnumDecl\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 9011, __PRETTY_FUNCTION__)); | ||||
9012 | |||||
9013 | DiagnoseUseOfDecl(ED, Loc); | ||||
9014 | |||||
9015 | Underlying = ED->getIntegerType(); | ||||
9016 | assert(!Underlying.isNull())((!Underlying.isNull()) ? static_cast<void> (0) : __assert_fail ("!Underlying.isNull()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 9016, __PRETTY_FUNCTION__)); | ||||
9017 | } | ||||
9018 | return Context.getUnaryTransformType(BaseType, Underlying, | ||||
9019 | UnaryTransformType::EnumUnderlyingType); | ||||
9020 | } | ||||
9021 | } | ||||
9022 | llvm_unreachable("unknown unary transform type")::llvm::llvm_unreachable_internal("unknown unary transform type" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/lib/Sema/SemaType.cpp" , 9022); | ||||
9023 | } | ||||
9024 | |||||
9025 | QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { | ||||
9026 | if (!T->isDependentType()) { | ||||
9027 | // FIXME: It isn't entirely clear whether incomplete atomic types | ||||
9028 | // are allowed or not; for simplicity, ban them for the moment. | ||||
9029 | if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) | ||||
9030 | return QualType(); | ||||
9031 | |||||
9032 | int DisallowedKind = -1; | ||||
9033 | if (T->isArrayType()) | ||||
9034 | DisallowedKind = 1; | ||||
9035 | else if (T->isFunctionType()) | ||||
9036 | DisallowedKind = 2; | ||||
9037 | else if (T->isReferenceType()) | ||||
9038 | DisallowedKind = 3; | ||||
9039 | else if (T->isAtomicType()) | ||||
9040 | DisallowedKind = 4; | ||||
9041 | else if (T.hasQualifiers()) | ||||
9042 | DisallowedKind = 5; | ||||
9043 | else if (T->isSizelessType()) | ||||
9044 | DisallowedKind = 6; | ||||
9045 | else if (!T.isTriviallyCopyableType(Context)) | ||||
9046 | // Some other non-trivially-copyable type (probably a C++ class) | ||||
9047 | DisallowedKind = 7; | ||||
9048 | else if (T->isExtIntType()) { | ||||
9049 | DisallowedKind = 8; | ||||
9050 | } | ||||
9051 | |||||
9052 | if (DisallowedKind != -1) { | ||||
9053 | Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; | ||||
9054 | return QualType(); | ||||
9055 | } | ||||
9056 | |||||
9057 | // FIXME: Do we need any handling for ARC here? | ||||
9058 | } | ||||
9059 | |||||
9060 | // Build the pointer type. | ||||
9061 | return Context.getAtomicType(T); | ||||
9062 | } |
1 | //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===// |
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 | /// \file |
10 | /// C Language Family Type Representation |
11 | /// |
12 | /// This file defines the clang::Type interface and subclasses, used to |
13 | /// represent types for languages in the C family. |
14 | // |
15 | //===----------------------------------------------------------------------===// |
16 | |
17 | #ifndef LLVM_CLANG_AST_TYPE_H |
18 | #define LLVM_CLANG_AST_TYPE_H |
19 | |
20 | #include "clang/AST/DependenceFlags.h" |
21 | #include "clang/AST/NestedNameSpecifier.h" |
22 | #include "clang/AST/TemplateName.h" |
23 | #include "clang/Basic/AddressSpaces.h" |
24 | #include "clang/Basic/AttrKinds.h" |
25 | #include "clang/Basic/Diagnostic.h" |
26 | #include "clang/Basic/ExceptionSpecificationType.h" |
27 | #include "clang/Basic/LLVM.h" |
28 | #include "clang/Basic/Linkage.h" |
29 | #include "clang/Basic/PartialDiagnostic.h" |
30 | #include "clang/Basic/SourceLocation.h" |
31 | #include "clang/Basic/Specifiers.h" |
32 | #include "clang/Basic/Visibility.h" |
33 | #include "llvm/ADT/APInt.h" |
34 | #include "llvm/ADT/APSInt.h" |
35 | #include "llvm/ADT/ArrayRef.h" |
36 | #include "llvm/ADT/FoldingSet.h" |
37 | #include "llvm/ADT/None.h" |
38 | #include "llvm/ADT/Optional.h" |
39 | #include "llvm/ADT/PointerIntPair.h" |
40 | #include "llvm/ADT/PointerUnion.h" |
41 | #include "llvm/ADT/StringRef.h" |
42 | #include "llvm/ADT/Twine.h" |
43 | #include "llvm/ADT/iterator_range.h" |
44 | #include "llvm/Support/Casting.h" |
45 | #include "llvm/Support/Compiler.h" |
46 | #include "llvm/Support/ErrorHandling.h" |
47 | #include "llvm/Support/PointerLikeTypeTraits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include "llvm/Support/type_traits.h" |
50 | #include <cassert> |
51 | #include <cstddef> |
52 | #include <cstdint> |
53 | #include <cstring> |
54 | #include <string> |
55 | #include <type_traits> |
56 | #include <utility> |
57 | |
58 | namespace clang { |
59 | |
60 | class ExtQuals; |
61 | class QualType; |
62 | class ConceptDecl; |
63 | class TagDecl; |
64 | class TemplateParameterList; |
65 | class Type; |
66 | |
67 | enum { |
68 | TypeAlignmentInBits = 4, |
69 | TypeAlignment = 1 << TypeAlignmentInBits |
70 | }; |
71 | |
72 | namespace serialization { |
73 | template <class T> class AbstractTypeReader; |
74 | template <class T> class AbstractTypeWriter; |
75 | } |
76 | |
77 | } // namespace clang |
78 | |
79 | namespace llvm { |
80 | |
81 | template <typename T> |
82 | struct PointerLikeTypeTraits; |
83 | template<> |
84 | struct PointerLikeTypeTraits< ::clang::Type*> { |
85 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
86 | |
87 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
88 | return static_cast< ::clang::Type*>(P); |
89 | } |
90 | |
91 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
92 | }; |
93 | |
94 | template<> |
95 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
96 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
97 | |
98 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
99 | return static_cast< ::clang::ExtQuals*>(P); |
100 | } |
101 | |
102 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
103 | }; |
104 | |
105 | } // namespace llvm |
106 | |
107 | namespace clang { |
108 | |
109 | class ASTContext; |
110 | template <typename> class CanQual; |
111 | class CXXRecordDecl; |
112 | class DeclContext; |
113 | class EnumDecl; |
114 | class Expr; |
115 | class ExtQualsTypeCommonBase; |
116 | class FunctionDecl; |
117 | class IdentifierInfo; |
118 | class NamedDecl; |
119 | class ObjCInterfaceDecl; |
120 | class ObjCProtocolDecl; |
121 | class ObjCTypeParamDecl; |
122 | struct PrintingPolicy; |
123 | class RecordDecl; |
124 | class Stmt; |
125 | class TagDecl; |
126 | class TemplateArgument; |
127 | class TemplateArgumentListInfo; |
128 | class TemplateArgumentLoc; |
129 | class TemplateTypeParmDecl; |
130 | class TypedefNameDecl; |
131 | class UnresolvedUsingTypenameDecl; |
132 | |
133 | using CanQualType = CanQual<Type>; |
134 | |
135 | // Provide forward declarations for all of the *Type classes. |
136 | #define TYPE(Class, Base) class Class##Type; |
137 | #include "clang/AST/TypeNodes.inc" |
138 | |
139 | /// The collection of all-type qualifiers we support. |
140 | /// Clang supports five independent qualifiers: |
141 | /// * C99: const, volatile, and restrict |
142 | /// * MS: __unaligned |
143 | /// * Embedded C (TR18037): address spaces |
144 | /// * Objective C: the GC attributes (none, weak, or strong) |
145 | class Qualifiers { |
146 | public: |
147 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
148 | Const = 0x1, |
149 | Restrict = 0x2, |
150 | Volatile = 0x4, |
151 | CVRMask = Const | Volatile | Restrict |
152 | }; |
153 | |
154 | enum GC { |
155 | GCNone = 0, |
156 | Weak, |
157 | Strong |
158 | }; |
159 | |
160 | enum ObjCLifetime { |
161 | /// There is no lifetime qualification on this type. |
162 | OCL_None, |
163 | |
164 | /// This object can be modified without requiring retains or |
165 | /// releases. |
166 | OCL_ExplicitNone, |
167 | |
168 | /// Assigning into this object requires the old value to be |
169 | /// released and the new value to be retained. The timing of the |
170 | /// release of the old value is inexact: it may be moved to |
171 | /// immediately after the last known point where the value is |
172 | /// live. |
173 | OCL_Strong, |
174 | |
175 | /// Reading or writing from this object requires a barrier call. |
176 | OCL_Weak, |
177 | |
178 | /// Assigning into this object requires a lifetime extension. |
179 | OCL_Autoreleasing |
180 | }; |
181 | |
182 | enum { |
183 | /// The maximum supported address space number. |
184 | /// 23 bits should be enough for anyone. |
185 | MaxAddressSpace = 0x7fffffu, |
186 | |
187 | /// The width of the "fast" qualifier mask. |
188 | FastWidth = 3, |
189 | |
190 | /// The fast qualifier mask. |
191 | FastMask = (1 << FastWidth) - 1 |
192 | }; |
193 | |
194 | /// Returns the common set of qualifiers while removing them from |
195 | /// the given sets. |
196 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
197 | // If both are only CVR-qualified, bit operations are sufficient. |
198 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
199 | Qualifiers Q; |
200 | Q.Mask = L.Mask & R.Mask; |
201 | L.Mask &= ~Q.Mask; |
202 | R.Mask &= ~Q.Mask; |
203 | return Q; |
204 | } |
205 | |
206 | Qualifiers Q; |
207 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
208 | Q.addCVRQualifiers(CommonCRV); |
209 | L.removeCVRQualifiers(CommonCRV); |
210 | R.removeCVRQualifiers(CommonCRV); |
211 | |
212 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
213 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
214 | L.removeObjCGCAttr(); |
215 | R.removeObjCGCAttr(); |
216 | } |
217 | |
218 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
219 | Q.setObjCLifetime(L.getObjCLifetime()); |
220 | L.removeObjCLifetime(); |
221 | R.removeObjCLifetime(); |
222 | } |
223 | |
224 | if (L.getAddressSpace() == R.getAddressSpace()) { |
225 | Q.setAddressSpace(L.getAddressSpace()); |
226 | L.removeAddressSpace(); |
227 | R.removeAddressSpace(); |
228 | } |
229 | return Q; |
230 | } |
231 | |
232 | static Qualifiers fromFastMask(unsigned Mask) { |
233 | Qualifiers Qs; |
234 | Qs.addFastQualifiers(Mask); |
235 | return Qs; |
236 | } |
237 | |
238 | static Qualifiers fromCVRMask(unsigned CVR) { |
239 | Qualifiers Qs; |
240 | Qs.addCVRQualifiers(CVR); |
241 | return Qs; |
242 | } |
243 | |
244 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
245 | Qualifiers Qs; |
246 | Qs.addCVRUQualifiers(CVRU); |
247 | return Qs; |
248 | } |
249 | |
250 | // Deserialize qualifiers from an opaque representation. |
251 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
252 | Qualifiers Qs; |
253 | Qs.Mask = opaque; |
254 | return Qs; |
255 | } |
256 | |
257 | // Serialize these qualifiers into an opaque representation. |
258 | unsigned getAsOpaqueValue() const { |
259 | return Mask; |
260 | } |
261 | |
262 | bool hasConst() const { return Mask & Const; } |
263 | bool hasOnlyConst() const { return Mask == Const; } |
264 | void removeConst() { Mask &= ~Const; } |
265 | void addConst() { Mask |= Const; } |
266 | |
267 | bool hasVolatile() const { return Mask & Volatile; } |
268 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
269 | void removeVolatile() { Mask &= ~Volatile; } |
270 | void addVolatile() { Mask |= Volatile; } |
271 | |
272 | bool hasRestrict() const { return Mask & Restrict; } |
273 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
274 | void removeRestrict() { Mask &= ~Restrict; } |
275 | void addRestrict() { Mask |= Restrict; } |
276 | |
277 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
278 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
279 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
280 | |
281 | void setCVRQualifiers(unsigned mask) { |
282 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 282, __PRETTY_FUNCTION__)); |
283 | Mask = (Mask & ~CVRMask) | mask; |
284 | } |
285 | void removeCVRQualifiers(unsigned mask) { |
286 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 286, __PRETTY_FUNCTION__)); |
287 | Mask &= ~mask; |
288 | } |
289 | void removeCVRQualifiers() { |
290 | removeCVRQualifiers(CVRMask); |
291 | } |
292 | void addCVRQualifiers(unsigned mask) { |
293 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 293, __PRETTY_FUNCTION__)); |
294 | Mask |= mask; |
295 | } |
296 | void addCVRUQualifiers(unsigned mask) { |
297 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 297, __PRETTY_FUNCTION__)); |
298 | Mask |= mask; |
299 | } |
300 | |
301 | bool hasUnaligned() const { return Mask & UMask; } |
302 | void setUnaligned(bool flag) { |
303 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
304 | } |
305 | void removeUnaligned() { Mask &= ~UMask; } |
306 | void addUnaligned() { Mask |= UMask; } |
307 | |
308 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
309 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
310 | void setObjCGCAttr(GC type) { |
311 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
312 | } |
313 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
314 | void addObjCGCAttr(GC type) { |
315 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 315, __PRETTY_FUNCTION__)); |
316 | setObjCGCAttr(type); |
317 | } |
318 | Qualifiers withoutObjCGCAttr() const { |
319 | Qualifiers qs = *this; |
320 | qs.removeObjCGCAttr(); |
321 | return qs; |
322 | } |
323 | Qualifiers withoutObjCLifetime() const { |
324 | Qualifiers qs = *this; |
325 | qs.removeObjCLifetime(); |
326 | return qs; |
327 | } |
328 | Qualifiers withoutAddressSpace() const { |
329 | Qualifiers qs = *this; |
330 | qs.removeAddressSpace(); |
331 | return qs; |
332 | } |
333 | |
334 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
335 | ObjCLifetime getObjCLifetime() const { |
336 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
337 | } |
338 | void setObjCLifetime(ObjCLifetime type) { |
339 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
340 | } |
341 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
342 | void addObjCLifetime(ObjCLifetime type) { |
343 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 343, __PRETTY_FUNCTION__)); |
344 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 344, __PRETTY_FUNCTION__)); |
345 | Mask |= (type << LifetimeShift); |
346 | } |
347 | |
348 | /// True if the lifetime is neither None or ExplicitNone. |
349 | bool hasNonTrivialObjCLifetime() const { |
350 | ObjCLifetime lifetime = getObjCLifetime(); |
351 | return (lifetime > OCL_ExplicitNone); |
352 | } |
353 | |
354 | /// True if the lifetime is either strong or weak. |
355 | bool hasStrongOrWeakObjCLifetime() const { |
356 | ObjCLifetime lifetime = getObjCLifetime(); |
357 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
358 | } |
359 | |
360 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
361 | LangAS getAddressSpace() const { |
362 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
363 | } |
364 | bool hasTargetSpecificAddressSpace() const { |
365 | return isTargetAddressSpace(getAddressSpace()); |
366 | } |
367 | /// Get the address space attribute value to be printed by diagnostics. |
368 | unsigned getAddressSpaceAttributePrintValue() const { |
369 | auto Addr = getAddressSpace(); |
370 | // This function is not supposed to be used with language specific |
371 | // address spaces. If that happens, the diagnostic message should consider |
372 | // printing the QualType instead of the address space value. |
373 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 373, __PRETTY_FUNCTION__)); |
374 | if (Addr != LangAS::Default) |
375 | return toTargetAddressSpace(Addr); |
376 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
377 | // since it cannot differentiate the situation where 0 denotes the default |
378 | // address space or user specified __attribute__((address_space(0))). |
379 | return 0; |
380 | } |
381 | void setAddressSpace(LangAS space) { |
382 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 382, __PRETTY_FUNCTION__)); |
383 | Mask = (Mask & ~AddressSpaceMask) |
384 | | (((uint32_t) space) << AddressSpaceShift); |
385 | } |
386 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
387 | void addAddressSpace(LangAS space) { |
388 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 388, __PRETTY_FUNCTION__)); |
389 | setAddressSpace(space); |
390 | } |
391 | |
392 | // Fast qualifiers are those that can be allocated directly |
393 | // on a QualType object. |
394 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
395 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
396 | void setFastQualifiers(unsigned mask) { |
397 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 397, __PRETTY_FUNCTION__)); |
398 | Mask = (Mask & ~FastMask) | mask; |
399 | } |
400 | void removeFastQualifiers(unsigned mask) { |
401 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 401, __PRETTY_FUNCTION__)); |
402 | Mask &= ~mask; |
403 | } |
404 | void removeFastQualifiers() { |
405 | removeFastQualifiers(FastMask); |
406 | } |
407 | void addFastQualifiers(unsigned mask) { |
408 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 408, __PRETTY_FUNCTION__)); |
409 | Mask |= mask; |
410 | } |
411 | |
412 | /// Return true if the set contains any qualifiers which require an ExtQuals |
413 | /// node to be allocated. |
414 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
415 | Qualifiers getNonFastQualifiers() const { |
416 | Qualifiers Quals = *this; |
417 | Quals.setFastQualifiers(0); |
418 | return Quals; |
419 | } |
420 | |
421 | /// Return true if the set contains any qualifiers. |
422 | bool hasQualifiers() const { return Mask; } |
423 | bool empty() const { return !Mask; } |
424 | |
425 | /// Add the qualifiers from the given set to this set. |
426 | void addQualifiers(Qualifiers Q) { |
427 | // If the other set doesn't have any non-boolean qualifiers, just |
428 | // bit-or it in. |
429 | if (!(Q.Mask & ~CVRMask)) |
430 | Mask |= Q.Mask; |
431 | else { |
432 | Mask |= (Q.Mask & CVRMask); |
433 | if (Q.hasAddressSpace()) |
434 | addAddressSpace(Q.getAddressSpace()); |
435 | if (Q.hasObjCGCAttr()) |
436 | addObjCGCAttr(Q.getObjCGCAttr()); |
437 | if (Q.hasObjCLifetime()) |
438 | addObjCLifetime(Q.getObjCLifetime()); |
439 | } |
440 | } |
441 | |
442 | /// Remove the qualifiers from the given set from this set. |
443 | void removeQualifiers(Qualifiers Q) { |
444 | // If the other set doesn't have any non-boolean qualifiers, just |
445 | // bit-and the inverse in. |
446 | if (!(Q.Mask & ~CVRMask)) |
447 | Mask &= ~Q.Mask; |
448 | else { |
449 | Mask &= ~(Q.Mask & CVRMask); |
450 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
451 | removeObjCGCAttr(); |
452 | if (getObjCLifetime() == Q.getObjCLifetime()) |
453 | removeObjCLifetime(); |
454 | if (getAddressSpace() == Q.getAddressSpace()) |
455 | removeAddressSpace(); |
456 | } |
457 | } |
458 | |
459 | /// Add the qualifiers from the given set to this set, given that |
460 | /// they don't conflict. |
461 | void addConsistentQualifiers(Qualifiers qs) { |
462 | assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 463, __PRETTY_FUNCTION__)) |
463 | !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 463, __PRETTY_FUNCTION__)); |
464 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 465, __PRETTY_FUNCTION__)) |
465 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 465, __PRETTY_FUNCTION__)); |
466 | assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 467, __PRETTY_FUNCTION__)) |
467 | !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 467, __PRETTY_FUNCTION__)); |
468 | Mask |= qs.Mask; |
469 | } |
470 | |
471 | /// Returns true if address space A is equal to or a superset of B. |
472 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
473 | /// overlapping address spaces. |
474 | /// CL1.1 or CL1.2: |
475 | /// every address space is a superset of itself. |
476 | /// CL2.0 adds: |
477 | /// __generic is a superset of any address space except for __constant. |
478 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
479 | // Address spaces must match exactly. |
480 | return A == B || |
481 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
482 | // for __constant can be used as __generic. |
483 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant) || |
484 | // We also define global_device and global_host address spaces, |
485 | // to distinguish global pointers allocated on host from pointers |
486 | // allocated on device, which are a subset of __global. |
487 | (A == LangAS::opencl_global && (B == LangAS::opencl_global_device || |
488 | B == LangAS::opencl_global_host)) || |
489 | // Consider pointer size address spaces to be equivalent to default. |
490 | ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && |
491 | (isPtrSizeAddressSpace(B) || B == LangAS::Default)); |
492 | } |
493 | |
494 | /// Returns true if the address space in these qualifiers is equal to or |
495 | /// a superset of the address space in the argument qualifiers. |
496 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
497 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
498 | } |
499 | |
500 | /// Determines if these qualifiers compatibly include another set. |
501 | /// Generally this answers the question of whether an object with the other |
502 | /// qualifiers can be safely used as an object with these qualifiers. |
503 | bool compatiblyIncludes(Qualifiers other) const { |
504 | return isAddressSpaceSupersetOf(other) && |
505 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
506 | // be changed. |
507 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
508 | !other.hasObjCGCAttr()) && |
509 | // ObjC lifetime qualifiers must match exactly. |
510 | getObjCLifetime() == other.getObjCLifetime() && |
511 | // CVR qualifiers may subset. |
512 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
513 | // U qualifier may superset. |
514 | (!other.hasUnaligned() || hasUnaligned()); |
515 | } |
516 | |
517 | /// Determines if these qualifiers compatibly include another set of |
518 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
519 | /// |
520 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
521 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
522 | /// including set also contains the 'const' qualifier, or both are non-__weak |
523 | /// and one is None (which can only happen in non-ARC modes). |
524 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
525 | if (getObjCLifetime() == other.getObjCLifetime()) |
526 | return true; |
527 | |
528 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
529 | return false; |
530 | |
531 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
532 | return true; |
533 | |
534 | return hasConst(); |
535 | } |
536 | |
537 | /// Determine whether this set of qualifiers is a strict superset of |
538 | /// another set of qualifiers, not considering qualifier compatibility. |
539 | bool isStrictSupersetOf(Qualifiers Other) const; |
540 | |
541 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
542 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
543 | |
544 | explicit operator bool() const { return hasQualifiers(); } |
545 | |
546 | Qualifiers &operator+=(Qualifiers R) { |
547 | addQualifiers(R); |
548 | return *this; |
549 | } |
550 | |
551 | // Union two qualifier sets. If an enumerated qualifier appears |
552 | // in both sets, use the one from the right. |
553 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
554 | L += R; |
555 | return L; |
556 | } |
557 | |
558 | Qualifiers &operator-=(Qualifiers R) { |
559 | removeQualifiers(R); |
560 | return *this; |
561 | } |
562 | |
563 | /// Compute the difference between two qualifier sets. |
564 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
565 | L -= R; |
566 | return L; |
567 | } |
568 | |
569 | std::string getAsString() const; |
570 | std::string getAsString(const PrintingPolicy &Policy) const; |
571 | |
572 | static std::string getAddrSpaceAsString(LangAS AS); |
573 | |
574 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
575 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
576 | bool appendSpaceIfNonEmpty = false) const; |
577 | |
578 | void Profile(llvm::FoldingSetNodeID &ID) const { |
579 | ID.AddInteger(Mask); |
580 | } |
581 | |
582 | private: |
583 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
584 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
585 | uint32_t Mask = 0; |
586 | |
587 | static const uint32_t UMask = 0x8; |
588 | static const uint32_t UShift = 3; |
589 | static const uint32_t GCAttrMask = 0x30; |
590 | static const uint32_t GCAttrShift = 4; |
591 | static const uint32_t LifetimeMask = 0x1C0; |
592 | static const uint32_t LifetimeShift = 6; |
593 | static const uint32_t AddressSpaceMask = |
594 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
595 | static const uint32_t AddressSpaceShift = 9; |
596 | }; |
597 | |
598 | /// A std::pair-like structure for storing a qualified type split |
599 | /// into its local qualifiers and its locally-unqualified type. |
600 | struct SplitQualType { |
601 | /// The locally-unqualified type. |
602 | const Type *Ty = nullptr; |
603 | |
604 | /// The local qualifiers. |
605 | Qualifiers Quals; |
606 | |
607 | SplitQualType() = default; |
608 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
609 | |
610 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
611 | |
612 | // Make std::tie work. |
613 | std::pair<const Type *,Qualifiers> asPair() const { |
614 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
615 | } |
616 | |
617 | friend bool operator==(SplitQualType a, SplitQualType b) { |
618 | return a.Ty == b.Ty && a.Quals == b.Quals; |
619 | } |
620 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
621 | return a.Ty != b.Ty || a.Quals != b.Quals; |
622 | } |
623 | }; |
624 | |
625 | /// The kind of type we are substituting Objective-C type arguments into. |
626 | /// |
627 | /// The kind of substitution affects the replacement of type parameters when |
628 | /// no concrete type information is provided, e.g., when dealing with an |
629 | /// unspecialized type. |
630 | enum class ObjCSubstitutionContext { |
631 | /// An ordinary type. |
632 | Ordinary, |
633 | |
634 | /// The result type of a method or function. |
635 | Result, |
636 | |
637 | /// The parameter type of a method or function. |
638 | Parameter, |
639 | |
640 | /// The type of a property. |
641 | Property, |
642 | |
643 | /// The superclass of a type. |
644 | Superclass, |
645 | }; |
646 | |
647 | /// A (possibly-)qualified type. |
648 | /// |
649 | /// For efficiency, we don't store CV-qualified types as nodes on their |
650 | /// own: instead each reference to a type stores the qualifiers. This |
651 | /// greatly reduces the number of nodes we need to allocate for types (for |
652 | /// example we only need one for 'int', 'const int', 'volatile int', |
653 | /// 'const volatile int', etc). |
654 | /// |
655 | /// As an added efficiency bonus, instead of making this a pair, we |
656 | /// just store the two bits we care about in the low bits of the |
657 | /// pointer. To handle the packing/unpacking, we make QualType be a |
658 | /// simple wrapper class that acts like a smart pointer. A third bit |
659 | /// indicates whether there are extended qualifiers present, in which |
660 | /// case the pointer points to a special structure. |
661 | class QualType { |
662 | friend class QualifierCollector; |
663 | |
664 | // Thankfully, these are efficiently composable. |
665 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
666 | Qualifiers::FastWidth> Value; |
667 | |
668 | const ExtQuals *getExtQualsUnsafe() const { |
669 | return Value.getPointer().get<const ExtQuals*>(); |
670 | } |
671 | |
672 | const Type *getTypePtrUnsafe() const { |
673 | return Value.getPointer().get<const Type*>(); |
674 | } |
675 | |
676 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
677 | assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer") ? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 677, __PRETTY_FUNCTION__)); |
678 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
679 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
680 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
681 | } |
682 | |
683 | public: |
684 | QualType() = default; |
685 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
686 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
687 | |
688 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
689 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
690 | |
691 | /// Retrieves a pointer to the underlying (unqualified) type. |
692 | /// |
693 | /// This function requires that the type not be NULL. If the type might be |
694 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
695 | const Type *getTypePtr() const; |
696 | |
697 | const Type *getTypePtrOrNull() const; |
698 | |
699 | /// Retrieves a pointer to the name of the base type. |
700 | const IdentifierInfo *getBaseTypeIdentifier() const; |
701 | |
702 | /// Divides a QualType into its unqualified type and a set of local |
703 | /// qualifiers. |
704 | SplitQualType split() const; |
705 | |
706 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
707 | |
708 | static QualType getFromOpaquePtr(const void *Ptr) { |
709 | QualType T; |
710 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
711 | return T; |
712 | } |
713 | |
714 | const Type &operator*() const { |
715 | return *getTypePtr(); |
716 | } |
717 | |
718 | const Type *operator->() const { |
719 | return getTypePtr(); |
720 | } |
721 | |
722 | bool isCanonical() const; |
723 | bool isCanonicalAsParam() const; |
724 | |
725 | /// Return true if this QualType doesn't point to a type yet. |
726 | bool isNull() const { |
727 | return Value.getPointer().isNull(); |
728 | } |
729 | |
730 | /// Determine whether this particular QualType instance has the |
731 | /// "const" qualifier set, without looking through typedefs that may have |
732 | /// added "const" at a different level. |
733 | bool isLocalConstQualified() const { |
734 | return (getLocalFastQualifiers() & Qualifiers::Const); |
735 | } |
736 | |
737 | /// Determine whether this type is const-qualified. |
738 | bool isConstQualified() const; |
739 | |
740 | /// Determine whether this particular QualType instance has the |
741 | /// "restrict" qualifier set, without looking through typedefs that may have |
742 | /// added "restrict" at a different level. |
743 | bool isLocalRestrictQualified() const { |
744 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
745 | } |
746 | |
747 | /// Determine whether this type is restrict-qualified. |
748 | bool isRestrictQualified() const; |
749 | |
750 | /// Determine whether this particular QualType instance has the |
751 | /// "volatile" qualifier set, without looking through typedefs that may have |
752 | /// added "volatile" at a different level. |
753 | bool isLocalVolatileQualified() const { |
754 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
755 | } |
756 | |
757 | /// Determine whether this type is volatile-qualified. |
758 | bool isVolatileQualified() const; |
759 | |
760 | /// Determine whether this particular QualType instance has any |
761 | /// qualifiers, without looking through any typedefs that might add |
762 | /// qualifiers at a different level. |
763 | bool hasLocalQualifiers() const { |
764 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
765 | } |
766 | |
767 | /// Determine whether this type has any qualifiers. |
768 | bool hasQualifiers() const; |
769 | |
770 | /// Determine whether this particular QualType instance has any |
771 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
772 | /// instance. |
773 | bool hasLocalNonFastQualifiers() const { |
774 | return Value.getPointer().is<const ExtQuals*>(); |
775 | } |
776 | |
777 | /// Retrieve the set of qualifiers local to this particular QualType |
778 | /// instance, not including any qualifiers acquired through typedefs or |
779 | /// other sugar. |
780 | Qualifiers getLocalQualifiers() const; |
781 | |
782 | /// Retrieve the set of qualifiers applied to this type. |
783 | Qualifiers getQualifiers() const; |
784 | |
785 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
786 | /// local to this particular QualType instance, not including any qualifiers |
787 | /// acquired through typedefs or other sugar. |
788 | unsigned getLocalCVRQualifiers() const { |
789 | return getLocalFastQualifiers(); |
790 | } |
791 | |
792 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
793 | /// applied to this type. |
794 | unsigned getCVRQualifiers() const; |
795 | |
796 | bool isConstant(const ASTContext& Ctx) const { |
797 | return QualType::isConstant(*this, Ctx); |
798 | } |
799 | |
800 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
801 | bool isPODType(const ASTContext &Context) const; |
802 | |
803 | /// Return true if this is a POD type according to the rules of the C++98 |
804 | /// standard, regardless of the current compilation's language. |
805 | bool isCXX98PODType(const ASTContext &Context) const; |
806 | |
807 | /// Return true if this is a POD type according to the more relaxed rules |
808 | /// of the C++11 standard, regardless of the current compilation's language. |
809 | /// (C++0x [basic.types]p9). Note that, unlike |
810 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
811 | bool isCXX11PODType(const ASTContext &Context) const; |
812 | |
813 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
814 | bool isTrivialType(const ASTContext &Context) const; |
815 | |
816 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
817 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
818 | |
819 | |
820 | /// Returns true if it is a class and it might be dynamic. |
821 | bool mayBeDynamicClass() const; |
822 | |
823 | /// Returns true if it is not a class or if the class might not be dynamic. |
824 | bool mayBeNotDynamicClass() const; |
825 | |
826 | // Don't promise in the API that anything besides 'const' can be |
827 | // easily added. |
828 | |
829 | /// Add the `const` type qualifier to this QualType. |
830 | void addConst() { |
831 | addFastQualifiers(Qualifiers::Const); |
832 | } |
833 | QualType withConst() const { |
834 | return withFastQualifiers(Qualifiers::Const); |
835 | } |
836 | |
837 | /// Add the `volatile` type qualifier to this QualType. |
838 | void addVolatile() { |
839 | addFastQualifiers(Qualifiers::Volatile); |
840 | } |
841 | QualType withVolatile() const { |
842 | return withFastQualifiers(Qualifiers::Volatile); |
843 | } |
844 | |
845 | /// Add the `restrict` qualifier to this QualType. |
846 | void addRestrict() { |
847 | addFastQualifiers(Qualifiers::Restrict); |
848 | } |
849 | QualType withRestrict() const { |
850 | return withFastQualifiers(Qualifiers::Restrict); |
851 | } |
852 | |
853 | QualType withCVRQualifiers(unsigned CVR) const { |
854 | return withFastQualifiers(CVR); |
855 | } |
856 | |
857 | void addFastQualifiers(unsigned TQs) { |
858 | assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 859, __PRETTY_FUNCTION__)) |
859 | && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 859, __PRETTY_FUNCTION__)); |
860 | Value.setInt(Value.getInt() | TQs); |
861 | } |
862 | |
863 | void removeLocalConst(); |
864 | void removeLocalVolatile(); |
865 | void removeLocalRestrict(); |
866 | void removeLocalCVRQualifiers(unsigned Mask); |
867 | |
868 | void removeLocalFastQualifiers() { Value.setInt(0); } |
869 | void removeLocalFastQualifiers(unsigned Mask) { |
870 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 870, __PRETTY_FUNCTION__)); |
871 | Value.setInt(Value.getInt() & ~Mask); |
872 | } |
873 | |
874 | // Creates a type with the given qualifiers in addition to any |
875 | // qualifiers already on this type. |
876 | QualType withFastQualifiers(unsigned TQs) const { |
877 | QualType T = *this; |
878 | T.addFastQualifiers(TQs); |
879 | return T; |
880 | } |
881 | |
882 | // Creates a type with exactly the given fast qualifiers, removing |
883 | // any existing fast qualifiers. |
884 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
885 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
886 | } |
887 | |
888 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
889 | QualType withoutLocalFastQualifiers() const { |
890 | QualType T = *this; |
891 | T.removeLocalFastQualifiers(); |
892 | return T; |
893 | } |
894 | |
895 | QualType getCanonicalType() const; |
896 | |
897 | /// Return this type with all of the instance-specific qualifiers |
898 | /// removed, but without removing any qualifiers that may have been applied |
899 | /// through typedefs. |
900 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
901 | |
902 | /// Retrieve the unqualified variant of the given type, |
903 | /// removing as little sugar as possible. |
904 | /// |
905 | /// This routine looks through various kinds of sugar to find the |
906 | /// least-desugared type that is unqualified. For example, given: |
907 | /// |
908 | /// \code |
909 | /// typedef int Integer; |
910 | /// typedef const Integer CInteger; |
911 | /// typedef CInteger DifferenceType; |
912 | /// \endcode |
913 | /// |
914 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
915 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
916 | /// |
917 | /// The resulting type might still be qualified if it's sugar for an array |
918 | /// type. To strip qualifiers even from within a sugared array type, use |
919 | /// ASTContext::getUnqualifiedArrayType. |
920 | inline QualType getUnqualifiedType() const; |
921 | |
922 | /// Retrieve the unqualified variant of the given type, removing as little |
923 | /// sugar as possible. |
924 | /// |
925 | /// Like getUnqualifiedType(), but also returns the set of |
926 | /// qualifiers that were built up. |
927 | /// |
928 | /// The resulting type might still be qualified if it's sugar for an array |
929 | /// type. To strip qualifiers even from within a sugared array type, use |
930 | /// ASTContext::getUnqualifiedArrayType. |
931 | inline SplitQualType getSplitUnqualifiedType() const; |
932 | |
933 | /// Determine whether this type is more qualified than the other |
934 | /// given type, requiring exact equality for non-CVR qualifiers. |
935 | bool isMoreQualifiedThan(QualType Other) const; |
936 | |
937 | /// Determine whether this type is at least as qualified as the other |
938 | /// given type, requiring exact equality for non-CVR qualifiers. |
939 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
940 | |
941 | QualType getNonReferenceType() const; |
942 | |
943 | /// Determine the type of a (typically non-lvalue) expression with the |
944 | /// specified result type. |
945 | /// |
946 | /// This routine should be used for expressions for which the return type is |
947 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
948 | /// an lvalue. It removes a top-level reference (since there are no |
949 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
950 | /// from non-class types (in C++) or all types (in C). |
951 | QualType getNonLValueExprType(const ASTContext &Context) const; |
952 | |
953 | /// Remove an outer pack expansion type (if any) from this type. Used as part |
954 | /// of converting the type of a declaration to the type of an expression that |
955 | /// references that expression. It's meaningless for an expression to have a |
956 | /// pack expansion type. |
957 | QualType getNonPackExpansionType() const; |
958 | |
959 | /// Return the specified type with any "sugar" removed from |
960 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
961 | /// the type is already concrete, it returns it unmodified. This is similar |
962 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
963 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
964 | /// concrete. |
965 | /// |
966 | /// Qualifiers are left in place. |
967 | QualType getDesugaredType(const ASTContext &Context) const { |
968 | return getDesugaredType(*this, Context); |
969 | } |
970 | |
971 | SplitQualType getSplitDesugaredType() const { |
972 | return getSplitDesugaredType(*this); |
973 | } |
974 | |
975 | /// Return the specified type with one level of "sugar" removed from |
976 | /// the type. |
977 | /// |
978 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
979 | /// of the type is already concrete, it returns it unmodified. |
980 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
981 | return getSingleStepDesugaredTypeImpl(*this, Context); |
982 | } |
983 | |
984 | /// Returns the specified type after dropping any |
985 | /// outer-level parentheses. |
986 | QualType IgnoreParens() const { |
987 | if (isa<ParenType>(*this)) |
988 | return QualType::IgnoreParens(*this); |
989 | return *this; |
990 | } |
991 | |
992 | /// Indicate whether the specified types and qualifiers are identical. |
993 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
994 | return LHS.Value == RHS.Value; |
995 | } |
996 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
997 | return LHS.Value != RHS.Value; |
998 | } |
999 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
1000 | return LHS.Value < RHS.Value; |
1001 | } |
1002 | |
1003 | static std::string getAsString(SplitQualType split, |
1004 | const PrintingPolicy &Policy) { |
1005 | return getAsString(split.Ty, split.Quals, Policy); |
1006 | } |
1007 | static std::string getAsString(const Type *ty, Qualifiers qs, |
1008 | const PrintingPolicy &Policy); |
1009 | |
1010 | std::string getAsString() const; |
1011 | std::string getAsString(const PrintingPolicy &Policy) const; |
1012 | |
1013 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
1014 | const Twine &PlaceHolder = Twine(), |
1015 | unsigned Indentation = 0) const; |
1016 | |
1017 | static void print(SplitQualType split, raw_ostream &OS, |
1018 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
1019 | unsigned Indentation = 0) { |
1020 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
1021 | } |
1022 | |
1023 | static void print(const Type *ty, Qualifiers qs, |
1024 | raw_ostream &OS, const PrintingPolicy &policy, |
1025 | const Twine &PlaceHolder, |
1026 | unsigned Indentation = 0); |
1027 | |
1028 | void getAsStringInternal(std::string &Str, |
1029 | const PrintingPolicy &Policy) const; |
1030 | |
1031 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1032 | const PrintingPolicy &policy) { |
1033 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1034 | } |
1035 | |
1036 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1037 | std::string &out, |
1038 | const PrintingPolicy &policy); |
1039 | |
1040 | class StreamedQualTypeHelper { |
1041 | const QualType &T; |
1042 | const PrintingPolicy &Policy; |
1043 | const Twine &PlaceHolder; |
1044 | unsigned Indentation; |
1045 | |
1046 | public: |
1047 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1048 | const Twine &PlaceHolder, unsigned Indentation) |
1049 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1050 | Indentation(Indentation) {} |
1051 | |
1052 | friend raw_ostream &operator<<(raw_ostream &OS, |
1053 | const StreamedQualTypeHelper &SQT) { |
1054 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1055 | return OS; |
1056 | } |
1057 | }; |
1058 | |
1059 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1060 | const Twine &PlaceHolder = Twine(), |
1061 | unsigned Indentation = 0) const { |
1062 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1063 | } |
1064 | |
1065 | void dump(const char *s) const; |
1066 | void dump() const; |
1067 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
1068 | |
1069 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1070 | ID.AddPointer(getAsOpaquePtr()); |
1071 | } |
1072 | |
1073 | /// Check if this type has any address space qualifier. |
1074 | inline bool hasAddressSpace() const; |
1075 | |
1076 | /// Return the address space of this type. |
1077 | inline LangAS getAddressSpace() const; |
1078 | |
1079 | /// Returns true if address space qualifiers overlap with T address space |
1080 | /// qualifiers. |
1081 | /// OpenCL C defines conversion rules for pointers to different address spaces |
1082 | /// and notion of overlapping address spaces. |
1083 | /// CL1.1 or CL1.2: |
1084 | /// address spaces overlap iff they are they same. |
1085 | /// OpenCL C v2.0 s6.5.5 adds: |
1086 | /// __generic overlaps with any address space except for __constant. |
1087 | bool isAddressSpaceOverlapping(QualType T) const { |
1088 | Qualifiers Q = getQualifiers(); |
1089 | Qualifiers TQ = T.getQualifiers(); |
1090 | // Address spaces overlap if at least one of them is a superset of another |
1091 | return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q); |
1092 | } |
1093 | |
1094 | /// Returns gc attribute of this type. |
1095 | inline Qualifiers::GC getObjCGCAttr() const; |
1096 | |
1097 | /// true when Type is objc's weak. |
1098 | bool isObjCGCWeak() const { |
1099 | return getObjCGCAttr() == Qualifiers::Weak; |
1100 | } |
1101 | |
1102 | /// true when Type is objc's strong. |
1103 | bool isObjCGCStrong() const { |
1104 | return getObjCGCAttr() == Qualifiers::Strong; |
1105 | } |
1106 | |
1107 | /// Returns lifetime attribute of this type. |
1108 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1109 | return getQualifiers().getObjCLifetime(); |
1110 | } |
1111 | |
1112 | bool hasNonTrivialObjCLifetime() const { |
1113 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1114 | } |
1115 | |
1116 | bool hasStrongOrWeakObjCLifetime() const { |
1117 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1118 | } |
1119 | |
1120 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1121 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1122 | |
1123 | enum PrimitiveDefaultInitializeKind { |
1124 | /// The type does not fall into any of the following categories. Note that |
1125 | /// this case is zero-valued so that values of this enum can be used as a |
1126 | /// boolean condition for non-triviality. |
1127 | PDIK_Trivial, |
1128 | |
1129 | /// The type is an Objective-C retainable pointer type that is qualified |
1130 | /// with the ARC __strong qualifier. |
1131 | PDIK_ARCStrong, |
1132 | |
1133 | /// The type is an Objective-C retainable pointer type that is qualified |
1134 | /// with the ARC __weak qualifier. |
1135 | PDIK_ARCWeak, |
1136 | |
1137 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1138 | PDIK_Struct |
1139 | }; |
1140 | |
1141 | /// Functions to query basic properties of non-trivial C struct types. |
1142 | |
1143 | /// Check if this is a non-trivial type that would cause a C struct |
1144 | /// transitively containing this type to be non-trivial to default initialize |
1145 | /// and return the kind. |
1146 | PrimitiveDefaultInitializeKind |
1147 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1148 | |
1149 | enum PrimitiveCopyKind { |
1150 | /// The type does not fall into any of the following categories. Note that |
1151 | /// this case is zero-valued so that values of this enum can be used as a |
1152 | /// boolean condition for non-triviality. |
1153 | PCK_Trivial, |
1154 | |
1155 | /// The type would be trivial except that it is volatile-qualified. Types |
1156 | /// that fall into one of the other non-trivial cases may additionally be |
1157 | /// volatile-qualified. |
1158 | PCK_VolatileTrivial, |
1159 | |
1160 | /// The type is an Objective-C retainable pointer type that is qualified |
1161 | /// with the ARC __strong qualifier. |
1162 | PCK_ARCStrong, |
1163 | |
1164 | /// The type is an Objective-C retainable pointer type that is qualified |
1165 | /// with the ARC __weak qualifier. |
1166 | PCK_ARCWeak, |
1167 | |
1168 | /// The type is a struct containing a field whose type is neither |
1169 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1170 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1171 | /// semantics are too complex to express here, in part because they depend |
1172 | /// on the exact constructor or assignment operator that is chosen by |
1173 | /// overload resolution to do the copy. |
1174 | PCK_Struct |
1175 | }; |
1176 | |
1177 | /// Check if this is a non-trivial type that would cause a C struct |
1178 | /// transitively containing this type to be non-trivial to copy and return the |
1179 | /// kind. |
1180 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1181 | |
1182 | /// Check if this is a non-trivial type that would cause a C struct |
1183 | /// transitively containing this type to be non-trivial to destructively |
1184 | /// move and return the kind. Destructive move in this context is a C++-style |
1185 | /// move in which the source object is placed in a valid but unspecified state |
1186 | /// after it is moved, as opposed to a truly destructive move in which the |
1187 | /// source object is placed in an uninitialized state. |
1188 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1189 | |
1190 | enum DestructionKind { |
1191 | DK_none, |
1192 | DK_cxx_destructor, |
1193 | DK_objc_strong_lifetime, |
1194 | DK_objc_weak_lifetime, |
1195 | DK_nontrivial_c_struct |
1196 | }; |
1197 | |
1198 | /// Returns a nonzero value if objects of this type require |
1199 | /// non-trivial work to clean up after. Non-zero because it's |
1200 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1201 | /// something require destruction. |
1202 | DestructionKind isDestructedType() const { |
1203 | return isDestructedTypeImpl(*this); |
1204 | } |
1205 | |
1206 | /// Check if this is or contains a C union that is non-trivial to |
1207 | /// default-initialize, which is a union that has a member that is non-trivial |
1208 | /// to default-initialize. If this returns true, |
1209 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1210 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1211 | |
1212 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1213 | /// which is a union that has a member that is non-trivial to destruct. If |
1214 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1215 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1216 | |
1217 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1218 | /// is a union that has a member that is non-trivial to copy. If this returns |
1219 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1220 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1221 | |
1222 | /// Determine whether expressions of the given type are forbidden |
1223 | /// from being lvalues in C. |
1224 | /// |
1225 | /// The expression types that are forbidden to be lvalues are: |
1226 | /// - 'void', but not qualified void |
1227 | /// - function types |
1228 | /// |
1229 | /// The exact rule here is C99 6.3.2.1: |
1230 | /// An lvalue is an expression with an object type or an incomplete |
1231 | /// type other than void. |
1232 | bool isCForbiddenLValueType() const; |
1233 | |
1234 | /// Substitute type arguments for the Objective-C type parameters used in the |
1235 | /// subject type. |
1236 | /// |
1237 | /// \param ctx ASTContext in which the type exists. |
1238 | /// |
1239 | /// \param typeArgs The type arguments that will be substituted for the |
1240 | /// Objective-C type parameters in the subject type, which are generally |
1241 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1242 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1243 | /// for the context. |
1244 | /// |
1245 | /// \param context The context in which the subject type was written. |
1246 | /// |
1247 | /// \returns the resulting type. |
1248 | QualType substObjCTypeArgs(ASTContext &ctx, |
1249 | ArrayRef<QualType> typeArgs, |
1250 | ObjCSubstitutionContext context) const; |
1251 | |
1252 | /// Substitute type arguments from an object type for the Objective-C type |
1253 | /// parameters used in the subject type. |
1254 | /// |
1255 | /// This operation combines the computation of type arguments for |
1256 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1257 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1258 | /// callers that need to perform a single substitution in isolation. |
1259 | /// |
1260 | /// \param objectType The type of the object whose member type we're |
1261 | /// substituting into. For example, this might be the receiver of a message |
1262 | /// or the base of a property access. |
1263 | /// |
1264 | /// \param dc The declaration context from which the subject type was |
1265 | /// retrieved, which indicates (for example) which type parameters should |
1266 | /// be substituted. |
1267 | /// |
1268 | /// \param context The context in which the subject type was written. |
1269 | /// |
1270 | /// \returns the subject type after replacing all of the Objective-C type |
1271 | /// parameters with their corresponding arguments. |
1272 | QualType substObjCMemberType(QualType objectType, |
1273 | const DeclContext *dc, |
1274 | ObjCSubstitutionContext context) const; |
1275 | |
1276 | /// Strip Objective-C "__kindof" types from the given type. |
1277 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1278 | |
1279 | /// Remove all qualifiers including _Atomic. |
1280 | QualType getAtomicUnqualifiedType() const; |
1281 | |
1282 | private: |
1283 | // These methods are implemented in a separate translation unit; |
1284 | // "static"-ize them to avoid creating temporary QualTypes in the |
1285 | // caller. |
1286 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1287 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1288 | static SplitQualType getSplitDesugaredType(QualType T); |
1289 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1290 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1291 | const ASTContext &C); |
1292 | static QualType IgnoreParens(QualType T); |
1293 | static DestructionKind isDestructedTypeImpl(QualType type); |
1294 | |
1295 | /// Check if \param RD is or contains a non-trivial C union. |
1296 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1297 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1298 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1299 | }; |
1300 | |
1301 | } // namespace clang |
1302 | |
1303 | namespace llvm { |
1304 | |
1305 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1306 | /// to a specific Type class. |
1307 | template<> struct simplify_type< ::clang::QualType> { |
1308 | using SimpleType = const ::clang::Type *; |
1309 | |
1310 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1311 | return Val.getTypePtr(); |
1312 | } |
1313 | }; |
1314 | |
1315 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1316 | template<> |
1317 | struct PointerLikeTypeTraits<clang::QualType> { |
1318 | static inline void *getAsVoidPointer(clang::QualType P) { |
1319 | return P.getAsOpaquePtr(); |
1320 | } |
1321 | |
1322 | static inline clang::QualType getFromVoidPointer(void *P) { |
1323 | return clang::QualType::getFromOpaquePtr(P); |
1324 | } |
1325 | |
1326 | // Various qualifiers go in low bits. |
1327 | static constexpr int NumLowBitsAvailable = 0; |
1328 | }; |
1329 | |
1330 | } // namespace llvm |
1331 | |
1332 | namespace clang { |
1333 | |
1334 | /// Base class that is common to both the \c ExtQuals and \c Type |
1335 | /// classes, which allows \c QualType to access the common fields between the |
1336 | /// two. |
1337 | class ExtQualsTypeCommonBase { |
1338 | friend class ExtQuals; |
1339 | friend class QualType; |
1340 | friend class Type; |
1341 | |
1342 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1343 | /// a self-referential pointer (for \c Type). |
1344 | /// |
1345 | /// This pointer allows an efficient mapping from a QualType to its |
1346 | /// underlying type pointer. |
1347 | const Type *const BaseType; |
1348 | |
1349 | /// The canonical type of this type. A QualType. |
1350 | QualType CanonicalType; |
1351 | |
1352 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1353 | : BaseType(baseType), CanonicalType(canon) {} |
1354 | }; |
1355 | |
1356 | /// We can encode up to four bits in the low bits of a |
1357 | /// type pointer, but there are many more type qualifiers that we want |
1358 | /// to be able to apply to an arbitrary type. Therefore we have this |
1359 | /// struct, intended to be heap-allocated and used by QualType to |
1360 | /// store qualifiers. |
1361 | /// |
1362 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1363 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1364 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1365 | /// Objective-C GC attributes) are much more rare. |
1366 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1367 | // NOTE: changing the fast qualifiers should be straightforward as |
1368 | // long as you don't make 'const' non-fast. |
1369 | // 1. Qualifiers: |
1370 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1371 | // Fast qualifiers must occupy the low-order bits. |
1372 | // b) Update Qualifiers::FastWidth and FastMask. |
1373 | // 2. QualType: |
1374 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1375 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1376 | // this header. |
1377 | // 3. ASTContext: |
1378 | // a) Update get{Volatile,Restrict}Type. |
1379 | |
1380 | /// The immutable set of qualifiers applied by this node. Always contains |
1381 | /// extended qualifiers. |
1382 | Qualifiers Quals; |
1383 | |
1384 | ExtQuals *this_() { return this; } |
1385 | |
1386 | public: |
1387 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1388 | : ExtQualsTypeCommonBase(baseType, |
1389 | canon.isNull() ? QualType(this_(), 0) : canon), |
1390 | Quals(quals) { |
1391 | assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 1392, __PRETTY_FUNCTION__)) |
1392 | && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 1392, __PRETTY_FUNCTION__)); |
1393 | assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 1394, __PRETTY_FUNCTION__)) |
1394 | && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 1394, __PRETTY_FUNCTION__)); |
1395 | } |
1396 | |
1397 | Qualifiers getQualifiers() const { return Quals; } |
1398 | |
1399 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1400 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1401 | |
1402 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1403 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1404 | return Quals.getObjCLifetime(); |
1405 | } |
1406 | |
1407 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1408 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1409 | |
1410 | const Type *getBaseType() const { return BaseType; } |
1411 | |
1412 | public: |
1413 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1414 | Profile(ID, getBaseType(), Quals); |
1415 | } |
1416 | |
1417 | static void Profile(llvm::FoldingSetNodeID &ID, |
1418 | const Type *BaseType, |
1419 | Qualifiers Quals) { |
1420 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 1420, __PRETTY_FUNCTION__)); |
1421 | ID.AddPointer(BaseType); |
1422 | Quals.Profile(ID); |
1423 | } |
1424 | }; |
1425 | |
1426 | /// The kind of C++11 ref-qualifier associated with a function type. |
1427 | /// This determines whether a member function's "this" object can be an |
1428 | /// lvalue, rvalue, or neither. |
1429 | enum RefQualifierKind { |
1430 | /// No ref-qualifier was provided. |
1431 | RQ_None = 0, |
1432 | |
1433 | /// An lvalue ref-qualifier was provided (\c &). |
1434 | RQ_LValue, |
1435 | |
1436 | /// An rvalue ref-qualifier was provided (\c &&). |
1437 | RQ_RValue |
1438 | }; |
1439 | |
1440 | /// Which keyword(s) were used to create an AutoType. |
1441 | enum class AutoTypeKeyword { |
1442 | /// auto |
1443 | Auto, |
1444 | |
1445 | /// decltype(auto) |
1446 | DecltypeAuto, |
1447 | |
1448 | /// __auto_type (GNU extension) |
1449 | GNUAutoType |
1450 | }; |
1451 | |
1452 | /// The base class of the type hierarchy. |
1453 | /// |
1454 | /// A central concept with types is that each type always has a canonical |
1455 | /// type. A canonical type is the type with any typedef names stripped out |
1456 | /// of it or the types it references. For example, consider: |
1457 | /// |
1458 | /// typedef int foo; |
1459 | /// typedef foo* bar; |
1460 | /// 'int *' 'foo *' 'bar' |
1461 | /// |
1462 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1463 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1464 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1465 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1466 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1467 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1468 | /// is also 'int*'. |
1469 | /// |
1470 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1471 | /// information about typedefs being used. Canonical types are useful for type |
1472 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1473 | /// about whether something has a particular form (e.g. is a function type), |
1474 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1475 | /// |
1476 | /// Types, once created, are immutable. |
1477 | /// |
1478 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1479 | public: |
1480 | enum TypeClass { |
1481 | #define TYPE(Class, Base) Class, |
1482 | #define LAST_TYPE(Class) TypeLast = Class |
1483 | #define ABSTRACT_TYPE(Class, Base) |
1484 | #include "clang/AST/TypeNodes.inc" |
1485 | }; |
1486 | |
1487 | private: |
1488 | /// Bitfields required by the Type class. |
1489 | class TypeBitfields { |
1490 | friend class Type; |
1491 | template <class T> friend class TypePropertyCache; |
1492 | |
1493 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1494 | unsigned TC : 8; |
1495 | |
1496 | /// Store information on the type dependency. |
1497 | unsigned Dependence : llvm::BitWidth<TypeDependence>; |
1498 | |
1499 | /// True if the cache (i.e. the bitfields here starting with |
1500 | /// 'Cache') is valid. |
1501 | mutable unsigned CacheValid : 1; |
1502 | |
1503 | /// Linkage of this type. |
1504 | mutable unsigned CachedLinkage : 3; |
1505 | |
1506 | /// Whether this type involves and local or unnamed types. |
1507 | mutable unsigned CachedLocalOrUnnamed : 1; |
1508 | |
1509 | /// Whether this type comes from an AST file. |
1510 | mutable unsigned FromAST : 1; |
1511 | |
1512 | bool isCacheValid() const { |
1513 | return CacheValid; |
1514 | } |
1515 | |
1516 | Linkage getLinkage() const { |
1517 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 1517, __PRETTY_FUNCTION__)); |
1518 | return static_cast<Linkage>(CachedLinkage); |
1519 | } |
1520 | |
1521 | bool hasLocalOrUnnamedType() const { |
1522 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 1522, __PRETTY_FUNCTION__)); |
1523 | return CachedLocalOrUnnamed; |
1524 | } |
1525 | }; |
1526 | enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 }; |
1527 | |
1528 | protected: |
1529 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1530 | // into Type. |
1531 | |
1532 | class ArrayTypeBitfields { |
1533 | friend class ArrayType; |
1534 | |
1535 | unsigned : NumTypeBits; |
1536 | |
1537 | /// CVR qualifiers from declarations like |
1538 | /// 'int X[static restrict 4]'. For function parameters only. |
1539 | unsigned IndexTypeQuals : 3; |
1540 | |
1541 | /// Storage class qualifiers from declarations like |
1542 | /// 'int X[static restrict 4]'. For function parameters only. |
1543 | /// Actually an ArrayType::ArraySizeModifier. |
1544 | unsigned SizeModifier : 3; |
1545 | }; |
1546 | |
1547 | class ConstantArrayTypeBitfields { |
1548 | friend class ConstantArrayType; |
1549 | |
1550 | unsigned : NumTypeBits + 3 + 3; |
1551 | |
1552 | /// Whether we have a stored size expression. |
1553 | unsigned HasStoredSizeExpr : 1; |
1554 | }; |
1555 | |
1556 | class BuiltinTypeBitfields { |
1557 | friend class BuiltinType; |
1558 | |
1559 | unsigned : NumTypeBits; |
1560 | |
1561 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1562 | unsigned Kind : 8; |
1563 | }; |
1564 | |
1565 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1566 | /// Only common bits are stored here. Additional uncommon bits are stored |
1567 | /// in a trailing object after FunctionProtoType. |
1568 | class FunctionTypeBitfields { |
1569 | friend class FunctionProtoType; |
1570 | friend class FunctionType; |
1571 | |
1572 | unsigned : NumTypeBits; |
1573 | |
1574 | /// Extra information which affects how the function is called, like |
1575 | /// regparm and the calling convention. |
1576 | unsigned ExtInfo : 13; |
1577 | |
1578 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1579 | /// |
1580 | /// This is a value of type \c RefQualifierKind. |
1581 | unsigned RefQualifier : 2; |
1582 | |
1583 | /// Used only by FunctionProtoType, put here to pack with the |
1584 | /// other bitfields. |
1585 | /// The qualifiers are part of FunctionProtoType because... |
1586 | /// |
1587 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1588 | /// cv-qualifier-seq, [...], are part of the function type. |
1589 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1590 | /// Whether this function has extended Qualifiers. |
1591 | unsigned HasExtQuals : 1; |
1592 | |
1593 | /// The number of parameters this function has, not counting '...'. |
1594 | /// According to [implimits] 8 bits should be enough here but this is |
1595 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1596 | /// keep NumParams as wide as reasonably possible. |
1597 | unsigned NumParams : 16; |
1598 | |
1599 | /// The type of exception specification this function has. |
1600 | unsigned ExceptionSpecType : 4; |
1601 | |
1602 | /// Whether this function has extended parameter information. |
1603 | unsigned HasExtParameterInfos : 1; |
1604 | |
1605 | /// Whether the function is variadic. |
1606 | unsigned Variadic : 1; |
1607 | |
1608 | /// Whether this function has a trailing return type. |
1609 | unsigned HasTrailingReturn : 1; |
1610 | }; |
1611 | |
1612 | class ObjCObjectTypeBitfields { |
1613 | friend class ObjCObjectType; |
1614 | |
1615 | unsigned : NumTypeBits; |
1616 | |
1617 | /// The number of type arguments stored directly on this object type. |
1618 | unsigned NumTypeArgs : 7; |
1619 | |
1620 | /// The number of protocols stored directly on this object type. |
1621 | unsigned NumProtocols : 6; |
1622 | |
1623 | /// Whether this is a "kindof" type. |
1624 | unsigned IsKindOf : 1; |
1625 | }; |
1626 | |
1627 | class ReferenceTypeBitfields { |
1628 | friend class ReferenceType; |
1629 | |
1630 | unsigned : NumTypeBits; |
1631 | |
1632 | /// True if the type was originally spelled with an lvalue sigil. |
1633 | /// This is never true of rvalue references but can also be false |
1634 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1635 | /// as follows: |
1636 | /// |
1637 | /// typedef int &ref; // lvalue, spelled lvalue |
1638 | /// typedef int &&rvref; // rvalue |
1639 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1640 | /// ref &&a; // lvalue, inner ref |
1641 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1642 | /// rvref &&a; // rvalue, inner ref |
1643 | unsigned SpelledAsLValue : 1; |
1644 | |
1645 | /// True if the inner type is a reference type. This only happens |
1646 | /// in non-canonical forms. |
1647 | unsigned InnerRef : 1; |
1648 | }; |
1649 | |
1650 | class TypeWithKeywordBitfields { |
1651 | friend class TypeWithKeyword; |
1652 | |
1653 | unsigned : NumTypeBits; |
1654 | |
1655 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1656 | unsigned Keyword : 8; |
1657 | }; |
1658 | |
1659 | enum { NumTypeWithKeywordBits = 8 }; |
1660 | |
1661 | class ElaboratedTypeBitfields { |
1662 | friend class ElaboratedType; |
1663 | |
1664 | unsigned : NumTypeBits; |
1665 | unsigned : NumTypeWithKeywordBits; |
1666 | |
1667 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1668 | unsigned HasOwnedTagDecl : 1; |
1669 | }; |
1670 | |
1671 | class VectorTypeBitfields { |
1672 | friend class VectorType; |
1673 | friend class DependentVectorType; |
1674 | |
1675 | unsigned : NumTypeBits; |
1676 | |
1677 | /// The kind of vector, either a generic vector type or some |
1678 | /// target-specific vector type such as for AltiVec or Neon. |
1679 | unsigned VecKind : 3; |
1680 | /// The number of elements in the vector. |
1681 | uint32_t NumElements; |
1682 | }; |
1683 | |
1684 | class AttributedTypeBitfields { |
1685 | friend class AttributedType; |
1686 | |
1687 | unsigned : NumTypeBits; |
1688 | |
1689 | /// An AttributedType::Kind |
1690 | unsigned AttrKind : 32 - NumTypeBits; |
1691 | }; |
1692 | |
1693 | class AutoTypeBitfields { |
1694 | friend class AutoType; |
1695 | |
1696 | unsigned : NumTypeBits; |
1697 | |
1698 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1699 | /// or '__auto_type'? AutoTypeKeyword value. |
1700 | unsigned Keyword : 2; |
1701 | |
1702 | /// The number of template arguments in the type-constraints, which is |
1703 | /// expected to be able to hold at least 1024 according to [implimits]. |
1704 | /// However as this limit is somewhat easy to hit with template |
1705 | /// metaprogramming we'd prefer to keep it as large as possible. |
1706 | /// At the moment it has been left as a non-bitfield since this type |
1707 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1708 | /// introduce the performance impact of a bitfield. |
1709 | unsigned NumArgs; |
1710 | }; |
1711 | |
1712 | class SubstTemplateTypeParmPackTypeBitfields { |
1713 | friend class SubstTemplateTypeParmPackType; |
1714 | |
1715 | unsigned : NumTypeBits; |
1716 | |
1717 | /// The number of template arguments in \c Arguments, which is |
1718 | /// expected to be able to hold at least 1024 according to [implimits]. |
1719 | /// However as this limit is somewhat easy to hit with template |
1720 | /// metaprogramming we'd prefer to keep it as large as possible. |
1721 | /// At the moment it has been left as a non-bitfield since this type |
1722 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1723 | /// introduce the performance impact of a bitfield. |
1724 | unsigned NumArgs; |
1725 | }; |
1726 | |
1727 | class TemplateSpecializationTypeBitfields { |
1728 | friend class TemplateSpecializationType; |
1729 | |
1730 | unsigned : NumTypeBits; |
1731 | |
1732 | /// Whether this template specialization type is a substituted type alias. |
1733 | unsigned TypeAlias : 1; |
1734 | |
1735 | /// The number of template arguments named in this class template |
1736 | /// specialization, which is expected to be able to hold at least 1024 |
1737 | /// according to [implimits]. However, as this limit is somewhat easy to |
1738 | /// hit with template metaprogramming we'd prefer to keep it as large |
1739 | /// as possible. At the moment it has been left as a non-bitfield since |
1740 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1741 | /// to introduce the performance impact of a bitfield. |
1742 | unsigned NumArgs; |
1743 | }; |
1744 | |
1745 | class DependentTemplateSpecializationTypeBitfields { |
1746 | friend class DependentTemplateSpecializationType; |
1747 | |
1748 | unsigned : NumTypeBits; |
1749 | unsigned : NumTypeWithKeywordBits; |
1750 | |
1751 | /// The number of template arguments named in this class template |
1752 | /// specialization, which is expected to be able to hold at least 1024 |
1753 | /// according to [implimits]. However, as this limit is somewhat easy to |
1754 | /// hit with template metaprogramming we'd prefer to keep it as large |
1755 | /// as possible. At the moment it has been left as a non-bitfield since |
1756 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1757 | /// to introduce the performance impact of a bitfield. |
1758 | unsigned NumArgs; |
1759 | }; |
1760 | |
1761 | class PackExpansionTypeBitfields { |
1762 | friend class PackExpansionType; |
1763 | |
1764 | unsigned : NumTypeBits; |
1765 | |
1766 | /// The number of expansions that this pack expansion will |
1767 | /// generate when substituted (+1), which is expected to be able to |
1768 | /// hold at least 1024 according to [implimits]. However, as this limit |
1769 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1770 | /// keep it as large as possible. At the moment it has been left as a |
1771 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1772 | /// there is no reason to introduce the performance impact of a bitfield. |
1773 | /// |
1774 | /// This field will only have a non-zero value when some of the parameter |
1775 | /// packs that occur within the pattern have been substituted but others |
1776 | /// have not. |
1777 | unsigned NumExpansions; |
1778 | }; |
1779 | |
1780 | union { |
1781 | TypeBitfields TypeBits; |
1782 | ArrayTypeBitfields ArrayTypeBits; |
1783 | ConstantArrayTypeBitfields ConstantArrayTypeBits; |
1784 | AttributedTypeBitfields AttributedTypeBits; |
1785 | AutoTypeBitfields AutoTypeBits; |
1786 | BuiltinTypeBitfields BuiltinTypeBits; |
1787 | FunctionTypeBitfields FunctionTypeBits; |
1788 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1789 | ReferenceTypeBitfields ReferenceTypeBits; |
1790 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1791 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1792 | VectorTypeBitfields VectorTypeBits; |
1793 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1794 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1795 | DependentTemplateSpecializationTypeBitfields |
1796 | DependentTemplateSpecializationTypeBits; |
1797 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1798 | }; |
1799 | |
1800 | private: |
1801 | template <class T> friend class TypePropertyCache; |
1802 | |
1803 | /// Set whether this type comes from an AST file. |
1804 | void setFromAST(bool V = true) const { |
1805 | TypeBits.FromAST = V; |
1806 | } |
1807 | |
1808 | protected: |
1809 | friend class ASTContext; |
1810 | |
1811 | Type(TypeClass tc, QualType canon, TypeDependence Dependence) |
1812 | : ExtQualsTypeCommonBase(this, |
1813 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1814 | static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase), |
1815 | "changing bitfields changed sizeof(Type)!"); |
1816 | static_assert(alignof(decltype(*this)) % sizeof(void *) == 0, |
1817 | "Insufficient alignment!"); |
1818 | TypeBits.TC = tc; |
1819 | TypeBits.Dependence = static_cast<unsigned>(Dependence); |
1820 | TypeBits.CacheValid = false; |
1821 | TypeBits.CachedLocalOrUnnamed = false; |
1822 | TypeBits.CachedLinkage = NoLinkage; |
1823 | TypeBits.FromAST = false; |
1824 | } |
1825 | |
1826 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1827 | Type *this_() { return this; } |
1828 | |
1829 | void setDependence(TypeDependence D) { |
1830 | TypeBits.Dependence = static_cast<unsigned>(D); |
1831 | } |
1832 | |
1833 | void addDependence(TypeDependence D) { setDependence(getDependence() | D); } |
1834 | |
1835 | public: |
1836 | friend class ASTReader; |
1837 | friend class ASTWriter; |
1838 | template <class T> friend class serialization::AbstractTypeReader; |
1839 | template <class T> friend class serialization::AbstractTypeWriter; |
1840 | |
1841 | Type(const Type &) = delete; |
1842 | Type(Type &&) = delete; |
1843 | Type &operator=(const Type &) = delete; |
1844 | Type &operator=(Type &&) = delete; |
1845 | |
1846 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1847 | |
1848 | /// Whether this type comes from an AST file. |
1849 | bool isFromAST() const { return TypeBits.FromAST; } |
1850 | |
1851 | /// Whether this type is or contains an unexpanded parameter |
1852 | /// pack, used to support C++0x variadic templates. |
1853 | /// |
1854 | /// A type that contains a parameter pack shall be expanded by the |
1855 | /// ellipsis operator at some point. For example, the typedef in the |
1856 | /// following example contains an unexpanded parameter pack 'T': |
1857 | /// |
1858 | /// \code |
1859 | /// template<typename ...T> |
1860 | /// struct X { |
1861 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1862 | /// }; |
1863 | /// \endcode |
1864 | /// |
1865 | /// Note that this routine does not specify which |
1866 | bool containsUnexpandedParameterPack() const { |
1867 | return getDependence() & TypeDependence::UnexpandedPack; |
1868 | } |
1869 | |
1870 | /// Determines if this type would be canonical if it had no further |
1871 | /// qualification. |
1872 | bool isCanonicalUnqualified() const { |
1873 | return CanonicalType == QualType(this, 0); |
1874 | } |
1875 | |
1876 | /// Pull a single level of sugar off of this locally-unqualified type. |
1877 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1878 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1879 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1880 | |
1881 | /// As an extension, we classify types as one of "sized" or "sizeless"; |
1882 | /// every type is one or the other. Standard types are all sized; |
1883 | /// sizeless types are purely an extension. |
1884 | /// |
1885 | /// Sizeless types contain data with no specified size, alignment, |
1886 | /// or layout. |
1887 | bool isSizelessType() const; |
1888 | bool isSizelessBuiltinType() const; |
1889 | |
1890 | /// Determines if this is a sizeless type supported by the |
1891 | /// 'arm_sve_vector_bits' type attribute, which can be applied to a single |
1892 | /// SVE vector or predicate, excluding tuple types such as svint32x4_t. |
1893 | bool isVLSTBuiltinType() const; |
1894 | |
1895 | /// Returns the representative type for the element of an SVE builtin type. |
1896 | /// This is used to represent fixed-length SVE vectors created with the |
1897 | /// 'arm_sve_vector_bits' type attribute as VectorType. |
1898 | QualType getSveEltType(const ASTContext &Ctx) const; |
1899 | |
1900 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1901 | /// object types, function types, and incomplete types. |
1902 | |
1903 | /// Return true if this is an incomplete type. |
1904 | /// A type that can describe objects, but which lacks information needed to |
1905 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1906 | /// routine will need to determine if the size is actually required. |
1907 | /// |
1908 | /// Def If non-null, and the type refers to some kind of declaration |
1909 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1910 | /// class), will be set to the declaration. |
1911 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1912 | |
1913 | /// Return true if this is an incomplete or object |
1914 | /// type, in other words, not a function type. |
1915 | bool isIncompleteOrObjectType() const { |
1916 | return !isFunctionType(); |
1917 | } |
1918 | |
1919 | /// Determine whether this type is an object type. |
1920 | bool isObjectType() const { |
1921 | // C++ [basic.types]p8: |
1922 | // An object type is a (possibly cv-qualified) type that is not a |
1923 | // function type, not a reference type, and not a void type. |
1924 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1925 | } |
1926 | |
1927 | /// Return true if this is a literal type |
1928 | /// (C++11 [basic.types]p10) |
1929 | bool isLiteralType(const ASTContext &Ctx) const; |
1930 | |
1931 | /// Determine if this type is a structural type, per C++20 [temp.param]p7. |
1932 | bool isStructuralType() const; |
1933 | |
1934 | /// Test if this type is a standard-layout type. |
1935 | /// (C++0x [basic.type]p9) |
1936 | bool isStandardLayoutType() const; |
1937 | |
1938 | /// Helper methods to distinguish type categories. All type predicates |
1939 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1940 | |
1941 | /// Returns true if the type is a builtin type. |
1942 | bool isBuiltinType() const; |
1943 | |
1944 | /// Test for a particular builtin type. |
1945 | bool isSpecificBuiltinType(unsigned K) const; |
1946 | |
1947 | /// Test for a type which does not represent an actual type-system type but |
1948 | /// is instead used as a placeholder for various convenient purposes within |
1949 | /// Clang. All such types are BuiltinTypes. |
1950 | bool isPlaceholderType() const; |
1951 | const BuiltinType *getAsPlaceholderType() const; |
1952 | |
1953 | /// Test for a specific placeholder type. |
1954 | bool isSpecificPlaceholderType(unsigned K) const; |
1955 | |
1956 | /// Test for a placeholder type other than Overload; see |
1957 | /// BuiltinType::isNonOverloadPlaceholderType. |
1958 | bool isNonOverloadPlaceholderType() const; |
1959 | |
1960 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1961 | /// isComplexIntegerType() can be used to test for complex integers. |
1962 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1963 | bool isEnumeralType() const; |
1964 | |
1965 | /// Determine whether this type is a scoped enumeration type. |
1966 | bool isScopedEnumeralType() const; |
1967 | bool isBooleanType() const; |
1968 | bool isCharType() const; |
1969 | bool isWideCharType() const; |
1970 | bool isChar8Type() const; |
1971 | bool isChar16Type() const; |
1972 | bool isChar32Type() const; |
1973 | bool isAnyCharacterType() const; |
1974 | bool isIntegralType(const ASTContext &Ctx) const; |
1975 | |
1976 | /// Determine whether this type is an integral or enumeration type. |
1977 | bool isIntegralOrEnumerationType() const; |
1978 | |
1979 | /// Determine whether this type is an integral or unscoped enumeration type. |
1980 | bool isIntegralOrUnscopedEnumerationType() const; |
1981 | bool isUnscopedEnumerationType() const; |
1982 | |
1983 | /// Floating point categories. |
1984 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1985 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1986 | /// isComplexIntegerType() can be used to test for complex integers. |
1987 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1988 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1989 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1990 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1991 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1992 | bool isBFloat16Type() const; |
1993 | bool isFloat128Type() const; |
1994 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1995 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1996 | bool isVoidType() const; // C99 6.2.5p19 |
1997 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1998 | bool isAggregateType() const; |
1999 | bool isFundamentalType() const; |
2000 | bool isCompoundType() const; |
2001 | |
2002 | // Type Predicates: Check to see if this type is structurally the specified |
2003 | // type, ignoring typedefs and qualifiers. |
2004 | bool isFunctionType() const; |
2005 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
2006 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
2007 | bool isPointerType() const; |
2008 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
2009 | bool isBlockPointerType() const; |
2010 | bool isVoidPointerType() const; |
2011 | bool isReferenceType() const; |
2012 | bool isLValueReferenceType() const; |
2013 | bool isRValueReferenceType() const; |
2014 | bool isObjectPointerType() const; |
2015 | bool isFunctionPointerType() const; |
2016 | bool isFunctionReferenceType() const; |
2017 | bool isMemberPointerType() const; |
2018 | bool isMemberFunctionPointerType() const; |
2019 | bool isMemberDataPointerType() const; |
2020 | bool isArrayType() const; |
2021 | bool isConstantArrayType() const; |
2022 | bool isIncompleteArrayType() const; |
2023 | bool isVariableArrayType() const; |
2024 | bool isDependentSizedArrayType() const; |
2025 | bool isRecordType() const; |
2026 | bool isClassType() const; |
2027 | bool isStructureType() const; |
2028 | bool isObjCBoxableRecordType() const; |
2029 | bool isInterfaceType() const; |
2030 | bool isStructureOrClassType() const; |
2031 | bool isUnionType() const; |
2032 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2033 | bool isVectorType() const; // GCC vector type. |
2034 | bool isExtVectorType() const; // Extended vector type. |
2035 | bool isMatrixType() const; // Matrix type. |
2036 | bool isConstantMatrixType() const; // Constant matrix type. |
2037 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2038 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2039 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2040 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2041 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2042 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2043 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2044 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2045 | // for the common case. |
2046 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2047 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2048 | bool isObjCQualifiedIdType() const; // id<foo> |
2049 | bool isObjCQualifiedClassType() const; // Class<foo> |
2050 | bool isObjCObjectOrInterfaceType() const; |
2051 | bool isObjCIdType() const; // id |
2052 | bool isDecltypeType() const; |
2053 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2054 | /// qualifier? |
2055 | /// |
2056 | /// This approximates the answer to the following question: if this |
2057 | /// translation unit were compiled in ARC, would this type be qualified |
2058 | /// with __unsafe_unretained? |
2059 | bool isObjCInertUnsafeUnretainedType() const { |
2060 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2061 | } |
2062 | |
2063 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2064 | /// object type, e.g., __kindof NSView * or __kindof id |
2065 | /// <NSCopying>. |
2066 | /// |
2067 | /// \param bound Will be set to the bound on non-id subtype types, |
2068 | /// which will be (possibly specialized) Objective-C class type, or |
2069 | /// null for 'id. |
2070 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2071 | const ObjCObjectType *&bound) const; |
2072 | |
2073 | bool isObjCClassType() const; // Class |
2074 | |
2075 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2076 | /// Class type, e.g., __kindof Class <NSCopying>. |
2077 | /// |
2078 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2079 | /// here because Objective-C's type system cannot express "a class |
2080 | /// object for a subclass of NSFoo". |
2081 | bool isObjCClassOrClassKindOfType() const; |
2082 | |
2083 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2084 | bool isObjCSelType() const; // Class |
2085 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2086 | bool isObjCARCBridgableType() const; |
2087 | bool isCARCBridgableType() const; |
2088 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2089 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2090 | bool isNothrowT() const; // C++ std::nothrow_t |
2091 | bool isAlignValT() const; // C++17 std::align_val_t |
2092 | bool isStdByteType() const; // C++17 std::byte |
2093 | bool isAtomicType() const; // C11 _Atomic() |
2094 | bool isUndeducedAutoType() const; // C++11 auto or |
2095 | // C++14 decltype(auto) |
2096 | |
2097 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2098 | bool is##Id##Type() const; |
2099 | #include "clang/Basic/OpenCLImageTypes.def" |
2100 | |
2101 | bool isImageType() const; // Any OpenCL image type |
2102 | |
2103 | bool isSamplerT() const; // OpenCL sampler_t |
2104 | bool isEventT() const; // OpenCL event_t |
2105 | bool isClkEventT() const; // OpenCL clk_event_t |
2106 | bool isQueueT() const; // OpenCL queue_t |
2107 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2108 | |
2109 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2110 | bool is##Id##Type() const; |
2111 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2112 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2113 | bool isOCLIntelSubgroupAVCType() const; |
2114 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2115 | |
2116 | bool isPipeType() const; // OpenCL pipe type |
2117 | bool isExtIntType() const; // Extended Int Type |
2118 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2119 | |
2120 | /// Determines if this type, which must satisfy |
2121 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2122 | /// than implicitly __strong. |
2123 | bool isObjCARCImplicitlyUnretainedType() const; |
2124 | |
2125 | /// Check if the type is the CUDA device builtin surface type. |
2126 | bool isCUDADeviceBuiltinSurfaceType() const; |
2127 | /// Check if the type is the CUDA device builtin texture type. |
2128 | bool isCUDADeviceBuiltinTextureType() const; |
2129 | |
2130 | /// Return the implicit lifetime for this type, which must not be dependent. |
2131 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2132 | |
2133 | enum ScalarTypeKind { |
2134 | STK_CPointer, |
2135 | STK_BlockPointer, |
2136 | STK_ObjCObjectPointer, |
2137 | STK_MemberPointer, |
2138 | STK_Bool, |
2139 | STK_Integral, |
2140 | STK_Floating, |
2141 | STK_IntegralComplex, |
2142 | STK_FloatingComplex, |
2143 | STK_FixedPoint |
2144 | }; |
2145 | |
2146 | /// Given that this is a scalar type, classify it. |
2147 | ScalarTypeKind getScalarTypeKind() const; |
2148 | |
2149 | TypeDependence getDependence() const { |
2150 | return static_cast<TypeDependence>(TypeBits.Dependence); |
2151 | } |
2152 | |
2153 | /// Whether this type is an error type. |
2154 | bool containsErrors() const { |
2155 | return getDependence() & TypeDependence::Error; |
2156 | } |
2157 | |
2158 | /// Whether this type is a dependent type, meaning that its definition |
2159 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2160 | bool isDependentType() const { |
2161 | return getDependence() & TypeDependence::Dependent; |
2162 | } |
2163 | |
2164 | /// Determine whether this type is an instantiation-dependent type, |
2165 | /// meaning that the type involves a template parameter (even if the |
2166 | /// definition does not actually depend on the type substituted for that |
2167 | /// template parameter). |
2168 | bool isInstantiationDependentType() const { |
2169 | return getDependence() & TypeDependence::Instantiation; |
2170 | } |
2171 | |
2172 | /// Determine whether this type is an undeduced type, meaning that |
2173 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2174 | /// deduced. |
2175 | bool isUndeducedType() const; |
2176 | |
2177 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2178 | bool isVariablyModifiedType() const { |
2179 | return getDependence() & TypeDependence::VariablyModified; |
2180 | } |
2181 | |
2182 | /// Whether this type involves a variable-length array type |
2183 | /// with a definite size. |
2184 | bool hasSizedVLAType() const; |
2185 | |
2186 | /// Whether this type is or contains a local or unnamed type. |
2187 | bool hasUnnamedOrLocalType() const; |
2188 | |
2189 | bool isOverloadableType() const; |
2190 | |
2191 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2192 | bool isElaboratedTypeSpecifier() const; |
2193 | |
2194 | bool canDecayToPointerType() const; |
2195 | |
2196 | /// Whether this type is represented natively as a pointer. This includes |
2197 | /// pointers, references, block pointers, and Objective-C interface, |
2198 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2199 | bool hasPointerRepresentation() const; |
2200 | |
2201 | /// Whether this type can represent an objective pointer type for the |
2202 | /// purpose of GC'ability |
2203 | bool hasObjCPointerRepresentation() const; |
2204 | |
2205 | /// Determine whether this type has an integer representation |
2206 | /// of some sort, e.g., it is an integer type or a vector. |
2207 | bool hasIntegerRepresentation() const; |
2208 | |
2209 | /// Determine whether this type has an signed integer representation |
2210 | /// of some sort, e.g., it is an signed integer type or a vector. |
2211 | bool hasSignedIntegerRepresentation() const; |
2212 | |
2213 | /// Determine whether this type has an unsigned integer representation |
2214 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2215 | bool hasUnsignedIntegerRepresentation() const; |
2216 | |
2217 | /// Determine whether this type has a floating-point representation |
2218 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2219 | bool hasFloatingRepresentation() const; |
2220 | |
2221 | // Type Checking Functions: Check to see if this type is structurally the |
2222 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2223 | // the best type we can. |
2224 | const RecordType *getAsStructureType() const; |
2225 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2226 | const RecordType *getAsUnionType() const; |
2227 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2228 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2229 | |
2230 | // The following is a convenience method that returns an ObjCObjectPointerType |
2231 | // for object declared using an interface. |
2232 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2233 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2234 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2235 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2236 | |
2237 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2238 | /// because the type is a RecordType or because it is the injected-class-name |
2239 | /// type of a class template or class template partial specialization. |
2240 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2241 | |
2242 | /// Retrieves the RecordDecl this type refers to. |
2243 | RecordDecl *getAsRecordDecl() const; |
2244 | |
2245 | /// Retrieves the TagDecl that this type refers to, either |
2246 | /// because the type is a TagType or because it is the injected-class-name |
2247 | /// type of a class template or class template partial specialization. |
2248 | TagDecl *getAsTagDecl() const; |
2249 | |
2250 | /// If this is a pointer or reference to a RecordType, return the |
2251 | /// CXXRecordDecl that the type refers to. |
2252 | /// |
2253 | /// If this is not a pointer or reference, or the type being pointed to does |
2254 | /// not refer to a CXXRecordDecl, returns NULL. |
2255 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2256 | |
2257 | /// Get the DeducedType whose type will be deduced for a variable with |
2258 | /// an initializer of this type. This looks through declarators like pointer |
2259 | /// types, but not through decltype or typedefs. |
2260 | DeducedType *getContainedDeducedType() const; |
2261 | |
2262 | /// Get the AutoType whose type will be deduced for a variable with |
2263 | /// an initializer of this type. This looks through declarators like pointer |
2264 | /// types, but not through decltype or typedefs. |
2265 | AutoType *getContainedAutoType() const { |
2266 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2267 | } |
2268 | |
2269 | /// Determine whether this type was written with a leading 'auto' |
2270 | /// corresponding to a trailing return type (possibly for a nested |
2271 | /// function type within a pointer to function type or similar). |
2272 | bool hasAutoForTrailingReturnType() const; |
2273 | |
2274 | /// Member-template getAs<specific type>'. Look through sugar for |
2275 | /// an instance of \<specific type>. This scheme will eventually |
2276 | /// replace the specific getAsXXXX methods above. |
2277 | /// |
2278 | /// There are some specializations of this member template listed |
2279 | /// immediately following this class. |
2280 | template <typename T> const T *getAs() const; |
2281 | |
2282 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2283 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2284 | /// This is used when you need to walk over sugar nodes that represent some |
2285 | /// kind of type adjustment from a type that was written as a \<specific type> |
2286 | /// to another type that is still canonically a \<specific type>. |
2287 | template <typename T> const T *getAsAdjusted() const; |
2288 | |
2289 | /// A variant of getAs<> for array types which silently discards |
2290 | /// qualifiers from the outermost type. |
2291 | const ArrayType *getAsArrayTypeUnsafe() const; |
2292 | |
2293 | /// Member-template castAs<specific type>. Look through sugar for |
2294 | /// the underlying instance of \<specific type>. |
2295 | /// |
2296 | /// This method has the same relationship to getAs<T> as cast<T> has |
2297 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2298 | /// have the intended type, and this method will never return null. |
2299 | template <typename T> const T *castAs() const; |
2300 | |
2301 | /// A variant of castAs<> for array type which silently discards |
2302 | /// qualifiers from the outermost type. |
2303 | const ArrayType *castAsArrayTypeUnsafe() const; |
2304 | |
2305 | /// Determine whether this type had the specified attribute applied to it |
2306 | /// (looking through top-level type sugar). |
2307 | bool hasAttr(attr::Kind AK) const; |
2308 | |
2309 | /// Get the base element type of this type, potentially discarding type |
2310 | /// qualifiers. This should never be used when type qualifiers |
2311 | /// are meaningful. |
2312 | const Type *getBaseElementTypeUnsafe() const; |
2313 | |
2314 | /// If this is an array type, return the element type of the array, |
2315 | /// potentially with type qualifiers missing. |
2316 | /// This should never be used when type qualifiers are meaningful. |
2317 | const Type *getArrayElementTypeNoTypeQual() const; |
2318 | |
2319 | /// If this is a pointer type, return the pointee type. |
2320 | /// If this is an array type, return the array element type. |
2321 | /// This should never be used when type qualifiers are meaningful. |
2322 | const Type *getPointeeOrArrayElementType() const; |
2323 | |
2324 | /// If this is a pointer, ObjC object pointer, or block |
2325 | /// pointer, this returns the respective pointee. |
2326 | QualType getPointeeType() const; |
2327 | |
2328 | /// Return the specified type with any "sugar" removed from the type, |
2329 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2330 | const Type *getUnqualifiedDesugaredType() const; |
2331 | |
2332 | /// More type predicates useful for type checking/promotion |
2333 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2334 | |
2335 | /// Return true if this is an integer type that is |
2336 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2337 | /// or an enum decl which has a signed representation. |
2338 | bool isSignedIntegerType() const; |
2339 | |
2340 | /// Return true if this is an integer type that is |
2341 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2342 | /// or an enum decl which has an unsigned representation. |
2343 | bool isUnsignedIntegerType() const; |
2344 | |
2345 | /// Determines whether this is an integer type that is signed or an |
2346 | /// enumeration types whose underlying type is a signed integer type. |
2347 | bool isSignedIntegerOrEnumerationType() const; |
2348 | |
2349 | /// Determines whether this is an integer type that is unsigned or an |
2350 | /// enumeration types whose underlying type is a unsigned integer type. |
2351 | bool isUnsignedIntegerOrEnumerationType() const; |
2352 | |
2353 | /// Return true if this is a fixed point type according to |
2354 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2355 | bool isFixedPointType() const; |
2356 | |
2357 | /// Return true if this is a fixed point or integer type. |
2358 | bool isFixedPointOrIntegerType() const; |
2359 | |
2360 | /// Return true if this is a saturated fixed point type according to |
2361 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2362 | bool isSaturatedFixedPointType() const; |
2363 | |
2364 | /// Return true if this is a saturated fixed point type according to |
2365 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2366 | bool isUnsaturatedFixedPointType() const; |
2367 | |
2368 | /// Return true if this is a fixed point type that is signed according |
2369 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2370 | bool isSignedFixedPointType() const; |
2371 | |
2372 | /// Return true if this is a fixed point type that is unsigned according |
2373 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2374 | bool isUnsignedFixedPointType() const; |
2375 | |
2376 | /// Return true if this is not a variable sized type, |
2377 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2378 | /// incomplete types. |
2379 | bool isConstantSizeType() const; |
2380 | |
2381 | /// Returns true if this type can be represented by some |
2382 | /// set of type specifiers. |
2383 | bool isSpecifierType() const; |
2384 | |
2385 | /// Determine the linkage of this type. |
2386 | Linkage getLinkage() const; |
2387 | |
2388 | /// Determine the visibility of this type. |
2389 | Visibility getVisibility() const { |
2390 | return getLinkageAndVisibility().getVisibility(); |
2391 | } |
2392 | |
2393 | /// Return true if the visibility was explicitly set is the code. |
2394 | bool isVisibilityExplicit() const { |
2395 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2396 | } |
2397 | |
2398 | /// Determine the linkage and visibility of this type. |
2399 | LinkageInfo getLinkageAndVisibility() const; |
2400 | |
2401 | /// True if the computed linkage is valid. Used for consistency |
2402 | /// checking. Should always return true. |
2403 | bool isLinkageValid() const; |
2404 | |
2405 | /// Determine the nullability of the given type. |
2406 | /// |
2407 | /// Note that nullability is only captured as sugar within the type |
2408 | /// system, not as part of the canonical type, so nullability will |
2409 | /// be lost by canonicalization and desugaring. |
2410 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2411 | |
2412 | /// Determine whether the given type can have a nullability |
2413 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2414 | /// |
2415 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2416 | /// this type can have nullability because it is dependent. |
2417 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2418 | |
2419 | /// Retrieve the set of substitutions required when accessing a member |
2420 | /// of the Objective-C receiver type that is declared in the given context. |
2421 | /// |
2422 | /// \c *this is the type of the object we're operating on, e.g., the |
2423 | /// receiver for a message send or the base of a property access, and is |
2424 | /// expected to be of some object or object pointer type. |
2425 | /// |
2426 | /// \param dc The declaration context for which we are building up a |
2427 | /// substitution mapping, which should be an Objective-C class, extension, |
2428 | /// category, or method within. |
2429 | /// |
2430 | /// \returns an array of type arguments that can be substituted for |
2431 | /// the type parameters of the given declaration context in any type described |
2432 | /// within that context, or an empty optional to indicate that no |
2433 | /// substitution is required. |
2434 | Optional<ArrayRef<QualType>> |
2435 | getObjCSubstitutions(const DeclContext *dc) const; |
2436 | |
2437 | /// Determines if this is an ObjC interface type that may accept type |
2438 | /// parameters. |
2439 | bool acceptsObjCTypeParams() const; |
2440 | |
2441 | const char *getTypeClassName() const; |
2442 | |
2443 | QualType getCanonicalTypeInternal() const { |
2444 | return CanonicalType; |
2445 | } |
2446 | |
2447 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2448 | void dump() const; |
2449 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
2450 | }; |
2451 | |
2452 | /// This will check for a TypedefType by removing any existing sugar |
2453 | /// until it reaches a TypedefType or a non-sugared type. |
2454 | template <> const TypedefType *Type::getAs() const; |
2455 | |
2456 | /// This will check for a TemplateSpecializationType by removing any |
2457 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2458 | /// non-sugared type. |
2459 | template <> const TemplateSpecializationType *Type::getAs() const; |
2460 | |
2461 | /// This will check for an AttributedType by removing any existing sugar |
2462 | /// until it reaches an AttributedType or a non-sugared type. |
2463 | template <> const AttributedType *Type::getAs() const; |
2464 | |
2465 | // We can do canonical leaf types faster, because we don't have to |
2466 | // worry about preserving child type decoration. |
2467 | #define TYPE(Class, Base) |
2468 | #define LEAF_TYPE(Class) \ |
2469 | template <> inline const Class##Type *Type::getAs() const { \ |
2470 | return dyn_cast<Class##Type>(CanonicalType); \ |
2471 | } \ |
2472 | template <> inline const Class##Type *Type::castAs() const { \ |
2473 | return cast<Class##Type>(CanonicalType); \ |
2474 | } |
2475 | #include "clang/AST/TypeNodes.inc" |
2476 | |
2477 | /// This class is used for builtin types like 'int'. Builtin |
2478 | /// types are always canonical and have a literal name field. |
2479 | class BuiltinType : public Type { |
2480 | public: |
2481 | enum Kind { |
2482 | // OpenCL image types |
2483 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2484 | #include "clang/Basic/OpenCLImageTypes.def" |
2485 | // OpenCL extension types |
2486 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2487 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2488 | // SVE Types |
2489 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2490 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2491 | // PPC MMA Types |
2492 | #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) Id, |
2493 | #include "clang/Basic/PPCTypes.def" |
2494 | // All other builtin types |
2495 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2496 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2497 | #include "clang/AST/BuiltinTypes.def" |
2498 | }; |
2499 | |
2500 | private: |
2501 | friend class ASTContext; // ASTContext creates these. |
2502 | |
2503 | BuiltinType(Kind K) |
2504 | : Type(Builtin, QualType(), |
2505 | K == Dependent ? TypeDependence::DependentInstantiation |
2506 | : TypeDependence::None) { |
2507 | BuiltinTypeBits.Kind = K; |
2508 | } |
2509 | |
2510 | public: |
2511 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2512 | StringRef getName(const PrintingPolicy &Policy) const; |
2513 | |
2514 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2515 | // The StringRef is null-terminated. |
2516 | StringRef str = getName(Policy); |
2517 | assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast <void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 2517, __PRETTY_FUNCTION__)); |
2518 | return str.data(); |
2519 | } |
2520 | |
2521 | bool isSugared() const { return false; } |
2522 | QualType desugar() const { return QualType(this, 0); } |
2523 | |
2524 | bool isInteger() const { |
2525 | return getKind() >= Bool && getKind() <= Int128; |
2526 | } |
2527 | |
2528 | bool isSignedInteger() const { |
2529 | return getKind() >= Char_S && getKind() <= Int128; |
2530 | } |
2531 | |
2532 | bool isUnsignedInteger() const { |
2533 | return getKind() >= Bool && getKind() <= UInt128; |
2534 | } |
2535 | |
2536 | bool isFloatingPoint() const { |
2537 | return getKind() >= Half && getKind() <= Float128; |
2538 | } |
2539 | |
2540 | /// Determines whether the given kind corresponds to a placeholder type. |
2541 | static bool isPlaceholderTypeKind(Kind K) { |
2542 | return K >= Overload; |
2543 | } |
2544 | |
2545 | /// Determines whether this type is a placeholder type, i.e. a type |
2546 | /// which cannot appear in arbitrary positions in a fully-formed |
2547 | /// expression. |
2548 | bool isPlaceholderType() const { |
2549 | return isPlaceholderTypeKind(getKind()); |
2550 | } |
2551 | |
2552 | /// Determines whether this type is a placeholder type other than |
2553 | /// Overload. Most placeholder types require only syntactic |
2554 | /// information about their context in order to be resolved (e.g. |
2555 | /// whether it is a call expression), which means they can (and |
2556 | /// should) be resolved in an earlier "phase" of analysis. |
2557 | /// Overload expressions sometimes pick up further information |
2558 | /// from their context, like whether the context expects a |
2559 | /// specific function-pointer type, and so frequently need |
2560 | /// special treatment. |
2561 | bool isNonOverloadPlaceholderType() const { |
2562 | return getKind() > Overload; |
2563 | } |
2564 | |
2565 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2566 | }; |
2567 | |
2568 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2569 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2570 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2571 | friend class ASTContext; // ASTContext creates these. |
2572 | |
2573 | QualType ElementType; |
2574 | |
2575 | ComplexType(QualType Element, QualType CanonicalPtr) |
2576 | : Type(Complex, CanonicalPtr, Element->getDependence()), |
2577 | ElementType(Element) {} |
2578 | |
2579 | public: |
2580 | QualType getElementType() const { return ElementType; } |
2581 | |
2582 | bool isSugared() const { return false; } |
2583 | QualType desugar() const { return QualType(this, 0); } |
2584 | |
2585 | void Profile(llvm::FoldingSetNodeID &ID) { |
2586 | Profile(ID, getElementType()); |
2587 | } |
2588 | |
2589 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2590 | ID.AddPointer(Element.getAsOpaquePtr()); |
2591 | } |
2592 | |
2593 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2594 | }; |
2595 | |
2596 | /// Sugar for parentheses used when specifying types. |
2597 | class ParenType : public Type, public llvm::FoldingSetNode { |
2598 | friend class ASTContext; // ASTContext creates these. |
2599 | |
2600 | QualType Inner; |
2601 | |
2602 | ParenType(QualType InnerType, QualType CanonType) |
2603 | : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {} |
2604 | |
2605 | public: |
2606 | QualType getInnerType() const { return Inner; } |
2607 | |
2608 | bool isSugared() const { return true; } |
2609 | QualType desugar() const { return getInnerType(); } |
2610 | |
2611 | void Profile(llvm::FoldingSetNodeID &ID) { |
2612 | Profile(ID, getInnerType()); |
2613 | } |
2614 | |
2615 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2616 | Inner.Profile(ID); |
2617 | } |
2618 | |
2619 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2620 | }; |
2621 | |
2622 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2623 | class PointerType : public Type, public llvm::FoldingSetNode { |
2624 | friend class ASTContext; // ASTContext creates these. |
2625 | |
2626 | QualType PointeeType; |
2627 | |
2628 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2629 | : Type(Pointer, CanonicalPtr, Pointee->getDependence()), |
2630 | PointeeType(Pointee) {} |
2631 | |
2632 | public: |
2633 | QualType getPointeeType() const { return PointeeType; } |
2634 | |
2635 | bool isSugared() const { return false; } |
2636 | QualType desugar() const { return QualType(this, 0); } |
2637 | |
2638 | void Profile(llvm::FoldingSetNodeID &ID) { |
2639 | Profile(ID, getPointeeType()); |
2640 | } |
2641 | |
2642 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2643 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2644 | } |
2645 | |
2646 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2647 | }; |
2648 | |
2649 | /// Represents a type which was implicitly adjusted by the semantic |
2650 | /// engine for arbitrary reasons. For example, array and function types can |
2651 | /// decay, and function types can have their calling conventions adjusted. |
2652 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2653 | QualType OriginalTy; |
2654 | QualType AdjustedTy; |
2655 | |
2656 | protected: |
2657 | friend class ASTContext; // ASTContext creates these. |
2658 | |
2659 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2660 | QualType CanonicalPtr) |
2661 | : Type(TC, CanonicalPtr, OriginalTy->getDependence()), |
2662 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2663 | |
2664 | public: |
2665 | QualType getOriginalType() const { return OriginalTy; } |
2666 | QualType getAdjustedType() const { return AdjustedTy; } |
2667 | |
2668 | bool isSugared() const { return true; } |
2669 | QualType desugar() const { return AdjustedTy; } |
2670 | |
2671 | void Profile(llvm::FoldingSetNodeID &ID) { |
2672 | Profile(ID, OriginalTy, AdjustedTy); |
2673 | } |
2674 | |
2675 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2676 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2677 | ID.AddPointer(New.getAsOpaquePtr()); |
2678 | } |
2679 | |
2680 | static bool classof(const Type *T) { |
2681 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2682 | } |
2683 | }; |
2684 | |
2685 | /// Represents a pointer type decayed from an array or function type. |
2686 | class DecayedType : public AdjustedType { |
2687 | friend class ASTContext; // ASTContext creates these. |
2688 | |
2689 | inline |
2690 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2691 | |
2692 | public: |
2693 | QualType getDecayedType() const { return getAdjustedType(); } |
2694 | |
2695 | inline QualType getPointeeType() const; |
2696 | |
2697 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2698 | }; |
2699 | |
2700 | /// Pointer to a block type. |
2701 | /// This type is to represent types syntactically represented as |
2702 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2703 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2704 | friend class ASTContext; // ASTContext creates these. |
2705 | |
2706 | // Block is some kind of pointer type |
2707 | QualType PointeeType; |
2708 | |
2709 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2710 | : Type(BlockPointer, CanonicalCls, Pointee->getDependence()), |
2711 | PointeeType(Pointee) {} |
2712 | |
2713 | public: |
2714 | // Get the pointee type. Pointee is required to always be a function type. |
2715 | QualType getPointeeType() const { return PointeeType; } |
2716 | |
2717 | bool isSugared() const { return false; } |
2718 | QualType desugar() const { return QualType(this, 0); } |
2719 | |
2720 | void Profile(llvm::FoldingSetNodeID &ID) { |
2721 | Profile(ID, getPointeeType()); |
2722 | } |
2723 | |
2724 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2725 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2726 | } |
2727 | |
2728 | static bool classof(const Type *T) { |
2729 | return T->getTypeClass() == BlockPointer; |
2730 | } |
2731 | }; |
2732 | |
2733 | /// Base for LValueReferenceType and RValueReferenceType |
2734 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2735 | QualType PointeeType; |
2736 | |
2737 | protected: |
2738 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2739 | bool SpelledAsLValue) |
2740 | : Type(tc, CanonicalRef, Referencee->getDependence()), |
2741 | PointeeType(Referencee) { |
2742 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2743 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2744 | } |
2745 | |
2746 | public: |
2747 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2748 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2749 | |
2750 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2751 | |
2752 | QualType getPointeeType() const { |
2753 | // FIXME: this might strip inner qualifiers; okay? |
2754 | const ReferenceType *T = this; |
2755 | while (T->isInnerRef()) |
2756 | T = T->PointeeType->castAs<ReferenceType>(); |
2757 | return T->PointeeType; |
2758 | } |
2759 | |
2760 | void Profile(llvm::FoldingSetNodeID &ID) { |
2761 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2762 | } |
2763 | |
2764 | static void Profile(llvm::FoldingSetNodeID &ID, |
2765 | QualType Referencee, |
2766 | bool SpelledAsLValue) { |
2767 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2768 | ID.AddBoolean(SpelledAsLValue); |
2769 | } |
2770 | |
2771 | static bool classof(const Type *T) { |
2772 | return T->getTypeClass() == LValueReference || |
2773 | T->getTypeClass() == RValueReference; |
2774 | } |
2775 | }; |
2776 | |
2777 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2778 | class LValueReferenceType : public ReferenceType { |
2779 | friend class ASTContext; // ASTContext creates these |
2780 | |
2781 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2782 | bool SpelledAsLValue) |
2783 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2784 | SpelledAsLValue) {} |
2785 | |
2786 | public: |
2787 | bool isSugared() const { return false; } |
2788 | QualType desugar() const { return QualType(this, 0); } |
2789 | |
2790 | static bool classof(const Type *T) { |
2791 | return T->getTypeClass() == LValueReference; |
2792 | } |
2793 | }; |
2794 | |
2795 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2796 | class RValueReferenceType : public ReferenceType { |
2797 | friend class ASTContext; // ASTContext creates these |
2798 | |
2799 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2800 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2801 | |
2802 | public: |
2803 | bool isSugared() const { return false; } |
2804 | QualType desugar() const { return QualType(this, 0); } |
2805 | |
2806 | static bool classof(const Type *T) { |
2807 | return T->getTypeClass() == RValueReference; |
2808 | } |
2809 | }; |
2810 | |
2811 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2812 | /// |
2813 | /// This includes both pointers to data members and pointer to member functions. |
2814 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2815 | friend class ASTContext; // ASTContext creates these. |
2816 | |
2817 | QualType PointeeType; |
2818 | |
2819 | /// The class of which the pointee is a member. Must ultimately be a |
2820 | /// RecordType, but could be a typedef or a template parameter too. |
2821 | const Type *Class; |
2822 | |
2823 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2824 | : Type(MemberPointer, CanonicalPtr, |
2825 | (Cls->getDependence() & ~TypeDependence::VariablyModified) | |
2826 | Pointee->getDependence()), |
2827 | PointeeType(Pointee), Class(Cls) {} |
2828 | |
2829 | public: |
2830 | QualType getPointeeType() const { return PointeeType; } |
2831 | |
2832 | /// Returns true if the member type (i.e. the pointee type) is a |
2833 | /// function type rather than a data-member type. |
2834 | bool isMemberFunctionPointer() const { |
2835 | return PointeeType->isFunctionProtoType(); |
2836 | } |
2837 | |
2838 | /// Returns true if the member type (i.e. the pointee type) is a |
2839 | /// data type rather than a function type. |
2840 | bool isMemberDataPointer() const { |
2841 | return !PointeeType->isFunctionProtoType(); |
2842 | } |
2843 | |
2844 | const Type *getClass() const { return Class; } |
2845 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2846 | |
2847 | bool isSugared() const { return false; } |
2848 | QualType desugar() const { return QualType(this, 0); } |
2849 | |
2850 | void Profile(llvm::FoldingSetNodeID &ID) { |
2851 | Profile(ID, getPointeeType(), getClass()); |
2852 | } |
2853 | |
2854 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2855 | const Type *Class) { |
2856 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2857 | ID.AddPointer(Class); |
2858 | } |
2859 | |
2860 | static bool classof(const Type *T) { |
2861 | return T->getTypeClass() == MemberPointer; |
2862 | } |
2863 | }; |
2864 | |
2865 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2866 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2867 | public: |
2868 | /// Capture whether this is a normal array (e.g. int X[4]) |
2869 | /// an array with a static size (e.g. int X[static 4]), or an array |
2870 | /// with a star size (e.g. int X[*]). |
2871 | /// 'static' is only allowed on function parameters. |
2872 | enum ArraySizeModifier { |
2873 | Normal, Static, Star |
2874 | }; |
2875 | |
2876 | private: |
2877 | /// The element type of the array. |
2878 | QualType ElementType; |
2879 | |
2880 | protected: |
2881 | friend class ASTContext; // ASTContext creates these. |
2882 | |
2883 | ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, |
2884 | unsigned tq, const Expr *sz = nullptr); |
2885 | |
2886 | public: |
2887 | QualType getElementType() const { return ElementType; } |
2888 | |
2889 | ArraySizeModifier getSizeModifier() const { |
2890 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2891 | } |
2892 | |
2893 | Qualifiers getIndexTypeQualifiers() const { |
2894 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2895 | } |
2896 | |
2897 | unsigned getIndexTypeCVRQualifiers() const { |
2898 | return ArrayTypeBits.IndexTypeQuals; |
2899 | } |
2900 | |
2901 | static bool classof(const Type *T) { |
2902 | return T->getTypeClass() == ConstantArray || |
2903 | T->getTypeClass() == VariableArray || |
2904 | T->getTypeClass() == IncompleteArray || |
2905 | T->getTypeClass() == DependentSizedArray; |
2906 | } |
2907 | }; |
2908 | |
2909 | /// Represents the canonical version of C arrays with a specified constant size. |
2910 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2911 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2912 | class ConstantArrayType final |
2913 | : public ArrayType, |
2914 | private llvm::TrailingObjects<ConstantArrayType, const Expr *> { |
2915 | friend class ASTContext; // ASTContext creates these. |
2916 | friend TrailingObjects; |
2917 | |
2918 | llvm::APInt Size; // Allows us to unique the type. |
2919 | |
2920 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2921 | const Expr *sz, ArraySizeModifier sm, unsigned tq) |
2922 | : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { |
2923 | ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; |
2924 | if (ConstantArrayTypeBits.HasStoredSizeExpr) { |
2925 | assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size" ) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 2925, __PRETTY_FUNCTION__)); |
2926 | *getTrailingObjects<const Expr*>() = sz; |
2927 | } |
2928 | } |
2929 | |
2930 | unsigned numTrailingObjects(OverloadToken<const Expr*>) const { |
2931 | return ConstantArrayTypeBits.HasStoredSizeExpr; |
2932 | } |
2933 | |
2934 | public: |
2935 | const llvm::APInt &getSize() const { return Size; } |
2936 | const Expr *getSizeExpr() const { |
2937 | return ConstantArrayTypeBits.HasStoredSizeExpr |
2938 | ? *getTrailingObjects<const Expr *>() |
2939 | : nullptr; |
2940 | } |
2941 | bool isSugared() const { return false; } |
2942 | QualType desugar() const { return QualType(this, 0); } |
2943 | |
2944 | /// Determine the number of bits required to address a member of |
2945 | // an array with the given element type and number of elements. |
2946 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2947 | QualType ElementType, |
2948 | const llvm::APInt &NumElements); |
2949 | |
2950 | /// Determine the maximum number of active bits that an array's size |
2951 | /// can require, which limits the maximum size of the array. |
2952 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2953 | |
2954 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
2955 | Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), |
2956 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2957 | } |
2958 | |
2959 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, |
2960 | QualType ET, const llvm::APInt &ArraySize, |
2961 | const Expr *SizeExpr, ArraySizeModifier SizeMod, |
2962 | unsigned TypeQuals); |
2963 | |
2964 | static bool classof(const Type *T) { |
2965 | return T->getTypeClass() == ConstantArray; |
2966 | } |
2967 | }; |
2968 | |
2969 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2970 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2971 | /// unspecified. |
2972 | class IncompleteArrayType : public ArrayType { |
2973 | friend class ASTContext; // ASTContext creates these. |
2974 | |
2975 | IncompleteArrayType(QualType et, QualType can, |
2976 | ArraySizeModifier sm, unsigned tq) |
2977 | : ArrayType(IncompleteArray, et, can, sm, tq) {} |
2978 | |
2979 | public: |
2980 | friend class StmtIteratorBase; |
2981 | |
2982 | bool isSugared() const { return false; } |
2983 | QualType desugar() const { return QualType(this, 0); } |
2984 | |
2985 | static bool classof(const Type *T) { |
2986 | return T->getTypeClass() == IncompleteArray; |
2987 | } |
2988 | |
2989 | void Profile(llvm::FoldingSetNodeID &ID) { |
2990 | Profile(ID, getElementType(), getSizeModifier(), |
2991 | getIndexTypeCVRQualifiers()); |
2992 | } |
2993 | |
2994 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2995 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
2996 | ID.AddPointer(ET.getAsOpaquePtr()); |
2997 | ID.AddInteger(SizeMod); |
2998 | ID.AddInteger(TypeQuals); |
2999 | } |
3000 | }; |
3001 | |
3002 | /// Represents a C array with a specified size that is not an |
3003 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
3004 | /// Since the size expression is an arbitrary expression, we store it as such. |
3005 | /// |
3006 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3007 | /// should not be: two lexically equivalent variable array types could mean |
3008 | /// different things, for example, these variables do not have the same type |
3009 | /// dynamically: |
3010 | /// |
3011 | /// void foo(int x) { |
3012 | /// int Y[x]; |
3013 | /// ++x; |
3014 | /// int Z[x]; |
3015 | /// } |
3016 | class VariableArrayType : public ArrayType { |
3017 | friend class ASTContext; // ASTContext creates these. |
3018 | |
3019 | /// An assignment-expression. VLA's are only permitted within |
3020 | /// a function block. |
3021 | Stmt *SizeExpr; |
3022 | |
3023 | /// The range spanned by the left and right array brackets. |
3024 | SourceRange Brackets; |
3025 | |
3026 | VariableArrayType(QualType et, QualType can, Expr *e, |
3027 | ArraySizeModifier sm, unsigned tq, |
3028 | SourceRange brackets) |
3029 | : ArrayType(VariableArray, et, can, sm, tq, e), |
3030 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3031 | |
3032 | public: |
3033 | friend class StmtIteratorBase; |
3034 | |
3035 | Expr *getSizeExpr() const { |
3036 | // We use C-style casts instead of cast<> here because we do not wish |
3037 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3038 | return (Expr*) SizeExpr; |
3039 | } |
3040 | |
3041 | SourceRange getBracketsRange() const { return Brackets; } |
3042 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3043 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3044 | |
3045 | bool isSugared() const { return false; } |
3046 | QualType desugar() const { return QualType(this, 0); } |
3047 | |
3048 | static bool classof(const Type *T) { |
3049 | return T->getTypeClass() == VariableArray; |
3050 | } |
3051 | |
3052 | void Profile(llvm::FoldingSetNodeID &ID) { |
3053 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 3053); |
3054 | } |
3055 | }; |
3056 | |
3057 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3058 | /// |
3059 | /// For example: |
3060 | /// \code |
3061 | /// template<typename T, int Size> |
3062 | /// class array { |
3063 | /// T data[Size]; |
3064 | /// }; |
3065 | /// \endcode |
3066 | /// |
3067 | /// For these types, we won't actually know what the array bound is |
3068 | /// until template instantiation occurs, at which point this will |
3069 | /// become either a ConstantArrayType or a VariableArrayType. |
3070 | class DependentSizedArrayType : public ArrayType { |
3071 | friend class ASTContext; // ASTContext creates these. |
3072 | |
3073 | const ASTContext &Context; |
3074 | |
3075 | /// An assignment expression that will instantiate to the |
3076 | /// size of the array. |
3077 | /// |
3078 | /// The expression itself might be null, in which case the array |
3079 | /// type will have its size deduced from an initializer. |
3080 | Stmt *SizeExpr; |
3081 | |
3082 | /// The range spanned by the left and right array brackets. |
3083 | SourceRange Brackets; |
3084 | |
3085 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3086 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3087 | SourceRange brackets); |
3088 | |
3089 | public: |
3090 | friend class StmtIteratorBase; |
3091 | |
3092 | Expr *getSizeExpr() const { |
3093 | // We use C-style casts instead of cast<> here because we do not wish |
3094 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3095 | return (Expr*) SizeExpr; |
3096 | } |
3097 | |
3098 | SourceRange getBracketsRange() const { return Brackets; } |
3099 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3100 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3101 | |
3102 | bool isSugared() const { return false; } |
3103 | QualType desugar() const { return QualType(this, 0); } |
3104 | |
3105 | static bool classof(const Type *T) { |
3106 | return T->getTypeClass() == DependentSizedArray; |
3107 | } |
3108 | |
3109 | void Profile(llvm::FoldingSetNodeID &ID) { |
3110 | Profile(ID, Context, getElementType(), |
3111 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3112 | } |
3113 | |
3114 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3115 | QualType ET, ArraySizeModifier SizeMod, |
3116 | unsigned TypeQuals, Expr *E); |
3117 | }; |
3118 | |
3119 | /// Represents an extended address space qualifier where the input address space |
3120 | /// value is dependent. Non-dependent address spaces are not represented with a |
3121 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3122 | /// |
3123 | /// For example: |
3124 | /// \code |
3125 | /// template<typename T, int AddrSpace> |
3126 | /// class AddressSpace { |
3127 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3128 | /// } |
3129 | /// \endcode |
3130 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3131 | friend class ASTContext; |
3132 | |
3133 | const ASTContext &Context; |
3134 | Expr *AddrSpaceExpr; |
3135 | QualType PointeeType; |
3136 | SourceLocation loc; |
3137 | |
3138 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3139 | QualType can, Expr *AddrSpaceExpr, |
3140 | SourceLocation loc); |
3141 | |
3142 | public: |
3143 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3144 | QualType getPointeeType() const { return PointeeType; } |
3145 | SourceLocation getAttributeLoc() const { return loc; } |
3146 | |
3147 | bool isSugared() const { return false; } |
3148 | QualType desugar() const { return QualType(this, 0); } |
3149 | |
3150 | static bool classof(const Type *T) { |
3151 | return T->getTypeClass() == DependentAddressSpace; |
3152 | } |
3153 | |
3154 | void Profile(llvm::FoldingSetNodeID &ID) { |
3155 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3156 | } |
3157 | |
3158 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3159 | QualType PointeeType, Expr *AddrSpaceExpr); |
3160 | }; |
3161 | |
3162 | /// Represents an extended vector type where either the type or size is |
3163 | /// dependent. |
3164 | /// |
3165 | /// For example: |
3166 | /// \code |
3167 | /// template<typename T, int Size> |
3168 | /// class vector { |
3169 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3170 | /// } |
3171 | /// \endcode |
3172 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3173 | friend class ASTContext; |
3174 | |
3175 | const ASTContext &Context; |
3176 | Expr *SizeExpr; |
3177 | |
3178 | /// The element type of the array. |
3179 | QualType ElementType; |
3180 | |
3181 | SourceLocation loc; |
3182 | |
3183 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3184 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3185 | |
3186 | public: |
3187 | Expr *getSizeExpr() const { return SizeExpr; } |
3188 | QualType getElementType() const { return ElementType; } |
3189 | SourceLocation getAttributeLoc() const { return loc; } |
3190 | |
3191 | bool isSugared() const { return false; } |
3192 | QualType desugar() const { return QualType(this, 0); } |
3193 | |
3194 | static bool classof(const Type *T) { |
3195 | return T->getTypeClass() == DependentSizedExtVector; |
3196 | } |
3197 | |
3198 | void Profile(llvm::FoldingSetNodeID &ID) { |
3199 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3200 | } |
3201 | |
3202 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3203 | QualType ElementType, Expr *SizeExpr); |
3204 | }; |
3205 | |
3206 | |
3207 | /// Represents a GCC generic vector type. This type is created using |
3208 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3209 | /// bytes; or from an Altivec __vector or vector declaration. |
3210 | /// Since the constructor takes the number of vector elements, the |
3211 | /// client is responsible for converting the size into the number of elements. |
3212 | class VectorType : public Type, public llvm::FoldingSetNode { |
3213 | public: |
3214 | enum VectorKind { |
3215 | /// not a target-specific vector type |
3216 | GenericVector, |
3217 | |
3218 | /// is AltiVec vector |
3219 | AltiVecVector, |
3220 | |
3221 | /// is AltiVec 'vector Pixel' |
3222 | AltiVecPixel, |
3223 | |
3224 | /// is AltiVec 'vector bool ...' |
3225 | AltiVecBool, |
3226 | |
3227 | /// is ARM Neon vector |
3228 | NeonVector, |
3229 | |
3230 | /// is ARM Neon polynomial vector |
3231 | NeonPolyVector, |
3232 | |
3233 | /// is AArch64 SVE fixed-length data vector |
3234 | SveFixedLengthDataVector, |
3235 | |
3236 | /// is AArch64 SVE fixed-length predicate vector |
3237 | SveFixedLengthPredicateVector |
3238 | }; |
3239 | |
3240 | protected: |
3241 | friend class ASTContext; // ASTContext creates these. |
3242 | |
3243 | /// The element type of the vector. |
3244 | QualType ElementType; |
3245 | |
3246 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3247 | VectorKind vecKind); |
3248 | |
3249 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3250 | QualType canonType, VectorKind vecKind); |
3251 | |
3252 | public: |
3253 | QualType getElementType() const { return ElementType; } |
3254 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3255 | |
3256 | bool isSugared() const { return false; } |
3257 | QualType desugar() const { return QualType(this, 0); } |
3258 | |
3259 | VectorKind getVectorKind() const { |
3260 | return VectorKind(VectorTypeBits.VecKind); |
3261 | } |
3262 | |
3263 | void Profile(llvm::FoldingSetNodeID &ID) { |
3264 | Profile(ID, getElementType(), getNumElements(), |
3265 | getTypeClass(), getVectorKind()); |
3266 | } |
3267 | |
3268 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3269 | unsigned NumElements, TypeClass TypeClass, |
3270 | VectorKind VecKind) { |
3271 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3272 | ID.AddInteger(NumElements); |
3273 | ID.AddInteger(TypeClass); |
3274 | ID.AddInteger(VecKind); |
3275 | } |
3276 | |
3277 | static bool classof(const Type *T) { |
3278 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3279 | } |
3280 | }; |
3281 | |
3282 | /// Represents a vector type where either the type or size is dependent. |
3283 | //// |
3284 | /// For example: |
3285 | /// \code |
3286 | /// template<typename T, int Size> |
3287 | /// class vector { |
3288 | /// typedef T __attribute__((vector_size(Size))) type; |
3289 | /// } |
3290 | /// \endcode |
3291 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3292 | friend class ASTContext; |
3293 | |
3294 | const ASTContext &Context; |
3295 | QualType ElementType; |
3296 | Expr *SizeExpr; |
3297 | SourceLocation Loc; |
3298 | |
3299 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3300 | QualType CanonType, Expr *SizeExpr, |
3301 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3302 | |
3303 | public: |
3304 | Expr *getSizeExpr() const { return SizeExpr; } |
3305 | QualType getElementType() const { return ElementType; } |
3306 | SourceLocation getAttributeLoc() const { return Loc; } |
3307 | VectorType::VectorKind getVectorKind() const { |
3308 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3309 | } |
3310 | |
3311 | bool isSugared() const { return false; } |
3312 | QualType desugar() const { return QualType(this, 0); } |
3313 | |
3314 | static bool classof(const Type *T) { |
3315 | return T->getTypeClass() == DependentVector; |
3316 | } |
3317 | |
3318 | void Profile(llvm::FoldingSetNodeID &ID) { |
3319 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3320 | } |
3321 | |
3322 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3323 | QualType ElementType, const Expr *SizeExpr, |
3324 | VectorType::VectorKind VecKind); |
3325 | }; |
3326 | |
3327 | /// ExtVectorType - Extended vector type. This type is created using |
3328 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3329 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3330 | /// class enables syntactic extensions, like Vector Components for accessing |
3331 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3332 | /// Shading Language). |
3333 | class ExtVectorType : public VectorType { |
3334 | friend class ASTContext; // ASTContext creates these. |
3335 | |
3336 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3337 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3338 | |
3339 | public: |
3340 | static int getPointAccessorIdx(char c) { |
3341 | switch (c) { |
3342 | default: return -1; |
3343 | case 'x': case 'r': return 0; |
3344 | case 'y': case 'g': return 1; |
3345 | case 'z': case 'b': return 2; |
3346 | case 'w': case 'a': return 3; |
3347 | } |
3348 | } |
3349 | |
3350 | static int getNumericAccessorIdx(char c) { |
3351 | switch (c) { |
3352 | default: return -1; |
3353 | case '0': return 0; |
3354 | case '1': return 1; |
3355 | case '2': return 2; |
3356 | case '3': return 3; |
3357 | case '4': return 4; |
3358 | case '5': return 5; |
3359 | case '6': return 6; |
3360 | case '7': return 7; |
3361 | case '8': return 8; |
3362 | case '9': return 9; |
3363 | case 'A': |
3364 | case 'a': return 10; |
3365 | case 'B': |
3366 | case 'b': return 11; |
3367 | case 'C': |
3368 | case 'c': return 12; |
3369 | case 'D': |
3370 | case 'd': return 13; |
3371 | case 'E': |
3372 | case 'e': return 14; |
3373 | case 'F': |
3374 | case 'f': return 15; |
3375 | } |
3376 | } |
3377 | |
3378 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3379 | if (isNumericAccessor) |
3380 | return getNumericAccessorIdx(c); |
3381 | else |
3382 | return getPointAccessorIdx(c); |
3383 | } |
3384 | |
3385 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3386 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3387 | return unsigned(idx-1) < getNumElements(); |
3388 | return false; |
3389 | } |
3390 | |
3391 | bool isSugared() const { return false; } |
3392 | QualType desugar() const { return QualType(this, 0); } |
3393 | |
3394 | static bool classof(const Type *T) { |
3395 | return T->getTypeClass() == ExtVector; |
3396 | } |
3397 | }; |
3398 | |
3399 | /// Represents a matrix type, as defined in the Matrix Types clang extensions. |
3400 | /// __attribute__((matrix_type(rows, columns))), where "rows" specifies |
3401 | /// number of rows and "columns" specifies the number of columns. |
3402 | class MatrixType : public Type, public llvm::FoldingSetNode { |
3403 | protected: |
3404 | friend class ASTContext; |
3405 | |
3406 | /// The element type of the matrix. |
3407 | QualType ElementType; |
3408 | |
3409 | MatrixType(QualType ElementTy, QualType CanonElementTy); |
3410 | |
3411 | MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy, |
3412 | const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr); |
3413 | |
3414 | public: |
3415 | /// Returns type of the elements being stored in the matrix |
3416 | QualType getElementType() const { return ElementType; } |
3417 | |
3418 | /// Valid elements types are the following: |
3419 | /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types |
3420 | /// and _Bool |
3421 | /// * the standard floating types float or double |
3422 | /// * a half-precision floating point type, if one is supported on the target |
3423 | static bool isValidElementType(QualType T) { |
3424 | return T->isDependentType() || |
3425 | (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType()); |
3426 | } |
3427 | |
3428 | bool isSugared() const { return false; } |
3429 | QualType desugar() const { return QualType(this, 0); } |
3430 | |
3431 | static bool classof(const Type *T) { |
3432 | return T->getTypeClass() == ConstantMatrix || |
3433 | T->getTypeClass() == DependentSizedMatrix; |
3434 | } |
3435 | }; |
3436 | |
3437 | /// Represents a concrete matrix type with constant number of rows and columns |
3438 | class ConstantMatrixType final : public MatrixType { |
3439 | protected: |
3440 | friend class ASTContext; |
3441 | |
3442 | /// The element type of the matrix. |
3443 | // FIXME: Appears to be unused? There is also MatrixType::ElementType... |
3444 | QualType ElementType; |
3445 | |
3446 | /// Number of rows and columns. |
3447 | unsigned NumRows; |
3448 | unsigned NumColumns; |
3449 | |
3450 | static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1; |
3451 | |
3452 | ConstantMatrixType(QualType MatrixElementType, unsigned NRows, |
3453 | unsigned NColumns, QualType CanonElementType); |
3454 | |
3455 | ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows, |
3456 | unsigned NColumns, QualType CanonElementType); |
3457 | |
3458 | public: |
3459 | /// Returns the number of rows in the matrix. |
3460 | unsigned getNumRows() const { return NumRows; } |
3461 | |
3462 | /// Returns the number of columns in the matrix. |
3463 | unsigned getNumColumns() const { return NumColumns; } |
3464 | |
3465 | /// Returns the number of elements required to embed the matrix into a vector. |
3466 | unsigned getNumElementsFlattened() const { |
3467 | return getNumRows() * getNumColumns(); |
3468 | } |
3469 | |
3470 | /// Returns true if \p NumElements is a valid matrix dimension. |
3471 | static constexpr bool isDimensionValid(size_t NumElements) { |
3472 | return NumElements > 0 && NumElements <= MaxElementsPerDimension; |
3473 | } |
3474 | |
3475 | /// Returns the maximum number of elements per dimension. |
3476 | static constexpr unsigned getMaxElementsPerDimension() { |
3477 | return MaxElementsPerDimension; |
3478 | } |
3479 | |
3480 | void Profile(llvm::FoldingSetNodeID &ID) { |
3481 | Profile(ID, getElementType(), getNumRows(), getNumColumns(), |
3482 | getTypeClass()); |
3483 | } |
3484 | |
3485 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3486 | unsigned NumRows, unsigned NumColumns, |
3487 | TypeClass TypeClass) { |
3488 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3489 | ID.AddInteger(NumRows); |
3490 | ID.AddInteger(NumColumns); |
3491 | ID.AddInteger(TypeClass); |
3492 | } |
3493 | |
3494 | static bool classof(const Type *T) { |
3495 | return T->getTypeClass() == ConstantMatrix; |
3496 | } |
3497 | }; |
3498 | |
3499 | /// Represents a matrix type where the type and the number of rows and columns |
3500 | /// is dependent on a template. |
3501 | class DependentSizedMatrixType final : public MatrixType { |
3502 | friend class ASTContext; |
3503 | |
3504 | const ASTContext &Context; |
3505 | Expr *RowExpr; |
3506 | Expr *ColumnExpr; |
3507 | |
3508 | SourceLocation loc; |
3509 | |
3510 | DependentSizedMatrixType(const ASTContext &Context, QualType ElementType, |
3511 | QualType CanonicalType, Expr *RowExpr, |
3512 | Expr *ColumnExpr, SourceLocation loc); |
3513 | |
3514 | public: |
3515 | QualType getElementType() const { return ElementType; } |
3516 | Expr *getRowExpr() const { return RowExpr; } |
3517 | Expr *getColumnExpr() const { return ColumnExpr; } |
3518 | SourceLocation getAttributeLoc() const { return loc; } |
3519 | |
3520 | bool isSugared() const { return false; } |
3521 | QualType desugar() const { return QualType(this, 0); } |
3522 | |
3523 | static bool classof(const Type *T) { |
3524 | return T->getTypeClass() == DependentSizedMatrix; |
3525 | } |
3526 | |
3527 | void Profile(llvm::FoldingSetNodeID &ID) { |
3528 | Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr()); |
3529 | } |
3530 | |
3531 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3532 | QualType ElementType, Expr *RowExpr, Expr *ColumnExpr); |
3533 | }; |
3534 | |
3535 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3536 | /// class of FunctionNoProtoType and FunctionProtoType. |
3537 | class FunctionType : public Type { |
3538 | // The type returned by the function. |
3539 | QualType ResultType; |
3540 | |
3541 | public: |
3542 | /// Interesting information about a specific parameter that can't simply |
3543 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3544 | /// but is in FunctionType to make this class available during the |
3545 | /// specification of the bases of FunctionProtoType. |
3546 | /// |
3547 | /// It makes sense to model language features this way when there's some |
3548 | /// sort of parameter-specific override (such as an attribute) that |
3549 | /// affects how the function is called. For example, the ARC ns_consumed |
3550 | /// attribute changes whether a parameter is passed at +0 (the default) |
3551 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3552 | /// but isn't really a change to the parameter type. |
3553 | /// |
3554 | /// One serious disadvantage of modelling language features this way is |
3555 | /// that they generally do not work with language features that attempt |
3556 | /// to destructure types. For example, template argument deduction will |
3557 | /// not be able to match a parameter declared as |
3558 | /// T (*)(U) |
3559 | /// against an argument of type |
3560 | /// void (*)(__attribute__((ns_consumed)) id) |
3561 | /// because the substitution of T=void, U=id into the former will |
3562 | /// not produce the latter. |
3563 | class ExtParameterInfo { |
3564 | enum { |
3565 | ABIMask = 0x0F, |
3566 | IsConsumed = 0x10, |
3567 | HasPassObjSize = 0x20, |
3568 | IsNoEscape = 0x40, |
3569 | }; |
3570 | unsigned char Data = 0; |
3571 | |
3572 | public: |
3573 | ExtParameterInfo() = default; |
3574 | |
3575 | /// Return the ABI treatment of this parameter. |
3576 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3577 | ExtParameterInfo withABI(ParameterABI kind) const { |
3578 | ExtParameterInfo copy = *this; |
3579 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3580 | return copy; |
3581 | } |
3582 | |
3583 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3584 | /// Consumed parameters must have retainable object type. |
3585 | bool isConsumed() const { return (Data & IsConsumed); } |
3586 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3587 | ExtParameterInfo copy = *this; |
3588 | if (consumed) |
3589 | copy.Data |= IsConsumed; |
3590 | else |
3591 | copy.Data &= ~IsConsumed; |
3592 | return copy; |
3593 | } |
3594 | |
3595 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3596 | ExtParameterInfo withHasPassObjectSize() const { |
3597 | ExtParameterInfo Copy = *this; |
3598 | Copy.Data |= HasPassObjSize; |
3599 | return Copy; |
3600 | } |
3601 | |
3602 | bool isNoEscape() const { return Data & IsNoEscape; } |
3603 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3604 | ExtParameterInfo Copy = *this; |
3605 | if (NoEscape) |
3606 | Copy.Data |= IsNoEscape; |
3607 | else |
3608 | Copy.Data &= ~IsNoEscape; |
3609 | return Copy; |
3610 | } |
3611 | |
3612 | unsigned char getOpaqueValue() const { return Data; } |
3613 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3614 | ExtParameterInfo result; |
3615 | result.Data = data; |
3616 | return result; |
3617 | } |
3618 | |
3619 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3620 | return lhs.Data == rhs.Data; |
3621 | } |
3622 | |
3623 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3624 | return lhs.Data != rhs.Data; |
3625 | } |
3626 | }; |
3627 | |
3628 | /// A class which abstracts out some details necessary for |
3629 | /// making a call. |
3630 | /// |
3631 | /// It is not actually used directly for storing this information in |
3632 | /// a FunctionType, although FunctionType does currently use the |
3633 | /// same bit-pattern. |
3634 | /// |
3635 | // If you add a field (say Foo), other than the obvious places (both, |
3636 | // constructors, compile failures), what you need to update is |
3637 | // * Operator== |
3638 | // * getFoo |
3639 | // * withFoo |
3640 | // * functionType. Add Foo, getFoo. |
3641 | // * ASTContext::getFooType |
3642 | // * ASTContext::mergeFunctionTypes |
3643 | // * FunctionNoProtoType::Profile |
3644 | // * FunctionProtoType::Profile |
3645 | // * TypePrinter::PrintFunctionProto |
3646 | // * AST read and write |
3647 | // * Codegen |
3648 | class ExtInfo { |
3649 | friend class FunctionType; |
3650 | |
3651 | // Feel free to rearrange or add bits, but if you go over 16, you'll need to |
3652 | // adjust the Bits field below, and if you add bits, you'll need to adjust |
3653 | // Type::FunctionTypeBitfields::ExtInfo as well. |
3654 | |
3655 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall| |
3656 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 | |
3657 | // |
3658 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3659 | enum { CallConvMask = 0x1F }; |
3660 | enum { NoReturnMask = 0x20 }; |
3661 | enum { ProducesResultMask = 0x40 }; |
3662 | enum { NoCallerSavedRegsMask = 0x80 }; |
3663 | enum { |
3664 | RegParmMask = 0x700, |
3665 | RegParmOffset = 8 |
3666 | }; |
3667 | enum { NoCfCheckMask = 0x800 }; |
3668 | enum { CmseNSCallMask = 0x1000 }; |
3669 | uint16_t Bits = CC_C; |
3670 | |
3671 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3672 | |
3673 | public: |
3674 | // Constructor with no defaults. Use this when you know that you |
3675 | // have all the elements (when reading an AST file for example). |
3676 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3677 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck, |
3678 | bool cmseNSCall) { |
3679 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value" ) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 3679, __PRETTY_FUNCTION__)); |
3680 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3681 | (producesResult ? ProducesResultMask : 0) | |
3682 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3683 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3684 | (NoCfCheck ? NoCfCheckMask : 0) | |
3685 | (cmseNSCall ? CmseNSCallMask : 0); |
3686 | } |
3687 | |
3688 | // Constructor with all defaults. Use when for example creating a |
3689 | // function known to use defaults. |
3690 | ExtInfo() = default; |
3691 | |
3692 | // Constructor with just the calling convention, which is an important part |
3693 | // of the canonical type. |
3694 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3695 | |
3696 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3697 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3698 | bool getCmseNSCall() const { return Bits & CmseNSCallMask; } |
3699 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3700 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3701 | bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; } |
3702 | |
3703 | unsigned getRegParm() const { |
3704 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3705 | if (RegParm > 0) |
3706 | --RegParm; |
3707 | return RegParm; |
3708 | } |
3709 | |
3710 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3711 | |
3712 | bool operator==(ExtInfo Other) const { |
3713 | return Bits == Other.Bits; |
3714 | } |
3715 | bool operator!=(ExtInfo Other) const { |
3716 | return Bits != Other.Bits; |
3717 | } |
3718 | |
3719 | // Note that we don't have setters. That is by design, use |
3720 | // the following with methods instead of mutating these objects. |
3721 | |
3722 | ExtInfo withNoReturn(bool noReturn) const { |
3723 | if (noReturn) |
3724 | return ExtInfo(Bits | NoReturnMask); |
3725 | else |
3726 | return ExtInfo(Bits & ~NoReturnMask); |
3727 | } |
3728 | |
3729 | ExtInfo withProducesResult(bool producesResult) const { |
3730 | if (producesResult) |
3731 | return ExtInfo(Bits | ProducesResultMask); |
3732 | else |
3733 | return ExtInfo(Bits & ~ProducesResultMask); |
3734 | } |
3735 | |
3736 | ExtInfo withCmseNSCall(bool cmseNSCall) const { |
3737 | if (cmseNSCall) |
3738 | return ExtInfo(Bits | CmseNSCallMask); |
3739 | else |
3740 | return ExtInfo(Bits & ~CmseNSCallMask); |
3741 | } |
3742 | |
3743 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3744 | if (noCallerSavedRegs) |
3745 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3746 | else |
3747 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3748 | } |
3749 | |
3750 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3751 | if (noCfCheck) |
3752 | return ExtInfo(Bits | NoCfCheckMask); |
3753 | else |
3754 | return ExtInfo(Bits & ~NoCfCheckMask); |
3755 | } |
3756 | |
3757 | ExtInfo withRegParm(unsigned RegParm) const { |
3758 | assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast <void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 3758, __PRETTY_FUNCTION__)); |
3759 | return ExtInfo((Bits & ~RegParmMask) | |
3760 | ((RegParm + 1) << RegParmOffset)); |
3761 | } |
3762 | |
3763 | ExtInfo withCallingConv(CallingConv cc) const { |
3764 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3765 | } |
3766 | |
3767 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3768 | ID.AddInteger(Bits); |
3769 | } |
3770 | }; |
3771 | |
3772 | /// A simple holder for a QualType representing a type in an |
3773 | /// exception specification. Unfortunately needed by FunctionProtoType |
3774 | /// because TrailingObjects cannot handle repeated types. |
3775 | struct ExceptionType { QualType Type; }; |
3776 | |
3777 | /// A simple holder for various uncommon bits which do not fit in |
3778 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3779 | /// alignment of subsequent objects in TrailingObjects. You must update |
3780 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3781 | struct alignas(void *) FunctionTypeExtraBitfields { |
3782 | /// The number of types in the exception specification. |
3783 | /// A whole unsigned is not needed here and according to |
3784 | /// [implimits] 8 bits would be enough here. |
3785 | unsigned NumExceptionType; |
3786 | }; |
3787 | |
3788 | protected: |
3789 | FunctionType(TypeClass tc, QualType res, QualType Canonical, |
3790 | TypeDependence Dependence, ExtInfo Info) |
3791 | : Type(tc, Canonical, Dependence), ResultType(res) { |
3792 | FunctionTypeBits.ExtInfo = Info.Bits; |
3793 | } |
3794 | |
3795 | Qualifiers getFastTypeQuals() const { |
3796 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3797 | } |
3798 | |
3799 | public: |
3800 | QualType getReturnType() const { return ResultType; } |
3801 | |
3802 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3803 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3804 | |
3805 | /// Determine whether this function type includes the GNU noreturn |
3806 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3807 | /// type. |
3808 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3809 | |
3810 | bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); } |
3811 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3812 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3813 | |
3814 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3815 | "Const, volatile and restrict are assumed to be a subset of " |
3816 | "the fast qualifiers."); |
3817 | |
3818 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3819 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3820 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3821 | |
3822 | /// Determine the type of an expression that calls a function of |
3823 | /// this type. |
3824 | QualType getCallResultType(const ASTContext &Context) const { |
3825 | return getReturnType().getNonLValueExprType(Context); |
3826 | } |
3827 | |
3828 | static StringRef getNameForCallConv(CallingConv CC); |
3829 | |
3830 | static bool classof(const Type *T) { |
3831 | return T->getTypeClass() == FunctionNoProto || |
3832 | T->getTypeClass() == FunctionProto; |
3833 | } |
3834 | }; |
3835 | |
3836 | /// Represents a K&R-style 'int foo()' function, which has |
3837 | /// no information available about its arguments. |
3838 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3839 | friend class ASTContext; // ASTContext creates these. |
3840 | |
3841 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3842 | : FunctionType(FunctionNoProto, Result, Canonical, |
3843 | Result->getDependence() & |
3844 | ~(TypeDependence::DependentInstantiation | |
3845 | TypeDependence::UnexpandedPack), |
3846 | Info) {} |
3847 | |
3848 | public: |
3849 | // No additional state past what FunctionType provides. |
3850 | |
3851 | bool isSugared() const { return false; } |
3852 | QualType desugar() const { return QualType(this, 0); } |
3853 | |
3854 | void Profile(llvm::FoldingSetNodeID &ID) { |
3855 | Profile(ID, getReturnType(), getExtInfo()); |
3856 | } |
3857 | |
3858 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3859 | ExtInfo Info) { |
3860 | Info.Profile(ID); |
3861 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3862 | } |
3863 | |
3864 | static bool classof(const Type *T) { |
3865 | return T->getTypeClass() == FunctionNoProto; |
3866 | } |
3867 | }; |
3868 | |
3869 | /// Represents a prototype with parameter type info, e.g. |
3870 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3871 | /// parameters, not as having a single void parameter. Such a type can have |
3872 | /// an exception specification, but this specification is not part of the |
3873 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3874 | /// which optional. For more information about the trailing objects see |
3875 | /// the first comment inside FunctionProtoType. |
3876 | class FunctionProtoType final |
3877 | : public FunctionType, |
3878 | public llvm::FoldingSetNode, |
3879 | private llvm::TrailingObjects< |
3880 | FunctionProtoType, QualType, SourceLocation, |
3881 | FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, |
3882 | Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> { |
3883 | friend class ASTContext; // ASTContext creates these. |
3884 | friend TrailingObjects; |
3885 | |
3886 | // FunctionProtoType is followed by several trailing objects, some of |
3887 | // which optional. They are in order: |
3888 | // |
3889 | // * An array of getNumParams() QualType holding the parameter types. |
3890 | // Always present. Note that for the vast majority of FunctionProtoType, |
3891 | // these will be the only trailing objects. |
3892 | // |
3893 | // * Optionally if the function is variadic, the SourceLocation of the |
3894 | // ellipsis. |
3895 | // |
3896 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3897 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3898 | // a single FunctionTypeExtraBitfields. Present if and only if |
3899 | // hasExtraBitfields() is true. |
3900 | // |
3901 | // * Optionally exactly one of: |
3902 | // * an array of getNumExceptions() ExceptionType, |
3903 | // * a single Expr *, |
3904 | // * a pair of FunctionDecl *, |
3905 | // * a single FunctionDecl * |
3906 | // used to store information about the various types of exception |
3907 | // specification. See getExceptionSpecSize for the details. |
3908 | // |
3909 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3910 | // an ExtParameterInfo for each of the parameters. Present if and |
3911 | // only if hasExtParameterInfos() is true. |
3912 | // |
3913 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3914 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3915 | // if hasExtQualifiers() is true. |
3916 | // |
3917 | // The optional FunctionTypeExtraBitfields has to be before the data |
3918 | // related to the exception specification since it contains the number |
3919 | // of exception types. |
3920 | // |
3921 | // We put the ExtParameterInfos last. If all were equal, it would make |
3922 | // more sense to put these before the exception specification, because |
3923 | // it's much easier to skip past them compared to the elaborate switch |
3924 | // required to skip the exception specification. However, all is not |
3925 | // equal; ExtParameterInfos are used to model very uncommon features, |
3926 | // and it's better not to burden the more common paths. |
3927 | |
3928 | public: |
3929 | /// Holds information about the various types of exception specification. |
3930 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3931 | /// used to group together the various bits of information about the |
3932 | /// exception specification. |
3933 | struct ExceptionSpecInfo { |
3934 | /// The kind of exception specification this is. |
3935 | ExceptionSpecificationType Type = EST_None; |
3936 | |
3937 | /// Explicitly-specified list of exception types. |
3938 | ArrayRef<QualType> Exceptions; |
3939 | |
3940 | /// Noexcept expression, if this is a computed noexcept specification. |
3941 | Expr *NoexceptExpr = nullptr; |
3942 | |
3943 | /// The function whose exception specification this is, for |
3944 | /// EST_Unevaluated and EST_Uninstantiated. |
3945 | FunctionDecl *SourceDecl = nullptr; |
3946 | |
3947 | /// The function template whose exception specification this is instantiated |
3948 | /// from, for EST_Uninstantiated. |
3949 | FunctionDecl *SourceTemplate = nullptr; |
3950 | |
3951 | ExceptionSpecInfo() = default; |
3952 | |
3953 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3954 | }; |
3955 | |
3956 | /// Extra information about a function prototype. ExtProtoInfo is not |
3957 | /// stored as such in FunctionProtoType but is used to group together |
3958 | /// the various bits of extra information about a function prototype. |
3959 | struct ExtProtoInfo { |
3960 | FunctionType::ExtInfo ExtInfo; |
3961 | bool Variadic : 1; |
3962 | bool HasTrailingReturn : 1; |
3963 | Qualifiers TypeQuals; |
3964 | RefQualifierKind RefQualifier = RQ_None; |
3965 | ExceptionSpecInfo ExceptionSpec; |
3966 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3967 | SourceLocation EllipsisLoc; |
3968 | |
3969 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3970 | |
3971 | ExtProtoInfo(CallingConv CC) |
3972 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3973 | |
3974 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3975 | ExtProtoInfo Result(*this); |
3976 | Result.ExceptionSpec = ESI; |
3977 | return Result; |
3978 | } |
3979 | }; |
3980 | |
3981 | private: |
3982 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3983 | return getNumParams(); |
3984 | } |
3985 | |
3986 | unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { |
3987 | return isVariadic(); |
3988 | } |
3989 | |
3990 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
3991 | return hasExtraBitfields(); |
3992 | } |
3993 | |
3994 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
3995 | return getExceptionSpecSize().NumExceptionType; |
3996 | } |
3997 | |
3998 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
3999 | return getExceptionSpecSize().NumExprPtr; |
4000 | } |
4001 | |
4002 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
4003 | return getExceptionSpecSize().NumFunctionDeclPtr; |
4004 | } |
4005 | |
4006 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
4007 | return hasExtParameterInfos() ? getNumParams() : 0; |
4008 | } |
4009 | |
4010 | /// Determine whether there are any argument types that |
4011 | /// contain an unexpanded parameter pack. |
4012 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
4013 | unsigned numArgs) { |
4014 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
4015 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
4016 | return true; |
4017 | |
4018 | return false; |
4019 | } |
4020 | |
4021 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
4022 | QualType canonical, const ExtProtoInfo &epi); |
4023 | |
4024 | /// This struct is returned by getExceptionSpecSize and is used to |
4025 | /// translate an ExceptionSpecificationType to the number and kind |
4026 | /// of trailing objects related to the exception specification. |
4027 | struct ExceptionSpecSizeHolder { |
4028 | unsigned NumExceptionType; |
4029 | unsigned NumExprPtr; |
4030 | unsigned NumFunctionDeclPtr; |
4031 | }; |
4032 | |
4033 | /// Return the number and kind of trailing objects |
4034 | /// related to the exception specification. |
4035 | static ExceptionSpecSizeHolder |
4036 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
4037 | switch (EST) { |
4038 | case EST_None: |
4039 | case EST_DynamicNone: |
4040 | case EST_MSAny: |
4041 | case EST_BasicNoexcept: |
4042 | case EST_Unparsed: |
4043 | case EST_NoThrow: |
4044 | return {0, 0, 0}; |
4045 | |
4046 | case EST_Dynamic: |
4047 | return {NumExceptions, 0, 0}; |
4048 | |
4049 | case EST_DependentNoexcept: |
4050 | case EST_NoexceptFalse: |
4051 | case EST_NoexceptTrue: |
4052 | return {0, 1, 0}; |
4053 | |
4054 | case EST_Uninstantiated: |
4055 | return {0, 0, 2}; |
4056 | |
4057 | case EST_Unevaluated: |
4058 | return {0, 0, 1}; |
4059 | } |
4060 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4060); |
4061 | } |
4062 | |
4063 | /// Return the number and kind of trailing objects |
4064 | /// related to the exception specification. |
4065 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
4066 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
4067 | } |
4068 | |
4069 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4070 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
4071 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
4072 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
4073 | return EST == EST_Dynamic; |
4074 | } |
4075 | |
4076 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4077 | bool hasExtraBitfields() const { |
4078 | return hasExtraBitfields(getExceptionSpecType()); |
4079 | } |
4080 | |
4081 | bool hasExtQualifiers() const { |
4082 | return FunctionTypeBits.HasExtQuals; |
4083 | } |
4084 | |
4085 | public: |
4086 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
4087 | |
4088 | QualType getParamType(unsigned i) const { |
4089 | assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index") ? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4089, __PRETTY_FUNCTION__)); |
4090 | return param_type_begin()[i]; |
4091 | } |
4092 | |
4093 | ArrayRef<QualType> getParamTypes() const { |
4094 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
4095 | } |
4096 | |
4097 | ExtProtoInfo getExtProtoInfo() const { |
4098 | ExtProtoInfo EPI; |
4099 | EPI.ExtInfo = getExtInfo(); |
4100 | EPI.Variadic = isVariadic(); |
4101 | EPI.EllipsisLoc = getEllipsisLoc(); |
4102 | EPI.HasTrailingReturn = hasTrailingReturn(); |
4103 | EPI.ExceptionSpec = getExceptionSpecInfo(); |
4104 | EPI.TypeQuals = getMethodQuals(); |
4105 | EPI.RefQualifier = getRefQualifier(); |
4106 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
4107 | return EPI; |
4108 | } |
4109 | |
4110 | /// Get the kind of exception specification on this function. |
4111 | ExceptionSpecificationType getExceptionSpecType() const { |
4112 | return static_cast<ExceptionSpecificationType>( |
4113 | FunctionTypeBits.ExceptionSpecType); |
4114 | } |
4115 | |
4116 | /// Return whether this function has any kind of exception spec. |
4117 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
4118 | |
4119 | /// Return whether this function has a dynamic (throw) exception spec. |
4120 | bool hasDynamicExceptionSpec() const { |
4121 | return isDynamicExceptionSpec(getExceptionSpecType()); |
4122 | } |
4123 | |
4124 | /// Return whether this function has a noexcept exception spec. |
4125 | bool hasNoexceptExceptionSpec() const { |
4126 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
4127 | } |
4128 | |
4129 | /// Return whether this function has a dependent exception spec. |
4130 | bool hasDependentExceptionSpec() const; |
4131 | |
4132 | /// Return whether this function has an instantiation-dependent exception |
4133 | /// spec. |
4134 | bool hasInstantiationDependentExceptionSpec() const; |
4135 | |
4136 | /// Return all the available information about this type's exception spec. |
4137 | ExceptionSpecInfo getExceptionSpecInfo() const { |
4138 | ExceptionSpecInfo Result; |
4139 | Result.Type = getExceptionSpecType(); |
4140 | if (Result.Type == EST_Dynamic) { |
4141 | Result.Exceptions = exceptions(); |
4142 | } else if (isComputedNoexcept(Result.Type)) { |
4143 | Result.NoexceptExpr = getNoexceptExpr(); |
4144 | } else if (Result.Type == EST_Uninstantiated) { |
4145 | Result.SourceDecl = getExceptionSpecDecl(); |
4146 | Result.SourceTemplate = getExceptionSpecTemplate(); |
4147 | } else if (Result.Type == EST_Unevaluated) { |
4148 | Result.SourceDecl = getExceptionSpecDecl(); |
4149 | } |
4150 | return Result; |
4151 | } |
4152 | |
4153 | /// Return the number of types in the exception specification. |
4154 | unsigned getNumExceptions() const { |
4155 | return getExceptionSpecType() == EST_Dynamic |
4156 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
4157 | ->NumExceptionType |
4158 | : 0; |
4159 | } |
4160 | |
4161 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
4162 | QualType getExceptionType(unsigned i) const { |
4163 | assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4163, __PRETTY_FUNCTION__)); |
4164 | return exception_begin()[i]; |
4165 | } |
4166 | |
4167 | /// Return the expression inside noexcept(expression), or a null pointer |
4168 | /// if there is none (because the exception spec is not of this form). |
4169 | Expr *getNoexceptExpr() const { |
4170 | if (!isComputedNoexcept(getExceptionSpecType())) |
4171 | return nullptr; |
4172 | return *getTrailingObjects<Expr *>(); |
4173 | } |
4174 | |
4175 | /// If this function type has an exception specification which hasn't |
4176 | /// been determined yet (either because it has not been evaluated or because |
4177 | /// it has not been instantiated), this is the function whose exception |
4178 | /// specification is represented by this type. |
4179 | FunctionDecl *getExceptionSpecDecl() const { |
4180 | if (getExceptionSpecType() != EST_Uninstantiated && |
4181 | getExceptionSpecType() != EST_Unevaluated) |
4182 | return nullptr; |
4183 | return getTrailingObjects<FunctionDecl *>()[0]; |
4184 | } |
4185 | |
4186 | /// If this function type has an uninstantiated exception |
4187 | /// specification, this is the function whose exception specification |
4188 | /// should be instantiated to find the exception specification for |
4189 | /// this type. |
4190 | FunctionDecl *getExceptionSpecTemplate() const { |
4191 | if (getExceptionSpecType() != EST_Uninstantiated) |
4192 | return nullptr; |
4193 | return getTrailingObjects<FunctionDecl *>()[1]; |
4194 | } |
4195 | |
4196 | /// Determine whether this function type has a non-throwing exception |
4197 | /// specification. |
4198 | CanThrowResult canThrow() const; |
4199 | |
4200 | /// Determine whether this function type has a non-throwing exception |
4201 | /// specification. If this depends on template arguments, returns |
4202 | /// \c ResultIfDependent. |
4203 | bool isNothrow(bool ResultIfDependent = false) const { |
4204 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4205 | } |
4206 | |
4207 | /// Whether this function prototype is variadic. |
4208 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4209 | |
4210 | SourceLocation getEllipsisLoc() const { |
4211 | return isVariadic() ? *getTrailingObjects<SourceLocation>() |
4212 | : SourceLocation(); |
4213 | } |
4214 | |
4215 | /// Determines whether this function prototype contains a |
4216 | /// parameter pack at the end. |
4217 | /// |
4218 | /// A function template whose last parameter is a parameter pack can be |
4219 | /// called with an arbitrary number of arguments, much like a variadic |
4220 | /// function. |
4221 | bool isTemplateVariadic() const; |
4222 | |
4223 | /// Whether this function prototype has a trailing return type. |
4224 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4225 | |
4226 | Qualifiers getMethodQuals() const { |
4227 | if (hasExtQualifiers()) |
4228 | return *getTrailingObjects<Qualifiers>(); |
4229 | else |
4230 | return getFastTypeQuals(); |
4231 | } |
4232 | |
4233 | /// Retrieve the ref-qualifier associated with this function type. |
4234 | RefQualifierKind getRefQualifier() const { |
4235 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4236 | } |
4237 | |
4238 | using param_type_iterator = const QualType *; |
4239 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4240 | |
4241 | param_type_range param_types() const { |
4242 | return param_type_range(param_type_begin(), param_type_end()); |
4243 | } |
4244 | |
4245 | param_type_iterator param_type_begin() const { |
4246 | return getTrailingObjects<QualType>(); |
4247 | } |
4248 | |
4249 | param_type_iterator param_type_end() const { |
4250 | return param_type_begin() + getNumParams(); |
4251 | } |
4252 | |
4253 | using exception_iterator = const QualType *; |
4254 | |
4255 | ArrayRef<QualType> exceptions() const { |
4256 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4257 | } |
4258 | |
4259 | exception_iterator exception_begin() const { |
4260 | return reinterpret_cast<exception_iterator>( |
4261 | getTrailingObjects<ExceptionType>()); |
4262 | } |
4263 | |
4264 | exception_iterator exception_end() const { |
4265 | return exception_begin() + getNumExceptions(); |
4266 | } |
4267 | |
4268 | /// Is there any interesting extra information for any of the parameters |
4269 | /// of this function type? |
4270 | bool hasExtParameterInfos() const { |
4271 | return FunctionTypeBits.HasExtParameterInfos; |
4272 | } |
4273 | |
4274 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4275 | assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4275, __PRETTY_FUNCTION__)); |
4276 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4277 | getNumParams()); |
4278 | } |
4279 | |
4280 | /// Return a pointer to the beginning of the array of extra parameter |
4281 | /// information, if present, or else null if none of the parameters |
4282 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4283 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4284 | if (!hasExtParameterInfos()) |
4285 | return nullptr; |
4286 | return getTrailingObjects<ExtParameterInfo>(); |
4287 | } |
4288 | |
4289 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4290 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4290, __PRETTY_FUNCTION__)); |
4291 | if (hasExtParameterInfos()) |
4292 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4293 | return ExtParameterInfo(); |
4294 | } |
4295 | |
4296 | ParameterABI getParameterABI(unsigned I) const { |
4297 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4297, __PRETTY_FUNCTION__)); |
4298 | if (hasExtParameterInfos()) |
4299 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4300 | return ParameterABI::Ordinary; |
4301 | } |
4302 | |
4303 | bool isParamConsumed(unsigned I) const { |
4304 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4304, __PRETTY_FUNCTION__)); |
4305 | if (hasExtParameterInfos()) |
4306 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4307 | return false; |
4308 | } |
4309 | |
4310 | bool isSugared() const { return false; } |
4311 | QualType desugar() const { return QualType(this, 0); } |
4312 | |
4313 | void printExceptionSpecification(raw_ostream &OS, |
4314 | const PrintingPolicy &Policy) const; |
4315 | |
4316 | static bool classof(const Type *T) { |
4317 | return T->getTypeClass() == FunctionProto; |
4318 | } |
4319 | |
4320 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
4321 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
4322 | param_type_iterator ArgTys, unsigned NumArgs, |
4323 | const ExtProtoInfo &EPI, const ASTContext &Context, |
4324 | bool Canonical); |
4325 | }; |
4326 | |
4327 | /// Represents the dependent type named by a dependently-scoped |
4328 | /// typename using declaration, e.g. |
4329 | /// using typename Base<T>::foo; |
4330 | /// |
4331 | /// Template instantiation turns these into the underlying type. |
4332 | class UnresolvedUsingType : public Type { |
4333 | friend class ASTContext; // ASTContext creates these. |
4334 | |
4335 | UnresolvedUsingTypenameDecl *Decl; |
4336 | |
4337 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
4338 | : Type(UnresolvedUsing, QualType(), |
4339 | TypeDependence::DependentInstantiation), |
4340 | Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {} |
4341 | |
4342 | public: |
4343 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
4344 | |
4345 | bool isSugared() const { return false; } |
4346 | QualType desugar() const { return QualType(this, 0); } |
4347 | |
4348 | static bool classof(const Type *T) { |
4349 | return T->getTypeClass() == UnresolvedUsing; |
4350 | } |
4351 | |
4352 | void Profile(llvm::FoldingSetNodeID &ID) { |
4353 | return Profile(ID, Decl); |
4354 | } |
4355 | |
4356 | static void Profile(llvm::FoldingSetNodeID &ID, |
4357 | UnresolvedUsingTypenameDecl *D) { |
4358 | ID.AddPointer(D); |
4359 | } |
4360 | }; |
4361 | |
4362 | class TypedefType : public Type { |
4363 | TypedefNameDecl *Decl; |
4364 | |
4365 | protected: |
4366 | friend class ASTContext; // ASTContext creates these. |
4367 | |
4368 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can); |
4369 | |
4370 | public: |
4371 | TypedefNameDecl *getDecl() const { return Decl; } |
4372 | |
4373 | bool isSugared() const { return true; } |
4374 | QualType desugar() const; |
4375 | |
4376 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
4377 | }; |
4378 | |
4379 | /// Sugar type that represents a type that was qualified by a qualifier written |
4380 | /// as a macro invocation. |
4381 | class MacroQualifiedType : public Type { |
4382 | friend class ASTContext; // ASTContext creates these. |
4383 | |
4384 | QualType UnderlyingTy; |
4385 | const IdentifierInfo *MacroII; |
4386 | |
4387 | MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, |
4388 | const IdentifierInfo *MacroII) |
4389 | : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()), |
4390 | UnderlyingTy(UnderlyingTy), MacroII(MacroII) { |
4391 | assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4392, __PRETTY_FUNCTION__)) |
4392 | "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4392, __PRETTY_FUNCTION__)); |
4393 | } |
4394 | |
4395 | public: |
4396 | const IdentifierInfo *getMacroIdentifier() const { return MacroII; } |
4397 | QualType getUnderlyingType() const { return UnderlyingTy; } |
4398 | |
4399 | /// Return this attributed type's modified type with no qualifiers attached to |
4400 | /// it. |
4401 | QualType getModifiedType() const; |
4402 | |
4403 | bool isSugared() const { return true; } |
4404 | QualType desugar() const; |
4405 | |
4406 | static bool classof(const Type *T) { |
4407 | return T->getTypeClass() == MacroQualified; |
4408 | } |
4409 | }; |
4410 | |
4411 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
4412 | class TypeOfExprType : public Type { |
4413 | Expr *TOExpr; |
4414 | |
4415 | protected: |
4416 | friend class ASTContext; // ASTContext creates these. |
4417 | |
4418 | TypeOfExprType(Expr *E, QualType can = QualType()); |
4419 | |
4420 | public: |
4421 | Expr *getUnderlyingExpr() const { return TOExpr; } |
4422 | |
4423 | /// Remove a single level of sugar. |
4424 | QualType desugar() const; |
4425 | |
4426 | /// Returns whether this type directly provides sugar. |
4427 | bool isSugared() const; |
4428 | |
4429 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
4430 | }; |
4431 | |
4432 | /// Internal representation of canonical, dependent |
4433 | /// `typeof(expr)` types. |
4434 | /// |
4435 | /// This class is used internally by the ASTContext to manage |
4436 | /// canonical, dependent types, only. Clients will only see instances |
4437 | /// of this class via TypeOfExprType nodes. |
4438 | class DependentTypeOfExprType |
4439 | : public TypeOfExprType, public llvm::FoldingSetNode { |
4440 | const ASTContext &Context; |
4441 | |
4442 | public: |
4443 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
4444 | : TypeOfExprType(E), Context(Context) {} |
4445 | |
4446 | void Profile(llvm::FoldingSetNodeID &ID) { |
4447 | Profile(ID, Context, getUnderlyingExpr()); |
4448 | } |
4449 | |
4450 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4451 | Expr *E); |
4452 | }; |
4453 | |
4454 | /// Represents `typeof(type)`, a GCC extension. |
4455 | class TypeOfType : public Type { |
4456 | friend class ASTContext; // ASTContext creates these. |
4457 | |
4458 | QualType TOType; |
4459 | |
4460 | TypeOfType(QualType T, QualType can) |
4461 | : Type(TypeOf, can, T->getDependence()), TOType(T) { |
4462 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4462, __PRETTY_FUNCTION__)); |
4463 | } |
4464 | |
4465 | public: |
4466 | QualType getUnderlyingType() const { return TOType; } |
4467 | |
4468 | /// Remove a single level of sugar. |
4469 | QualType desugar() const { return getUnderlyingType(); } |
4470 | |
4471 | /// Returns whether this type directly provides sugar. |
4472 | bool isSugared() const { return true; } |
4473 | |
4474 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
4475 | }; |
4476 | |
4477 | /// Represents the type `decltype(expr)` (C++11). |
4478 | class DecltypeType : public Type { |
4479 | Expr *E; |
4480 | QualType UnderlyingType; |
4481 | |
4482 | protected: |
4483 | friend class ASTContext; // ASTContext creates these. |
4484 | |
4485 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
4486 | |
4487 | public: |
4488 | Expr *getUnderlyingExpr() const { return E; } |
4489 | QualType getUnderlyingType() const { return UnderlyingType; } |
4490 | |
4491 | /// Remove a single level of sugar. |
4492 | QualType desugar() const; |
4493 | |
4494 | /// Returns whether this type directly provides sugar. |
4495 | bool isSugared() const; |
4496 | |
4497 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
4498 | }; |
4499 | |
4500 | /// Internal representation of canonical, dependent |
4501 | /// decltype(expr) types. |
4502 | /// |
4503 | /// This class is used internally by the ASTContext to manage |
4504 | /// canonical, dependent types, only. Clients will only see instances |
4505 | /// of this class via DecltypeType nodes. |
4506 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
4507 | const ASTContext &Context; |
4508 | |
4509 | public: |
4510 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
4511 | |
4512 | void Profile(llvm::FoldingSetNodeID &ID) { |
4513 | Profile(ID, Context, getUnderlyingExpr()); |
4514 | } |
4515 | |
4516 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4517 | Expr *E); |
4518 | }; |
4519 | |
4520 | /// A unary type transform, which is a type constructed from another. |
4521 | class UnaryTransformType : public Type { |
4522 | public: |
4523 | enum UTTKind { |
4524 | EnumUnderlyingType |
4525 | }; |
4526 | |
4527 | private: |
4528 | /// The untransformed type. |
4529 | QualType BaseType; |
4530 | |
4531 | /// The transformed type if not dependent, otherwise the same as BaseType. |
4532 | QualType UnderlyingType; |
4533 | |
4534 | UTTKind UKind; |
4535 | |
4536 | protected: |
4537 | friend class ASTContext; |
4538 | |
4539 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
4540 | QualType CanonicalTy); |
4541 | |
4542 | public: |
4543 | bool isSugared() const { return !isDependentType(); } |
4544 | QualType desugar() const { return UnderlyingType; } |
4545 | |
4546 | QualType getUnderlyingType() const { return UnderlyingType; } |
4547 | QualType getBaseType() const { return BaseType; } |
4548 | |
4549 | UTTKind getUTTKind() const { return UKind; } |
4550 | |
4551 | static bool classof(const Type *T) { |
4552 | return T->getTypeClass() == UnaryTransform; |
4553 | } |
4554 | }; |
4555 | |
4556 | /// Internal representation of canonical, dependent |
4557 | /// __underlying_type(type) types. |
4558 | /// |
4559 | /// This class is used internally by the ASTContext to manage |
4560 | /// canonical, dependent types, only. Clients will only see instances |
4561 | /// of this class via UnaryTransformType nodes. |
4562 | class DependentUnaryTransformType : public UnaryTransformType, |
4563 | public llvm::FoldingSetNode { |
4564 | public: |
4565 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
4566 | UTTKind UKind); |
4567 | |
4568 | void Profile(llvm::FoldingSetNodeID &ID) { |
4569 | Profile(ID, getBaseType(), getUTTKind()); |
4570 | } |
4571 | |
4572 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
4573 | UTTKind UKind) { |
4574 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
4575 | ID.AddInteger((unsigned)UKind); |
4576 | } |
4577 | }; |
4578 | |
4579 | class TagType : public Type { |
4580 | friend class ASTReader; |
4581 | template <class T> friend class serialization::AbstractTypeReader; |
4582 | |
4583 | /// Stores the TagDecl associated with this type. The decl may point to any |
4584 | /// TagDecl that declares the entity. |
4585 | TagDecl *decl; |
4586 | |
4587 | protected: |
4588 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
4589 | |
4590 | public: |
4591 | TagDecl *getDecl() const; |
4592 | |
4593 | /// Determines whether this type is in the process of being defined. |
4594 | bool isBeingDefined() const; |
4595 | |
4596 | static bool classof(const Type *T) { |
4597 | return T->getTypeClass() == Enum || T->getTypeClass() == Record; |
4598 | } |
4599 | }; |
4600 | |
4601 | /// A helper class that allows the use of isa/cast/dyncast |
4602 | /// to detect TagType objects of structs/unions/classes. |
4603 | class RecordType : public TagType { |
4604 | protected: |
4605 | friend class ASTContext; // ASTContext creates these. |
4606 | |
4607 | explicit RecordType(const RecordDecl *D) |
4608 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4609 | explicit RecordType(TypeClass TC, RecordDecl *D) |
4610 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4611 | |
4612 | public: |
4613 | RecordDecl *getDecl() const { |
4614 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
4615 | } |
4616 | |
4617 | /// Recursively check all fields in the record for const-ness. If any field |
4618 | /// is declared const, return true. Otherwise, return false. |
4619 | bool hasConstFields() const; |
4620 | |
4621 | bool isSugared() const { return false; } |
4622 | QualType desugar() const { return QualType(this, 0); } |
4623 | |
4624 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4625 | }; |
4626 | |
4627 | /// A helper class that allows the use of isa/cast/dyncast |
4628 | /// to detect TagType objects of enums. |
4629 | class EnumType : public TagType { |
4630 | friend class ASTContext; // ASTContext creates these. |
4631 | |
4632 | explicit EnumType(const EnumDecl *D) |
4633 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4634 | |
4635 | public: |
4636 | EnumDecl *getDecl() const { |
4637 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4638 | } |
4639 | |
4640 | bool isSugared() const { return false; } |
4641 | QualType desugar() const { return QualType(this, 0); } |
4642 | |
4643 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4644 | }; |
4645 | |
4646 | /// An attributed type is a type to which a type attribute has been applied. |
4647 | /// |
4648 | /// The "modified type" is the fully-sugared type to which the attributed |
4649 | /// type was applied; generally it is not canonically equivalent to the |
4650 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4651 | /// which the type is canonically equivalent to. |
4652 | /// |
4653 | /// For example, in the following attributed type: |
4654 | /// int32_t __attribute__((vector_size(16))) |
4655 | /// - the modified type is the TypedefType for int32_t |
4656 | /// - the equivalent type is VectorType(16, int32_t) |
4657 | /// - the canonical type is VectorType(16, int) |
4658 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4659 | public: |
4660 | using Kind = attr::Kind; |
4661 | |
4662 | private: |
4663 | friend class ASTContext; // ASTContext creates these |
4664 | |
4665 | QualType ModifiedType; |
4666 | QualType EquivalentType; |
4667 | |
4668 | AttributedType(QualType canon, attr::Kind attrKind, QualType modified, |
4669 | QualType equivalent) |
4670 | : Type(Attributed, canon, equivalent->getDependence()), |
4671 | ModifiedType(modified), EquivalentType(equivalent) { |
4672 | AttributedTypeBits.AttrKind = attrKind; |
4673 | } |
4674 | |
4675 | public: |
4676 | Kind getAttrKind() const { |
4677 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4678 | } |
4679 | |
4680 | QualType getModifiedType() const { return ModifiedType; } |
4681 | QualType getEquivalentType() const { return EquivalentType; } |
4682 | |
4683 | bool isSugared() const { return true; } |
4684 | QualType desugar() const { return getEquivalentType(); } |
4685 | |
4686 | /// Does this attribute behave like a type qualifier? |
4687 | /// |
4688 | /// A type qualifier adjusts a type to provide specialized rules for |
4689 | /// a specific object, like the standard const and volatile qualifiers. |
4690 | /// This includes attributes controlling things like nullability, |
4691 | /// address spaces, and ARC ownership. The value of the object is still |
4692 | /// largely described by the modified type. |
4693 | /// |
4694 | /// In contrast, many type attributes "rewrite" their modified type to |
4695 | /// produce a fundamentally different type, not necessarily related in any |
4696 | /// formalizable way to the original type. For example, calling convention |
4697 | /// and vector attributes are not simple type qualifiers. |
4698 | /// |
4699 | /// Type qualifiers are often, but not always, reflected in the canonical |
4700 | /// type. |
4701 | bool isQualifier() const; |
4702 | |
4703 | bool isMSTypeSpec() const; |
4704 | |
4705 | bool isCallingConv() const; |
4706 | |
4707 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4708 | |
4709 | /// Retrieve the attribute kind corresponding to the given |
4710 | /// nullability kind. |
4711 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4712 | switch (kind) { |
4713 | case NullabilityKind::NonNull: |
4714 | return attr::TypeNonNull; |
4715 | |
4716 | case NullabilityKind::Nullable: |
4717 | return attr::TypeNullable; |
4718 | |
4719 | case NullabilityKind::Unspecified: |
4720 | return attr::TypeNullUnspecified; |
4721 | } |
4722 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 4722); |
4723 | } |
4724 | |
4725 | /// Strip off the top-level nullability annotation on the given |
4726 | /// type, if it's there. |
4727 | /// |
4728 | /// \param T The type to strip. If the type is exactly an |
4729 | /// AttributedType specifying nullability (without looking through |
4730 | /// type sugar), the nullability is returned and this type changed |
4731 | /// to the underlying modified type. |
4732 | /// |
4733 | /// \returns the top-level nullability, if present. |
4734 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4735 | |
4736 | void Profile(llvm::FoldingSetNodeID &ID) { |
4737 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4738 | } |
4739 | |
4740 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4741 | QualType modified, QualType equivalent) { |
4742 | ID.AddInteger(attrKind); |
4743 | ID.AddPointer(modified.getAsOpaquePtr()); |
4744 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4745 | } |
4746 | |
4747 | static bool classof(const Type *T) { |
4748 | return T->getTypeClass() == Attributed; |
4749 | } |
4750 | }; |
4751 | |
4752 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4753 | friend class ASTContext; // ASTContext creates these |
4754 | |
4755 | // Helper data collector for canonical types. |
4756 | struct CanonicalTTPTInfo { |
4757 | unsigned Depth : 15; |
4758 | unsigned ParameterPack : 1; |
4759 | unsigned Index : 16; |
4760 | }; |
4761 | |
4762 | union { |
4763 | // Info for the canonical type. |
4764 | CanonicalTTPTInfo CanTTPTInfo; |
4765 | |
4766 | // Info for the non-canonical type. |
4767 | TemplateTypeParmDecl *TTPDecl; |
4768 | }; |
4769 | |
4770 | /// Build a non-canonical type. |
4771 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4772 | : Type(TemplateTypeParm, Canon, |
4773 | TypeDependence::DependentInstantiation | |
4774 | (Canon->getDependence() & TypeDependence::UnexpandedPack)), |
4775 | TTPDecl(TTPDecl) {} |
4776 | |
4777 | /// Build the canonical type. |
4778 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4779 | : Type(TemplateTypeParm, QualType(this, 0), |
4780 | TypeDependence::DependentInstantiation | |
4781 | (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) { |
4782 | CanTTPTInfo.Depth = D; |
4783 | CanTTPTInfo.Index = I; |
4784 | CanTTPTInfo.ParameterPack = PP; |
4785 | } |
4786 | |
4787 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4788 | QualType Can = getCanonicalTypeInternal(); |
4789 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4790 | } |
4791 | |
4792 | public: |
4793 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4794 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4795 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4796 | |
4797 | TemplateTypeParmDecl *getDecl() const { |
4798 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4799 | } |
4800 | |
4801 | IdentifierInfo *getIdentifier() const; |
4802 | |
4803 | bool isSugared() const { return false; } |
4804 | QualType desugar() const { return QualType(this, 0); } |
4805 | |
4806 | void Profile(llvm::FoldingSetNodeID &ID) { |
4807 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4808 | } |
4809 | |
4810 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4811 | unsigned Index, bool ParameterPack, |
4812 | TemplateTypeParmDecl *TTPDecl) { |
4813 | ID.AddInteger(Depth); |
4814 | ID.AddInteger(Index); |
4815 | ID.AddBoolean(ParameterPack); |
4816 | ID.AddPointer(TTPDecl); |
4817 | } |
4818 | |
4819 | static bool classof(const Type *T) { |
4820 | return T->getTypeClass() == TemplateTypeParm; |
4821 | } |
4822 | }; |
4823 | |
4824 | /// Represents the result of substituting a type for a template |
4825 | /// type parameter. |
4826 | /// |
4827 | /// Within an instantiated template, all template type parameters have |
4828 | /// been replaced with these. They are used solely to record that a |
4829 | /// type was originally written as a template type parameter; |
4830 | /// therefore they are never canonical. |
4831 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4832 | friend class ASTContext; |
4833 | |
4834 | // The original type parameter. |
4835 | const TemplateTypeParmType *Replaced; |
4836 | |
4837 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4838 | : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()), |
4839 | Replaced(Param) {} |
4840 | |
4841 | public: |
4842 | /// Gets the template parameter that was substituted for. |
4843 | const TemplateTypeParmType *getReplacedParameter() const { |
4844 | return Replaced; |
4845 | } |
4846 | |
4847 | /// Gets the type that was substituted for the template |
4848 | /// parameter. |
4849 | QualType getReplacementType() const { |
4850 | return getCanonicalTypeInternal(); |
4851 | } |
4852 | |
4853 | bool isSugared() const { return true; } |
4854 | QualType desugar() const { return getReplacementType(); } |
4855 | |
4856 | void Profile(llvm::FoldingSetNodeID &ID) { |
4857 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4858 | } |
4859 | |
4860 | static void Profile(llvm::FoldingSetNodeID &ID, |
4861 | const TemplateTypeParmType *Replaced, |
4862 | QualType Replacement) { |
4863 | ID.AddPointer(Replaced); |
4864 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4865 | } |
4866 | |
4867 | static bool classof(const Type *T) { |
4868 | return T->getTypeClass() == SubstTemplateTypeParm; |
4869 | } |
4870 | }; |
4871 | |
4872 | /// Represents the result of substituting a set of types for a template |
4873 | /// type parameter pack. |
4874 | /// |
4875 | /// When a pack expansion in the source code contains multiple parameter packs |
4876 | /// and those parameter packs correspond to different levels of template |
4877 | /// parameter lists, this type node is used to represent a template type |
4878 | /// parameter pack from an outer level, which has already had its argument pack |
4879 | /// substituted but that still lives within a pack expansion that itself |
4880 | /// could not be instantiated. When actually performing a substitution into |
4881 | /// that pack expansion (e.g., when all template parameters have corresponding |
4882 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4883 | /// at the current pack substitution index. |
4884 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4885 | friend class ASTContext; |
4886 | |
4887 | /// The original type parameter. |
4888 | const TemplateTypeParmType *Replaced; |
4889 | |
4890 | /// A pointer to the set of template arguments that this |
4891 | /// parameter pack is instantiated with. |
4892 | const TemplateArgument *Arguments; |
4893 | |
4894 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4895 | QualType Canon, |
4896 | const TemplateArgument &ArgPack); |
4897 | |
4898 | public: |
4899 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4900 | |
4901 | /// Gets the template parameter that was substituted for. |
4902 | const TemplateTypeParmType *getReplacedParameter() const { |
4903 | return Replaced; |
4904 | } |
4905 | |
4906 | unsigned getNumArgs() const { |
4907 | return SubstTemplateTypeParmPackTypeBits.NumArgs; |
4908 | } |
4909 | |
4910 | bool isSugared() const { return false; } |
4911 | QualType desugar() const { return QualType(this, 0); } |
4912 | |
4913 | TemplateArgument getArgumentPack() const; |
4914 | |
4915 | void Profile(llvm::FoldingSetNodeID &ID); |
4916 | static void Profile(llvm::FoldingSetNodeID &ID, |
4917 | const TemplateTypeParmType *Replaced, |
4918 | const TemplateArgument &ArgPack); |
4919 | |
4920 | static bool classof(const Type *T) { |
4921 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4922 | } |
4923 | }; |
4924 | |
4925 | /// Common base class for placeholders for types that get replaced by |
4926 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4927 | /// class template types, and constrained type names. |
4928 | /// |
4929 | /// These types are usually a placeholder for a deduced type. However, before |
4930 | /// the initializer is attached, or (usually) if the initializer is |
4931 | /// type-dependent, there is no deduced type and the type is canonical. In |
4932 | /// the latter case, it is also a dependent type. |
4933 | class DeducedType : public Type { |
4934 | protected: |
4935 | DeducedType(TypeClass TC, QualType DeducedAsType, |
4936 | TypeDependence ExtraDependence) |
4937 | : Type(TC, |
4938 | // FIXME: Retain the sugared deduced type? |
4939 | DeducedAsType.isNull() ? QualType(this, 0) |
4940 | : DeducedAsType.getCanonicalType(), |
4941 | ExtraDependence | (DeducedAsType.isNull() |
4942 | ? TypeDependence::None |
4943 | : DeducedAsType->getDependence() & |
4944 | ~TypeDependence::VariablyModified)) {} |
4945 | |
4946 | public: |
4947 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4948 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4949 | |
4950 | /// Get the type deduced for this placeholder type, or null if it's |
4951 | /// either not been deduced or was deduced to a dependent type. |
4952 | QualType getDeducedType() const { |
4953 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4954 | } |
4955 | bool isDeduced() const { |
4956 | return !isCanonicalUnqualified() || isDependentType(); |
4957 | } |
4958 | |
4959 | static bool classof(const Type *T) { |
4960 | return T->getTypeClass() == Auto || |
4961 | T->getTypeClass() == DeducedTemplateSpecialization; |
4962 | } |
4963 | }; |
4964 | |
4965 | /// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained |
4966 | /// by a type-constraint. |
4967 | class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode { |
4968 | friend class ASTContext; // ASTContext creates these |
4969 | |
4970 | ConceptDecl *TypeConstraintConcept; |
4971 | |
4972 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4973 | TypeDependence ExtraDependence, ConceptDecl *CD, |
4974 | ArrayRef<TemplateArgument> TypeConstraintArgs); |
4975 | |
4976 | const TemplateArgument *getArgBuffer() const { |
4977 | return reinterpret_cast<const TemplateArgument*>(this+1); |
4978 | } |
4979 | |
4980 | TemplateArgument *getArgBuffer() { |
4981 | return reinterpret_cast<TemplateArgument*>(this+1); |
4982 | } |
4983 | |
4984 | public: |
4985 | /// Retrieve the template arguments. |
4986 | const TemplateArgument *getArgs() const { |
4987 | return getArgBuffer(); |
4988 | } |
4989 | |
4990 | /// Retrieve the number of template arguments. |
4991 | unsigned getNumArgs() const { |
4992 | return AutoTypeBits.NumArgs; |
4993 | } |
4994 | |
4995 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
4996 | |
4997 | ArrayRef<TemplateArgument> getTypeConstraintArguments() const { |
4998 | return {getArgs(), getNumArgs()}; |
4999 | } |
5000 | |
5001 | ConceptDecl *getTypeConstraintConcept() const { |
5002 | return TypeConstraintConcept; |
5003 | } |
5004 | |
5005 | bool isConstrained() const { |
5006 | return TypeConstraintConcept != nullptr; |
5007 | } |
5008 | |
5009 | bool isDecltypeAuto() const { |
5010 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
5011 | } |
5012 | |
5013 | AutoTypeKeyword getKeyword() const { |
5014 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
5015 | } |
5016 | |
5017 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5018 | Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(), |
5019 | getTypeConstraintConcept(), getTypeConstraintArguments()); |
5020 | } |
5021 | |
5022 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
5023 | QualType Deduced, AutoTypeKeyword Keyword, |
5024 | bool IsDependent, ConceptDecl *CD, |
5025 | ArrayRef<TemplateArgument> Arguments); |
5026 | |
5027 | static bool classof(const Type *T) { |
5028 | return T->getTypeClass() == Auto; |
5029 | } |
5030 | }; |
5031 | |
5032 | /// Represents a C++17 deduced template specialization type. |
5033 | class DeducedTemplateSpecializationType : public DeducedType, |
5034 | public llvm::FoldingSetNode { |
5035 | friend class ASTContext; // ASTContext creates these |
5036 | |
5037 | /// The name of the template whose arguments will be deduced. |
5038 | TemplateName Template; |
5039 | |
5040 | DeducedTemplateSpecializationType(TemplateName Template, |
5041 | QualType DeducedAsType, |
5042 | bool IsDeducedAsDependent) |
5043 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
5044 | toTypeDependence(Template.getDependence()) | |
5045 | (IsDeducedAsDependent |
5046 | ? TypeDependence::DependentInstantiation |
5047 | : TypeDependence::None)), |
5048 | Template(Template) {} |
5049 | |
5050 | public: |
5051 | /// Retrieve the name of the template that we are deducing. |
5052 | TemplateName getTemplateName() const { return Template;} |
5053 | |
5054 | void Profile(llvm::FoldingSetNodeID &ID) { |
5055 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
5056 | } |
5057 | |
5058 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
5059 | QualType Deduced, bool IsDependent) { |
5060 | Template.Profile(ID); |
5061 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
5062 | ID.AddBoolean(IsDependent); |
5063 | } |
5064 | |
5065 | static bool classof(const Type *T) { |
5066 | return T->getTypeClass() == DeducedTemplateSpecialization; |
5067 | } |
5068 | }; |
5069 | |
5070 | /// Represents a type template specialization; the template |
5071 | /// must be a class template, a type alias template, or a template |
5072 | /// template parameter. A template which cannot be resolved to one of |
5073 | /// these, e.g. because it is written with a dependent scope |
5074 | /// specifier, is instead represented as a |
5075 | /// @c DependentTemplateSpecializationType. |
5076 | /// |
5077 | /// A non-dependent template specialization type is always "sugar", |
5078 | /// typically for a \c RecordType. For example, a class template |
5079 | /// specialization type of \c vector<int> will refer to a tag type for |
5080 | /// the instantiation \c std::vector<int, std::allocator<int>> |
5081 | /// |
5082 | /// Template specializations are dependent if either the template or |
5083 | /// any of the template arguments are dependent, in which case the |
5084 | /// type may also be canonical. |
5085 | /// |
5086 | /// Instances of this type are allocated with a trailing array of |
5087 | /// TemplateArguments, followed by a QualType representing the |
5088 | /// non-canonical aliased type when the template is a type alias |
5089 | /// template. |
5090 | class alignas(8) TemplateSpecializationType |
5091 | : public Type, |
5092 | public llvm::FoldingSetNode { |
5093 | friend class ASTContext; // ASTContext creates these |
5094 | |
5095 | /// The name of the template being specialized. This is |
5096 | /// either a TemplateName::Template (in which case it is a |
5097 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
5098 | /// TypeAliasTemplateDecl*), a |
5099 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
5100 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
5101 | /// replacement must, recursively, be one of these). |
5102 | TemplateName Template; |
5103 | |
5104 | TemplateSpecializationType(TemplateName T, |
5105 | ArrayRef<TemplateArgument> Args, |
5106 | QualType Canon, |
5107 | QualType Aliased); |
5108 | |
5109 | public: |
5110 | /// Determine whether any of the given template arguments are dependent. |
5111 | static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
5112 | bool &InstantiationDependent); |
5113 | |
5114 | static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
5115 | bool &InstantiationDependent); |
5116 | |
5117 | /// True if this template specialization type matches a current |
5118 | /// instantiation in the context in which it is found. |
5119 | bool isCurrentInstantiation() const { |
5120 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
5121 | } |
5122 | |
5123 | /// Determine if this template specialization type is for a type alias |
5124 | /// template that has been substituted. |
5125 | /// |
5126 | /// Nearly every template specialization type whose template is an alias |
5127 | /// template will be substituted. However, this is not the case when |
5128 | /// the specialization contains a pack expansion but the template alias |
5129 | /// does not have a corresponding parameter pack, e.g., |
5130 | /// |
5131 | /// \code |
5132 | /// template<typename T, typename U, typename V> struct S; |
5133 | /// template<typename T, typename U> using A = S<T, int, U>; |
5134 | /// template<typename... Ts> struct X { |
5135 | /// typedef A<Ts...> type; // not a type alias |
5136 | /// }; |
5137 | /// \endcode |
5138 | bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } |
5139 | |
5140 | /// Get the aliased type, if this is a specialization of a type alias |
5141 | /// template. |
5142 | QualType getAliasedType() const { |
5143 | assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization" ) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5143, __PRETTY_FUNCTION__)); |
5144 | return *reinterpret_cast<const QualType*>(end()); |
5145 | } |
5146 | |
5147 | using iterator = const TemplateArgument *; |
5148 | |
5149 | iterator begin() const { return getArgs(); } |
5150 | iterator end() const; // defined inline in TemplateBase.h |
5151 | |
5152 | /// Retrieve the name of the template that we are specializing. |
5153 | TemplateName getTemplateName() const { return Template; } |
5154 | |
5155 | /// Retrieve the template arguments. |
5156 | const TemplateArgument *getArgs() const { |
5157 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
5158 | } |
5159 | |
5160 | /// Retrieve the number of template arguments. |
5161 | unsigned getNumArgs() const { |
5162 | return TemplateSpecializationTypeBits.NumArgs; |
5163 | } |
5164 | |
5165 | /// Retrieve a specific template argument as a type. |
5166 | /// \pre \c isArgType(Arg) |
5167 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5168 | |
5169 | ArrayRef<TemplateArgument> template_arguments() const { |
5170 | return {getArgs(), getNumArgs()}; |
5171 | } |
5172 | |
5173 | bool isSugared() const { |
5174 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
5175 | } |
5176 | |
5177 | QualType desugar() const { |
5178 | return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); |
5179 | } |
5180 | |
5181 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
5182 | Profile(ID, Template, template_arguments(), Ctx); |
5183 | if (isTypeAlias()) |
5184 | getAliasedType().Profile(ID); |
5185 | } |
5186 | |
5187 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
5188 | ArrayRef<TemplateArgument> Args, |
5189 | const ASTContext &Context); |
5190 | |
5191 | static bool classof(const Type *T) { |
5192 | return T->getTypeClass() == TemplateSpecialization; |
5193 | } |
5194 | }; |
5195 | |
5196 | /// Print a template argument list, including the '<' and '>' |
5197 | /// enclosing the template arguments. |
5198 | void printTemplateArgumentList(raw_ostream &OS, |
5199 | ArrayRef<TemplateArgument> Args, |
5200 | const PrintingPolicy &Policy, |
5201 | const TemplateParameterList *TPL = nullptr); |
5202 | |
5203 | void printTemplateArgumentList(raw_ostream &OS, |
5204 | ArrayRef<TemplateArgumentLoc> Args, |
5205 | const PrintingPolicy &Policy, |
5206 | const TemplateParameterList *TPL = nullptr); |
5207 | |
5208 | void printTemplateArgumentList(raw_ostream &OS, |
5209 | const TemplateArgumentListInfo &Args, |
5210 | const PrintingPolicy &Policy, |
5211 | const TemplateParameterList *TPL = nullptr); |
5212 | |
5213 | /// The injected class name of a C++ class template or class |
5214 | /// template partial specialization. Used to record that a type was |
5215 | /// spelled with a bare identifier rather than as a template-id; the |
5216 | /// equivalent for non-templated classes is just RecordType. |
5217 | /// |
5218 | /// Injected class name types are always dependent. Template |
5219 | /// instantiation turns these into RecordTypes. |
5220 | /// |
5221 | /// Injected class name types are always canonical. This works |
5222 | /// because it is impossible to compare an injected class name type |
5223 | /// with the corresponding non-injected template type, for the same |
5224 | /// reason that it is impossible to directly compare template |
5225 | /// parameters from different dependent contexts: injected class name |
5226 | /// types can only occur within the scope of a particular templated |
5227 | /// declaration, and within that scope every template specialization |
5228 | /// will canonicalize to the injected class name (when appropriate |
5229 | /// according to the rules of the language). |
5230 | class InjectedClassNameType : public Type { |
5231 | friend class ASTContext; // ASTContext creates these. |
5232 | friend class ASTNodeImporter; |
5233 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
5234 | // currently suitable for AST reading, too much |
5235 | // interdependencies. |
5236 | template <class T> friend class serialization::AbstractTypeReader; |
5237 | |
5238 | CXXRecordDecl *Decl; |
5239 | |
5240 | /// The template specialization which this type represents. |
5241 | /// For example, in |
5242 | /// template <class T> class A { ... }; |
5243 | /// this is A<T>, whereas in |
5244 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
5245 | /// this is A<B<X,Y> >. |
5246 | /// |
5247 | /// It is always unqualified, always a template specialization type, |
5248 | /// and always dependent. |
5249 | QualType InjectedType; |
5250 | |
5251 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
5252 | : Type(InjectedClassName, QualType(), |
5253 | TypeDependence::DependentInstantiation), |
5254 | Decl(D), InjectedType(TST) { |
5255 | assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast< void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5255, __PRETTY_FUNCTION__)); |
5256 | assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5256, __PRETTY_FUNCTION__)); |
5257 | assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5257, __PRETTY_FUNCTION__)); |
5258 | } |
5259 | |
5260 | public: |
5261 | QualType getInjectedSpecializationType() const { return InjectedType; } |
5262 | |
5263 | const TemplateSpecializationType *getInjectedTST() const { |
5264 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
5265 | } |
5266 | |
5267 | TemplateName getTemplateName() const { |
5268 | return getInjectedTST()->getTemplateName(); |
5269 | } |
5270 | |
5271 | CXXRecordDecl *getDecl() const; |
5272 | |
5273 | bool isSugared() const { return false; } |
5274 | QualType desugar() const { return QualType(this, 0); } |
5275 | |
5276 | static bool classof(const Type *T) { |
5277 | return T->getTypeClass() == InjectedClassName; |
5278 | } |
5279 | }; |
5280 | |
5281 | /// The kind of a tag type. |
5282 | enum TagTypeKind { |
5283 | /// The "struct" keyword. |
5284 | TTK_Struct, |
5285 | |
5286 | /// The "__interface" keyword. |
5287 | TTK_Interface, |
5288 | |
5289 | /// The "union" keyword. |
5290 | TTK_Union, |
5291 | |
5292 | /// The "class" keyword. |
5293 | TTK_Class, |
5294 | |
5295 | /// The "enum" keyword. |
5296 | TTK_Enum |
5297 | }; |
5298 | |
5299 | /// The elaboration keyword that precedes a qualified type name or |
5300 | /// introduces an elaborated-type-specifier. |
5301 | enum ElaboratedTypeKeyword { |
5302 | /// The "struct" keyword introduces the elaborated-type-specifier. |
5303 | ETK_Struct, |
5304 | |
5305 | /// The "__interface" keyword introduces the elaborated-type-specifier. |
5306 | ETK_Interface, |
5307 | |
5308 | /// The "union" keyword introduces the elaborated-type-specifier. |
5309 | ETK_Union, |
5310 | |
5311 | /// The "class" keyword introduces the elaborated-type-specifier. |
5312 | ETK_Class, |
5313 | |
5314 | /// The "enum" keyword introduces the elaborated-type-specifier. |
5315 | ETK_Enum, |
5316 | |
5317 | /// The "typename" keyword precedes the qualified type name, e.g., |
5318 | /// \c typename T::type. |
5319 | ETK_Typename, |
5320 | |
5321 | /// No keyword precedes the qualified type name. |
5322 | ETK_None |
5323 | }; |
5324 | |
5325 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
5326 | /// The keyword in stored in the free bits of the base class. |
5327 | /// Also provides a few static helpers for converting and printing |
5328 | /// elaborated type keyword and tag type kind enumerations. |
5329 | class TypeWithKeyword : public Type { |
5330 | protected: |
5331 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
5332 | QualType Canonical, TypeDependence Dependence) |
5333 | : Type(tc, Canonical, Dependence) { |
5334 | TypeWithKeywordBits.Keyword = Keyword; |
5335 | } |
5336 | |
5337 | public: |
5338 | ElaboratedTypeKeyword getKeyword() const { |
5339 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
5340 | } |
5341 | |
5342 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
5343 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
5344 | |
5345 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
5346 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
5347 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
5348 | |
5349 | /// Converts a TagTypeKind into an elaborated type keyword. |
5350 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
5351 | |
5352 | /// Converts an elaborated type keyword into a TagTypeKind. |
5353 | /// It is an error to provide an elaborated type keyword |
5354 | /// which *isn't* a tag kind here. |
5355 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
5356 | |
5357 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
5358 | |
5359 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
5360 | |
5361 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
5362 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
5363 | } |
5364 | |
5365 | class CannotCastToThisType {}; |
5366 | static CannotCastToThisType classof(const Type *); |
5367 | }; |
5368 | |
5369 | /// Represents a type that was referred to using an elaborated type |
5370 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
5371 | /// or both. |
5372 | /// |
5373 | /// This type is used to keep track of a type name as written in the |
5374 | /// source code, including tag keywords and any nested-name-specifiers. |
5375 | /// The type itself is always "sugar", used to express what was written |
5376 | /// in the source code but containing no additional semantic information. |
5377 | class ElaboratedType final |
5378 | : public TypeWithKeyword, |
5379 | public llvm::FoldingSetNode, |
5380 | private llvm::TrailingObjects<ElaboratedType, TagDecl *> { |
5381 | friend class ASTContext; // ASTContext creates these |
5382 | friend TrailingObjects; |
5383 | |
5384 | /// The nested name specifier containing the qualifier. |
5385 | NestedNameSpecifier *NNS; |
5386 | |
5387 | /// The type that this qualified name refers to. |
5388 | QualType NamedType; |
5389 | |
5390 | /// The (re)declaration of this tag type owned by this occurrence is stored |
5391 | /// as a trailing object if there is one. Use getOwnedTagDecl to obtain |
5392 | /// it, or obtain a null pointer if there is none. |
5393 | |
5394 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5395 | QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) |
5396 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
5397 | NamedType->getDependence()), |
5398 | NNS(NNS), NamedType(NamedType) { |
5399 | ElaboratedTypeBits.HasOwnedTagDecl = false; |
5400 | if (OwnedTagDecl) { |
5401 | ElaboratedTypeBits.HasOwnedTagDecl = true; |
5402 | *getTrailingObjects<TagDecl *>() = OwnedTagDecl; |
5403 | } |
5404 | assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5406, __PRETTY_FUNCTION__)) |
5405 | "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5406, __PRETTY_FUNCTION__)) |
5406 | "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5406, __PRETTY_FUNCTION__)); |
5407 | } |
5408 | |
5409 | public: |
5410 | /// Retrieve the qualification on this type. |
5411 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5412 | |
5413 | /// Retrieve the type named by the qualified-id. |
5414 | QualType getNamedType() const { return NamedType; } |
5415 | |
5416 | /// Remove a single level of sugar. |
5417 | QualType desugar() const { return getNamedType(); } |
5418 | |
5419 | /// Returns whether this type directly provides sugar. |
5420 | bool isSugared() const { return true; } |
5421 | |
5422 | /// Return the (re)declaration of this type owned by this occurrence of this |
5423 | /// type, or nullptr if there is none. |
5424 | TagDecl *getOwnedTagDecl() const { |
5425 | return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() |
5426 | : nullptr; |
5427 | } |
5428 | |
5429 | void Profile(llvm::FoldingSetNodeID &ID) { |
5430 | Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); |
5431 | } |
5432 | |
5433 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5434 | NestedNameSpecifier *NNS, QualType NamedType, |
5435 | TagDecl *OwnedTagDecl) { |
5436 | ID.AddInteger(Keyword); |
5437 | ID.AddPointer(NNS); |
5438 | NamedType.Profile(ID); |
5439 | ID.AddPointer(OwnedTagDecl); |
5440 | } |
5441 | |
5442 | static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } |
5443 | }; |
5444 | |
5445 | /// Represents a qualified type name for which the type name is |
5446 | /// dependent. |
5447 | /// |
5448 | /// DependentNameType represents a class of dependent types that involve a |
5449 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
5450 | /// name of a type. The DependentNameType may start with a "typename" (for a |
5451 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
5452 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
5453 | /// know that we must be referring to a type, e.g., in a base class specifier). |
5454 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
5455 | /// mode, this type is used with non-dependent names to delay name lookup until |
5456 | /// instantiation. |
5457 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
5458 | friend class ASTContext; // ASTContext creates these |
5459 | |
5460 | /// The nested name specifier containing the qualifier. |
5461 | NestedNameSpecifier *NNS; |
5462 | |
5463 | /// The type that this typename specifier refers to. |
5464 | const IdentifierInfo *Name; |
5465 | |
5466 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5467 | const IdentifierInfo *Name, QualType CanonType) |
5468 | : TypeWithKeyword(Keyword, DependentName, CanonType, |
5469 | TypeDependence::DependentInstantiation | |
5470 | toTypeDependence(NNS->getDependence())), |
5471 | NNS(NNS), Name(Name) {} |
5472 | |
5473 | public: |
5474 | /// Retrieve the qualification on this type. |
5475 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5476 | |
5477 | /// Retrieve the type named by the typename specifier as an identifier. |
5478 | /// |
5479 | /// This routine will return a non-NULL identifier pointer when the |
5480 | /// form of the original typename was terminated by an identifier, |
5481 | /// e.g., "typename T::type". |
5482 | const IdentifierInfo *getIdentifier() const { |
5483 | return Name; |
5484 | } |
5485 | |
5486 | bool isSugared() const { return false; } |
5487 | QualType desugar() const { return QualType(this, 0); } |
5488 | |
5489 | void Profile(llvm::FoldingSetNodeID &ID) { |
5490 | Profile(ID, getKeyword(), NNS, Name); |
5491 | } |
5492 | |
5493 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5494 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
5495 | ID.AddInteger(Keyword); |
5496 | ID.AddPointer(NNS); |
5497 | ID.AddPointer(Name); |
5498 | } |
5499 | |
5500 | static bool classof(const Type *T) { |
5501 | return T->getTypeClass() == DependentName; |
5502 | } |
5503 | }; |
5504 | |
5505 | /// Represents a template specialization type whose template cannot be |
5506 | /// resolved, e.g. |
5507 | /// A<T>::template B<T> |
5508 | class alignas(8) DependentTemplateSpecializationType |
5509 | : public TypeWithKeyword, |
5510 | public llvm::FoldingSetNode { |
5511 | friend class ASTContext; // ASTContext creates these |
5512 | |
5513 | /// The nested name specifier containing the qualifier. |
5514 | NestedNameSpecifier *NNS; |
5515 | |
5516 | /// The identifier of the template. |
5517 | const IdentifierInfo *Name; |
5518 | |
5519 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
5520 | NestedNameSpecifier *NNS, |
5521 | const IdentifierInfo *Name, |
5522 | ArrayRef<TemplateArgument> Args, |
5523 | QualType Canon); |
5524 | |
5525 | const TemplateArgument *getArgBuffer() const { |
5526 | return reinterpret_cast<const TemplateArgument*>(this+1); |
5527 | } |
5528 | |
5529 | TemplateArgument *getArgBuffer() { |
5530 | return reinterpret_cast<TemplateArgument*>(this+1); |
5531 | } |
5532 | |
5533 | public: |
5534 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5535 | const IdentifierInfo *getIdentifier() const { return Name; } |
5536 | |
5537 | /// Retrieve the template arguments. |
5538 | const TemplateArgument *getArgs() const { |
5539 | return getArgBuffer(); |
5540 | } |
5541 | |
5542 | /// Retrieve the number of template arguments. |
5543 | unsigned getNumArgs() const { |
5544 | return DependentTemplateSpecializationTypeBits.NumArgs; |
5545 | } |
5546 | |
5547 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5548 | |
5549 | ArrayRef<TemplateArgument> template_arguments() const { |
5550 | return {getArgs(), getNumArgs()}; |
5551 | } |
5552 | |
5553 | using iterator = const TemplateArgument *; |
5554 | |
5555 | iterator begin() const { return getArgs(); } |
5556 | iterator end() const; // inline in TemplateBase.h |
5557 | |
5558 | bool isSugared() const { return false; } |
5559 | QualType desugar() const { return QualType(this, 0); } |
5560 | |
5561 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5562 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); |
5563 | } |
5564 | |
5565 | static void Profile(llvm::FoldingSetNodeID &ID, |
5566 | const ASTContext &Context, |
5567 | ElaboratedTypeKeyword Keyword, |
5568 | NestedNameSpecifier *Qualifier, |
5569 | const IdentifierInfo *Name, |
5570 | ArrayRef<TemplateArgument> Args); |
5571 | |
5572 | static bool classof(const Type *T) { |
5573 | return T->getTypeClass() == DependentTemplateSpecialization; |
5574 | } |
5575 | }; |
5576 | |
5577 | /// Represents a pack expansion of types. |
5578 | /// |
5579 | /// Pack expansions are part of C++11 variadic templates. A pack |
5580 | /// expansion contains a pattern, which itself contains one or more |
5581 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
5582 | /// produces a series of types, each instantiated from the pattern of |
5583 | /// the expansion, where the Ith instantiation of the pattern uses the |
5584 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
5585 | /// pack expansion is considered to "expand" these unexpanded |
5586 | /// parameter packs. |
5587 | /// |
5588 | /// \code |
5589 | /// template<typename ...Types> struct tuple; |
5590 | /// |
5591 | /// template<typename ...Types> |
5592 | /// struct tuple_of_references { |
5593 | /// typedef tuple<Types&...> type; |
5594 | /// }; |
5595 | /// \endcode |
5596 | /// |
5597 | /// Here, the pack expansion \c Types&... is represented via a |
5598 | /// PackExpansionType whose pattern is Types&. |
5599 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5600 | friend class ASTContext; // ASTContext creates these |
5601 | |
5602 | /// The pattern of the pack expansion. |
5603 | QualType Pattern; |
5604 | |
5605 | PackExpansionType(QualType Pattern, QualType Canon, |
5606 | Optional<unsigned> NumExpansions) |
5607 | : Type(PackExpansion, Canon, |
5608 | (Pattern->getDependence() | TypeDependence::Dependent | |
5609 | TypeDependence::Instantiation) & |
5610 | ~TypeDependence::UnexpandedPack), |
5611 | Pattern(Pattern) { |
5612 | PackExpansionTypeBits.NumExpansions = |
5613 | NumExpansions ? *NumExpansions + 1 : 0; |
5614 | } |
5615 | |
5616 | public: |
5617 | /// Retrieve the pattern of this pack expansion, which is the |
5618 | /// type that will be repeatedly instantiated when instantiating the |
5619 | /// pack expansion itself. |
5620 | QualType getPattern() const { return Pattern; } |
5621 | |
5622 | /// Retrieve the number of expansions that this pack expansion will |
5623 | /// generate, if known. |
5624 | Optional<unsigned> getNumExpansions() const { |
5625 | if (PackExpansionTypeBits.NumExpansions) |
5626 | return PackExpansionTypeBits.NumExpansions - 1; |
5627 | return None; |
5628 | } |
5629 | |
5630 | bool isSugared() const { return false; } |
5631 | QualType desugar() const { return QualType(this, 0); } |
5632 | |
5633 | void Profile(llvm::FoldingSetNodeID &ID) { |
5634 | Profile(ID, getPattern(), getNumExpansions()); |
5635 | } |
5636 | |
5637 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5638 | Optional<unsigned> NumExpansions) { |
5639 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5640 | ID.AddBoolean(NumExpansions.hasValue()); |
5641 | if (NumExpansions) |
5642 | ID.AddInteger(*NumExpansions); |
5643 | } |
5644 | |
5645 | static bool classof(const Type *T) { |
5646 | return T->getTypeClass() == PackExpansion; |
5647 | } |
5648 | }; |
5649 | |
5650 | /// This class wraps the list of protocol qualifiers. For types that can |
5651 | /// take ObjC protocol qualifers, they can subclass this class. |
5652 | template <class T> |
5653 | class ObjCProtocolQualifiers { |
5654 | protected: |
5655 | ObjCProtocolQualifiers() = default; |
5656 | |
5657 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5658 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5659 | } |
5660 | |
5661 | ObjCProtocolDecl **getProtocolStorage() { |
5662 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5663 | } |
5664 | |
5665 | void setNumProtocols(unsigned N) { |
5666 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5667 | } |
5668 | |
5669 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5670 | setNumProtocols(protocols.size()); |
5671 | assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5672, __PRETTY_FUNCTION__)) |
5672 | "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5672, __PRETTY_FUNCTION__)); |
5673 | if (!protocols.empty()) |
5674 | memcpy(getProtocolStorage(), protocols.data(), |
5675 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5676 | } |
5677 | |
5678 | public: |
5679 | using qual_iterator = ObjCProtocolDecl * const *; |
5680 | using qual_range = llvm::iterator_range<qual_iterator>; |
5681 | |
5682 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5683 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5684 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5685 | |
5686 | bool qual_empty() const { return getNumProtocols() == 0; } |
5687 | |
5688 | /// Return the number of qualifying protocols in this type, or 0 if |
5689 | /// there are none. |
5690 | unsigned getNumProtocols() const { |
5691 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5692 | } |
5693 | |
5694 | /// Fetch a protocol by index. |
5695 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5696 | assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access" ) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5696, __PRETTY_FUNCTION__)); |
5697 | return qual_begin()[I]; |
5698 | } |
5699 | |
5700 | /// Retrieve all of the protocol qualifiers. |
5701 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5702 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5703 | } |
5704 | }; |
5705 | |
5706 | /// Represents a type parameter type in Objective C. It can take |
5707 | /// a list of protocols. |
5708 | class ObjCTypeParamType : public Type, |
5709 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5710 | public llvm::FoldingSetNode { |
5711 | friend class ASTContext; |
5712 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5713 | |
5714 | /// The number of protocols stored on this type. |
5715 | unsigned NumProtocols : 6; |
5716 | |
5717 | ObjCTypeParamDecl *OTPDecl; |
5718 | |
5719 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5720 | /// canonical type, the list of protocols are sorted alphabetically |
5721 | /// and uniqued. |
5722 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5723 | |
5724 | /// Return the number of qualifying protocols in this interface type, |
5725 | /// or 0 if there are none. |
5726 | unsigned getNumProtocolsImpl() const { |
5727 | return NumProtocols; |
5728 | } |
5729 | |
5730 | void setNumProtocolsImpl(unsigned N) { |
5731 | NumProtocols = N; |
5732 | } |
5733 | |
5734 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5735 | QualType can, |
5736 | ArrayRef<ObjCProtocolDecl *> protocols); |
5737 | |
5738 | public: |
5739 | bool isSugared() const { return true; } |
5740 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5741 | |
5742 | static bool classof(const Type *T) { |
5743 | return T->getTypeClass() == ObjCTypeParam; |
5744 | } |
5745 | |
5746 | void Profile(llvm::FoldingSetNodeID &ID); |
5747 | static void Profile(llvm::FoldingSetNodeID &ID, |
5748 | const ObjCTypeParamDecl *OTPDecl, |
5749 | QualType CanonicalType, |
5750 | ArrayRef<ObjCProtocolDecl *> protocols); |
5751 | |
5752 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5753 | }; |
5754 | |
5755 | /// Represents a class type in Objective C. |
5756 | /// |
5757 | /// Every Objective C type is a combination of a base type, a set of |
5758 | /// type arguments (optional, for parameterized classes) and a list of |
5759 | /// protocols. |
5760 | /// |
5761 | /// Given the following declarations: |
5762 | /// \code |
5763 | /// \@class C<T>; |
5764 | /// \@protocol P; |
5765 | /// \endcode |
5766 | /// |
5767 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5768 | /// with base C and no protocols. |
5769 | /// |
5770 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5771 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5772 | /// protocol list. |
5773 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5774 | /// and protocol list [P]. |
5775 | /// |
5776 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5777 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5778 | /// and no protocols. |
5779 | /// |
5780 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5781 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5782 | /// this should get its own sugar class to better represent the source. |
5783 | class ObjCObjectType : public Type, |
5784 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5785 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5786 | |
5787 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5788 | // after the ObjCObjectPointerType node. |
5789 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5790 | // after the type arguments of ObjCObjectPointerType node. |
5791 | // |
5792 | // These protocols are those written directly on the type. If |
5793 | // protocol qualifiers ever become additive, the iterators will need |
5794 | // to get kindof complicated. |
5795 | // |
5796 | // In the canonical object type, these are sorted alphabetically |
5797 | // and uniqued. |
5798 | |
5799 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5800 | QualType BaseType; |
5801 | |
5802 | /// Cached superclass type. |
5803 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5804 | CachedSuperClassType; |
5805 | |
5806 | QualType *getTypeArgStorage(); |
5807 | const QualType *getTypeArgStorage() const { |
5808 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5809 | } |
5810 | |
5811 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5812 | /// Return the number of qualifying protocols in this interface type, |
5813 | /// or 0 if there are none. |
5814 | unsigned getNumProtocolsImpl() const { |
5815 | return ObjCObjectTypeBits.NumProtocols; |
5816 | } |
5817 | void setNumProtocolsImpl(unsigned N) { |
5818 | ObjCObjectTypeBits.NumProtocols = N; |
5819 | } |
5820 | |
5821 | protected: |
5822 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5823 | |
5824 | ObjCObjectType(QualType Canonical, QualType Base, |
5825 | ArrayRef<QualType> typeArgs, |
5826 | ArrayRef<ObjCProtocolDecl *> protocols, |
5827 | bool isKindOf); |
5828 | |
5829 | ObjCObjectType(enum Nonce_ObjCInterface) |
5830 | : Type(ObjCInterface, QualType(), TypeDependence::None), |
5831 | BaseType(QualType(this_(), 0)) { |
5832 | ObjCObjectTypeBits.NumProtocols = 0; |
5833 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5834 | ObjCObjectTypeBits.IsKindOf = 0; |
5835 | } |
5836 | |
5837 | void computeSuperClassTypeSlow() const; |
5838 | |
5839 | public: |
5840 | /// Gets the base type of this object type. This is always (possibly |
5841 | /// sugar for) one of: |
5842 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5843 | /// user, which is a typedef for an ObjCObjectPointerType) |
5844 | /// - the 'Class' builtin type (same caveat) |
5845 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5846 | QualType getBaseType() const { return BaseType; } |
5847 | |
5848 | bool isObjCId() const { |
5849 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5850 | } |
5851 | |
5852 | bool isObjCClass() const { |
5853 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5854 | } |
5855 | |
5856 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5857 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5858 | bool isObjCUnqualifiedIdOrClass() const { |
5859 | if (!qual_empty()) return false; |
5860 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5861 | return T->getKind() == BuiltinType::ObjCId || |
5862 | T->getKind() == BuiltinType::ObjCClass; |
5863 | return false; |
5864 | } |
5865 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5866 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5867 | |
5868 | /// Gets the interface declaration for this object type, if the base type |
5869 | /// really is an interface. |
5870 | ObjCInterfaceDecl *getInterface() const; |
5871 | |
5872 | /// Determine whether this object type is "specialized", meaning |
5873 | /// that it has type arguments. |
5874 | bool isSpecialized() const; |
5875 | |
5876 | /// Determine whether this object type was written with type arguments. |
5877 | bool isSpecializedAsWritten() const { |
5878 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5879 | } |
5880 | |
5881 | /// Determine whether this object type is "unspecialized", meaning |
5882 | /// that it has no type arguments. |
5883 | bool isUnspecialized() const { return !isSpecialized(); } |
5884 | |
5885 | /// Determine whether this object type is "unspecialized" as |
5886 | /// written, meaning that it has no type arguments. |
5887 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5888 | |
5889 | /// Retrieve the type arguments of this object type (semantically). |
5890 | ArrayRef<QualType> getTypeArgs() const; |
5891 | |
5892 | /// Retrieve the type arguments of this object type as they were |
5893 | /// written. |
5894 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5895 | return llvm::makeArrayRef(getTypeArgStorage(), |
5896 | ObjCObjectTypeBits.NumTypeArgs); |
5897 | } |
5898 | |
5899 | /// Whether this is a "__kindof" type as written. |
5900 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5901 | |
5902 | /// Whether this ia a "__kindof" type (semantically). |
5903 | bool isKindOfType() const; |
5904 | |
5905 | /// Retrieve the type of the superclass of this object type. |
5906 | /// |
5907 | /// This operation substitutes any type arguments into the |
5908 | /// superclass of the current class type, potentially producing a |
5909 | /// specialization of the superclass type. Produces a null type if |
5910 | /// there is no superclass. |
5911 | QualType getSuperClassType() const { |
5912 | if (!CachedSuperClassType.getInt()) |
5913 | computeSuperClassTypeSlow(); |
5914 | |
5915 | assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?" ) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 5915, __PRETTY_FUNCTION__)); |
5916 | return QualType(CachedSuperClassType.getPointer(), 0); |
5917 | } |
5918 | |
5919 | /// Strip off the Objective-C "kindof" type and (with it) any |
5920 | /// protocol qualifiers. |
5921 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5922 | |
5923 | bool isSugared() const { return false; } |
5924 | QualType desugar() const { return QualType(this, 0); } |
5925 | |
5926 | static bool classof(const Type *T) { |
5927 | return T->getTypeClass() == ObjCObject || |
5928 | T->getTypeClass() == ObjCInterface; |
5929 | } |
5930 | }; |
5931 | |
5932 | /// A class providing a concrete implementation |
5933 | /// of ObjCObjectType, so as to not increase the footprint of |
5934 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5935 | /// system should not reference this type. |
5936 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5937 | friend class ASTContext; |
5938 | |
5939 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5940 | // will need to be modified. |
5941 | |
5942 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5943 | ArrayRef<QualType> typeArgs, |
5944 | ArrayRef<ObjCProtocolDecl *> protocols, |
5945 | bool isKindOf) |
5946 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5947 | |
5948 | public: |
5949 | void Profile(llvm::FoldingSetNodeID &ID); |
5950 | static void Profile(llvm::FoldingSetNodeID &ID, |
5951 | QualType Base, |
5952 | ArrayRef<QualType> typeArgs, |
5953 | ArrayRef<ObjCProtocolDecl *> protocols, |
5954 | bool isKindOf); |
5955 | }; |
5956 | |
5957 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5958 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5959 | } |
5960 | |
5961 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5962 | return reinterpret_cast<ObjCProtocolDecl**>( |
5963 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
5964 | } |
5965 | |
5966 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
5967 | return reinterpret_cast<ObjCProtocolDecl**>( |
5968 | static_cast<ObjCTypeParamType*>(this)+1); |
5969 | } |
5970 | |
5971 | /// Interfaces are the core concept in Objective-C for object oriented design. |
5972 | /// They basically correspond to C++ classes. There are two kinds of interface |
5973 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
5974 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
5975 | /// |
5976 | /// ObjCInterfaceType guarantees the following properties when considered |
5977 | /// as a subtype of its superclass, ObjCObjectType: |
5978 | /// - There are no protocol qualifiers. To reinforce this, code which |
5979 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
5980 | /// fail to compile. |
5981 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
5982 | /// T->getBaseType() == QualType(T, 0). |
5983 | class ObjCInterfaceType : public ObjCObjectType { |
5984 | friend class ASTContext; // ASTContext creates these. |
5985 | friend class ASTReader; |
5986 | friend class ObjCInterfaceDecl; |
5987 | template <class T> friend class serialization::AbstractTypeReader; |
5988 | |
5989 | mutable ObjCInterfaceDecl *Decl; |
5990 | |
5991 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
5992 | : ObjCObjectType(Nonce_ObjCInterface), |
5993 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
5994 | |
5995 | public: |
5996 | /// Get the declaration of this interface. |
5997 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
5998 | |
5999 | bool isSugared() const { return false; } |
6000 | QualType desugar() const { return QualType(this, 0); } |
6001 | |
6002 | static bool classof(const Type *T) { |
6003 | return T->getTypeClass() == ObjCInterface; |
6004 | } |
6005 | |
6006 | // Nonsense to "hide" certain members of ObjCObjectType within this |
6007 | // class. People asking for protocols on an ObjCInterfaceType are |
6008 | // not going to get what they want: ObjCInterfaceTypes are |
6009 | // guaranteed to have no protocols. |
6010 | enum { |
6011 | qual_iterator, |
6012 | qual_begin, |
6013 | qual_end, |
6014 | getNumProtocols, |
6015 | getProtocol |
6016 | }; |
6017 | }; |
6018 | |
6019 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
6020 | QualType baseType = getBaseType(); |
6021 | while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { |
6022 | if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
6023 | return T->getDecl(); |
6024 | |
6025 | baseType = ObjT->getBaseType(); |
6026 | } |
6027 | |
6028 | return nullptr; |
6029 | } |
6030 | |
6031 | /// Represents a pointer to an Objective C object. |
6032 | /// |
6033 | /// These are constructed from pointer declarators when the pointee type is |
6034 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
6035 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
6036 | /// and 'Class<P>' are translated into these. |
6037 | /// |
6038 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
6039 | /// only the first level of pointer gets it own type implementation. |
6040 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
6041 | friend class ASTContext; // ASTContext creates these. |
6042 | |
6043 | QualType PointeeType; |
6044 | |
6045 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
6046 | : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()), |
6047 | PointeeType(Pointee) {} |
6048 | |
6049 | public: |
6050 | /// Gets the type pointed to by this ObjC pointer. |
6051 | /// The result will always be an ObjCObjectType or sugar thereof. |
6052 | QualType getPointeeType() const { return PointeeType; } |
6053 | |
6054 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
6055 | /// |
6056 | /// This method is equivalent to getPointeeType() except that |
6057 | /// it discards any typedefs (or other sugar) between this |
6058 | /// type and the "outermost" object type. So for: |
6059 | /// \code |
6060 | /// \@class A; \@protocol P; \@protocol Q; |
6061 | /// typedef A<P> AP; |
6062 | /// typedef A A1; |
6063 | /// typedef A1<P> A1P; |
6064 | /// typedef A1P<Q> A1PQ; |
6065 | /// \endcode |
6066 | /// For 'A*', getObjectType() will return 'A'. |
6067 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
6068 | /// For 'AP*', getObjectType() will return 'A<P>'. |
6069 | /// For 'A1*', getObjectType() will return 'A'. |
6070 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
6071 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
6072 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
6073 | /// adding protocols to a protocol-qualified base discards the |
6074 | /// old qualifiers (for now). But if it didn't, getObjectType() |
6075 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
6076 | /// qualifiers more complicated). |
6077 | const ObjCObjectType *getObjectType() const { |
6078 | return PointeeType->castAs<ObjCObjectType>(); |
6079 | } |
6080 | |
6081 | /// If this pointer points to an Objective C |
6082 | /// \@interface type, gets the type for that interface. Any protocol |
6083 | /// qualifiers on the interface are ignored. |
6084 | /// |
6085 | /// \return null if the base type for this pointer is 'id' or 'Class' |
6086 | const ObjCInterfaceType *getInterfaceType() const; |
6087 | |
6088 | /// If this pointer points to an Objective \@interface |
6089 | /// type, gets the declaration for that interface. |
6090 | /// |
6091 | /// \return null if the base type for this pointer is 'id' or 'Class' |
6092 | ObjCInterfaceDecl *getInterfaceDecl() const { |
6093 | return getObjectType()->getInterface(); |
6094 | } |
6095 | |
6096 | /// True if this is equivalent to the 'id' type, i.e. if |
6097 | /// its object type is the primitive 'id' type with no protocols. |
6098 | bool isObjCIdType() const { |
6099 | return getObjectType()->isObjCUnqualifiedId(); |
6100 | } |
6101 | |
6102 | /// True if this is equivalent to the 'Class' type, |
6103 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
6104 | bool isObjCClassType() const { |
6105 | return getObjectType()->isObjCUnqualifiedClass(); |
6106 | } |
6107 | |
6108 | /// True if this is equivalent to the 'id' or 'Class' type, |
6109 | bool isObjCIdOrClassType() const { |
6110 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
6111 | } |
6112 | |
6113 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
6114 | /// protocols. |
6115 | bool isObjCQualifiedIdType() const { |
6116 | return getObjectType()->isObjCQualifiedId(); |
6117 | } |
6118 | |
6119 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
6120 | /// protocols. |
6121 | bool isObjCQualifiedClassType() const { |
6122 | return getObjectType()->isObjCQualifiedClass(); |
6123 | } |
6124 | |
6125 | /// Whether this is a "__kindof" type. |
6126 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
6127 | |
6128 | /// Whether this type is specialized, meaning that it has type arguments. |
6129 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
6130 | |
6131 | /// Whether this type is specialized, meaning that it has type arguments. |
6132 | bool isSpecializedAsWritten() const { |
6133 | return getObjectType()->isSpecializedAsWritten(); |
6134 | } |
6135 | |
6136 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
6137 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
6138 | |
6139 | /// Determine whether this object type is "unspecialized" as |
6140 | /// written, meaning that it has no type arguments. |
6141 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
6142 | |
6143 | /// Retrieve the type arguments for this type. |
6144 | ArrayRef<QualType> getTypeArgs() const { |
6145 | return getObjectType()->getTypeArgs(); |
6146 | } |
6147 | |
6148 | /// Retrieve the type arguments for this type. |
6149 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
6150 | return getObjectType()->getTypeArgsAsWritten(); |
6151 | } |
6152 | |
6153 | /// An iterator over the qualifiers on the object type. Provided |
6154 | /// for convenience. This will always iterate over the full set of |
6155 | /// protocols on a type, not just those provided directly. |
6156 | using qual_iterator = ObjCObjectType::qual_iterator; |
6157 | using qual_range = llvm::iterator_range<qual_iterator>; |
6158 | |
6159 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
6160 | |
6161 | qual_iterator qual_begin() const { |
6162 | return getObjectType()->qual_begin(); |
6163 | } |
6164 | |
6165 | qual_iterator qual_end() const { |
6166 | return getObjectType()->qual_end(); |
6167 | } |
6168 | |
6169 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
6170 | |
6171 | /// Return the number of qualifying protocols on the object type. |
6172 | unsigned getNumProtocols() const { |
6173 | return getObjectType()->getNumProtocols(); |
6174 | } |
6175 | |
6176 | /// Retrieve a qualifying protocol by index on the object type. |
6177 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
6178 | return getObjectType()->getProtocol(I); |
6179 | } |
6180 | |
6181 | bool isSugared() const { return false; } |
6182 | QualType desugar() const { return QualType(this, 0); } |
6183 | |
6184 | /// Retrieve the type of the superclass of this object pointer type. |
6185 | /// |
6186 | /// This operation substitutes any type arguments into the |
6187 | /// superclass of the current class type, potentially producing a |
6188 | /// pointer to a specialization of the superclass type. Produces a |
6189 | /// null type if there is no superclass. |
6190 | QualType getSuperClassType() const; |
6191 | |
6192 | /// Strip off the Objective-C "kindof" type and (with it) any |
6193 | /// protocol qualifiers. |
6194 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
6195 | const ASTContext &ctx) const; |
6196 | |
6197 | void Profile(llvm::FoldingSetNodeID &ID) { |
6198 | Profile(ID, getPointeeType()); |
6199 | } |
6200 | |
6201 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6202 | ID.AddPointer(T.getAsOpaquePtr()); |
6203 | } |
6204 | |
6205 | static bool classof(const Type *T) { |
6206 | return T->getTypeClass() == ObjCObjectPointer; |
6207 | } |
6208 | }; |
6209 | |
6210 | class AtomicType : public Type, public llvm::FoldingSetNode { |
6211 | friend class ASTContext; // ASTContext creates these. |
6212 | |
6213 | QualType ValueType; |
6214 | |
6215 | AtomicType(QualType ValTy, QualType Canonical) |
6216 | : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {} |
6217 | |
6218 | public: |
6219 | /// Gets the type contained by this atomic type, i.e. |
6220 | /// the type returned by performing an atomic load of this atomic type. |
6221 | QualType getValueType() const { return ValueType; } |
6222 | |
6223 | bool isSugared() const { return false; } |
6224 | QualType desugar() const { return QualType(this, 0); } |
6225 | |
6226 | void Profile(llvm::FoldingSetNodeID &ID) { |
6227 | Profile(ID, getValueType()); |
6228 | } |
6229 | |
6230 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6231 | ID.AddPointer(T.getAsOpaquePtr()); |
6232 | } |
6233 | |
6234 | static bool classof(const Type *T) { |
6235 | return T->getTypeClass() == Atomic; |
6236 | } |
6237 | }; |
6238 | |
6239 | /// PipeType - OpenCL20. |
6240 | class PipeType : public Type, public llvm::FoldingSetNode { |
6241 | friend class ASTContext; // ASTContext creates these. |
6242 | |
6243 | QualType ElementType; |
6244 | bool isRead; |
6245 | |
6246 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
6247 | : Type(Pipe, CanonicalPtr, elemType->getDependence()), |
6248 | ElementType(elemType), isRead(isRead) {} |
6249 | |
6250 | public: |
6251 | QualType getElementType() const { return ElementType; } |
6252 | |
6253 | bool isSugared() const { return false; } |
6254 | |
6255 | QualType desugar() const { return QualType(this, 0); } |
6256 | |
6257 | void Profile(llvm::FoldingSetNodeID &ID) { |
6258 | Profile(ID, getElementType(), isReadOnly()); |
6259 | } |
6260 | |
6261 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
6262 | ID.AddPointer(T.getAsOpaquePtr()); |
6263 | ID.AddBoolean(isRead); |
6264 | } |
6265 | |
6266 | static bool classof(const Type *T) { |
6267 | return T->getTypeClass() == Pipe; |
6268 | } |
6269 | |
6270 | bool isReadOnly() const { return isRead; } |
6271 | }; |
6272 | |
6273 | /// A fixed int type of a specified bitwidth. |
6274 | class ExtIntType final : public Type, public llvm::FoldingSetNode { |
6275 | friend class ASTContext; |
6276 | unsigned IsUnsigned : 1; |
6277 | unsigned NumBits : 24; |
6278 | |
6279 | protected: |
6280 | ExtIntType(bool isUnsigned, unsigned NumBits); |
6281 | |
6282 | public: |
6283 | bool isUnsigned() const { return IsUnsigned; } |
6284 | bool isSigned() const { return !IsUnsigned; } |
6285 | unsigned getNumBits() const { return NumBits; } |
6286 | |
6287 | bool isSugared() const { return false; } |
6288 | QualType desugar() const { return QualType(this, 0); } |
6289 | |
6290 | void Profile(llvm::FoldingSetNodeID &ID) { |
6291 | Profile(ID, isUnsigned(), getNumBits()); |
6292 | } |
6293 | |
6294 | static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned, |
6295 | unsigned NumBits) { |
6296 | ID.AddBoolean(IsUnsigned); |
6297 | ID.AddInteger(NumBits); |
6298 | } |
6299 | |
6300 | static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; } |
6301 | }; |
6302 | |
6303 | class DependentExtIntType final : public Type, public llvm::FoldingSetNode { |
6304 | friend class ASTContext; |
6305 | const ASTContext &Context; |
6306 | llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned; |
6307 | |
6308 | protected: |
6309 | DependentExtIntType(const ASTContext &Context, bool IsUnsigned, |
6310 | Expr *NumBits); |
6311 | |
6312 | public: |
6313 | bool isUnsigned() const; |
6314 | bool isSigned() const { return !isUnsigned(); } |
6315 | Expr *getNumBitsExpr() const; |
6316 | |
6317 | bool isSugared() const { return false; } |
6318 | QualType desugar() const { return QualType(this, 0); } |
6319 | |
6320 | void Profile(llvm::FoldingSetNodeID &ID) { |
6321 | Profile(ID, Context, isUnsigned(), getNumBitsExpr()); |
6322 | } |
6323 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
6324 | bool IsUnsigned, Expr *NumBitsExpr); |
6325 | |
6326 | static bool classof(const Type *T) { |
6327 | return T->getTypeClass() == DependentExtInt; |
6328 | } |
6329 | }; |
6330 | |
6331 | /// A qualifier set is used to build a set of qualifiers. |
6332 | class QualifierCollector : public Qualifiers { |
6333 | public: |
6334 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
6335 | |
6336 | /// Collect any qualifiers on the given type and return an |
6337 | /// unqualified type. The qualifiers are assumed to be consistent |
6338 | /// with those already in the type. |
6339 | const Type *strip(QualType type) { |
6340 | addFastQualifiers(type.getLocalFastQualifiers()); |
6341 | if (!type.hasLocalNonFastQualifiers()) |
6342 | return type.getTypePtrUnsafe(); |
6343 | |
6344 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
6345 | addConsistentQualifiers(extQuals->getQualifiers()); |
6346 | return extQuals->getBaseType(); |
6347 | } |
6348 | |
6349 | /// Apply the collected qualifiers to the given type. |
6350 | QualType apply(const ASTContext &Context, QualType QT) const; |
6351 | |
6352 | /// Apply the collected qualifiers to the given type. |
6353 | QualType apply(const ASTContext &Context, const Type* T) const; |
6354 | }; |
6355 | |
6356 | /// A container of type source information. |
6357 | /// |
6358 | /// A client can read the relevant info using TypeLoc wrappers, e.g: |
6359 | /// @code |
6360 | /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); |
6361 | /// TL.getBeginLoc().print(OS, SrcMgr); |
6362 | /// @endcode |
6363 | class alignas(8) TypeSourceInfo { |
6364 | // Contains a memory block after the class, used for type source information, |
6365 | // allocated by ASTContext. |
6366 | friend class ASTContext; |
6367 | |
6368 | QualType Ty; |
6369 | |
6370 | TypeSourceInfo(QualType ty) : Ty(ty) {} |
6371 | |
6372 | public: |
6373 | /// Return the type wrapped by this type source info. |
6374 | QualType getType() const { return Ty; } |
6375 | |
6376 | /// Return the TypeLoc wrapper for the type source info. |
6377 | TypeLoc getTypeLoc() const; // implemented in TypeLoc.h |
6378 | |
6379 | /// Override the type stored in this TypeSourceInfo. Use with caution! |
6380 | void overrideType(QualType T) { Ty = T; } |
6381 | }; |
6382 | |
6383 | // Inline function definitions. |
6384 | |
6385 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
6386 | SplitQualType desugar = |
6387 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
6388 | desugar.Quals.addConsistentQualifiers(Quals); |
6389 | return desugar; |
6390 | } |
6391 | |
6392 | inline const Type *QualType::getTypePtr() const { |
6393 | return getCommonPtr()->BaseType; |
6394 | } |
6395 | |
6396 | inline const Type *QualType::getTypePtrOrNull() const { |
6397 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
6398 | } |
6399 | |
6400 | inline SplitQualType QualType::split() const { |
6401 | if (!hasLocalNonFastQualifiers()) |
6402 | return SplitQualType(getTypePtrUnsafe(), |
6403 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
6404 | |
6405 | const ExtQuals *eq = getExtQualsUnsafe(); |
6406 | Qualifiers qs = eq->getQualifiers(); |
6407 | qs.addFastQualifiers(getLocalFastQualifiers()); |
6408 | return SplitQualType(eq->getBaseType(), qs); |
6409 | } |
6410 | |
6411 | inline Qualifiers QualType::getLocalQualifiers() const { |
6412 | Qualifiers Quals; |
6413 | if (hasLocalNonFastQualifiers()) |
6414 | Quals = getExtQualsUnsafe()->getQualifiers(); |
6415 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
6416 | return Quals; |
6417 | } |
6418 | |
6419 | inline Qualifiers QualType::getQualifiers() const { |
6420 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
6421 | quals.addFastQualifiers(getLocalFastQualifiers()); |
6422 | return quals; |
6423 | } |
6424 | |
6425 | inline unsigned QualType::getCVRQualifiers() const { |
6426 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
6427 | cvr |= getLocalCVRQualifiers(); |
6428 | return cvr; |
6429 | } |
6430 | |
6431 | inline QualType QualType::getCanonicalType() const { |
6432 | QualType canon = getCommonPtr()->CanonicalType; |
6433 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
6434 | } |
6435 | |
6436 | inline bool QualType::isCanonical() const { |
6437 | return getTypePtr()->isCanonicalUnqualified(); |
6438 | } |
6439 | |
6440 | inline bool QualType::isCanonicalAsParam() const { |
6441 | if (!isCanonical()) return false; |
6442 | if (hasLocalQualifiers()) return false; |
6443 | |
6444 | const Type *T = getTypePtr(); |
6445 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
6446 | return false; |
6447 | |
6448 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
6449 | } |
6450 | |
6451 | inline bool QualType::isConstQualified() const { |
6452 | return isLocalConstQualified() || |
6453 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
6454 | } |
6455 | |
6456 | inline bool QualType::isRestrictQualified() const { |
6457 | return isLocalRestrictQualified() || |
6458 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
6459 | } |
6460 | |
6461 | |
6462 | inline bool QualType::isVolatileQualified() const { |
6463 | return isLocalVolatileQualified() || |
6464 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
6465 | } |
6466 | |
6467 | inline bool QualType::hasQualifiers() const { |
6468 | return hasLocalQualifiers() || |
6469 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
6470 | } |
6471 | |
6472 | inline QualType QualType::getUnqualifiedType() const { |
6473 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6474 | return QualType(getTypePtr(), 0); |
6475 | |
6476 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
6477 | } |
6478 | |
6479 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
6480 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6481 | return split(); |
6482 | |
6483 | return getSplitUnqualifiedTypeImpl(*this); |
6484 | } |
6485 | |
6486 | inline void QualType::removeLocalConst() { |
6487 | removeLocalFastQualifiers(Qualifiers::Const); |
6488 | } |
6489 | |
6490 | inline void QualType::removeLocalRestrict() { |
6491 | removeLocalFastQualifiers(Qualifiers::Restrict); |
6492 | } |
6493 | |
6494 | inline void QualType::removeLocalVolatile() { |
6495 | removeLocalFastQualifiers(Qualifiers::Volatile); |
6496 | } |
6497 | |
6498 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
6499 | assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\"" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 6499, __PRETTY_FUNCTION__)); |
6500 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
6501 | "Fast bits differ from CVR bits!"); |
6502 | |
6503 | // Fast path: we don't need to touch the slow qualifiers. |
6504 | removeLocalFastQualifiers(Mask); |
6505 | } |
6506 | |
6507 | /// Check if this type has any address space qualifier. |
6508 | inline bool QualType::hasAddressSpace() const { |
6509 | return getQualifiers().hasAddressSpace(); |
6510 | } |
6511 | |
6512 | /// Return the address space of this type. |
6513 | inline LangAS QualType::getAddressSpace() const { |
6514 | return getQualifiers().getAddressSpace(); |
6515 | } |
6516 | |
6517 | /// Return the gc attribute of this type. |
6518 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
6519 | return getQualifiers().getObjCGCAttr(); |
6520 | } |
6521 | |
6522 | inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
6523 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6524 | return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); |
6525 | return false; |
6526 | } |
6527 | |
6528 | inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { |
6529 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6530 | return hasNonTrivialToPrimitiveDestructCUnion(RD); |
6531 | return false; |
6532 | } |
6533 | |
6534 | inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { |
6535 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6536 | return hasNonTrivialToPrimitiveCopyCUnion(RD); |
6537 | return false; |
6538 | } |
6539 | |
6540 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
6541 | if (const auto *PT = t.getAs<PointerType>()) { |
6542 | if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) |
6543 | return FT->getExtInfo(); |
6544 | } else if (const auto *FT = t.getAs<FunctionType>()) |
6545 | return FT->getExtInfo(); |
6546 | |
6547 | return FunctionType::ExtInfo(); |
6548 | } |
6549 | |
6550 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
6551 | return getFunctionExtInfo(*t); |
6552 | } |
6553 | |
6554 | /// Determine whether this type is more |
6555 | /// qualified than the Other type. For example, "const volatile int" |
6556 | /// is more qualified than "const int", "volatile int", and |
6557 | /// "int". However, it is not more qualified than "const volatile |
6558 | /// int". |
6559 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
6560 | Qualifiers MyQuals = getQualifiers(); |
6561 | Qualifiers OtherQuals = other.getQualifiers(); |
6562 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
6563 | } |
6564 | |
6565 | /// Determine whether this type is at last |
6566 | /// as qualified as the Other type. For example, "const volatile |
6567 | /// int" is at least as qualified as "const int", "volatile int", |
6568 | /// "int", and "const volatile int". |
6569 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
6570 | Qualifiers OtherQuals = other.getQualifiers(); |
6571 | |
6572 | // Ignore __unaligned qualifier if this type is a void. |
6573 | if (getUnqualifiedType()->isVoidType()) |
6574 | OtherQuals.removeUnaligned(); |
6575 | |
6576 | return getQualifiers().compatiblyIncludes(OtherQuals); |
6577 | } |
6578 | |
6579 | /// If Type is a reference type (e.g., const |
6580 | /// int&), returns the type that the reference refers to ("const |
6581 | /// int"). Otherwise, returns the type itself. This routine is used |
6582 | /// throughout Sema to implement C++ 5p6: |
6583 | /// |
6584 | /// If an expression initially has the type "reference to T" (8.3.2, |
6585 | /// 8.5.3), the type is adjusted to "T" prior to any further |
6586 | /// analysis, the expression designates the object or function |
6587 | /// denoted by the reference, and the expression is an lvalue. |
6588 | inline QualType QualType::getNonReferenceType() const { |
6589 | if (const auto *RefType = (*this)->getAs<ReferenceType>()) |
6590 | return RefType->getPointeeType(); |
6591 | else |
6592 | return *this; |
6593 | } |
6594 | |
6595 | inline bool QualType::isCForbiddenLValueType() const { |
6596 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
6597 | getTypePtr()->isFunctionType()); |
6598 | } |
6599 | |
6600 | /// Tests whether the type is categorized as a fundamental type. |
6601 | /// |
6602 | /// \returns True for types specified in C++0x [basic.fundamental]. |
6603 | inline bool Type::isFundamentalType() const { |
6604 | return isVoidType() || |
6605 | isNullPtrType() || |
6606 | // FIXME: It's really annoying that we don't have an |
6607 | // 'isArithmeticType()' which agrees with the standard definition. |
6608 | (isArithmeticType() && !isEnumeralType()); |
6609 | } |
6610 | |
6611 | /// Tests whether the type is categorized as a compound type. |
6612 | /// |
6613 | /// \returns True for types specified in C++0x [basic.compound]. |
6614 | inline bool Type::isCompoundType() const { |
6615 | // C++0x [basic.compound]p1: |
6616 | // Compound types can be constructed in the following ways: |
6617 | // -- arrays of objects of a given type [...]; |
6618 | return isArrayType() || |
6619 | // -- functions, which have parameters of given types [...]; |
6620 | isFunctionType() || |
6621 | // -- pointers to void or objects or functions [...]; |
6622 | isPointerType() || |
6623 | // -- references to objects or functions of a given type. [...] |
6624 | isReferenceType() || |
6625 | // -- classes containing a sequence of objects of various types, [...]; |
6626 | isRecordType() || |
6627 | // -- unions, which are classes capable of containing objects of different |
6628 | // types at different times; |
6629 | isUnionType() || |
6630 | // -- enumerations, which comprise a set of named constant values. [...]; |
6631 | isEnumeralType() || |
6632 | // -- pointers to non-static class members, [...]. |
6633 | isMemberPointerType(); |
6634 | } |
6635 | |
6636 | inline bool Type::isFunctionType() const { |
6637 | return isa<FunctionType>(CanonicalType); |
6638 | } |
6639 | |
6640 | inline bool Type::isPointerType() const { |
6641 | return isa<PointerType>(CanonicalType); |
6642 | } |
6643 | |
6644 | inline bool Type::isAnyPointerType() const { |
6645 | return isPointerType() || isObjCObjectPointerType(); |
6646 | } |
6647 | |
6648 | inline bool Type::isBlockPointerType() const { |
6649 | return isa<BlockPointerType>(CanonicalType); |
6650 | } |
6651 | |
6652 | inline bool Type::isReferenceType() const { |
6653 | return isa<ReferenceType>(CanonicalType); |
6654 | } |
6655 | |
6656 | inline bool Type::isLValueReferenceType() const { |
6657 | return isa<LValueReferenceType>(CanonicalType); |
6658 | } |
6659 | |
6660 | inline bool Type::isRValueReferenceType() const { |
6661 | return isa<RValueReferenceType>(CanonicalType); |
6662 | } |
6663 | |
6664 | inline bool Type::isObjectPointerType() const { |
6665 | // Note: an "object pointer type" is not the same thing as a pointer to an |
6666 | // object type; rather, it is a pointer to an object type or a pointer to cv |
6667 | // void. |
6668 | if (const auto *T = getAs<PointerType>()) |
6669 | return !T->getPointeeType()->isFunctionType(); |
6670 | else |
6671 | return false; |
6672 | } |
6673 | |
6674 | inline bool Type::isFunctionPointerType() const { |
6675 | if (const auto *T = getAs<PointerType>()) |
6676 | return T->getPointeeType()->isFunctionType(); |
6677 | else |
6678 | return false; |
6679 | } |
6680 | |
6681 | inline bool Type::isFunctionReferenceType() const { |
6682 | if (const auto *T = getAs<ReferenceType>()) |
6683 | return T->getPointeeType()->isFunctionType(); |
6684 | else |
6685 | return false; |
6686 | } |
6687 | |
6688 | inline bool Type::isMemberPointerType() const { |
6689 | return isa<MemberPointerType>(CanonicalType); |
6690 | } |
6691 | |
6692 | inline bool Type::isMemberFunctionPointerType() const { |
6693 | if (const auto *T = getAs<MemberPointerType>()) |
6694 | return T->isMemberFunctionPointer(); |
6695 | else |
6696 | return false; |
6697 | } |
6698 | |
6699 | inline bool Type::isMemberDataPointerType() const { |
6700 | if (const auto *T = getAs<MemberPointerType>()) |
6701 | return T->isMemberDataPointer(); |
6702 | else |
6703 | return false; |
6704 | } |
6705 | |
6706 | inline bool Type::isArrayType() const { |
6707 | return isa<ArrayType>(CanonicalType); |
6708 | } |
6709 | |
6710 | inline bool Type::isConstantArrayType() const { |
6711 | return isa<ConstantArrayType>(CanonicalType); |
6712 | } |
6713 | |
6714 | inline bool Type::isIncompleteArrayType() const { |
6715 | return isa<IncompleteArrayType>(CanonicalType); |
6716 | } |
6717 | |
6718 | inline bool Type::isVariableArrayType() const { |
6719 | return isa<VariableArrayType>(CanonicalType); |
6720 | } |
6721 | |
6722 | inline bool Type::isDependentSizedArrayType() const { |
6723 | return isa<DependentSizedArrayType>(CanonicalType); |
6724 | } |
6725 | |
6726 | inline bool Type::isBuiltinType() const { |
6727 | return isa<BuiltinType>(CanonicalType); |
6728 | } |
6729 | |
6730 | inline bool Type::isRecordType() const { |
6731 | return isa<RecordType>(CanonicalType); |
6732 | } |
6733 | |
6734 | inline bool Type::isEnumeralType() const { |
6735 | return isa<EnumType>(CanonicalType); |
6736 | } |
6737 | |
6738 | inline bool Type::isAnyComplexType() const { |
6739 | return isa<ComplexType>(CanonicalType); |
6740 | } |
6741 | |
6742 | inline bool Type::isVectorType() const { |
6743 | return isa<VectorType>(CanonicalType); |
6744 | } |
6745 | |
6746 | inline bool Type::isExtVectorType() const { |
6747 | return isa<ExtVectorType>(CanonicalType); |
6748 | } |
6749 | |
6750 | inline bool Type::isMatrixType() const { |
6751 | return isa<MatrixType>(CanonicalType); |
6752 | } |
6753 | |
6754 | inline bool Type::isConstantMatrixType() const { |
6755 | return isa<ConstantMatrixType>(CanonicalType); |
6756 | } |
6757 | |
6758 | inline bool Type::isDependentAddressSpaceType() const { |
6759 | return isa<DependentAddressSpaceType>(CanonicalType); |
6760 | } |
6761 | |
6762 | inline bool Type::isObjCObjectPointerType() const { |
6763 | return isa<ObjCObjectPointerType>(CanonicalType); |
6764 | } |
6765 | |
6766 | inline bool Type::isObjCObjectType() const { |
6767 | return isa<ObjCObjectType>(CanonicalType); |
6768 | } |
6769 | |
6770 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6771 | return isa<ObjCInterfaceType>(CanonicalType) || |
6772 | isa<ObjCObjectType>(CanonicalType); |
6773 | } |
6774 | |
6775 | inline bool Type::isAtomicType() const { |
6776 | return isa<AtomicType>(CanonicalType); |
6777 | } |
6778 | |
6779 | inline bool Type::isUndeducedAutoType() const { |
6780 | return isa<AutoType>(CanonicalType); |
6781 | } |
6782 | |
6783 | inline bool Type::isObjCQualifiedIdType() const { |
6784 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6785 | return OPT->isObjCQualifiedIdType(); |
6786 | return false; |
6787 | } |
6788 | |
6789 | inline bool Type::isObjCQualifiedClassType() const { |
6790 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6791 | return OPT->isObjCQualifiedClassType(); |
6792 | return false; |
6793 | } |
6794 | |
6795 | inline bool Type::isObjCIdType() const { |
6796 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6797 | return OPT->isObjCIdType(); |
6798 | return false; |
6799 | } |
6800 | |
6801 | inline bool Type::isObjCClassType() const { |
6802 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6803 | return OPT->isObjCClassType(); |
6804 | return false; |
6805 | } |
6806 | |
6807 | inline bool Type::isObjCSelType() const { |
6808 | if (const auto *OPT = getAs<PointerType>()) |
6809 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6810 | return false; |
6811 | } |
6812 | |
6813 | inline bool Type::isObjCBuiltinType() const { |
6814 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6815 | } |
6816 | |
6817 | inline bool Type::isDecltypeType() const { |
6818 | return isa<DecltypeType>(this); |
6819 | } |
6820 | |
6821 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6822 | inline bool Type::is##Id##Type() const { \ |
6823 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6824 | } |
6825 | #include "clang/Basic/OpenCLImageTypes.def" |
6826 | |
6827 | inline bool Type::isSamplerT() const { |
6828 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6829 | } |
6830 | |
6831 | inline bool Type::isEventT() const { |
6832 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6833 | } |
6834 | |
6835 | inline bool Type::isClkEventT() const { |
6836 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6837 | } |
6838 | |
6839 | inline bool Type::isQueueT() const { |
6840 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6841 | } |
6842 | |
6843 | inline bool Type::isReserveIDT() const { |
6844 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6845 | } |
6846 | |
6847 | inline bool Type::isImageType() const { |
6848 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6849 | return |
6850 | #include "clang/Basic/OpenCLImageTypes.def" |
6851 | false; // end boolean or operation |
6852 | } |
6853 | |
6854 | inline bool Type::isPipeType() const { |
6855 | return isa<PipeType>(CanonicalType); |
6856 | } |
6857 | |
6858 | inline bool Type::isExtIntType() const { |
6859 | return isa<ExtIntType>(CanonicalType); |
6860 | } |
6861 | |
6862 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6863 | inline bool Type::is##Id##Type() const { \ |
6864 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6865 | } |
6866 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6867 | |
6868 | inline bool Type::isOCLIntelSubgroupAVCType() const { |
6869 | #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ |
6870 | isOCLIntelSubgroupAVC##Id##Type() || |
6871 | return |
6872 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6873 | false; // end of boolean or operation |
6874 | } |
6875 | |
6876 | inline bool Type::isOCLExtOpaqueType() const { |
6877 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || |
6878 | return |
6879 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6880 | false; // end of boolean or operation |
6881 | } |
6882 | |
6883 | inline bool Type::isOpenCLSpecificType() const { |
6884 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6885 | isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); |
6886 | } |
6887 | |
6888 | inline bool Type::isTemplateTypeParmType() const { |
6889 | return isa<TemplateTypeParmType>(CanonicalType); |
6890 | } |
6891 | |
6892 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6893 | if (const BuiltinType *BT = getAs<BuiltinType>()) { |
6894 | return BT->getKind() == static_cast<BuiltinType::Kind>(K); |
6895 | } |
6896 | return false; |
6897 | } |
6898 | |
6899 | inline bool Type::isPlaceholderType() const { |
6900 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6901 | return BT->isPlaceholderType(); |
6902 | return false; |
6903 | } |
6904 | |
6905 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6906 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6907 | if (BT->isPlaceholderType()) |
6908 | return BT; |
6909 | return nullptr; |
6910 | } |
6911 | |
6912 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6913 | assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ? static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)" , "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 6913, __PRETTY_FUNCTION__)); |
6914 | return isSpecificBuiltinType(K); |
6915 | } |
6916 | |
6917 | inline bool Type::isNonOverloadPlaceholderType() const { |
6918 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6919 | return BT->isNonOverloadPlaceholderType(); |
6920 | return false; |
6921 | } |
6922 | |
6923 | inline bool Type::isVoidType() const { |
6924 | return isSpecificBuiltinType(BuiltinType::Void); |
6925 | } |
6926 | |
6927 | inline bool Type::isHalfType() const { |
6928 | // FIXME: Should we allow complex __fp16? Probably not. |
6929 | return isSpecificBuiltinType(BuiltinType::Half); |
6930 | } |
6931 | |
6932 | inline bool Type::isFloat16Type() const { |
6933 | return isSpecificBuiltinType(BuiltinType::Float16); |
6934 | } |
6935 | |
6936 | inline bool Type::isBFloat16Type() const { |
6937 | return isSpecificBuiltinType(BuiltinType::BFloat16); |
6938 | } |
6939 | |
6940 | inline bool Type::isFloat128Type() const { |
6941 | return isSpecificBuiltinType(BuiltinType::Float128); |
6942 | } |
6943 | |
6944 | inline bool Type::isNullPtrType() const { |
6945 | return isSpecificBuiltinType(BuiltinType::NullPtr); |
6946 | } |
6947 | |
6948 | bool IsEnumDeclComplete(EnumDecl *); |
6949 | bool IsEnumDeclScoped(EnumDecl *); |
6950 | |
6951 | inline bool Type::isIntegerType() const { |
6952 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6953 | return BT->getKind() >= BuiltinType::Bool && |
6954 | BT->getKind() <= BuiltinType::Int128; |
6955 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6956 | // Incomplete enum types are not treated as integer types. |
6957 | // FIXME: In C++, enum types are never integer types. |
6958 | return IsEnumDeclComplete(ET->getDecl()) && |
6959 | !IsEnumDeclScoped(ET->getDecl()); |
6960 | } |
6961 | return isExtIntType(); |
6962 | } |
6963 | |
6964 | inline bool Type::isFixedPointType() const { |
6965 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6966 | return BT->getKind() >= BuiltinType::ShortAccum && |
6967 | BT->getKind() <= BuiltinType::SatULongFract; |
6968 | } |
6969 | return false; |
6970 | } |
6971 | |
6972 | inline bool Type::isFixedPointOrIntegerType() const { |
6973 | return isFixedPointType() || isIntegerType(); |
6974 | } |
6975 | |
6976 | inline bool Type::isSaturatedFixedPointType() const { |
6977 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6978 | return BT->getKind() >= BuiltinType::SatShortAccum && |
6979 | BT->getKind() <= BuiltinType::SatULongFract; |
6980 | } |
6981 | return false; |
6982 | } |
6983 | |
6984 | inline bool Type::isUnsaturatedFixedPointType() const { |
6985 | return isFixedPointType() && !isSaturatedFixedPointType(); |
6986 | } |
6987 | |
6988 | inline bool Type::isSignedFixedPointType() const { |
6989 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6990 | return ((BT->getKind() >= BuiltinType::ShortAccum && |
6991 | BT->getKind() <= BuiltinType::LongAccum) || |
6992 | (BT->getKind() >= BuiltinType::ShortFract && |
6993 | BT->getKind() <= BuiltinType::LongFract) || |
6994 | (BT->getKind() >= BuiltinType::SatShortAccum && |
6995 | BT->getKind() <= BuiltinType::SatLongAccum) || |
6996 | (BT->getKind() >= BuiltinType::SatShortFract && |
6997 | BT->getKind() <= BuiltinType::SatLongFract)); |
6998 | } |
6999 | return false; |
7000 | } |
7001 | |
7002 | inline bool Type::isUnsignedFixedPointType() const { |
7003 | return isFixedPointType() && !isSignedFixedPointType(); |
7004 | } |
7005 | |
7006 | inline bool Type::isScalarType() const { |
7007 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7008 | return BT->getKind() > BuiltinType::Void && |
7009 | BT->getKind() <= BuiltinType::NullPtr; |
7010 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
7011 | // Enums are scalar types, but only if they are defined. Incomplete enums |
7012 | // are not treated as scalar types. |
7013 | return IsEnumDeclComplete(ET->getDecl()); |
7014 | return isa<PointerType>(CanonicalType) || |
7015 | isa<BlockPointerType>(CanonicalType) || |
7016 | isa<MemberPointerType>(CanonicalType) || |
7017 | isa<ComplexType>(CanonicalType) || |
7018 | isa<ObjCObjectPointerType>(CanonicalType) || |
7019 | isExtIntType(); |
7020 | } |
7021 | |
7022 | inline bool Type::isIntegralOrEnumerationType() const { |
7023 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7024 | return BT->getKind() >= BuiltinType::Bool && |
7025 | BT->getKind() <= BuiltinType::Int128; |
7026 | |
7027 | // Check for a complete enum type; incomplete enum types are not properly an |
7028 | // enumeration type in the sense required here. |
7029 | if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) |
7030 | return IsEnumDeclComplete(ET->getDecl()); |
7031 | |
7032 | return isExtIntType(); |
7033 | } |
7034 | |
7035 | inline bool Type::isBooleanType() const { |
7036 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7037 | return BT->getKind() == BuiltinType::Bool; |
7038 | return false; |
7039 | } |
7040 | |
7041 | inline bool Type::isUndeducedType() const { |
7042 | auto *DT = getContainedDeducedType(); |
7043 | return DT && !DT->isDeduced(); |
7044 | } |
7045 | |
7046 | /// Determines whether this is a type for which one can define |
7047 | /// an overloaded operator. |
7048 | inline bool Type::isOverloadableType() const { |
7049 | return isDependentType() || isRecordType() || isEnumeralType(); |
7050 | } |
7051 | |
7052 | /// Determines whether this type can decay to a pointer type. |
7053 | inline bool Type::canDecayToPointerType() const { |
7054 | return isFunctionType() || isArrayType(); |
7055 | } |
7056 | |
7057 | inline bool Type::hasPointerRepresentation() const { |
7058 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
7059 | isObjCObjectPointerType() || isNullPtrType()); |
7060 | } |
7061 | |
7062 | inline bool Type::hasObjCPointerRepresentation() const { |
7063 | return isObjCObjectPointerType(); |
7064 | } |
7065 | |
7066 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
7067 | const Type *type = this; |
7068 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
7069 | type = arrayType->getElementType().getTypePtr(); |
7070 | return type; |
7071 | } |
7072 | |
7073 | inline const Type *Type::getPointeeOrArrayElementType() const { |
7074 | const Type *type = this; |
7075 | if (type->isAnyPointerType()) |
7076 | return type->getPointeeType().getTypePtr(); |
7077 | else if (type->isArrayType()) |
7078 | return type->getBaseElementTypeUnsafe(); |
7079 | return type; |
7080 | } |
7081 | /// Insertion operator for partial diagnostics. This allows sending adress |
7082 | /// spaces into a diagnostic with <<. |
7083 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7084 | LangAS AS) { |
7085 | PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), |
7086 | DiagnosticsEngine::ArgumentKind::ak_addrspace); |
7087 | return PD; |
7088 | } |
7089 | |
7090 | /// Insertion operator for partial diagnostics. This allows sending Qualifiers |
7091 | /// into a diagnostic with <<. |
7092 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7093 | Qualifiers Q) { |
7094 | PD.AddTaggedVal(Q.getAsOpaqueValue(), |
7095 | DiagnosticsEngine::ArgumentKind::ak_qual); |
7096 | return PD; |
7097 | } |
7098 | |
7099 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
7100 | /// into a diagnostic with <<. |
7101 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7102 | QualType T) { |
7103 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
7104 | DiagnosticsEngine::ak_qualtype); |
7105 | return PD; |
7106 | } |
7107 | |
7108 | // Helper class template that is used by Type::getAs to ensure that one does |
7109 | // not try to look through a qualified type to get to an array type. |
7110 | template <typename T> |
7111 | using TypeIsArrayType = |
7112 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
7113 | std::is_base_of<ArrayType, T>::value>; |
7114 | |
7115 | // Member-template getAs<specific type>'. |
7116 | template <typename T> const T *Type::getAs() const { |
7117 | static_assert(!TypeIsArrayType<T>::value, |
7118 | "ArrayType cannot be used with getAs!"); |
7119 | |
7120 | // If this is directly a T type, return it. |
7121 | if (const auto *Ty = dyn_cast<T>(this)) |
7122 | return Ty; |
7123 | |
7124 | // If the canonical form of this type isn't the right kind, reject it. |
7125 | if (!isa<T>(CanonicalType)) |
7126 | return nullptr; |
7127 | |
7128 | // If this is a typedef for the type, strip the typedef off without |
7129 | // losing all typedef information. |
7130 | return cast<T>(getUnqualifiedDesugaredType()); |
7131 | } |
7132 | |
7133 | template <typename T> const T *Type::getAsAdjusted() const { |
7134 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
7135 | |
7136 | // If this is directly a T type, return it. |
7137 | if (const auto *Ty = dyn_cast<T>(this)) |
7138 | return Ty; |
7139 | |
7140 | // If the canonical form of this type isn't the right kind, reject it. |
7141 | if (!isa<T>(CanonicalType)) |
7142 | return nullptr; |
7143 | |
7144 | // Strip off type adjustments that do not modify the underlying nature of the |
7145 | // type. |
7146 | const Type *Ty = this; |
7147 | while (Ty) { |
7148 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
7149 | Ty = A->getModifiedType().getTypePtr(); |
7150 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
7151 | Ty = E->desugar().getTypePtr(); |
7152 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
7153 | Ty = P->desugar().getTypePtr(); |
7154 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
7155 | Ty = A->desugar().getTypePtr(); |
7156 | else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) |
7157 | Ty = M->desugar().getTypePtr(); |
7158 | else |
7159 | break; |
7160 | } |
7161 | |
7162 | // Just because the canonical type is correct does not mean we can use cast<>, |
7163 | // since we may not have stripped off all the sugar down to the base type. |
7164 | return dyn_cast<T>(Ty); |
7165 | } |
7166 | |
7167 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
7168 | // If this is directly an array type, return it. |
7169 | if (const auto *arr = dyn_cast<ArrayType>(this)) |
7170 | return arr; |
7171 | |
7172 | // If the canonical form of this type isn't the right kind, reject it. |
7173 | if (!isa<ArrayType>(CanonicalType)) |
7174 | return nullptr; |
7175 | |
7176 | // If this is a typedef for the type, strip the typedef off without |
7177 | // losing all typedef information. |
7178 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7179 | } |
7180 | |
7181 | template <typename T> const T *Type::castAs() const { |
7182 | static_assert(!TypeIsArrayType<T>::value, |
7183 | "ArrayType cannot be used with castAs!"); |
7184 | |
7185 | if (const auto *ty = dyn_cast<T>(this)) return ty; |
7186 | assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 7186, __PRETTY_FUNCTION__)); |
7187 | return cast<T>(getUnqualifiedDesugaredType()); |
7188 | } |
7189 | |
7190 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
7191 | assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 7191, __PRETTY_FUNCTION__)); |
7192 | if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; |
7193 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7194 | } |
7195 | |
7196 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
7197 | QualType CanonicalPtr) |
7198 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
7199 | #ifndef NDEBUG |
7200 | QualType Adjusted = getAdjustedType(); |
7201 | (void)AttributedType::stripOuterNullability(Adjusted); |
7202 | assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-12~++20201207111113+1df0677e6ac/clang/include/clang/AST/Type.h" , 7202, __PRETTY_FUNCTION__)); |
7203 | #endif |
7204 | } |
7205 | |
7206 | QualType DecayedType::getPointeeType() const { |
7207 | QualType Decayed = getDecayedType(); |
7208 | (void)AttributedType::stripOuterNullability(Decayed); |
7209 | return cast<PointerType>(Decayed)->getPointeeType(); |
7210 | } |
7211 | |
7212 | // Get the decimal string representation of a fixed point type, represented |
7213 | // as a scaled integer. |
7214 | // TODO: At some point, we should change the arguments to instead just accept an |
7215 | // APFixedPoint instead of APSInt and scale. |
7216 | void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, |
7217 | unsigned Scale); |
7218 | |
7219 | } // namespace clang |
7220 | |
7221 | #endif // LLVM_CLANG_AST_TYPE_H |