File: | build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema/SemaType.cpp |
Warning: | line 952, column 13 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file implements type-related semantic analysis. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "TypeLocBuilder.h" | |||
14 | #include "clang/AST/ASTConsumer.h" | |||
15 | #include "clang/AST/ASTContext.h" | |||
16 | #include "clang/AST/ASTMutationListener.h" | |||
17 | #include "clang/AST/ASTStructuralEquivalence.h" | |||
18 | #include "clang/AST/CXXInheritance.h" | |||
19 | #include "clang/AST/DeclObjC.h" | |||
20 | #include "clang/AST/DeclTemplate.h" | |||
21 | #include "clang/AST/Expr.h" | |||
22 | #include "clang/AST/Type.h" | |||
23 | #include "clang/AST/TypeLoc.h" | |||
24 | #include "clang/AST/TypeLocVisitor.h" | |||
25 | #include "clang/Basic/PartialDiagnostic.h" | |||
26 | #include "clang/Basic/SourceLocation.h" | |||
27 | #include "clang/Basic/Specifiers.h" | |||
28 | #include "clang/Basic/TargetInfo.h" | |||
29 | #include "clang/Lex/Preprocessor.h" | |||
30 | #include "clang/Sema/DeclSpec.h" | |||
31 | #include "clang/Sema/DelayedDiagnostic.h" | |||
32 | #include "clang/Sema/Lookup.h" | |||
33 | #include "clang/Sema/ParsedTemplate.h" | |||
34 | #include "clang/Sema/ScopeInfo.h" | |||
35 | #include "clang/Sema/SemaInternal.h" | |||
36 | #include "clang/Sema/Template.h" | |||
37 | #include "clang/Sema/TemplateInstCallback.h" | |||
38 | #include "llvm/ADT/ArrayRef.h" | |||
39 | #include "llvm/ADT/SmallPtrSet.h" | |||
40 | #include "llvm/ADT/SmallString.h" | |||
41 | #include "llvm/IR/DerivedTypes.h" | |||
42 | #include "llvm/Support/ErrorHandling.h" | |||
43 | #include <bitset> | |||
44 | ||||
45 | using namespace clang; | |||
46 | ||||
47 | enum TypeDiagSelector { | |||
48 | TDS_Function, | |||
49 | TDS_Pointer, | |||
50 | TDS_ObjCObjOrBlock | |||
51 | }; | |||
52 | ||||
53 | /// isOmittedBlockReturnType - Return true if this declarator is missing a | |||
54 | /// return type because this is a omitted return type on a block literal. | |||
55 | static bool isOmittedBlockReturnType(const Declarator &D) { | |||
56 | if (D.getContext() != DeclaratorContext::BlockLiteral || | |||
57 | D.getDeclSpec().hasTypeSpecifier()) | |||
58 | return false; | |||
59 | ||||
60 | if (D.getNumTypeObjects() == 0) | |||
61 | return true; // ^{ ... } | |||
62 | ||||
63 | if (D.getNumTypeObjects() == 1 && | |||
64 | D.getTypeObject(0).Kind == DeclaratorChunk::Function) | |||
65 | return true; // ^(int X, float Y) { ... } | |||
66 | ||||
67 | return false; | |||
68 | } | |||
69 | ||||
70 | /// diagnoseBadTypeAttribute - Diagnoses a type attribute which | |||
71 | /// doesn't apply to the given type. | |||
72 | static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, | |||
73 | QualType type) { | |||
74 | TypeDiagSelector WhichType; | |||
75 | bool useExpansionLoc = true; | |||
76 | switch (attr.getKind()) { | |||
77 | case ParsedAttr::AT_ObjCGC: | |||
78 | WhichType = TDS_Pointer; | |||
79 | break; | |||
80 | case ParsedAttr::AT_ObjCOwnership: | |||
81 | WhichType = TDS_ObjCObjOrBlock; | |||
82 | break; | |||
83 | default: | |||
84 | // Assume everything else was a function attribute. | |||
85 | WhichType = TDS_Function; | |||
86 | useExpansionLoc = false; | |||
87 | break; | |||
88 | } | |||
89 | ||||
90 | SourceLocation loc = attr.getLoc(); | |||
91 | StringRef name = attr.getAttrName()->getName(); | |||
92 | ||||
93 | // The GC attributes are usually written with macros; special-case them. | |||
94 | IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident | |||
95 | : nullptr; | |||
96 | if (useExpansionLoc && loc.isMacroID() && II) { | |||
97 | if (II->isStr("strong")) { | |||
98 | if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; | |||
99 | } else if (II->isStr("weak")) { | |||
100 | if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; | |||
101 | } | |||
102 | } | |||
103 | ||||
104 | S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType | |||
105 | << type; | |||
106 | } | |||
107 | ||||
108 | // objc_gc applies to Objective-C pointers or, otherwise, to the | |||
109 | // smallest available pointer type (i.e. 'void*' in 'void**'). | |||
110 | #define OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership \ | |||
111 | case ParsedAttr::AT_ObjCGC: \ | |||
112 | case ParsedAttr::AT_ObjCOwnership | |||
113 | ||||
114 | // Calling convention attributes. | |||
115 | #define CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_AArch64SVEPcs : case ParsedAttr::AT_AMDGPUKernelCall: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll \ | |||
116 | case ParsedAttr::AT_CDecl: \ | |||
117 | case ParsedAttr::AT_FastCall: \ | |||
118 | case ParsedAttr::AT_StdCall: \ | |||
119 | case ParsedAttr::AT_ThisCall: \ | |||
120 | case ParsedAttr::AT_RegCall: \ | |||
121 | case ParsedAttr::AT_Pascal: \ | |||
122 | case ParsedAttr::AT_SwiftCall: \ | |||
123 | case ParsedAttr::AT_SwiftAsyncCall: \ | |||
124 | case ParsedAttr::AT_VectorCall: \ | |||
125 | case ParsedAttr::AT_AArch64VectorPcs: \ | |||
126 | case ParsedAttr::AT_AArch64SVEPcs: \ | |||
127 | case ParsedAttr::AT_AMDGPUKernelCall: \ | |||
128 | case ParsedAttr::AT_MSABI: \ | |||
129 | case ParsedAttr::AT_SysVABI: \ | |||
130 | case ParsedAttr::AT_Pcs: \ | |||
131 | case ParsedAttr::AT_IntelOclBicc: \ | |||
132 | case ParsedAttr::AT_PreserveMost: \ | |||
133 | case ParsedAttr::AT_PreserveAll | |||
134 | ||||
135 | // Function type attributes. | |||
136 | #define FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_SwiftAsyncCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_AArch64SVEPcs: case ParsedAttr::AT_AMDGPUKernelCall : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll \ | |||
137 | case ParsedAttr::AT_NSReturnsRetained: \ | |||
138 | case ParsedAttr::AT_NoReturn: \ | |||
139 | case ParsedAttr::AT_Regparm: \ | |||
140 | case ParsedAttr::AT_CmseNSCall: \ | |||
141 | case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ | |||
142 | case ParsedAttr::AT_AnyX86NoCfCheck: \ | |||
143 | CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_AArch64SVEPcs : case ParsedAttr::AT_AMDGPUKernelCall: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll | |||
144 | ||||
145 | // Microsoft-specific type qualifiers. | |||
146 | #define MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr \ | |||
147 | case ParsedAttr::AT_Ptr32: \ | |||
148 | case ParsedAttr::AT_Ptr64: \ | |||
149 | case ParsedAttr::AT_SPtr: \ | |||
150 | case ParsedAttr::AT_UPtr | |||
151 | ||||
152 | // Nullability qualifiers. | |||
153 | #define NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified \ | |||
154 | case ParsedAttr::AT_TypeNonNull: \ | |||
155 | case ParsedAttr::AT_TypeNullable: \ | |||
156 | case ParsedAttr::AT_TypeNullableResult: \ | |||
157 | case ParsedAttr::AT_TypeNullUnspecified | |||
158 | ||||
159 | namespace { | |||
160 | /// An object which stores processing state for the entire | |||
161 | /// GetTypeForDeclarator process. | |||
162 | class TypeProcessingState { | |||
163 | Sema &sema; | |||
164 | ||||
165 | /// The declarator being processed. | |||
166 | Declarator &declarator; | |||
167 | ||||
168 | /// The index of the declarator chunk we're currently processing. | |||
169 | /// May be the total number of valid chunks, indicating the | |||
170 | /// DeclSpec. | |||
171 | unsigned chunkIndex; | |||
172 | ||||
173 | /// The original set of attributes on the DeclSpec. | |||
174 | SmallVector<ParsedAttr *, 2> savedAttrs; | |||
175 | ||||
176 | /// A list of attributes to diagnose the uselessness of when the | |||
177 | /// processing is complete. | |||
178 | SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; | |||
179 | ||||
180 | /// Attributes corresponding to AttributedTypeLocs that we have not yet | |||
181 | /// populated. | |||
182 | // FIXME: The two-phase mechanism by which we construct Types and fill | |||
183 | // their TypeLocs makes it hard to correctly assign these. We keep the | |||
184 | // attributes in creation order as an attempt to make them line up | |||
185 | // properly. | |||
186 | using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; | |||
187 | SmallVector<TypeAttrPair, 8> AttrsForTypes; | |||
188 | bool AttrsForTypesSorted = true; | |||
189 | ||||
190 | /// MacroQualifiedTypes mapping to macro expansion locations that will be | |||
191 | /// stored in a MacroQualifiedTypeLoc. | |||
192 | llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros; | |||
193 | ||||
194 | /// Flag to indicate we parsed a noderef attribute. This is used for | |||
195 | /// validating that noderef was used on a pointer or array. | |||
196 | bool parsedNoDeref; | |||
197 | ||||
198 | public: | |||
199 | TypeProcessingState(Sema &sema, Declarator &declarator) | |||
200 | : sema(sema), declarator(declarator), | |||
201 | chunkIndex(declarator.getNumTypeObjects()), 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())(static_cast <bool> (idx <= declarator.getNumTypeObjects ()) ? void (0) : __assert_fail ("idx <= declarator.getNumTypeObjects()" , "clang/lib/Sema/SemaType.cpp", 220, __extension__ __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 (!savedAttrs.empty()) | |||
234 | return; | |||
235 | ||||
236 | DeclSpec &spec = getMutableDeclSpec(); | |||
237 | llvm::append_range(savedAttrs, | |||
238 | llvm::make_pointer_range(spec.getAttributes())); | |||
239 | } | |||
240 | ||||
241 | /// Record that we had nowhere to put the given type attribute. | |||
242 | /// We will diagnose such attributes later. | |||
243 | void addIgnoredTypeAttr(ParsedAttr &attr) { | |||
244 | ignoredTypeAttrs.push_back(&attr); | |||
245 | } | |||
246 | ||||
247 | /// Diagnose all the ignored type attributes, given that the | |||
248 | /// declarator worked out to the given type. | |||
249 | void diagnoseIgnoredTypeAttrs(QualType type) const { | |||
250 | for (auto *Attr : ignoredTypeAttrs) | |||
251 | diagnoseBadTypeAttribute(getSema(), *Attr, type); | |||
252 | } | |||
253 | ||||
254 | /// Get an attributed type for the given attribute, and remember the Attr | |||
255 | /// object so that we can attach it to the AttributedTypeLoc. | |||
256 | QualType getAttributedType(Attr *A, QualType ModifiedType, | |||
257 | QualType EquivType) { | |||
258 | QualType T = | |||
259 | sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType); | |||
260 | AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); | |||
261 | AttrsForTypesSorted = false; | |||
262 | return T; | |||
263 | } | |||
264 | ||||
265 | /// Get a BTFTagAttributed type for the btf_type_tag attribute. | |||
266 | QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, | |||
267 | QualType WrappedType) { | |||
268 | return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType); | |||
269 | } | |||
270 | ||||
271 | /// Completely replace the \c auto in \p TypeWithAuto by | |||
272 | /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if | |||
273 | /// necessary. | |||
274 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { | |||
275 | QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); | |||
276 | if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { | |||
277 | // Attributed type still should be an attributed type after replacement. | |||
278 | auto *NewAttrTy = cast<AttributedType>(T.getTypePtr()); | |||
279 | for (TypeAttrPair &A : AttrsForTypes) { | |||
280 | if (A.first == AttrTy) | |||
281 | A.first = NewAttrTy; | |||
282 | } | |||
283 | AttrsForTypesSorted = false; | |||
284 | } | |||
285 | return T; | |||
286 | } | |||
287 | ||||
288 | /// Extract and remove the Attr* for a given attributed type. | |||
289 | const Attr *takeAttrForAttributedType(const AttributedType *AT) { | |||
290 | if (!AttrsForTypesSorted) { | |||
291 | llvm::stable_sort(AttrsForTypes, llvm::less_first()); | |||
292 | AttrsForTypesSorted = true; | |||
293 | } | |||
294 | ||||
295 | // FIXME: This is quadratic if we have lots of reuses of the same | |||
296 | // attributed type. | |||
297 | for (auto It = std::partition_point( | |||
298 | AttrsForTypes.begin(), AttrsForTypes.end(), | |||
299 | [=](const TypeAttrPair &A) { return A.first < AT; }); | |||
300 | It != AttrsForTypes.end() && It->first == AT; ++It) { | |||
301 | if (It->second) { | |||
302 | const Attr *Result = It->second; | |||
303 | It->second = nullptr; | |||
304 | return Result; | |||
305 | } | |||
306 | } | |||
307 | ||||
308 | llvm_unreachable("no Attr* for AttributedType*")::llvm::llvm_unreachable_internal("no Attr* for AttributedType*" , "clang/lib/Sema/SemaType.cpp", 308); | |||
309 | } | |||
310 | ||||
311 | SourceLocation | |||
312 | getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const { | |||
313 | auto FoundLoc = LocsForMacros.find(MQT); | |||
314 | assert(FoundLoc != LocsForMacros.end() &&(static_cast <bool> (FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType" ) ? void (0) : __assert_fail ("FoundLoc != LocsForMacros.end() && \"Unable to find macro expansion location for MacroQualifedType\"" , "clang/lib/Sema/SemaType.cpp", 315, __extension__ __PRETTY_FUNCTION__ )) | |||
315 | "Unable to find macro expansion location for MacroQualifedType")(static_cast <bool> (FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType" ) ? void (0) : __assert_fail ("FoundLoc != LocsForMacros.end() && \"Unable to find macro expansion location for MacroQualifedType\"" , "clang/lib/Sema/SemaType.cpp", 315, __extension__ __PRETTY_FUNCTION__ )); | |||
316 | return FoundLoc->second; | |||
317 | } | |||
318 | ||||
319 | void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT, | |||
320 | SourceLocation Loc) { | |||
321 | LocsForMacros[MQT] = Loc; | |||
322 | } | |||
323 | ||||
324 | void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } | |||
325 | ||||
326 | bool didParseNoDeref() const { return parsedNoDeref; } | |||
327 | ||||
328 | ~TypeProcessingState() { | |||
329 | if (savedAttrs.empty()) | |||
330 | return; | |||
331 | ||||
332 | getMutableDeclSpec().getAttributes().clearListOnly(); | |||
333 | for (ParsedAttr *AL : savedAttrs) | |||
334 | getMutableDeclSpec().getAttributes().addAtEnd(AL); | |||
335 | } | |||
336 | ||||
337 | private: | |||
338 | DeclSpec &getMutableDeclSpec() const { | |||
339 | return const_cast<DeclSpec&>(declarator.getDeclSpec()); | |||
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, | |||
363 | const ParsedAttributesView &attrs); | |||
364 | ||||
365 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
366 | QualType &type); | |||
367 | ||||
368 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, | |||
369 | ParsedAttr &attr, QualType &type); | |||
370 | ||||
371 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
372 | QualType &type); | |||
373 | ||||
374 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | |||
375 | ParsedAttr &attr, QualType &type); | |||
376 | ||||
377 | static bool handleObjCPointerTypeAttr(TypeProcessingState &state, | |||
378 | ParsedAttr &attr, QualType &type) { | |||
379 | if (attr.getKind() == ParsedAttr::AT_ObjCGC) | |||
380 | return handleObjCGCTypeAttr(state, attr, type); | |||
381 | assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership)(static_cast <bool> (attr.getKind() == ParsedAttr::AT_ObjCOwnership ) ? void (0) : __assert_fail ("attr.getKind() == ParsedAttr::AT_ObjCOwnership" , "clang/lib/Sema/SemaType.cpp", 381, __extension__ __PRETTY_FUNCTION__ )); | |||
382 | return handleObjCOwnershipTypeAttr(state, attr, type); | |||
383 | } | |||
384 | ||||
385 | /// Given the index of a declarator chunk, check whether that chunk | |||
386 | /// directly specifies the return type of a function and, if so, find | |||
387 | /// an appropriate place for it. | |||
388 | /// | |||
389 | /// \param i - a notional index which the search will start | |||
390 | /// immediately inside | |||
391 | /// | |||
392 | /// \param onlyBlockPointers Whether we should only look into block | |||
393 | /// pointer types (vs. all pointer types). | |||
394 | static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, | |||
395 | unsigned i, | |||
396 | bool onlyBlockPointers) { | |||
397 | assert(i <= declarator.getNumTypeObjects())(static_cast <bool> (i <= declarator.getNumTypeObjects ()) ? void (0) : __assert_fail ("i <= declarator.getNumTypeObjects()" , "clang/lib/Sema/SemaType.cpp", 397, __extension__ __PRETTY_FUNCTION__ )); | |||
398 | ||||
399 | DeclaratorChunk *result = nullptr; | |||
400 | ||||
401 | // First, look inwards past parens for a function declarator. | |||
402 | for (; i != 0; --i) { | |||
403 | DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); | |||
404 | switch (fnChunk.Kind) { | |||
405 | case DeclaratorChunk::Paren: | |||
406 | continue; | |||
407 | ||||
408 | // If we find anything except a function, bail out. | |||
409 | case DeclaratorChunk::Pointer: | |||
410 | case DeclaratorChunk::BlockPointer: | |||
411 | case DeclaratorChunk::Array: | |||
412 | case DeclaratorChunk::Reference: | |||
413 | case DeclaratorChunk::MemberPointer: | |||
414 | case DeclaratorChunk::Pipe: | |||
415 | return result; | |||
416 | ||||
417 | // If we do find a function declarator, scan inwards from that, | |||
418 | // looking for a (block-)pointer declarator. | |||
419 | case DeclaratorChunk::Function: | |||
420 | for (--i; i != 0; --i) { | |||
421 | DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); | |||
422 | switch (ptrChunk.Kind) { | |||
423 | case DeclaratorChunk::Paren: | |||
424 | case DeclaratorChunk::Array: | |||
425 | case DeclaratorChunk::Function: | |||
426 | case DeclaratorChunk::Reference: | |||
427 | case DeclaratorChunk::Pipe: | |||
428 | continue; | |||
429 | ||||
430 | case DeclaratorChunk::MemberPointer: | |||
431 | case DeclaratorChunk::Pointer: | |||
432 | if (onlyBlockPointers) | |||
433 | continue; | |||
434 | ||||
435 | [[fallthrough]]; | |||
436 | ||||
437 | case DeclaratorChunk::BlockPointer: | |||
438 | result = &ptrChunk; | |||
439 | goto continue_outer; | |||
440 | } | |||
441 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "clang/lib/Sema/SemaType.cpp", 441); | |||
442 | } | |||
443 | ||||
444 | // If we run out of declarators doing that, we're done. | |||
445 | return result; | |||
446 | } | |||
447 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "clang/lib/Sema/SemaType.cpp", 447); | |||
448 | ||||
449 | // Okay, reconsider from our new point. | |||
450 | continue_outer: ; | |||
451 | } | |||
452 | ||||
453 | // Ran out of chunks, bail out. | |||
454 | return result; | |||
455 | } | |||
456 | ||||
457 | /// Given that an objc_gc attribute was written somewhere on a | |||
458 | /// declaration *other* than on the declarator itself (for which, use | |||
459 | /// distributeObjCPointerTypeAttrFromDeclarator), and given that it | |||
460 | /// didn't apply in whatever position it was written in, try to move | |||
461 | /// it to a more appropriate position. | |||
462 | static void distributeObjCPointerTypeAttr(TypeProcessingState &state, | |||
463 | ParsedAttr &attr, QualType type) { | |||
464 | Declarator &declarator = state.getDeclarator(); | |||
465 | ||||
466 | // Move it to the outermost normal or block pointer declarator. | |||
467 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
468 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
469 | switch (chunk.Kind) { | |||
470 | case DeclaratorChunk::Pointer: | |||
471 | case DeclaratorChunk::BlockPointer: { | |||
472 | // But don't move an ARC ownership attribute to the return type | |||
473 | // of a block. | |||
474 | DeclaratorChunk *destChunk = nullptr; | |||
475 | if (state.isProcessingDeclSpec() && | |||
476 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) | |||
477 | destChunk = maybeMovePastReturnType(declarator, i - 1, | |||
478 | /*onlyBlockPointers=*/true); | |||
479 | if (!destChunk) destChunk = &chunk; | |||
480 | ||||
481 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
482 | destChunk->getAttrs()); | |||
483 | return; | |||
484 | } | |||
485 | ||||
486 | case DeclaratorChunk::Paren: | |||
487 | case DeclaratorChunk::Array: | |||
488 | continue; | |||
489 | ||||
490 | // We may be starting at the return type of a block. | |||
491 | case DeclaratorChunk::Function: | |||
492 | if (state.isProcessingDeclSpec() && | |||
493 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
494 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | |||
495 | declarator, i, | |||
496 | /*onlyBlockPointers=*/true)) { | |||
497 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
498 | dest->getAttrs()); | |||
499 | return; | |||
500 | } | |||
501 | } | |||
502 | goto error; | |||
503 | ||||
504 | // Don't walk through these. | |||
505 | case DeclaratorChunk::Reference: | |||
506 | case DeclaratorChunk::MemberPointer: | |||
507 | case DeclaratorChunk::Pipe: | |||
508 | goto error; | |||
509 | } | |||
510 | } | |||
511 | error: | |||
512 | ||||
513 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
514 | } | |||
515 | ||||
516 | /// Distribute an objc_gc type attribute that was written on the | |||
517 | /// declarator. | |||
518 | static void distributeObjCPointerTypeAttrFromDeclarator( | |||
519 | TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { | |||
520 | Declarator &declarator = state.getDeclarator(); | |||
521 | ||||
522 | // objc_gc goes on the innermost pointer to something that's not a | |||
523 | // pointer. | |||
524 | unsigned innermost = -1U; | |||
525 | bool considerDeclSpec = true; | |||
526 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
527 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
528 | switch (chunk.Kind) { | |||
529 | case DeclaratorChunk::Pointer: | |||
530 | case DeclaratorChunk::BlockPointer: | |||
531 | innermost = i; | |||
532 | continue; | |||
533 | ||||
534 | case DeclaratorChunk::Reference: | |||
535 | case DeclaratorChunk::MemberPointer: | |||
536 | case DeclaratorChunk::Paren: | |||
537 | case DeclaratorChunk::Array: | |||
538 | case DeclaratorChunk::Pipe: | |||
539 | continue; | |||
540 | ||||
541 | case DeclaratorChunk::Function: | |||
542 | considerDeclSpec = false; | |||
543 | goto done; | |||
544 | } | |||
545 | } | |||
546 | done: | |||
547 | ||||
548 | // That might actually be the decl spec if we weren't blocked by | |||
549 | // anything in the declarator. | |||
550 | if (considerDeclSpec) { | |||
551 | if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { | |||
552 | // Splice the attribute into the decl spec. Prevents the | |||
553 | // attribute from being applied multiple times and gives | |||
554 | // the source-location-filler something to work with. | |||
555 | state.saveDeclSpecAttrs(); | |||
556 | declarator.getMutableDeclSpec().getAttributes().takeOneFrom( | |||
557 | declarator.getAttributes(), &attr); | |||
558 | return; | |||
559 | } | |||
560 | } | |||
561 | ||||
562 | // Otherwise, if we found an appropriate chunk, splice the attribute | |||
563 | // into it. | |||
564 | if (innermost != -1U) { | |||
565 | moveAttrFromListToList(attr, declarator.getAttributes(), | |||
566 | declarator.getTypeObject(innermost).getAttrs()); | |||
567 | return; | |||
568 | } | |||
569 | ||||
570 | // Otherwise, diagnose when we're done building the type. | |||
571 | declarator.getAttributes().remove(&attr); | |||
572 | state.addIgnoredTypeAttr(attr); | |||
573 | } | |||
574 | ||||
575 | /// A function type attribute was written somewhere in a declaration | |||
576 | /// *other* than on the declarator itself or in the decl spec. Given | |||
577 | /// that it didn't apply in whatever position it was written in, try | |||
578 | /// to move it to a more appropriate position. | |||
579 | static void distributeFunctionTypeAttr(TypeProcessingState &state, | |||
580 | ParsedAttr &attr, QualType type) { | |||
581 | Declarator &declarator = state.getDeclarator(); | |||
582 | ||||
583 | // Try to push the attribute from the return type of a function to | |||
584 | // the function itself. | |||
585 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
586 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
587 | switch (chunk.Kind) { | |||
588 | case DeclaratorChunk::Function: | |||
589 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
590 | chunk.getAttrs()); | |||
591 | return; | |||
592 | ||||
593 | case DeclaratorChunk::Paren: | |||
594 | case DeclaratorChunk::Pointer: | |||
595 | case DeclaratorChunk::BlockPointer: | |||
596 | case DeclaratorChunk::Array: | |||
597 | case DeclaratorChunk::Reference: | |||
598 | case DeclaratorChunk::MemberPointer: | |||
599 | case DeclaratorChunk::Pipe: | |||
600 | continue; | |||
601 | } | |||
602 | } | |||
603 | ||||
604 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
605 | } | |||
606 | ||||
607 | /// Try to distribute a function type attribute to the innermost | |||
608 | /// function chunk or type. Returns true if the attribute was | |||
609 | /// distributed, false if no location was found. | |||
610 | static bool distributeFunctionTypeAttrToInnermost( | |||
611 | TypeProcessingState &state, ParsedAttr &attr, | |||
612 | ParsedAttributesView &attrList, QualType &declSpecType) { | |||
613 | Declarator &declarator = state.getDeclarator(); | |||
614 | ||||
615 | // Put it on the innermost function chunk, if there is one. | |||
616 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
617 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
618 | if (chunk.Kind != DeclaratorChunk::Function) continue; | |||
619 | ||||
620 | moveAttrFromListToList(attr, attrList, chunk.getAttrs()); | |||
621 | return true; | |||
622 | } | |||
623 | ||||
624 | return handleFunctionTypeAttr(state, attr, declSpecType); | |||
625 | } | |||
626 | ||||
627 | /// A function type attribute was written in the decl spec. Try to | |||
628 | /// apply it somewhere. | |||
629 | static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, | |||
630 | ParsedAttr &attr, | |||
631 | QualType &declSpecType) { | |||
632 | state.saveDeclSpecAttrs(); | |||
633 | ||||
634 | // Try to distribute to the innermost. | |||
635 | if (distributeFunctionTypeAttrToInnermost( | |||
636 | state, attr, state.getCurrentAttributes(), declSpecType)) | |||
637 | return; | |||
638 | ||||
639 | // If that failed, diagnose the bad attribute when the declarator is | |||
640 | // fully built. | |||
641 | state.addIgnoredTypeAttr(attr); | |||
642 | } | |||
643 | ||||
644 | /// A function type attribute was written on the declarator or declaration. | |||
645 | /// Try to apply it somewhere. | |||
646 | /// `Attrs` is the attribute list containing the declaration (either of the | |||
647 | /// declarator or the declaration). | |||
648 | static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, | |||
649 | ParsedAttr &attr, | |||
650 | QualType &declSpecType) { | |||
651 | Declarator &declarator = state.getDeclarator(); | |||
652 | ||||
653 | // Try to distribute to the innermost. | |||
654 | if (distributeFunctionTypeAttrToInnermost( | |||
655 | state, attr, declarator.getAttributes(), declSpecType)) | |||
656 | return; | |||
657 | ||||
658 | // If that failed, diagnose the bad attribute when the declarator is | |||
659 | // fully built. | |||
660 | declarator.getAttributes().remove(&attr); | |||
661 | state.addIgnoredTypeAttr(attr); | |||
662 | } | |||
663 | ||||
664 | /// Given that there are attributes written on the declarator or declaration | |||
665 | /// itself, try to distribute any type attributes to the appropriate | |||
666 | /// declarator chunk. | |||
667 | /// | |||
668 | /// These are attributes like the following: | |||
669 | /// int f ATTR; | |||
670 | /// int (f ATTR)(); | |||
671 | /// but not necessarily this: | |||
672 | /// int f() ATTR; | |||
673 | /// | |||
674 | /// `Attrs` is the attribute list containing the declaration (either of the | |||
675 | /// declarator or the declaration). | |||
676 | static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, | |||
677 | QualType &declSpecType) { | |||
678 | // The called functions in this loop actually remove things from the current | |||
679 | // list, so iterating over the existing list isn't possible. Instead, make a | |||
680 | // non-owning copy and iterate over that. | |||
681 | ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; | |||
682 | for (ParsedAttr &attr : AttrsCopy) { | |||
683 | // Do not distribute [[]] attributes. They have strict rules for what | |||
684 | // they appertain to. | |||
685 | if (attr.isStandardAttributeSyntax()) | |||
686 | continue; | |||
687 | ||||
688 | switch (attr.getKind()) { | |||
689 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: | |||
690 | distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); | |||
691 | break; | |||
692 | ||||
693 | FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_SwiftAsyncCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_AArch64SVEPcs: case ParsedAttr::AT_AMDGPUKernelCall : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll: | |||
694 | distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType); | |||
695 | break; | |||
696 | ||||
697 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: | |||
698 | // Microsoft type attributes cannot go after the declarator-id. | |||
699 | continue; | |||
700 | ||||
701 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified: | |||
702 | // Nullability specifiers cannot go after the declarator-id. | |||
703 | ||||
704 | // Objective-C __kindof does not get distributed. | |||
705 | case ParsedAttr::AT_ObjCKindOf: | |||
706 | continue; | |||
707 | ||||
708 | default: | |||
709 | break; | |||
710 | } | |||
711 | } | |||
712 | } | |||
713 | ||||
714 | /// Add a synthetic '()' to a block-literal declarator if it is | |||
715 | /// required, given the return type. | |||
716 | static void maybeSynthesizeBlockSignature(TypeProcessingState &state, | |||
717 | QualType declSpecType) { | |||
718 | Declarator &declarator = state.getDeclarator(); | |||
719 | ||||
720 | // First, check whether the declarator would produce a function, | |||
721 | // i.e. whether the innermost semantic chunk is a function. | |||
722 | if (declarator.isFunctionDeclarator()) { | |||
723 | // If so, make that declarator a prototyped declarator. | |||
724 | declarator.getFunctionTypeInfo().hasPrototype = true; | |||
725 | return; | |||
726 | } | |||
727 | ||||
728 | // If there are any type objects, the type as written won't name a | |||
729 | // function, regardless of the decl spec type. This is because a | |||
730 | // block signature declarator is always an abstract-declarator, and | |||
731 | // abstract-declarators can't just be parentheses chunks. Therefore | |||
732 | // we need to build a function chunk unless there are no type | |||
733 | // objects and the decl spec type is a function. | |||
734 | if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) | |||
735 | return; | |||
736 | ||||
737 | // Note that there *are* cases with invalid declarators where | |||
738 | // declarators consist solely of parentheses. In general, these | |||
739 | // occur only in failed efforts to make function declarators, so | |||
740 | // faking up the function chunk is still the right thing to do. | |||
741 | ||||
742 | // Otherwise, we need to fake up a function declarator. | |||
743 | SourceLocation loc = declarator.getBeginLoc(); | |||
744 | ||||
745 | // ...and *prepend* it to the declarator. | |||
746 | SourceLocation NoLoc; | |||
747 | declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( | |||
748 | /*HasProto=*/true, | |||
749 | /*IsAmbiguous=*/false, | |||
750 | /*LParenLoc=*/NoLoc, | |||
751 | /*ArgInfo=*/nullptr, | |||
752 | /*NumParams=*/0, | |||
753 | /*EllipsisLoc=*/NoLoc, | |||
754 | /*RParenLoc=*/NoLoc, | |||
755 | /*RefQualifierIsLvalueRef=*/true, | |||
756 | /*RefQualifierLoc=*/NoLoc, | |||
757 | /*MutableLoc=*/NoLoc, EST_None, | |||
758 | /*ESpecRange=*/SourceRange(), | |||
759 | /*Exceptions=*/nullptr, | |||
760 | /*ExceptionRanges=*/nullptr, | |||
761 | /*NumExceptions=*/0, | |||
762 | /*NoexceptExpr=*/nullptr, | |||
763 | /*ExceptionSpecTokens=*/nullptr, | |||
764 | /*DeclsInPrototype=*/None, loc, loc, declarator)); | |||
765 | ||||
766 | // For consistency, make sure the state still has us as processing | |||
767 | // the decl spec. | |||
768 | assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1)(static_cast <bool> (state.getCurrentChunkIndex() == declarator .getNumTypeObjects() - 1) ? void (0) : __assert_fail ("state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1" , "clang/lib/Sema/SemaType.cpp", 768, __extension__ __PRETTY_FUNCTION__ )); | |||
769 | state.setCurrentChunkIndex(declarator.getNumTypeObjects()); | |||
770 | } | |||
771 | ||||
772 | static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, | |||
773 | unsigned &TypeQuals, | |||
774 | QualType TypeSoFar, | |||
775 | unsigned RemoveTQs, | |||
776 | unsigned DiagID) { | |||
777 | // If this occurs outside a template instantiation, warn the user about | |||
778 | // it; they probably didn't mean to specify a redundant qualifier. | |||
779 | typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; | |||
780 | for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), | |||
781 | QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), | |||
782 | QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), | |||
783 | QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { | |||
784 | if (!(RemoveTQs & Qual.first)) | |||
785 | continue; | |||
786 | ||||
787 | if (!S.inTemplateInstantiation()) { | |||
788 | if (TypeQuals & Qual.first) | |||
789 | S.Diag(Qual.second, DiagID) | |||
790 | << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar | |||
791 | << FixItHint::CreateRemoval(Qual.second); | |||
792 | } | |||
793 | ||||
794 | TypeQuals &= ~Qual.first; | |||
795 | } | |||
796 | } | |||
797 | ||||
798 | /// Return true if this is omitted block return type. Also check type | |||
799 | /// attributes and type qualifiers when returning true. | |||
800 | static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, | |||
801 | QualType Result) { | |||
802 | if (!isOmittedBlockReturnType(declarator)) | |||
803 | return false; | |||
804 | ||||
805 | // Warn if we see type attributes for omitted return type on a block literal. | |||
806 | SmallVector<ParsedAttr *, 2> ToBeRemoved; | |||
807 | for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { | |||
808 | if (AL.isInvalid() || !AL.isTypeAttr()) | |||
809 | continue; | |||
810 | S.Diag(AL.getLoc(), | |||
811 | diag::warn_block_literal_attributes_on_omitted_return_type) | |||
812 | << AL; | |||
813 | ToBeRemoved.push_back(&AL); | |||
814 | } | |||
815 | // Remove bad attributes from the list. | |||
816 | for (ParsedAttr *AL : ToBeRemoved) | |||
817 | declarator.getMutableDeclSpec().getAttributes().remove(AL); | |||
818 | ||||
819 | // Warn if we see type qualifiers for omitted return type on a block literal. | |||
820 | const DeclSpec &DS = declarator.getDeclSpec(); | |||
821 | unsigned TypeQuals = DS.getTypeQualifiers(); | |||
822 | diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, | |||
823 | diag::warn_block_literal_qualifiers_on_omitted_return_type); | |||
824 | declarator.getMutableDeclSpec().ClearTypeQualifiers(); | |||
825 | ||||
826 | return true; | |||
827 | } | |||
828 | ||||
829 | /// Apply Objective-C type arguments to the given type. | |||
830 | static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, | |||
831 | ArrayRef<TypeSourceInfo *> typeArgs, | |||
832 | SourceRange typeArgsRange, | |||
833 | bool failOnError = false) { | |||
834 | // We can only apply type arguments to an Objective-C class type. | |||
835 | const auto *objcObjectType = type->getAs<ObjCObjectType>(); | |||
836 | if (!objcObjectType || !objcObjectType->getInterface()) { | |||
837 | S.Diag(loc, diag::err_objc_type_args_non_class) | |||
838 | << type | |||
839 | << typeArgsRange; | |||
840 | ||||
841 | if (failOnError) | |||
842 | return QualType(); | |||
843 | return type; | |||
844 | } | |||
845 | ||||
846 | // The class type must be parameterized. | |||
847 | ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); | |||
848 | ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); | |||
849 | if (!typeParams) { | |||
850 | S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) | |||
851 | << objcClass->getDeclName() | |||
852 | << FixItHint::CreateRemoval(typeArgsRange); | |||
853 | ||||
854 | if (failOnError) | |||
855 | return QualType(); | |||
856 | ||||
857 | return type; | |||
858 | } | |||
859 | ||||
860 | // The type must not already be specialized. | |||
861 | if (objcObjectType->isSpecialized()) { | |||
862 | S.Diag(loc, diag::err_objc_type_args_specialized_class) | |||
863 | << type | |||
864 | << FixItHint::CreateRemoval(typeArgsRange); | |||
865 | ||||
866 | if (failOnError) | |||
867 | return QualType(); | |||
868 | ||||
869 | return type; | |||
870 | } | |||
871 | ||||
872 | // Check the type arguments. | |||
873 | SmallVector<QualType, 4> finalTypeArgs; | |||
874 | unsigned numTypeParams = typeParams->size(); | |||
875 | bool anyPackExpansions = false; | |||
876 | for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { | |||
877 | TypeSourceInfo *typeArgInfo = typeArgs[i]; | |||
878 | QualType typeArg = typeArgInfo->getType(); | |||
879 | ||||
880 | // Type arguments cannot have explicit qualifiers or nullability. | |||
881 | // We ignore indirect sources of these, e.g. behind typedefs or | |||
882 | // template arguments. | |||
883 | if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { | |||
884 | bool diagnosed = false; | |||
885 | SourceRange rangeToRemove; | |||
886 | if (auto attr = qual.getAs<AttributedTypeLoc>()) { | |||
887 | rangeToRemove = attr.getLocalSourceRange(); | |||
888 | if (attr.getTypePtr()->getImmediateNullability()) { | |||
889 | typeArg = attr.getTypePtr()->getModifiedType(); | |||
890 | S.Diag(attr.getBeginLoc(), | |||
891 | diag::err_objc_type_arg_explicit_nullability) | |||
892 | << typeArg << FixItHint::CreateRemoval(rangeToRemove); | |||
893 | diagnosed = true; | |||
894 | } | |||
895 | } | |||
896 | ||||
897 | if (!diagnosed) { | |||
898 | S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) | |||
899 | << typeArg << typeArg.getQualifiers().getAsString() | |||
900 | << FixItHint::CreateRemoval(rangeToRemove); | |||
901 | } | |||
902 | } | |||
903 | ||||
904 | // Remove qualifiers even if they're non-local. | |||
905 | typeArg = typeArg.getUnqualifiedType(); | |||
906 | ||||
907 | finalTypeArgs.push_back(typeArg); | |||
908 | ||||
909 | if (typeArg->getAs<PackExpansionType>()) | |||
910 | anyPackExpansions = true; | |||
911 | ||||
912 | // Find the corresponding type parameter, if there is one. | |||
913 | ObjCTypeParamDecl *typeParam = nullptr; | |||
914 | if (!anyPackExpansions
| |||
915 | if (i < numTypeParams) { | |||
916 | typeParam = typeParams->begin()[i]; | |||
917 | } else { | |||
918 | // Too many arguments. | |||
919 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | |||
920 | << false | |||
921 | << objcClass->getDeclName() | |||
922 | << (unsigned)typeArgs.size() | |||
923 | << numTypeParams; | |||
924 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | |||
925 | << objcClass; | |||
926 | ||||
927 | if (failOnError) | |||
928 | return QualType(); | |||
929 | ||||
930 | return type; | |||
931 | } | |||
932 | } | |||
933 | ||||
934 | // Objective-C object pointer types must be substitutable for the bounds. | |||
935 | if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { | |||
936 | // If we don't have a type parameter to match against, assume | |||
937 | // everything is fine. There was a prior pack expansion that | |||
938 | // means we won't be able to match anything. | |||
939 | if (!typeParam) { | |||
940 | assert(anyPackExpansions && "Too many arguments?")(static_cast <bool> (anyPackExpansions && "Too many arguments?" ) ? void (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "clang/lib/Sema/SemaType.cpp", 940, __extension__ __PRETTY_FUNCTION__ )); | |||
941 | continue; | |||
942 | } | |||
943 | ||||
944 | // Retrieve the bound. | |||
945 | QualType bound = typeParam->getUnderlyingType(); | |||
946 | const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); | |||
947 | ||||
948 | // Determine whether the type argument is substitutable for the bound. | |||
949 | if (typeArgObjC->isObjCIdType()) { | |||
950 | // When the type argument is 'id', the only acceptable type | |||
951 | // parameter bound is 'id'. | |||
952 | if (boundObjC->isObjCIdType()) | |||
| ||||
953 | continue; | |||
954 | } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { | |||
955 | // Otherwise, we follow the assignability rules. | |||
956 | continue; | |||
957 | } | |||
958 | ||||
959 | // Diagnose the mismatch. | |||
960 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
961 | diag::err_objc_type_arg_does_not_match_bound) | |||
962 | << typeArg << bound << typeParam->getDeclName(); | |||
963 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | |||
964 | << typeParam->getDeclName(); | |||
965 | ||||
966 | if (failOnError) | |||
967 | return QualType(); | |||
968 | ||||
969 | return type; | |||
970 | } | |||
971 | ||||
972 | // Block pointer types are permitted for unqualified 'id' bounds. | |||
973 | if (typeArg->isBlockPointerType()) { | |||
974 | // If we don't have a type parameter to match against, assume | |||
975 | // everything is fine. There was a prior pack expansion that | |||
976 | // means we won't be able to match anything. | |||
977 | if (!typeParam) { | |||
978 | assert(anyPackExpansions && "Too many arguments?")(static_cast <bool> (anyPackExpansions && "Too many arguments?" ) ? void (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "clang/lib/Sema/SemaType.cpp", 978, __extension__ __PRETTY_FUNCTION__ )); | |||
979 | continue; | |||
980 | } | |||
981 | ||||
982 | // Retrieve the bound. | |||
983 | QualType bound = typeParam->getUnderlyingType(); | |||
984 | if (bound->isBlockCompatibleObjCPointerType(S.Context)) | |||
985 | continue; | |||
986 | ||||
987 | // Diagnose the mismatch. | |||
988 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
989 | diag::err_objc_type_arg_does_not_match_bound) | |||
990 | << typeArg << bound << typeParam->getDeclName(); | |||
991 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | |||
992 | << typeParam->getDeclName(); | |||
993 | ||||
994 | if (failOnError) | |||
995 | return QualType(); | |||
996 | ||||
997 | return type; | |||
998 | } | |||
999 | ||||
1000 | // Dependent types will be checked at instantiation time. | |||
1001 | if (typeArg->isDependentType()) { | |||
1002 | continue; | |||
1003 | } | |||
1004 | ||||
1005 | // Diagnose non-id-compatible type arguments. | |||
1006 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
1007 | diag::err_objc_type_arg_not_id_compatible) | |||
1008 | << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); | |||
1009 | ||||
1010 | if (failOnError) | |||
1011 | return QualType(); | |||
1012 | ||||
1013 | return type; | |||
1014 | } | |||
1015 | ||||
1016 | // Make sure we didn't have the wrong number of arguments. | |||
1017 | if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { | |||
1018 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | |||
1019 | << (typeArgs.size() < typeParams->size()) | |||
1020 | << objcClass->getDeclName() | |||
1021 | << (unsigned)finalTypeArgs.size() | |||
1022 | << (unsigned)numTypeParams; | |||
1023 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | |||
1024 | << objcClass; | |||
1025 | ||||
1026 | if (failOnError) | |||
1027 | return QualType(); | |||
1028 | ||||
1029 | return type; | |||
1030 | } | |||
1031 | ||||
1032 | // Success. Form the specialized type. | |||
1033 | return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); | |||
1034 | } | |||
1035 | ||||
1036 | QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, | |||
1037 | SourceLocation ProtocolLAngleLoc, | |||
1038 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
1039 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1040 | SourceLocation ProtocolRAngleLoc, | |||
1041 | bool FailOnError) { | |||
1042 | QualType Result = QualType(Decl->getTypeForDecl(), 0); | |||
1043 | if (!Protocols.empty()) { | |||
1044 | bool HasError; | |||
1045 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | |||
1046 | HasError); | |||
1047 | if (HasError) { | |||
1048 | Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) | |||
1049 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | |||
1050 | if (FailOnError) Result = QualType(); | |||
1051 | } | |||
1052 | if (FailOnError && Result.isNull()) | |||
1053 | return QualType(); | |||
1054 | } | |||
1055 | ||||
1056 | return Result; | |||
1057 | } | |||
1058 | ||||
1059 | QualType Sema::BuildObjCObjectType(QualType BaseType, | |||
1060 | SourceLocation Loc, | |||
1061 | SourceLocation TypeArgsLAngleLoc, | |||
1062 | ArrayRef<TypeSourceInfo *> TypeArgs, | |||
1063 | SourceLocation TypeArgsRAngleLoc, | |||
1064 | SourceLocation ProtocolLAngleLoc, | |||
1065 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
1066 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1067 | SourceLocation ProtocolRAngleLoc, | |||
1068 | bool FailOnError) { | |||
1069 | QualType Result = BaseType; | |||
1070 | if (!TypeArgs.empty()) { | |||
1071 | Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, | |||
1072 | SourceRange(TypeArgsLAngleLoc, | |||
1073 | TypeArgsRAngleLoc), | |||
1074 | FailOnError); | |||
1075 | if (FailOnError && Result.isNull()) | |||
1076 | return QualType(); | |||
1077 | } | |||
1078 | ||||
1079 | if (!Protocols.empty()) { | |||
1080 | bool HasError; | |||
1081 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | |||
1082 | HasError); | |||
1083 | if (HasError) { | |||
1084 | Diag(Loc, diag::err_invalid_protocol_qualifiers) | |||
1085 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | |||
1086 | if (FailOnError) Result = QualType(); | |||
1087 | } | |||
1088 | if (FailOnError && Result.isNull()) | |||
1089 | return QualType(); | |||
1090 | } | |||
1091 | ||||
1092 | return Result; | |||
1093 | } | |||
1094 | ||||
1095 | TypeResult Sema::actOnObjCProtocolQualifierType( | |||
1096 | SourceLocation lAngleLoc, | |||
1097 | ArrayRef<Decl *> protocols, | |||
1098 | ArrayRef<SourceLocation> protocolLocs, | |||
1099 | SourceLocation rAngleLoc) { | |||
1100 | // Form id<protocol-list>. | |||
1101 | QualType Result = Context.getObjCObjectType( | |||
1102 | Context.ObjCBuiltinIdTy, { }, | |||
1103 | llvm::makeArrayRef( | |||
1104 | (ObjCProtocolDecl * const *)protocols.data(), | |||
1105 | protocols.size()), | |||
1106 | false); | |||
1107 | Result = Context.getObjCObjectPointerType(Result); | |||
1108 | ||||
1109 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | |||
1110 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | |||
1111 | ||||
1112 | auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); | |||
1113 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit | |||
1114 | ||||
1115 | auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() | |||
1116 | .castAs<ObjCObjectTypeLoc>(); | |||
1117 | ObjCObjectTL.setHasBaseTypeAsWritten(false); | |||
1118 | ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); | |||
1119 | ||||
1120 | // No type arguments. | |||
1121 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | |||
1122 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | |||
1123 | ||||
1124 | // Fill in protocol qualifiers. | |||
1125 | ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); | |||
1126 | ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); | |||
1127 | for (unsigned i = 0, n = protocols.size(); i != n; ++i) | |||
1128 | ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); | |||
1129 | ||||
1130 | // We're done. Return the completed type to the parser. | |||
1131 | return CreateParsedType(Result, ResultTInfo); | |||
1132 | } | |||
1133 | ||||
1134 | TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( | |||
1135 | Scope *S, | |||
1136 | SourceLocation Loc, | |||
1137 | ParsedType BaseType, | |||
1138 | SourceLocation TypeArgsLAngleLoc, | |||
1139 | ArrayRef<ParsedType> TypeArgs, | |||
1140 | SourceLocation TypeArgsRAngleLoc, | |||
1141 | SourceLocation ProtocolLAngleLoc, | |||
1142 | ArrayRef<Decl *> Protocols, | |||
1143 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1144 | SourceLocation ProtocolRAngleLoc) { | |||
1145 | TypeSourceInfo *BaseTypeInfo = nullptr; | |||
1146 | QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); | |||
1147 | if (T.isNull()) | |||
| ||||
1148 | return true; | |||
1149 | ||||
1150 | // Handle missing type-source info. | |||
1151 | if (!BaseTypeInfo
| |||
1152 | BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
1153 | ||||
1154 | // Extract type arguments. | |||
1155 | SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; | |||
1156 | for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { | |||
1157 | TypeSourceInfo *TypeArgInfo = nullptr; | |||
1158 | QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); | |||
1159 | if (TypeArg.isNull()) { | |||
1160 | ActualTypeArgInfos.clear(); | |||
1161 | break; | |||
1162 | } | |||
1163 | ||||
1164 | assert(TypeArgInfo && "No type source info?")(static_cast <bool> (TypeArgInfo && "No type source info?" ) ? void (0) : __assert_fail ("TypeArgInfo && \"No type source info?\"" , "clang/lib/Sema/SemaType.cpp", 1164, __extension__ __PRETTY_FUNCTION__ )); | |||
1165 | ActualTypeArgInfos.push_back(TypeArgInfo); | |||
1166 | } | |||
1167 | ||||
1168 | // Build the object type. | |||
1169 | QualType Result = BuildObjCObjectType( | |||
1170 | T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), | |||
1171 | TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, | |||
1172 | ProtocolLAngleLoc, | |||
1173 | llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), | |||
1174 | Protocols.size()), | |||
1175 | ProtocolLocs, ProtocolRAngleLoc, | |||
1176 | /*FailOnError=*/false); | |||
1177 | ||||
1178 | if (Result == T) | |||
1179 | return BaseType; | |||
1180 | ||||
1181 | // Create source information for this type. | |||
1182 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | |||
1183 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | |||
1184 | ||||
1185 | // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an | |||
1186 | // object pointer type. Fill in source information for it. | |||
1187 | if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { | |||
1188 | // The '*' is implicit. | |||
1189 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); | |||
1190 | ResultTL = ObjCObjectPointerTL.getPointeeLoc(); | |||
1191 | } | |||
1192 | ||||
1193 | if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { | |||
1194 | // Protocol qualifier information. | |||
1195 | if (OTPTL.getNumProtocols() > 0) { | |||
1196 | assert(OTPTL.getNumProtocols() == Protocols.size())(static_cast <bool> (OTPTL.getNumProtocols() == Protocols .size()) ? void (0) : __assert_fail ("OTPTL.getNumProtocols() == Protocols.size()" , "clang/lib/Sema/SemaType.cpp", 1196, __extension__ __PRETTY_FUNCTION__ )); | |||
1197 | OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | |||
1198 | OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | |||
1199 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | |||
1200 | OTPTL.setProtocolLoc(i, ProtocolLocs[i]); | |||
1201 | } | |||
1202 | ||||
1203 | // We're done. Return the completed type to the parser. | |||
1204 | return CreateParsedType(Result, ResultTInfo); | |||
1205 | } | |||
1206 | ||||
1207 | auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); | |||
1208 | ||||
1209 | // Type argument information. | |||
1210 | if (ObjCObjectTL.getNumTypeArgs() > 0) { | |||
1211 | assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size())(static_cast <bool> (ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos .size()) ? void (0) : __assert_fail ("ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()" , "clang/lib/Sema/SemaType.cpp", 1211, __extension__ __PRETTY_FUNCTION__ )); | |||
1212 | ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); | |||
1213 | ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); | |||
1214 | for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) | |||
1215 | ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); | |||
1216 | } else { | |||
1217 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | |||
1218 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | |||
1219 | } | |||
1220 | ||||
1221 | // Protocol qualifier information. | |||
1222 | if (ObjCObjectTL.getNumProtocols() > 0) { | |||
1223 | assert(ObjCObjectTL.getNumProtocols() == Protocols.size())(static_cast <bool> (ObjCObjectTL.getNumProtocols() == Protocols .size()) ? void (0) : __assert_fail ("ObjCObjectTL.getNumProtocols() == Protocols.size()" , "clang/lib/Sema/SemaType.cpp", 1223, __extension__ __PRETTY_FUNCTION__ )); | |||
1224 | ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | |||
1225 | ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | |||
1226 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | |||
1227 | ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); | |||
1228 | } else { | |||
1229 | ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); | |||
1230 | ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); | |||
1231 | } | |||
1232 | ||||
1233 | // Base type. | |||
1234 | ObjCObjectTL.setHasBaseTypeAsWritten(true); | |||
1235 | if (ObjCObjectTL.getType() == T) | |||
1236 | ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); | |||
1237 | else | |||
1238 | ObjCObjectTL.getBaseLoc().initialize(Context, Loc); | |||
1239 | ||||
1240 | // We're done. Return the completed type to the parser. | |||
1241 | return CreateParsedType(Result, ResultTInfo); | |||
1242 | } | |||
1243 | ||||
1244 | static OpenCLAccessAttr::Spelling | |||
1245 | getImageAccess(const ParsedAttributesView &Attrs) { | |||
1246 | for (const ParsedAttr &AL : Attrs) | |||
1247 | if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) | |||
1248 | return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); | |||
1249 | return OpenCLAccessAttr::Keyword_read_only; | |||
1250 | } | |||
1251 | ||||
1252 | static UnaryTransformType::UTTKind | |||
1253 | TSTToUnaryTransformType(DeclSpec::TST SwitchTST) { | |||
1254 | switch (SwitchTST) { | |||
1255 | #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \ | |||
1256 | case TST_##Trait: \ | |||
1257 | return UnaryTransformType::Enum; | |||
1258 | #include "clang/Basic/TransformTypeTraits.def" | |||
1259 | default: | |||
1260 | llvm_unreachable("attempted to parse a non-unary transform builtin")::llvm::llvm_unreachable_internal("attempted to parse a non-unary transform builtin" , "clang/lib/Sema/SemaType.cpp", 1260); | |||
1261 | } | |||
1262 | } | |||
1263 | ||||
1264 | /// Convert the specified declspec to the appropriate type | |||
1265 | /// object. | |||
1266 | /// \param state Specifies the declarator containing the declaration specifier | |||
1267 | /// to be converted, along with other associated processing state. | |||
1268 | /// \returns The type described by the declaration specifiers. This function | |||
1269 | /// never returns null. | |||
1270 | static QualType ConvertDeclSpecToType(TypeProcessingState &state) { | |||
1271 | // FIXME: Should move the logic from DeclSpec::Finish to here for validity | |||
1272 | // checking. | |||
1273 | ||||
1274 | Sema &S = state.getSema(); | |||
1275 | Declarator &declarator = state.getDeclarator(); | |||
1276 | DeclSpec &DS = declarator.getMutableDeclSpec(); | |||
1277 | SourceLocation DeclLoc = declarator.getIdentifierLoc(); | |||
1278 | if (DeclLoc.isInvalid()) | |||
1279 | DeclLoc = DS.getBeginLoc(); | |||
1280 | ||||
1281 | ASTContext &Context = S.Context; | |||
1282 | ||||
1283 | QualType Result; | |||
1284 | switch (DS.getTypeSpecType()) { | |||
1285 | case DeclSpec::TST_void: | |||
1286 | Result = Context.VoidTy; | |||
1287 | break; | |||
1288 | case DeclSpec::TST_char: | |||
1289 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) | |||
1290 | Result = Context.CharTy; | |||
1291 | else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) | |||
1292 | Result = Context.SignedCharTy; | |||
1293 | else { | |||
1294 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1295, __extension__ __PRETTY_FUNCTION__ )) | |||
1295 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1295, __extension__ __PRETTY_FUNCTION__ )); | |||
1296 | Result = Context.UnsignedCharTy; | |||
1297 | } | |||
1298 | break; | |||
1299 | case DeclSpec::TST_wchar: | |||
1300 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) | |||
1301 | Result = Context.WCharTy; | |||
1302 | else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) { | |||
1303 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) | |||
1304 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1305 | Context.getPrintingPolicy()); | |||
1306 | Result = Context.getSignedWCharType(); | |||
1307 | } else { | |||
1308 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1309, __extension__ __PRETTY_FUNCTION__ )) | |||
1309 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1309, __extension__ __PRETTY_FUNCTION__ )); | |||
1310 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) | |||
1311 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1312 | Context.getPrintingPolicy()); | |||
1313 | Result = Context.getUnsignedWCharType(); | |||
1314 | } | |||
1315 | break; | |||
1316 | case DeclSpec::TST_char8: | |||
1317 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1318, __extension__ __PRETTY_FUNCTION__ )) | |||
1318 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1318, __extension__ __PRETTY_FUNCTION__ )); | |||
1319 | Result = Context.Char8Ty; | |||
1320 | break; | |||
1321 | case DeclSpec::TST_char16: | |||
1322 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1323, __extension__ __PRETTY_FUNCTION__ )) | |||
1323 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1323, __extension__ __PRETTY_FUNCTION__ )); | |||
1324 | Result = Context.Char16Ty; | |||
1325 | break; | |||
1326 | case DeclSpec::TST_char32: | |||
1327 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1328, __extension__ __PRETTY_FUNCTION__ )) | |||
1328 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1328, __extension__ __PRETTY_FUNCTION__ )); | |||
1329 | Result = Context.Char32Ty; | |||
1330 | break; | |||
1331 | case DeclSpec::TST_unspecified: | |||
1332 | // If this is a missing declspec in a block literal return context, then it | |||
1333 | // is inferred from the return statements inside the block. | |||
1334 | // The declspec is always missing in a lambda expr context; it is either | |||
1335 | // specified with a trailing return type or inferred. | |||
1336 | if (S.getLangOpts().CPlusPlus14 && | |||
1337 | declarator.getContext() == DeclaratorContext::LambdaExpr) { | |||
1338 | // In C++1y, a lambda's implicit return type is 'auto'. | |||
1339 | Result = Context.getAutoDeductType(); | |||
1340 | break; | |||
1341 | } else if (declarator.getContext() == DeclaratorContext::LambdaExpr || | |||
1342 | checkOmittedBlockReturnType(S, declarator, | |||
1343 | Context.DependentTy)) { | |||
1344 | Result = Context.DependentTy; | |||
1345 | break; | |||
1346 | } | |||
1347 | ||||
1348 | // Unspecified typespec defaults to int in C90. However, the C90 grammar | |||
1349 | // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, | |||
1350 | // type-qualifier, or storage-class-specifier. If not, emit an extwarn. | |||
1351 | // Note that the one exception to this is function definitions, which are | |||
1352 | // allowed to be completely missing a declspec. This is handled in the | |||
1353 | // parser already though by it pretending to have seen an 'int' in this | |||
1354 | // case. | |||
1355 | if (S.getLangOpts().isImplicitIntRequired()) { | |||
1356 | S.Diag(DeclLoc, diag::warn_missing_type_specifier) | |||
1357 | << DS.getSourceRange() | |||
1358 | << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); | |||
1359 | } else if (!DS.hasTypeSpecifier()) { | |||
1360 | // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: | |||
1361 | // "At least one type specifier shall be given in the declaration | |||
1362 | // specifiers in each declaration, and in the specifier-qualifier list in | |||
1363 | // each struct declaration and type name." | |||
1364 | if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) { | |||
1365 | S.Diag(DeclLoc, diag::err_missing_type_specifier) | |||
1366 | << DS.getSourceRange(); | |||
1367 | ||||
1368 | // When this occurs, often something is very broken with the value | |||
1369 | // being declared, poison it as invalid so we don't get chains of | |||
1370 | // errors. | |||
1371 | declarator.setInvalidType(true); | |||
1372 | } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 && | |||
1373 | DS.isTypeSpecPipe()) { | |||
1374 | S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) | |||
1375 | << DS.getSourceRange(); | |||
1376 | declarator.setInvalidType(true); | |||
1377 | } else { | |||
1378 | assert(S.getLangOpts().isImplicitIntAllowed() &&(static_cast <bool> (S.getLangOpts().isImplicitIntAllowed () && "implicit int is disabled?") ? void (0) : __assert_fail ("S.getLangOpts().isImplicitIntAllowed() && \"implicit int is disabled?\"" , "clang/lib/Sema/SemaType.cpp", 1379, __extension__ __PRETTY_FUNCTION__ )) | |||
1379 | "implicit int is disabled?")(static_cast <bool> (S.getLangOpts().isImplicitIntAllowed () && "implicit int is disabled?") ? void (0) : __assert_fail ("S.getLangOpts().isImplicitIntAllowed() && \"implicit int is disabled?\"" , "clang/lib/Sema/SemaType.cpp", 1379, __extension__ __PRETTY_FUNCTION__ )); | |||
1380 | S.Diag(DeclLoc, diag::ext_missing_type_specifier) | |||
1381 | << DS.getSourceRange() | |||
1382 | << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); | |||
1383 | } | |||
1384 | } | |||
1385 | ||||
1386 | [[fallthrough]]; | |||
1387 | case DeclSpec::TST_int: { | |||
1388 | if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) { | |||
1389 | switch (DS.getTypeSpecWidth()) { | |||
1390 | case TypeSpecifierWidth::Unspecified: | |||
1391 | Result = Context.IntTy; | |||
1392 | break; | |||
1393 | case TypeSpecifierWidth::Short: | |||
1394 | Result = Context.ShortTy; | |||
1395 | break; | |||
1396 | case TypeSpecifierWidth::Long: | |||
1397 | Result = Context.LongTy; | |||
1398 | break; | |||
1399 | case TypeSpecifierWidth::LongLong: | |||
1400 | Result = Context.LongLongTy; | |||
1401 | ||||
1402 | // 'long long' is a C99 or C++11 feature. | |||
1403 | if (!S.getLangOpts().C99) { | |||
1404 | if (S.getLangOpts().CPlusPlus) | |||
1405 | S.Diag(DS.getTypeSpecWidthLoc(), | |||
1406 | S.getLangOpts().CPlusPlus11 ? | |||
1407 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
1408 | else | |||
1409 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | |||
1410 | } | |||
1411 | break; | |||
1412 | } | |||
1413 | } else { | |||
1414 | switch (DS.getTypeSpecWidth()) { | |||
1415 | case TypeSpecifierWidth::Unspecified: | |||
1416 | Result = Context.UnsignedIntTy; | |||
1417 | break; | |||
1418 | case TypeSpecifierWidth::Short: | |||
1419 | Result = Context.UnsignedShortTy; | |||
1420 | break; | |||
1421 | case TypeSpecifierWidth::Long: | |||
1422 | Result = Context.UnsignedLongTy; | |||
1423 | break; | |||
1424 | case TypeSpecifierWidth::LongLong: | |||
1425 | Result = Context.UnsignedLongLongTy; | |||
1426 | ||||
1427 | // 'long long' is a C99 or C++11 feature. | |||
1428 | if (!S.getLangOpts().C99) { | |||
1429 | if (S.getLangOpts().CPlusPlus) | |||
1430 | S.Diag(DS.getTypeSpecWidthLoc(), | |||
1431 | S.getLangOpts().CPlusPlus11 ? | |||
1432 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
1433 | else | |||
1434 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | |||
1435 | } | |||
1436 | break; | |||
1437 | } | |||
1438 | } | |||
1439 | break; | |||
1440 | } | |||
1441 | case DeclSpec::TST_bitint: { | |||
1442 | if (!S.Context.getTargetInfo().hasBitIntType()) | |||
1443 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt"; | |||
1444 | Result = | |||
1445 | S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned, | |||
1446 | DS.getRepAsExpr(), DS.getBeginLoc()); | |||
1447 | if (Result.isNull()) { | |||
1448 | Result = Context.IntTy; | |||
1449 | declarator.setInvalidType(true); | |||
1450 | } | |||
1451 | break; | |||
1452 | } | |||
1453 | case DeclSpec::TST_accum: { | |||
1454 | switch (DS.getTypeSpecWidth()) { | |||
1455 | case TypeSpecifierWidth::Short: | |||
1456 | Result = Context.ShortAccumTy; | |||
1457 | break; | |||
1458 | case TypeSpecifierWidth::Unspecified: | |||
1459 | Result = Context.AccumTy; | |||
1460 | break; | |||
1461 | case TypeSpecifierWidth::Long: | |||
1462 | Result = Context.LongAccumTy; | |||
1463 | break; | |||
1464 | case TypeSpecifierWidth::LongLong: | |||
1465 | llvm_unreachable("Unable to specify long long as _Accum width")::llvm::llvm_unreachable_internal("Unable to specify long long as _Accum width" , "clang/lib/Sema/SemaType.cpp", 1465); | |||
1466 | } | |||
1467 | ||||
1468 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | |||
1469 | Result = Context.getCorrespondingUnsignedType(Result); | |||
1470 | ||||
1471 | if (DS.isTypeSpecSat()) | |||
1472 | Result = Context.getCorrespondingSaturatedType(Result); | |||
1473 | ||||
1474 | break; | |||
1475 | } | |||
1476 | case DeclSpec::TST_fract: { | |||
1477 | switch (DS.getTypeSpecWidth()) { | |||
1478 | case TypeSpecifierWidth::Short: | |||
1479 | Result = Context.ShortFractTy; | |||
1480 | break; | |||
1481 | case TypeSpecifierWidth::Unspecified: | |||
1482 | Result = Context.FractTy; | |||
1483 | break; | |||
1484 | case TypeSpecifierWidth::Long: | |||
1485 | Result = Context.LongFractTy; | |||
1486 | break; | |||
1487 | case TypeSpecifierWidth::LongLong: | |||
1488 | llvm_unreachable("Unable to specify long long as _Fract width")::llvm::llvm_unreachable_internal("Unable to specify long long as _Fract width" , "clang/lib/Sema/SemaType.cpp", 1488); | |||
1489 | } | |||
1490 | ||||
1491 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | |||
1492 | Result = Context.getCorrespondingUnsignedType(Result); | |||
1493 | ||||
1494 | if (DS.isTypeSpecSat()) | |||
1495 | Result = Context.getCorrespondingSaturatedType(Result); | |||
1496 | ||||
1497 | break; | |||
1498 | } | |||
1499 | case DeclSpec::TST_int128: | |||
1500 | if (!S.Context.getTargetInfo().hasInt128Type() && | |||
1501 | !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice || | |||
1502 | (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))) | |||
1503 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1504 | << "__int128"; | |||
1505 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | |||
1506 | Result = Context.UnsignedInt128Ty; | |||
1507 | else | |||
1508 | Result = Context.Int128Ty; | |||
1509 | break; | |||
1510 | case DeclSpec::TST_float16: | |||
1511 | // CUDA host and device may have different _Float16 support, therefore | |||
1512 | // do not diagnose _Float16 usage to avoid false alarm. | |||
1513 | // ToDo: more precise diagnostics for CUDA. | |||
1514 | if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA && | |||
1515 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1516 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1517 | << "_Float16"; | |||
1518 | Result = Context.Float16Ty; | |||
1519 | break; | |||
1520 | case DeclSpec::TST_half: Result = Context.HalfTy; break; | |||
1521 | case DeclSpec::TST_BFloat16: | |||
1522 | if (!S.Context.getTargetInfo().hasBFloat16Type()) | |||
1523 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1524 | << "__bf16"; | |||
1525 | Result = Context.BFloat16Ty; | |||
1526 | break; | |||
1527 | case DeclSpec::TST_float: Result = Context.FloatTy; break; | |||
1528 | case DeclSpec::TST_double: | |||
1529 | if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long) | |||
1530 | Result = Context.LongDoubleTy; | |||
1531 | else | |||
1532 | Result = Context.DoubleTy; | |||
1533 | if (S.getLangOpts().OpenCL) { | |||
1534 | if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts())) | |||
1535 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) | |||
1536 | << 0 << Result | |||
1537 | << (S.getLangOpts().getOpenCLCompatibleVersion() == 300 | |||
1538 | ? "cl_khr_fp64 and __opencl_c_fp64" | |||
1539 | : "cl_khr_fp64"); | |||
1540 | else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts())) | |||
1541 | S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma); | |||
1542 | } | |||
1543 | break; | |||
1544 | case DeclSpec::TST_float128: | |||
1545 | if (!S.Context.getTargetInfo().hasFloat128Type() && | |||
1546 | !S.getLangOpts().SYCLIsDevice && | |||
1547 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1548 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1549 | << "__float128"; | |||
1550 | Result = Context.Float128Ty; | |||
1551 | break; | |||
1552 | case DeclSpec::TST_ibm128: | |||
1553 | if (!S.Context.getTargetInfo().hasIbm128Type() && | |||
1554 | !S.getLangOpts().SYCLIsDevice && | |||
1555 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1556 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128"; | |||
1557 | Result = Context.Ibm128Ty; | |||
1558 | break; | |||
1559 | case DeclSpec::TST_bool: | |||
1560 | Result = Context.BoolTy; // _Bool or bool | |||
1561 | break; | |||
1562 | case DeclSpec::TST_decimal32: // _Decimal32 | |||
1563 | case DeclSpec::TST_decimal64: // _Decimal64 | |||
1564 | case DeclSpec::TST_decimal128: // _Decimal128 | |||
1565 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); | |||
1566 | Result = Context.IntTy; | |||
1567 | declarator.setInvalidType(true); | |||
1568 | break; | |||
1569 | case DeclSpec::TST_class: | |||
1570 | case DeclSpec::TST_enum: | |||
1571 | case DeclSpec::TST_union: | |||
1572 | case DeclSpec::TST_struct: | |||
1573 | case DeclSpec::TST_interface: { | |||
1574 | TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()); | |||
1575 | if (!D) { | |||
1576 | // This can happen in C++ with ambiguous lookups. | |||
1577 | Result = Context.IntTy; | |||
1578 | declarator.setInvalidType(true); | |||
1579 | break; | |||
1580 | } | |||
1581 | ||||
1582 | // If the type is deprecated or unavailable, diagnose it. | |||
1583 | S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); | |||
1584 | ||||
1585 | assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "clang/lib/Sema/SemaType.cpp", 1588, __extension__ __PRETTY_FUNCTION__ )) | |||
1586 | DS.getTypeSpecComplex() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "clang/lib/Sema/SemaType.cpp", 1588, __extension__ __PRETTY_FUNCTION__ )) | |||
1587 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "clang/lib/Sema/SemaType.cpp", 1588, __extension__ __PRETTY_FUNCTION__ )) | |||
1588 | "No qualifiers on tag names!")(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "clang/lib/Sema/SemaType.cpp", 1588, __extension__ __PRETTY_FUNCTION__ )); | |||
1589 | ||||
1590 | // TypeQuals handled by caller. | |||
1591 | Result = Context.getTypeDeclType(D); | |||
1592 | ||||
1593 | // In both C and C++, make an ElaboratedType. | |||
1594 | ElaboratedTypeKeyword Keyword | |||
1595 | = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); | |||
1596 | Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result, | |||
1597 | DS.isTypeSpecOwned() ? D : nullptr); | |||
1598 | break; | |||
1599 | } | |||
1600 | case DeclSpec::TST_typename: { | |||
1601 | assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "clang/lib/Sema/SemaType.cpp", 1604, __extension__ __PRETTY_FUNCTION__ )) | |||
1602 | DS.getTypeSpecComplex() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "clang/lib/Sema/SemaType.cpp", 1604, __extension__ __PRETTY_FUNCTION__ )) | |||
1603 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "clang/lib/Sema/SemaType.cpp", 1604, __extension__ __PRETTY_FUNCTION__ )) | |||
1604 | "Can't handle qualifiers on typedef names yet!")(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "clang/lib/Sema/SemaType.cpp", 1604, __extension__ __PRETTY_FUNCTION__ )); | |||
1605 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1606 | if (Result.isNull()) { | |||
1607 | declarator.setInvalidType(true); | |||
1608 | } | |||
1609 | ||||
1610 | // TypeQuals handled by caller. | |||
1611 | break; | |||
1612 | } | |||
1613 | case DeclSpec::TST_typeof_unqualType: | |||
1614 | case DeclSpec::TST_typeofType: | |||
1615 | // FIXME: Preserve type source info. | |||
1616 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1617 | assert(!Result.isNull() && "Didn't get a type for typeof?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for typeof?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for typeof?\"" , "clang/lib/Sema/SemaType.cpp", 1617, __extension__ __PRETTY_FUNCTION__ )); | |||
1618 | if (!Result->isDependentType()) | |||
1619 | if (const TagType *TT = Result->getAs<TagType>()) | |||
1620 | S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); | |||
1621 | // TypeQuals handled by caller. | |||
1622 | Result = Context.getTypeOfType( | |||
1623 | Result, DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType | |||
1624 | ? TypeOfKind::Unqualified | |||
1625 | : TypeOfKind::Qualified); | |||
1626 | break; | |||
1627 | case DeclSpec::TST_typeof_unqualExpr: | |||
1628 | case DeclSpec::TST_typeofExpr: { | |||
1629 | Expr *E = DS.getRepAsExpr(); | |||
1630 | assert(E && "Didn't get an expression for typeof?")(static_cast <bool> (E && "Didn't get an expression for typeof?" ) ? void (0) : __assert_fail ("E && \"Didn't get an expression for typeof?\"" , "clang/lib/Sema/SemaType.cpp", 1630, __extension__ __PRETTY_FUNCTION__ )); | |||
1631 | // TypeQuals handled by caller. | |||
1632 | Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() == | |||
1633 | DeclSpec::TST_typeof_unqualExpr | |||
1634 | ? TypeOfKind::Unqualified | |||
1635 | : TypeOfKind::Qualified); | |||
1636 | if (Result.isNull()) { | |||
1637 | Result = Context.IntTy; | |||
1638 | declarator.setInvalidType(true); | |||
1639 | } | |||
1640 | break; | |||
1641 | } | |||
1642 | case DeclSpec::TST_decltype: { | |||
1643 | Expr *E = DS.getRepAsExpr(); | |||
1644 | assert(E && "Didn't get an expression for decltype?")(static_cast <bool> (E && "Didn't get an expression for decltype?" ) ? void (0) : __assert_fail ("E && \"Didn't get an expression for decltype?\"" , "clang/lib/Sema/SemaType.cpp", 1644, __extension__ __PRETTY_FUNCTION__ )); | |||
1645 | // TypeQuals handled by caller. | |||
1646 | Result = S.BuildDecltypeType(E); | |||
1647 | if (Result.isNull()) { | |||
1648 | Result = Context.IntTy; | |||
1649 | declarator.setInvalidType(true); | |||
1650 | } | |||
1651 | break; | |||
1652 | } | |||
1653 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: | |||
1654 | #include "clang/Basic/TransformTypeTraits.def" | |||
1655 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1656 | assert(!Result.isNull() && "Didn't get a type for the transformation?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for the transformation?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for the transformation?\"" , "clang/lib/Sema/SemaType.cpp", 1656, __extension__ __PRETTY_FUNCTION__ )); | |||
1657 | Result = S.BuildUnaryTransformType( | |||
1658 | Result, TSTToUnaryTransformType(DS.getTypeSpecType()), | |||
1659 | DS.getTypeSpecTypeLoc()); | |||
1660 | if (Result.isNull()) { | |||
1661 | Result = Context.IntTy; | |||
1662 | declarator.setInvalidType(true); | |||
1663 | } | |||
1664 | break; | |||
1665 | ||||
1666 | case DeclSpec::TST_auto: | |||
1667 | case DeclSpec::TST_decltype_auto: { | |||
1668 | auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto | |||
1669 | ? AutoTypeKeyword::DecltypeAuto | |||
1670 | : AutoTypeKeyword::Auto; | |||
1671 | ||||
1672 | ConceptDecl *TypeConstraintConcept = nullptr; | |||
1673 | llvm::SmallVector<TemplateArgument, 8> TemplateArgs; | |||
1674 | if (DS.isConstrainedAuto()) { | |||
1675 | if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) { | |||
1676 | TypeConstraintConcept = | |||
1677 | cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()); | |||
1678 | TemplateArgumentListInfo TemplateArgsInfo; | |||
1679 | TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc); | |||
1680 | TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc); | |||
1681 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
1682 | TemplateId->NumArgs); | |||
1683 | S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | |||
1684 | for (const auto &ArgLoc : TemplateArgsInfo.arguments()) | |||
1685 | TemplateArgs.push_back(ArgLoc.getArgument()); | |||
1686 | } else { | |||
1687 | declarator.setInvalidType(true); | |||
1688 | } | |||
1689 | } | |||
1690 | Result = S.Context.getAutoType(QualType(), AutoKW, | |||
1691 | /*IsDependent*/ false, /*IsPack=*/false, | |||
1692 | TypeConstraintConcept, TemplateArgs); | |||
1693 | break; | |||
1694 | } | |||
1695 | ||||
1696 | case DeclSpec::TST_auto_type: | |||
1697 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); | |||
1698 | break; | |||
1699 | ||||
1700 | case DeclSpec::TST_unknown_anytype: | |||
1701 | Result = Context.UnknownAnyTy; | |||
1702 | break; | |||
1703 | ||||
1704 | case DeclSpec::TST_atomic: | |||
1705 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1706 | assert(!Result.isNull() && "Didn't get a type for _Atomic?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for _Atomic?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for _Atomic?\"" , "clang/lib/Sema/SemaType.cpp", 1706, __extension__ __PRETTY_FUNCTION__ )); | |||
1707 | Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); | |||
1708 | if (Result.isNull()) { | |||
1709 | Result = Context.IntTy; | |||
1710 | declarator.setInvalidType(true); | |||
1711 | } | |||
1712 | break; | |||
1713 | ||||
1714 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ | |||
1715 | case DeclSpec::TST_##ImgType##_t: \ | |||
1716 | switch (getImageAccess(DS.getAttributes())) { \ | |||
1717 | case OpenCLAccessAttr::Keyword_write_only: \ | |||
1718 | Result = Context.Id##WOTy; \ | |||
1719 | break; \ | |||
1720 | case OpenCLAccessAttr::Keyword_read_write: \ | |||
1721 | Result = Context.Id##RWTy; \ | |||
1722 | break; \ | |||
1723 | case OpenCLAccessAttr::Keyword_read_only: \ | |||
1724 | Result = Context.Id##ROTy; \ | |||
1725 | break; \ | |||
1726 | case OpenCLAccessAttr::SpellingNotCalculated: \ | |||
1727 | llvm_unreachable("Spelling not yet calculated")::llvm::llvm_unreachable_internal("Spelling not yet calculated" , "clang/lib/Sema/SemaType.cpp", 1727); \ | |||
1728 | } \ | |||
1729 | break; | |||
1730 | #include "clang/Basic/OpenCLImageTypes.def" | |||
1731 | ||||
1732 | case DeclSpec::TST_error: | |||
1733 | Result = Context.IntTy; | |||
1734 | declarator.setInvalidType(true); | |||
1735 | break; | |||
1736 | } | |||
1737 | ||||
1738 | // FIXME: we want resulting declarations to be marked invalid, but claiming | |||
1739 | // the type is invalid is too strong - e.g. it causes ActOnTypeName to return | |||
1740 | // a null type. | |||
1741 | if (Result->containsErrors()) | |||
1742 | declarator.setInvalidType(); | |||
1743 | ||||
1744 | if (S.getLangOpts().OpenCL) { | |||
1745 | const auto &OpenCLOptions = S.getOpenCLOptions(); | |||
1746 | bool IsOpenCLC30Compatible = | |||
1747 | S.getLangOpts().getOpenCLCompatibleVersion() == 300; | |||
1748 | // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images | |||
1749 | // support. | |||
1750 | // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support | |||
1751 | // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the | |||
1752 | // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices | |||
1753 | // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and | |||
1754 | // only when the optional feature is supported | |||
1755 | if ((Result->isImageType() || Result->isSamplerT()) && | |||
1756 | (IsOpenCLC30Compatible && | |||
1757 | !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) { | |||
1758 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) | |||
1759 | << 0 << Result << "__opencl_c_images"; | |||
1760 | declarator.setInvalidType(); | |||
1761 | } else if (Result->isOCLImage3dWOType() && | |||
1762 | !OpenCLOptions.isSupported("cl_khr_3d_image_writes", | |||
1763 | S.getLangOpts())) { | |||
1764 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) | |||
1765 | << 0 << Result | |||
1766 | << (IsOpenCLC30Compatible | |||
1767 | ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes" | |||
1768 | : "cl_khr_3d_image_writes"); | |||
1769 | declarator.setInvalidType(); | |||
1770 | } | |||
1771 | } | |||
1772 | ||||
1773 | bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || | |||
1774 | DS.getTypeSpecType() == DeclSpec::TST_fract; | |||
1775 | ||||
1776 | // Only fixed point types can be saturated | |||
1777 | if (DS.isTypeSpecSat() && !IsFixedPointType) | |||
1778 | S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) | |||
1779 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1780 | Context.getPrintingPolicy()); | |||
1781 | ||||
1782 | // Handle complex types. | |||
1783 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { | |||
1784 | if (S.getLangOpts().Freestanding) | |||
1785 | S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); | |||
1786 | Result = Context.getComplexType(Result); | |||
1787 | } else if (DS.isTypeAltiVecVector()) { | |||
1788 | unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); | |||
1789 | assert(typeSize > 0 && "type size for vector must be greater than 0 bits")(static_cast <bool> (typeSize > 0 && "type size for vector must be greater than 0 bits" ) ? void (0) : __assert_fail ("typeSize > 0 && \"type size for vector must be greater than 0 bits\"" , "clang/lib/Sema/SemaType.cpp", 1789, __extension__ __PRETTY_FUNCTION__ )); | |||
1790 | VectorType::VectorKind VecKind = VectorType::AltiVecVector; | |||
1791 | if (DS.isTypeAltiVecPixel()) | |||
1792 | VecKind = VectorType::AltiVecPixel; | |||
1793 | else if (DS.isTypeAltiVecBool()) | |||
1794 | VecKind = VectorType::AltiVecBool; | |||
1795 | Result = Context.getVectorType(Result, 128/typeSize, VecKind); | |||
1796 | } | |||
1797 | ||||
1798 | // FIXME: Imaginary. | |||
1799 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) | |||
1800 | S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); | |||
1801 | ||||
1802 | // Before we process any type attributes, synthesize a block literal | |||
1803 | // function declarator if necessary. | |||
1804 | if (declarator.getContext() == DeclaratorContext::BlockLiteral) | |||
1805 | maybeSynthesizeBlockSignature(state, Result); | |||
1806 | ||||
1807 | // Apply any type attributes from the decl spec. This may cause the | |||
1808 | // list of type attributes to be temporarily saved while the type | |||
1809 | // attributes are pushed around. | |||
1810 | // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) | |||
1811 | if (!DS.isTypeSpecPipe()) { | |||
1812 | // We also apply declaration attributes that "slide" to the decl spec. | |||
1813 | // Ordering can be important for attributes. The decalaration attributes | |||
1814 | // come syntactically before the decl spec attributes, so we process them | |||
1815 | // in that order. | |||
1816 | ParsedAttributesView SlidingAttrs; | |||
1817 | for (ParsedAttr &AL : declarator.getDeclarationAttributes()) { | |||
1818 | if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) { | |||
1819 | SlidingAttrs.addAtEnd(&AL); | |||
1820 | ||||
1821 | // For standard syntax attributes, which would normally appertain to the | |||
1822 | // declaration here, suggest moving them to the type instead. But only | |||
1823 | // do this for our own vendor attributes; moving other vendors' | |||
1824 | // attributes might hurt portability. | |||
1825 | // There's one special case that we need to deal with here: The | |||
1826 | // `MatrixType` attribute may only be used in a typedef declaration. If | |||
1827 | // it's being used anywhere else, don't output the warning as | |||
1828 | // ProcessDeclAttributes() will output an error anyway. | |||
1829 | if (AL.isStandardAttributeSyntax() && AL.isClangScope() && | |||
1830 | !(AL.getKind() == ParsedAttr::AT_MatrixType && | |||
1831 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) { | |||
1832 | S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl) | |||
1833 | << AL; | |||
1834 | } | |||
1835 | } | |||
1836 | } | |||
1837 | // During this call to processTypeAttrs(), | |||
1838 | // TypeProcessingState::getCurrentAttributes() will erroneously return a | |||
1839 | // reference to the DeclSpec attributes, rather than the declaration | |||
1840 | // attributes. However, this doesn't matter, as getCurrentAttributes() | |||
1841 | // is only called when distributing attributes from one attribute list | |||
1842 | // to another. Declaration attributes are always C++11 attributes, and these | |||
1843 | // are never distributed. | |||
1844 | processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs); | |||
1845 | processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes()); | |||
1846 | } | |||
1847 | ||||
1848 | // Apply const/volatile/restrict qualifiers to T. | |||
1849 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | |||
1850 | // Warn about CV qualifiers on function types. | |||
1851 | // C99 6.7.3p8: | |||
1852 | // If the specification of a function type includes any type qualifiers, | |||
1853 | // the behavior is undefined. | |||
1854 | // C++11 [dcl.fct]p7: | |||
1855 | // The effect of a cv-qualifier-seq in a function declarator is not the | |||
1856 | // same as adding cv-qualification on top of the function type. In the | |||
1857 | // latter case, the cv-qualifiers are ignored. | |||
1858 | if (Result->isFunctionType()) { | |||
1859 | diagnoseAndRemoveTypeQualifiers( | |||
1860 | S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, | |||
1861 | S.getLangOpts().CPlusPlus | |||
1862 | ? diag::warn_typecheck_function_qualifiers_ignored | |||
1863 | : diag::warn_typecheck_function_qualifiers_unspecified); | |||
1864 | // No diagnostic for 'restrict' or '_Atomic' applied to a | |||
1865 | // function type; we'll diagnose those later, in BuildQualifiedType. | |||
1866 | } | |||
1867 | ||||
1868 | // C++11 [dcl.ref]p1: | |||
1869 | // Cv-qualified references are ill-formed except when the | |||
1870 | // cv-qualifiers are introduced through the use of a typedef-name | |||
1871 | // or decltype-specifier, in which case the cv-qualifiers are ignored. | |||
1872 | // | |||
1873 | // There don't appear to be any other contexts in which a cv-qualified | |||
1874 | // reference type could be formed, so the 'ill-formed' clause here appears | |||
1875 | // to never happen. | |||
1876 | if (TypeQuals && Result->isReferenceType()) { | |||
1877 | diagnoseAndRemoveTypeQualifiers( | |||
1878 | S, DS, TypeQuals, Result, | |||
1879 | DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, | |||
1880 | diag::warn_typecheck_reference_qualifiers); | |||
1881 | } | |||
1882 | ||||
1883 | // C90 6.5.3 constraints: "The same type qualifier shall not appear more | |||
1884 | // than once in the same specifier-list or qualifier-list, either directly | |||
1885 | // or via one or more typedefs." | |||
1886 | if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus | |||
1887 | && TypeQuals & Result.getCVRQualifiers()) { | |||
1888 | if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { | |||
1889 | S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) | |||
1890 | << "const"; | |||
1891 | } | |||
1892 | ||||
1893 | if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { | |||
1894 | S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) | |||
1895 | << "volatile"; | |||
1896 | } | |||
1897 | ||||
1898 | // C90 doesn't have restrict nor _Atomic, so it doesn't force us to | |||
1899 | // produce a warning in this case. | |||
1900 | } | |||
1901 | ||||
1902 | QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); | |||
1903 | ||||
1904 | // If adding qualifiers fails, just use the unqualified type. | |||
1905 | if (Qualified.isNull()) | |||
1906 | declarator.setInvalidType(true); | |||
1907 | else | |||
1908 | Result = Qualified; | |||
1909 | } | |||
1910 | ||||
1911 | assert(!Result.isNull() && "This function should not return a null type")(static_cast <bool> (!Result.isNull() && "This function should not return a null type" ) ? void (0) : __assert_fail ("!Result.isNull() && \"This function should not return a null type\"" , "clang/lib/Sema/SemaType.cpp", 1911, __extension__ __PRETTY_FUNCTION__ )); | |||
1912 | return Result; | |||
1913 | } | |||
1914 | ||||
1915 | static std::string getPrintableNameForEntity(DeclarationName Entity) { | |||
1916 | if (Entity) | |||
1917 | return Entity.getAsString(); | |||
1918 | ||||
1919 | return "type name"; | |||
1920 | } | |||
1921 | ||||
1922 | static bool isDependentOrGNUAutoType(QualType T) { | |||
1923 | if (T->isDependentType()) | |||
1924 | return true; | |||
1925 | ||||
1926 | const auto *AT = dyn_cast<AutoType>(T); | |||
1927 | return AT && AT->isGNUAutoType(); | |||
1928 | } | |||
1929 | ||||
1930 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | |||
1931 | Qualifiers Qs, const DeclSpec *DS) { | |||
1932 | if (T.isNull()) | |||
1933 | return QualType(); | |||
1934 | ||||
1935 | // Ignore any attempt to form a cv-qualified reference. | |||
1936 | if (T->isReferenceType()) { | |||
1937 | Qs.removeConst(); | |||
1938 | Qs.removeVolatile(); | |||
1939 | } | |||
1940 | ||||
1941 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from | |||
1942 | // object or incomplete types shall not be restrict-qualified." | |||
1943 | if (Qs.hasRestrict()) { | |||
1944 | unsigned DiagID = 0; | |||
1945 | QualType ProblemTy; | |||
1946 | ||||
1947 | if (T->isAnyPointerType() || T->isReferenceType() || | |||
1948 | T->isMemberPointerType()) { | |||
1949 | QualType EltTy; | |||
1950 | if (T->isObjCObjectPointerType()) | |||
1951 | EltTy = T; | |||
1952 | else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) | |||
1953 | EltTy = PTy->getPointeeType(); | |||
1954 | else | |||
1955 | EltTy = T->getPointeeType(); | |||
1956 | ||||
1957 | // If we have a pointer or reference, the pointee must have an object | |||
1958 | // incomplete type. | |||
1959 | if (!EltTy->isIncompleteOrObjectType()) { | |||
1960 | DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; | |||
1961 | ProblemTy = EltTy; | |||
1962 | } | |||
1963 | } else if (!isDependentOrGNUAutoType(T)) { | |||
1964 | // For an __auto_type variable, we may not have seen the initializer yet | |||
1965 | // and so have no idea whether the underlying type is a pointer type or | |||
1966 | // not. | |||
1967 | DiagID = diag::err_typecheck_invalid_restrict_not_pointer; | |||
1968 | ProblemTy = T; | |||
1969 | } | |||
1970 | ||||
1971 | if (DiagID) { | |||
1972 | Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; | |||
1973 | Qs.removeRestrict(); | |||
1974 | } | |||
1975 | } | |||
1976 | ||||
1977 | return Context.getQualifiedType(T, Qs); | |||
1978 | } | |||
1979 | ||||
1980 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | |||
1981 | unsigned CVRAU, const DeclSpec *DS) { | |||
1982 | if (T.isNull()) | |||
1983 | return QualType(); | |||
1984 | ||||
1985 | // Ignore any attempt to form a cv-qualified reference. | |||
1986 | if (T->isReferenceType()) | |||
1987 | CVRAU &= | |||
1988 | ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); | |||
1989 | ||||
1990 | // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and | |||
1991 | // TQ_unaligned; | |||
1992 | unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); | |||
1993 | ||||
1994 | // C11 6.7.3/5: | |||
1995 | // If the same qualifier appears more than once in the same | |||
1996 | // specifier-qualifier-list, either directly or via one or more typedefs, | |||
1997 | // the behavior is the same as if it appeared only once. | |||
1998 | // | |||
1999 | // It's not specified what happens when the _Atomic qualifier is applied to | |||
2000 | // a type specified with the _Atomic specifier, but we assume that this | |||
2001 | // should be treated as if the _Atomic qualifier appeared multiple times. | |||
2002 | if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { | |||
2003 | // C11 6.7.3/5: | |||
2004 | // If other qualifiers appear along with the _Atomic qualifier in a | |||
2005 | // specifier-qualifier-list, the resulting type is the so-qualified | |||
2006 | // atomic type. | |||
2007 | // | |||
2008 | // Don't need to worry about array types here, since _Atomic can't be | |||
2009 | // applied to such types. | |||
2010 | SplitQualType Split = T.getSplitUnqualifiedType(); | |||
2011 | T = BuildAtomicType(QualType(Split.Ty, 0), | |||
2012 | DS ? DS->getAtomicSpecLoc() : Loc); | |||
2013 | if (T.isNull()) | |||
2014 | return T; | |||
2015 | Split.Quals.addCVRQualifiers(CVR); | |||
2016 | return BuildQualifiedType(T, Loc, Split.Quals); | |||
2017 | } | |||
2018 | ||||
2019 | Qualifiers Q = Qualifiers::fromCVRMask(CVR); | |||
2020 | Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); | |||
2021 | return BuildQualifiedType(T, Loc, Q, DS); | |||
2022 | } | |||
2023 | ||||
2024 | /// Build a paren type including \p T. | |||
2025 | QualType Sema::BuildParenType(QualType T) { | |||
2026 | return Context.getParenType(T); | |||
2027 | } | |||
2028 | ||||
2029 | /// Given that we're building a pointer or reference to the given | |||
2030 | static QualType inferARCLifetimeForPointee(Sema &S, QualType type, | |||
2031 | SourceLocation loc, | |||
2032 | bool isReference) { | |||
2033 | // Bail out if retention is unrequired or already specified. | |||
2034 | if (!type->isObjCLifetimeType() || | |||
2035 | type.getObjCLifetime() != Qualifiers::OCL_None) | |||
2036 | return type; | |||
2037 | ||||
2038 | Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; | |||
2039 | ||||
2040 | // If the object type is const-qualified, we can safely use | |||
2041 | // __unsafe_unretained. This is safe (because there are no read | |||
2042 | // barriers), and it'll be safe to coerce anything but __weak* to | |||
2043 | // the resulting type. | |||
2044 | if (type.isConstQualified()) { | |||
2045 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | |||
2046 | ||||
2047 | // Otherwise, check whether the static type does not require | |||
2048 | // retaining. This currently only triggers for Class (possibly | |||
2049 | // protocol-qualifed, and arrays thereof). | |||
2050 | } else if (type->isObjCARCImplicitlyUnretainedType()) { | |||
2051 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | |||
2052 | ||||
2053 | // If we are in an unevaluated context, like sizeof, skip adding a | |||
2054 | // qualification. | |||
2055 | } else if (S.isUnevaluatedContext()) { | |||
2056 | return type; | |||
2057 | ||||
2058 | // If that failed, give an error and recover using __strong. __strong | |||
2059 | // is the option most likely to prevent spurious second-order diagnostics, | |||
2060 | // like when binding a reference to a field. | |||
2061 | } else { | |||
2062 | // These types can show up in private ivars in system headers, so | |||
2063 | // we need this to not be an error in those cases. Instead we | |||
2064 | // want to delay. | |||
2065 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | |||
2066 | S.DelayedDiagnostics.add( | |||
2067 | sema::DelayedDiagnostic::makeForbiddenType(loc, | |||
2068 | diag::err_arc_indirect_no_ownership, type, isReference)); | |||
2069 | } else { | |||
2070 | S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; | |||
2071 | } | |||
2072 | implicitLifetime = Qualifiers::OCL_Strong; | |||
2073 | } | |||
2074 | assert(implicitLifetime && "didn't infer any lifetime!")(static_cast <bool> (implicitLifetime && "didn't infer any lifetime!" ) ? void (0) : __assert_fail ("implicitLifetime && \"didn't infer any lifetime!\"" , "clang/lib/Sema/SemaType.cpp", 2074, __extension__ __PRETTY_FUNCTION__ )); | |||
2075 | ||||
2076 | Qualifiers qs; | |||
2077 | qs.addObjCLifetime(implicitLifetime); | |||
2078 | return S.Context.getQualifiedType(type, qs); | |||
2079 | } | |||
2080 | ||||
2081 | static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ | |||
2082 | std::string Quals = FnTy->getMethodQuals().getAsString(); | |||
2083 | ||||
2084 | switch (FnTy->getRefQualifier()) { | |||
2085 | case RQ_None: | |||
2086 | break; | |||
2087 | ||||
2088 | case RQ_LValue: | |||
2089 | if (!Quals.empty()) | |||
2090 | Quals += ' '; | |||
2091 | Quals += '&'; | |||
2092 | break; | |||
2093 | ||||
2094 | case RQ_RValue: | |||
2095 | if (!Quals.empty()) | |||
2096 | Quals += ' '; | |||
2097 | Quals += "&&"; | |||
2098 | break; | |||
2099 | } | |||
2100 | ||||
2101 | return Quals; | |||
2102 | } | |||
2103 | ||||
2104 | namespace { | |||
2105 | /// Kinds of declarator that cannot contain a qualified function type. | |||
2106 | /// | |||
2107 | /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: | |||
2108 | /// a function type with a cv-qualifier or a ref-qualifier can only appear | |||
2109 | /// at the topmost level of a type. | |||
2110 | /// | |||
2111 | /// Parens and member pointers are permitted. We don't diagnose array and | |||
2112 | /// function declarators, because they don't allow function types at all. | |||
2113 | /// | |||
2114 | /// The values of this enum are used in diagnostics. | |||
2115 | enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; | |||
2116 | } // end anonymous namespace | |||
2117 | ||||
2118 | /// Check whether the type T is a qualified function type, and if it is, | |||
2119 | /// diagnose that it cannot be contained within the given kind of declarator. | |||
2120 | static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, | |||
2121 | QualifiedFunctionKind QFK) { | |||
2122 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | |||
2123 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); | |||
2124 | if (!FPT || | |||
2125 | (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) | |||
2126 | return false; | |||
2127 | ||||
2128 | S.Diag(Loc, diag::err_compound_qualified_function_type) | |||
2129 | << QFK << isa<FunctionType>(T.IgnoreParens()) << T | |||
2130 | << getFunctionQualifiersAsString(FPT); | |||
2131 | return true; | |||
2132 | } | |||
2133 | ||||
2134 | bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) { | |||
2135 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); | |||
2136 | if (!FPT || | |||
2137 | (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) | |||
2138 | return false; | |||
2139 | ||||
2140 | Diag(Loc, diag::err_qualified_function_typeid) | |||
2141 | << T << getFunctionQualifiersAsString(FPT); | |||
2142 | return true; | |||
2143 | } | |||
2144 | ||||
2145 | // Helper to deduce addr space of a pointee type in OpenCL mode. | |||
2146 | static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) { | |||
2147 | if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() && | |||
2148 | !PointeeType->isSamplerT() && | |||
2149 | !PointeeType.hasAddressSpace()) | |||
2150 | PointeeType = S.getASTContext().getAddrSpaceQualType( | |||
2151 | PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace()); | |||
2152 | return PointeeType; | |||
2153 | } | |||
2154 | ||||
2155 | /// Build a pointer type. | |||
2156 | /// | |||
2157 | /// \param T The type to which we'll be building a pointer. | |||
2158 | /// | |||
2159 | /// \param Loc The location of the entity whose type involves this | |||
2160 | /// pointer type or, if there is no such entity, the location of the | |||
2161 | /// type that will have pointer type. | |||
2162 | /// | |||
2163 | /// \param Entity The name of the entity that involves the pointer | |||
2164 | /// type, if known. | |||
2165 | /// | |||
2166 | /// \returns A suitable pointer type, if there are no | |||
2167 | /// errors. Otherwise, returns a NULL type. | |||
2168 | QualType Sema::BuildPointerType(QualType T, | |||
2169 | SourceLocation Loc, DeclarationName Entity) { | |||
2170 | if (T->isReferenceType()) { | |||
2171 | // C++ 8.3.2p4: There shall be no ... pointers to references ... | |||
2172 | Diag(Loc, diag::err_illegal_decl_pointer_to_reference) | |||
2173 | << getPrintableNameForEntity(Entity) << T; | |||
2174 | return QualType(); | |||
2175 | } | |||
2176 | ||||
2177 | if (T->isFunctionType() && getLangOpts().OpenCL && | |||
2178 | !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", | |||
2179 | getLangOpts())) { | |||
2180 | Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0; | |||
2181 | return QualType(); | |||
2182 | } | |||
2183 | ||||
2184 | if (getLangOpts().HLSL && Loc.isValid()) { | |||
2185 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0; | |||
2186 | return QualType(); | |||
2187 | } | |||
2188 | ||||
2189 | if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) | |||
2190 | return QualType(); | |||
2191 | ||||
2192 | assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType")(static_cast <bool> (!T->isObjCObjectType() && "Should build ObjCObjectPointerType") ? void (0) : __assert_fail ("!T->isObjCObjectType() && \"Should build ObjCObjectPointerType\"" , "clang/lib/Sema/SemaType.cpp", 2192, __extension__ __PRETTY_FUNCTION__ )); | |||
2193 | ||||
2194 | // In ARC, it is forbidden to build pointers to unqualified pointers. | |||
2195 | if (getLangOpts().ObjCAutoRefCount) | |||
2196 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); | |||
2197 | ||||
2198 | if (getLangOpts().OpenCL) | |||
2199 | T = deduceOpenCLPointeeAddrSpace(*this, T); | |||
2200 | ||||
2201 | // Build the pointer type. | |||
2202 | return Context.getPointerType(T); | |||
2203 | } | |||
2204 | ||||
2205 | /// Build a reference type. | |||
2206 | /// | |||
2207 | /// \param T The type to which we'll be building a reference. | |||
2208 | /// | |||
2209 | /// \param Loc The location of the entity whose type involves this | |||
2210 | /// reference type or, if there is no such entity, the location of the | |||
2211 | /// type that will have reference type. | |||
2212 | /// | |||
2213 | /// \param Entity The name of the entity that involves the reference | |||
2214 | /// type, if known. | |||
2215 | /// | |||
2216 | /// \returns A suitable reference type, if there are no | |||
2217 | /// errors. Otherwise, returns a NULL type. | |||
2218 | QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, | |||
2219 | SourceLocation Loc, | |||
2220 | DeclarationName Entity) { | |||
2221 | assert(Context.getCanonicalType(T) != Context.OverloadTy &&(static_cast <bool> (Context.getCanonicalType(T) != Context .OverloadTy && "Unresolved overloaded function type") ? void (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "clang/lib/Sema/SemaType.cpp", 2222, __extension__ __PRETTY_FUNCTION__ )) | |||
2222 | "Unresolved overloaded function type")(static_cast <bool> (Context.getCanonicalType(T) != Context .OverloadTy && "Unresolved overloaded function type") ? void (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "clang/lib/Sema/SemaType.cpp", 2222, __extension__ __PRETTY_FUNCTION__ )); | |||
2223 | ||||
2224 | // C++0x [dcl.ref]p6: | |||
2225 | // If a typedef (7.1.3), a type template-parameter (14.3.1), or a | |||
2226 | // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a | |||
2227 | // type T, an attempt to create the type "lvalue reference to cv TR" creates | |||
2228 | // the type "lvalue reference to T", while an attempt to create the type | |||
2229 | // "rvalue reference to cv TR" creates the type TR. | |||
2230 | bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); | |||
2231 | ||||
2232 | // C++ [dcl.ref]p4: There shall be no references to references. | |||
2233 | // | |||
2234 | // According to C++ DR 106, references to references are only | |||
2235 | // diagnosed when they are written directly (e.g., "int & &"), | |||
2236 | // but not when they happen via a typedef: | |||
2237 | // | |||
2238 | // typedef int& intref; | |||
2239 | // typedef intref& intref2; | |||
2240 | // | |||
2241 | // Parser::ParseDeclaratorInternal diagnoses the case where | |||
2242 | // references are written directly; here, we handle the | |||
2243 | // collapsing of references-to-references as described in C++0x. | |||
2244 | // DR 106 and 540 introduce reference-collapsing into C++98/03. | |||
2245 | ||||
2246 | // C++ [dcl.ref]p1: | |||
2247 | // A declarator that specifies the type "reference to cv void" | |||
2248 | // is ill-formed. | |||
2249 | if (T->isVoidType()) { | |||
2250 | Diag(Loc, diag::err_reference_to_void); | |||
2251 | return QualType(); | |||
2252 | } | |||
2253 | ||||
2254 | if (getLangOpts().HLSL && Loc.isValid()) { | |||
2255 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1; | |||
2256 | return QualType(); | |||
2257 | } | |||
2258 | ||||
2259 | if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) | |||
2260 | return QualType(); | |||
2261 | ||||
2262 | if (T->isFunctionType() && getLangOpts().OpenCL && | |||
2263 | !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", | |||
2264 | getLangOpts())) { | |||
2265 | Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1; | |||
2266 | return QualType(); | |||
2267 | } | |||
2268 | ||||
2269 | // In ARC, it is forbidden to build references to unqualified pointers. | |||
2270 | if (getLangOpts().ObjCAutoRefCount) | |||
2271 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); | |||
2272 | ||||
2273 | if (getLangOpts().OpenCL) | |||
2274 | T = deduceOpenCLPointeeAddrSpace(*this, T); | |||
2275 | ||||
2276 | // Handle restrict on references. | |||
2277 | if (LValueRef) | |||
2278 | return Context.getLValueReferenceType(T, SpelledAsLValue); | |||
2279 | return Context.getRValueReferenceType(T); | |||
2280 | } | |||
2281 | ||||
2282 | /// Build a Read-only Pipe type. | |||
2283 | /// | |||
2284 | /// \param T The type to which we'll be building a Pipe. | |||
2285 | /// | |||
2286 | /// \param Loc We do not use it for now. | |||
2287 | /// | |||
2288 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | |||
2289 | /// NULL type. | |||
2290 | QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { | |||
2291 | return Context.getReadPipeType(T); | |||
2292 | } | |||
2293 | ||||
2294 | /// Build a Write-only Pipe type. | |||
2295 | /// | |||
2296 | /// \param T The type to which we'll be building a Pipe. | |||
2297 | /// | |||
2298 | /// \param Loc We do not use it for now. | |||
2299 | /// | |||
2300 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | |||
2301 | /// NULL type. | |||
2302 | QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { | |||
2303 | return Context.getWritePipeType(T); | |||
2304 | } | |||
2305 | ||||
2306 | /// Build a bit-precise integer type. | |||
2307 | /// | |||
2308 | /// \param IsUnsigned Boolean representing the signedness of the type. | |||
2309 | /// | |||
2310 | /// \param BitWidth Size of this int type in bits, or an expression representing | |||
2311 | /// that. | |||
2312 | /// | |||
2313 | /// \param Loc Location of the keyword. | |||
2314 | QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth, | |||
2315 | SourceLocation Loc) { | |||
2316 | if (BitWidth->isInstantiationDependent()) | |||
2317 | return Context.getDependentBitIntType(IsUnsigned, BitWidth); | |||
2318 | ||||
2319 | llvm::APSInt Bits(32); | |||
2320 | ExprResult ICE = | |||
2321 | VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold); | |||
2322 | ||||
2323 | if (ICE.isInvalid()) | |||
2324 | return QualType(); | |||
2325 | ||||
2326 | size_t NumBits = Bits.getZExtValue(); | |||
2327 | if (!IsUnsigned && NumBits < 2) { | |||
2328 | Diag(Loc, diag::err_bit_int_bad_size) << 0; | |||
2329 | return QualType(); | |||
2330 | } | |||
2331 | ||||
2332 | if (IsUnsigned && NumBits < 1) { | |||
2333 | Diag(Loc, diag::err_bit_int_bad_size) << 1; | |||
2334 | return QualType(); | |||
2335 | } | |||
2336 | ||||
2337 | const TargetInfo &TI = getASTContext().getTargetInfo(); | |||
2338 | if (NumBits > TI.getMaxBitIntWidth()) { | |||
2339 | Diag(Loc, diag::err_bit_int_max_size) | |||
2340 | << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth()); | |||
2341 | return QualType(); | |||
2342 | } | |||
2343 | ||||
2344 | return Context.getBitIntType(IsUnsigned, NumBits); | |||
2345 | } | |||
2346 | ||||
2347 | /// Check whether the specified array bound can be evaluated using the relevant | |||
2348 | /// language rules. If so, returns the possibly-converted expression and sets | |||
2349 | /// SizeVal to the size. If not, but the expression might be a VLA bound, | |||
2350 | /// returns ExprResult(). Otherwise, produces a diagnostic and returns | |||
2351 | /// ExprError(). | |||
2352 | static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, | |||
2353 | llvm::APSInt &SizeVal, unsigned VLADiag, | |||
2354 | bool VLAIsError) { | |||
2355 | if (S.getLangOpts().CPlusPlus14 && | |||
2356 | (VLAIsError || | |||
2357 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) { | |||
2358 | // C++14 [dcl.array]p1: | |||
2359 | // The constant-expression shall be a converted constant expression of | |||
2360 | // type std::size_t. | |||
2361 | // | |||
2362 | // Don't apply this rule if we might be forming a VLA: in that case, we | |||
2363 | // allow non-constant expressions and constant-folding. We only need to use | |||
2364 | // the converted constant expression rules (to properly convert the source) | |||
2365 | // when the source expression is of class type. | |||
2366 | return S.CheckConvertedConstantExpression( | |||
2367 | ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound); | |||
2368 | } | |||
2369 | ||||
2370 | // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode | |||
2371 | // (like gnu99, but not c99) accept any evaluatable value as an extension. | |||
2372 | class VLADiagnoser : public Sema::VerifyICEDiagnoser { | |||
2373 | public: | |||
2374 | unsigned VLADiag; | |||
2375 | bool VLAIsError; | |||
2376 | bool IsVLA = false; | |||
2377 | ||||
2378 | VLADiagnoser(unsigned VLADiag, bool VLAIsError) | |||
2379 | : VLADiag(VLADiag), VLAIsError(VLAIsError) {} | |||
2380 | ||||
2381 | Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | |||
2382 | QualType T) override { | |||
2383 | return S.Diag(Loc, diag::err_array_size_non_int) << T; | |||
2384 | } | |||
2385 | ||||
2386 | Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, | |||
2387 | SourceLocation Loc) override { | |||
2388 | IsVLA = !VLAIsError; | |||
2389 | return S.Diag(Loc, VLADiag); | |||
2390 | } | |||
2391 | ||||
2392 | Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S, | |||
2393 | SourceLocation Loc) override { | |||
2394 | return S.Diag(Loc, diag::ext_vla_folded_to_constant); | |||
2395 | } | |||
2396 | } Diagnoser(VLADiag, VLAIsError); | |||
2397 | ||||
2398 | ExprResult R = | |||
2399 | S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser); | |||
2400 | if (Diagnoser.IsVLA) | |||
2401 | return ExprResult(); | |||
2402 | return R; | |||
2403 | } | |||
2404 | ||||
2405 | bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) { | |||
2406 | EltTy = Context.getBaseElementType(EltTy); | |||
2407 | if (EltTy->isIncompleteType() || EltTy->isDependentType() || | |||
2408 | EltTy->isUndeducedType()) | |||
2409 | return true; | |||
2410 | ||||
2411 | CharUnits Size = Context.getTypeSizeInChars(EltTy); | |||
2412 | CharUnits Alignment = Context.getTypeAlignInChars(EltTy); | |||
2413 | ||||
2414 | if (Size.isMultipleOf(Alignment)) | |||
2415 | return true; | |||
2416 | ||||
2417 | Diag(Loc, diag::err_array_element_alignment) | |||
2418 | << EltTy << Size.getQuantity() << Alignment.getQuantity(); | |||
2419 | return false; | |||
2420 | } | |||
2421 | ||||
2422 | /// Build an array type. | |||
2423 | /// | |||
2424 | /// \param T The type of each element in the array. | |||
2425 | /// | |||
2426 | /// \param ASM C99 array size modifier (e.g., '*', 'static'). | |||
2427 | /// | |||
2428 | /// \param ArraySize Expression describing the size of the array. | |||
2429 | /// | |||
2430 | /// \param Brackets The range from the opening '[' to the closing ']'. | |||
2431 | /// | |||
2432 | /// \param Entity The name of the entity that involves the array | |||
2433 | /// type, if known. | |||
2434 | /// | |||
2435 | /// \returns A suitable array type, if there are no errors. Otherwise, | |||
2436 | /// returns a NULL type. | |||
2437 | QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, | |||
2438 | Expr *ArraySize, unsigned Quals, | |||
2439 | SourceRange Brackets, DeclarationName Entity) { | |||
2440 | ||||
2441 | SourceLocation Loc = Brackets.getBegin(); | |||
2442 | if (getLangOpts().CPlusPlus) { | |||
2443 | // C++ [dcl.array]p1: | |||
2444 | // T is called the array element type; this type shall not be a reference | |||
2445 | // type, the (possibly cv-qualified) type void, a function type or an | |||
2446 | // abstract class type. | |||
2447 | // | |||
2448 | // C++ [dcl.array]p3: | |||
2449 | // When several "array of" specifications are adjacent, [...] only the | |||
2450 | // first of the constant expressions that specify the bounds of the arrays | |||
2451 | // may be omitted. | |||
2452 | // | |||
2453 | // Note: function types are handled in the common path with C. | |||
2454 | if (T->isReferenceType()) { | |||
2455 | Diag(Loc, diag::err_illegal_decl_array_of_references) | |||
2456 | << getPrintableNameForEntity(Entity) << T; | |||
2457 | return QualType(); | |||
2458 | } | |||
2459 | ||||
2460 | if (T->isVoidType() || T->isIncompleteArrayType()) { | |||
2461 | Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T; | |||
2462 | return QualType(); | |||
2463 | } | |||
2464 | ||||
2465 | if (RequireNonAbstractType(Brackets.getBegin(), T, | |||
2466 | diag::err_array_of_abstract_type)) | |||
2467 | return QualType(); | |||
2468 | ||||
2469 | // Mentioning a member pointer type for an array type causes us to lock in | |||
2470 | // an inheritance model, even if it's inside an unused typedef. | |||
2471 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
2472 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) | |||
2473 | if (!MPTy->getClass()->isDependentType()) | |||
2474 | (void)isCompleteType(Loc, T); | |||
2475 | ||||
2476 | } else { | |||
2477 | // C99 6.7.5.2p1: If the element type is an incomplete or function type, | |||
2478 | // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) | |||
2479 | if (RequireCompleteSizedType(Loc, T, | |||
2480 | diag::err_array_incomplete_or_sizeless_type)) | |||
2481 | return QualType(); | |||
2482 | } | |||
2483 | ||||
2484 | if (T->isSizelessType()) { | |||
2485 | Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T; | |||
2486 | return QualType(); | |||
2487 | } | |||
2488 | ||||
2489 | if (T->isFunctionType()) { | |||
2490 | Diag(Loc, diag::err_illegal_decl_array_of_functions) | |||
2491 | << getPrintableNameForEntity(Entity) << T; | |||
2492 | return QualType(); | |||
2493 | } | |||
2494 | ||||
2495 | if (const RecordType *EltTy = T->getAs<RecordType>()) { | |||
2496 | // If the element type is a struct or union that contains a variadic | |||
2497 | // array, accept it as a GNU extension: C99 6.7.2.1p2. | |||
2498 | if (EltTy->getDecl()->hasFlexibleArrayMember()) | |||
2499 | Diag(Loc, diag::ext_flexible_array_in_array) << T; | |||
2500 | } else if (T->isObjCObjectType()) { | |||
2501 | Diag(Loc, diag::err_objc_array_of_interfaces) << T; | |||
2502 | return QualType(); | |||
2503 | } | |||
2504 | ||||
2505 | if (!checkArrayElementAlignment(T, Loc)) | |||
2506 | return QualType(); | |||
2507 | ||||
2508 | // Do placeholder conversions on the array size expression. | |||
2509 | if (ArraySize && ArraySize->hasPlaceholderType()) { | |||
2510 | ExprResult Result = CheckPlaceholderExpr(ArraySize); | |||
2511 | if (Result.isInvalid()) return QualType(); | |||
2512 | ArraySize = Result.get(); | |||
2513 | } | |||
2514 | ||||
2515 | // Do lvalue-to-rvalue conversions on the array size expression. | |||
2516 | if (ArraySize && !ArraySize->isPRValue()) { | |||
2517 | ExprResult Result = DefaultLvalueConversion(ArraySize); | |||
2518 | if (Result.isInvalid()) | |||
2519 | return QualType(); | |||
2520 | ||||
2521 | ArraySize = Result.get(); | |||
2522 | } | |||
2523 | ||||
2524 | // C99 6.7.5.2p1: The size expression shall have integer type. | |||
2525 | // C++11 allows contextual conversions to such types. | |||
2526 | if (!getLangOpts().CPlusPlus11 && | |||
2527 | ArraySize && !ArraySize->isTypeDependent() && | |||
2528 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
2529 | Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) | |||
2530 | << ArraySize->getType() << ArraySize->getSourceRange(); | |||
2531 | return QualType(); | |||
2532 | } | |||
2533 | ||||
2534 | // VLAs always produce at least a -Wvla diagnostic, sometimes an error. | |||
2535 | unsigned VLADiag; | |||
2536 | bool VLAIsError; | |||
2537 | if (getLangOpts().OpenCL) { | |||
2538 | // OpenCL v1.2 s6.9.d: variable length arrays are not supported. | |||
2539 | VLADiag = diag::err_opencl_vla; | |||
2540 | VLAIsError = true; | |||
2541 | } else if (getLangOpts().C99) { | |||
2542 | VLADiag = diag::warn_vla_used; | |||
2543 | VLAIsError = false; | |||
2544 | } else if (isSFINAEContext()) { | |||
2545 | VLADiag = diag::err_vla_in_sfinae; | |||
2546 | VLAIsError = true; | |||
2547 | } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) { | |||
2548 | VLADiag = diag::err_openmp_vla_in_task_untied; | |||
2549 | VLAIsError = true; | |||
2550 | } else { | |||
2551 | VLADiag = diag::ext_vla; | |||
2552 | VLAIsError = false; | |||
2553 | } | |||
2554 | ||||
2555 | llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); | |||
2556 | if (!ArraySize) { | |||
2557 | if (ASM == ArrayType::Star) { | |||
2558 | Diag(Loc, VLADiag); | |||
2559 | if (VLAIsError) | |||
2560 | return QualType(); | |||
2561 | ||||
2562 | T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); | |||
2563 | } else { | |||
2564 | T = Context.getIncompleteArrayType(T, ASM, Quals); | |||
2565 | } | |||
2566 | } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { | |||
2567 | T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2568 | } else { | |||
2569 | ExprResult R = | |||
2570 | checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError); | |||
2571 | if (R.isInvalid()) | |||
2572 | return QualType(); | |||
2573 | ||||
2574 | if (!R.isUsable()) { | |||
2575 | // C99: an array with a non-ICE size is a VLA. We accept any expression | |||
2576 | // that we can fold to a non-zero positive value as a non-VLA as an | |||
2577 | // extension. | |||
2578 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2579 | } else if (!T->isDependentType() && !T->isIncompleteType() && | |||
2580 | !T->isConstantSizeType()) { | |||
2581 | // C99: an array with an element type that has a non-constant-size is a | |||
2582 | // VLA. | |||
2583 | // FIXME: Add a note to explain why this isn't a VLA. | |||
2584 | Diag(Loc, VLADiag); | |||
2585 | if (VLAIsError) | |||
2586 | return QualType(); | |||
2587 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2588 | } else { | |||
2589 | // C99 6.7.5.2p1: If the expression is a constant expression, it shall | |||
2590 | // have a value greater than zero. | |||
2591 | // In C++, this follows from narrowing conversions being disallowed. | |||
2592 | if (ConstVal.isSigned() && ConstVal.isNegative()) { | |||
2593 | if (Entity) | |||
2594 | Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) | |||
2595 | << getPrintableNameForEntity(Entity) | |||
2596 | << ArraySize->getSourceRange(); | |||
2597 | else | |||
2598 | Diag(ArraySize->getBeginLoc(), | |||
2599 | diag::err_typecheck_negative_array_size) | |||
2600 | << ArraySize->getSourceRange(); | |||
2601 | return QualType(); | |||
2602 | } | |||
2603 | if (ConstVal == 0) { | |||
2604 | // GCC accepts zero sized static arrays. We allow them when | |||
2605 | // we're not in a SFINAE context. | |||
2606 | Diag(ArraySize->getBeginLoc(), | |||
2607 | isSFINAEContext() ? diag::err_typecheck_zero_array_size | |||
2608 | : diag::ext_typecheck_zero_array_size) | |||
2609 | << 0 << ArraySize->getSourceRange(); | |||
2610 | } | |||
2611 | ||||
2612 | // Is the array too large? | |||
2613 | unsigned ActiveSizeBits = | |||
2614 | (!T->isDependentType() && !T->isVariablyModifiedType() && | |||
2615 | !T->isIncompleteType() && !T->isUndeducedType()) | |||
2616 | ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal) | |||
2617 | : ConstVal.getActiveBits(); | |||
2618 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | |||
2619 | Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) | |||
2620 | << toString(ConstVal, 10) << ArraySize->getSourceRange(); | |||
2621 | return QualType(); | |||
2622 | } | |||
2623 | ||||
2624 | T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals); | |||
2625 | } | |||
2626 | } | |||
2627 | ||||
2628 | if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) { | |||
2629 | // CUDA device code and some other targets don't support VLAs. | |||
2630 | targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) | |||
2631 | ? diag::err_cuda_vla | |||
2632 | : diag::err_vla_unsupported) | |||
2633 | << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice) | |||
2634 | ? CurrentCUDATarget() | |||
2635 | : CFT_InvalidTarget); | |||
2636 | } | |||
2637 | ||||
2638 | // If this is not C99, diagnose array size modifiers on non-VLAs. | |||
2639 | if (!getLangOpts().C99 && !T->isVariableArrayType() && | |||
2640 | (ASM != ArrayType::Normal || Quals != 0)) { | |||
2641 | Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx | |||
2642 | : diag::ext_c99_array_usage) | |||
2643 | << ASM; | |||
2644 | } | |||
2645 | ||||
2646 | // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. | |||
2647 | // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. | |||
2648 | // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. | |||
2649 | if (getLangOpts().OpenCL) { | |||
2650 | const QualType ArrType = Context.getBaseElementType(T); | |||
2651 | if (ArrType->isBlockPointerType() || ArrType->isPipeType() || | |||
2652 | ArrType->isSamplerT() || ArrType->isImageType()) { | |||
2653 | Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; | |||
2654 | return QualType(); | |||
2655 | } | |||
2656 | } | |||
2657 | ||||
2658 | return T; | |||
2659 | } | |||
2660 | ||||
2661 | QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, | |||
2662 | SourceLocation AttrLoc) { | |||
2663 | // The base type must be integer (not Boolean or enumeration) or float, and | |||
2664 | // can't already be a vector. | |||
2665 | if ((!CurType->isDependentType() && | |||
2666 | (!CurType->isBuiltinType() || CurType->isBooleanType() || | |||
2667 | (!CurType->isIntegerType() && !CurType->isRealFloatingType())) && | |||
2668 | !CurType->isBitIntType()) || | |||
2669 | CurType->isArrayType()) { | |||
2670 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; | |||
2671 | return QualType(); | |||
2672 | } | |||
2673 | // Only support _BitInt elements with byte-sized power of 2 NumBits. | |||
2674 | if (CurType->isBitIntType()) { | |||
2675 | unsigned NumBits = CurType->getAs<BitIntType>()->getNumBits(); | |||
2676 | if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) { | |||
2677 | Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type) | |||
2678 | << (NumBits < 8); | |||
2679 | return QualType(); | |||
2680 | } | |||
2681 | } | |||
2682 | ||||
2683 | if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) | |||
2684 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, | |||
2685 | VectorType::GenericVector); | |||
2686 | ||||
2687 | Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context); | |||
2688 | if (!VecSize) { | |||
2689 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2690 | << "vector_size" << AANT_ArgumentIntegerConstant | |||
2691 | << SizeExpr->getSourceRange(); | |||
2692 | return QualType(); | |||
2693 | } | |||
2694 | ||||
2695 | if (CurType->isDependentType()) | |||
2696 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, | |||
2697 | VectorType::GenericVector); | |||
2698 | ||||
2699 | // vecSize is specified in bytes - convert to bits. | |||
2700 | if (!VecSize->isIntN(61)) { | |||
2701 | // Bit size will overflow uint64. | |||
2702 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2703 | << SizeExpr->getSourceRange() << "vector"; | |||
2704 | return QualType(); | |||
2705 | } | |||
2706 | uint64_t VectorSizeBits = VecSize->getZExtValue() * 8; | |||
2707 | unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType)); | |||
2708 | ||||
2709 | if (VectorSizeBits == 0) { | |||
2710 | Diag(AttrLoc, diag::err_attribute_zero_size) | |||
2711 | << SizeExpr->getSourceRange() << "vector"; | |||
2712 | return QualType(); | |||
2713 | } | |||
2714 | ||||
2715 | if (!TypeSize || VectorSizeBits % TypeSize) { | |||
2716 | Diag(AttrLoc, diag::err_attribute_invalid_size) | |||
2717 | << SizeExpr->getSourceRange(); | |||
2718 | return QualType(); | |||
2719 | } | |||
2720 | ||||
2721 | if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) { | |||
2722 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2723 | << SizeExpr->getSourceRange() << "vector"; | |||
2724 | return QualType(); | |||
2725 | } | |||
2726 | ||||
2727 | return Context.getVectorType(CurType, VectorSizeBits / TypeSize, | |||
2728 | VectorType::GenericVector); | |||
2729 | } | |||
2730 | ||||
2731 | /// Build an ext-vector type. | |||
2732 | /// | |||
2733 | /// Run the required checks for the extended vector type. | |||
2734 | QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, | |||
2735 | SourceLocation AttrLoc) { | |||
2736 | // Unlike gcc's vector_size attribute, we do not allow vectors to be defined | |||
2737 | // in conjunction with complex types (pointers, arrays, functions, etc.). | |||
2738 | // | |||
2739 | // Additionally, OpenCL prohibits vectors of booleans (they're considered a | |||
2740 | // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects | |||
2741 | // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors | |||
2742 | // of bool aren't allowed. | |||
2743 | // | |||
2744 | // We explictly allow bool elements in ext_vector_type for C/C++. | |||
2745 | bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus; | |||
2746 | if ((!T->isDependentType() && !T->isIntegerType() && | |||
2747 | !T->isRealFloatingType()) || | |||
2748 | (IsNoBoolVecLang && T->isBooleanType())) { | |||
2749 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; | |||
2750 | return QualType(); | |||
2751 | } | |||
2752 | ||||
2753 | // Only support _BitInt elements with byte-sized power of 2 NumBits. | |||
2754 | if (T->isBitIntType()) { | |||
2755 | unsigned NumBits = T->getAs<BitIntType>()->getNumBits(); | |||
2756 | if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) { | |||
2757 | Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type) | |||
2758 | << (NumBits < 8); | |||
2759 | return QualType(); | |||
2760 | } | |||
2761 | } | |||
2762 | ||||
2763 | if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { | |||
2764 | Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context); | |||
2765 | if (!vecSize) { | |||
2766 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2767 | << "ext_vector_type" << AANT_ArgumentIntegerConstant | |||
2768 | << ArraySize->getSourceRange(); | |||
2769 | return QualType(); | |||
2770 | } | |||
2771 | ||||
2772 | if (!vecSize->isIntN(32)) { | |||
2773 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2774 | << ArraySize->getSourceRange() << "vector"; | |||
2775 | return QualType(); | |||
2776 | } | |||
2777 | // Unlike gcc's vector_size attribute, the size is specified as the | |||
2778 | // number of elements, not the number of bytes. | |||
2779 | unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue()); | |||
2780 | ||||
2781 | if (vectorSize == 0) { | |||
2782 | Diag(AttrLoc, diag::err_attribute_zero_size) | |||
2783 | << ArraySize->getSourceRange() << "vector"; | |||
2784 | return QualType(); | |||
2785 | } | |||
2786 | ||||
2787 | return Context.getExtVectorType(T, vectorSize); | |||
2788 | } | |||
2789 | ||||
2790 | return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); | |||
2791 | } | |||
2792 | ||||
2793 | QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols, | |||
2794 | SourceLocation AttrLoc) { | |||
2795 | assert(Context.getLangOpts().MatrixTypes &&(static_cast <bool> (Context.getLangOpts().MatrixTypes && "Should never build a matrix type when it is disabled") ? void (0) : __assert_fail ("Context.getLangOpts().MatrixTypes && \"Should never build a matrix type when it is disabled\"" , "clang/lib/Sema/SemaType.cpp", 2796, __extension__ __PRETTY_FUNCTION__ )) | |||
2796 | "Should never build a matrix type when it is disabled")(static_cast <bool> (Context.getLangOpts().MatrixTypes && "Should never build a matrix type when it is disabled") ? void (0) : __assert_fail ("Context.getLangOpts().MatrixTypes && \"Should never build a matrix type when it is disabled\"" , "clang/lib/Sema/SemaType.cpp", 2796, __extension__ __PRETTY_FUNCTION__ )); | |||
2797 | ||||
2798 | // Check element type, if it is not dependent. | |||
2799 | if (!ElementTy->isDependentType() && | |||
2800 | !MatrixType::isValidElementType(ElementTy)) { | |||
2801 | Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy; | |||
2802 | return QualType(); | |||
2803 | } | |||
2804 | ||||
2805 | if (NumRows->isTypeDependent() || NumCols->isTypeDependent() || | |||
2806 | NumRows->isValueDependent() || NumCols->isValueDependent()) | |||
2807 | return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols, | |||
2808 | AttrLoc); | |||
2809 | ||||
2810 | Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context); | |||
2811 | Optional<llvm::APSInt> ValueColumns = | |||
2812 | NumCols->getIntegerConstantExpr(Context); | |||
2813 | ||||
2814 | auto const RowRange = NumRows->getSourceRange(); | |||
2815 | auto const ColRange = NumCols->getSourceRange(); | |||
2816 | ||||
2817 | // Both are row and column expressions are invalid. | |||
2818 | if (!ValueRows && !ValueColumns) { | |||
2819 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2820 | << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange | |||
2821 | << ColRange; | |||
2822 | return QualType(); | |||
2823 | } | |||
2824 | ||||
2825 | // Only the row expression is invalid. | |||
2826 | if (!ValueRows) { | |||
2827 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2828 | << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange; | |||
2829 | return QualType(); | |||
2830 | } | |||
2831 | ||||
2832 | // Only the column expression is invalid. | |||
2833 | if (!ValueColumns) { | |||
2834 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2835 | << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange; | |||
2836 | return QualType(); | |||
2837 | } | |||
2838 | ||||
2839 | // Check the matrix dimensions. | |||
2840 | unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue()); | |||
2841 | unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue()); | |||
2842 | if (MatrixRows == 0 && MatrixColumns == 0) { | |||
2843 | Diag(AttrLoc, diag::err_attribute_zero_size) | |||
2844 | << "matrix" << RowRange << ColRange; | |||
2845 | return QualType(); | |||
2846 | } | |||
2847 | if (MatrixRows == 0) { | |||
2848 | Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange; | |||
2849 | return QualType(); | |||
2850 | } | |||
2851 | if (MatrixColumns == 0) { | |||
2852 | Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange; | |||
2853 | return QualType(); | |||
2854 | } | |||
2855 | if (!ConstantMatrixType::isDimensionValid(MatrixRows)) { | |||
2856 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2857 | << RowRange << "matrix row"; | |||
2858 | return QualType(); | |||
2859 | } | |||
2860 | if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) { | |||
2861 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2862 | << ColRange << "matrix column"; | |||
2863 | return QualType(); | |||
2864 | } | |||
2865 | return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns); | |||
2866 | } | |||
2867 | ||||
2868 | bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { | |||
2869 | if (T->isArrayType() || T->isFunctionType()) { | |||
2870 | Diag(Loc, diag::err_func_returning_array_function) | |||
2871 | << T->isFunctionType() << T; | |||
2872 | return true; | |||
2873 | } | |||
2874 | ||||
2875 | // Functions cannot return half FP. | |||
2876 | if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns && | |||
2877 | !Context.getTargetInfo().allowHalfArgsAndReturns()) { | |||
2878 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << | |||
2879 | FixItHint::CreateInsertion(Loc, "*"); | |||
2880 | return true; | |||
2881 | } | |||
2882 | ||||
2883 | // Methods cannot return interface types. All ObjC objects are | |||
2884 | // passed by reference. | |||
2885 | if (T->isObjCObjectType()) { | |||
2886 | Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) | |||
2887 | << 0 << T << FixItHint::CreateInsertion(Loc, "*"); | |||
2888 | return true; | |||
2889 | } | |||
2890 | ||||
2891 | if (T.hasNonTrivialToPrimitiveDestructCUnion() || | |||
2892 | T.hasNonTrivialToPrimitiveCopyCUnion()) | |||
2893 | checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn, | |||
2894 | NTCUK_Destruct|NTCUK_Copy); | |||
2895 | ||||
2896 | // C++2a [dcl.fct]p12: | |||
2897 | // A volatile-qualified return type is deprecated | |||
2898 | if (T.isVolatileQualified() && getLangOpts().CPlusPlus20) | |||
2899 | Diag(Loc, diag::warn_deprecated_volatile_return) << T; | |||
2900 | ||||
2901 | return false; | |||
2902 | } | |||
2903 | ||||
2904 | /// Check the extended parameter information. Most of the necessary | |||
2905 | /// checking should occur when applying the parameter attribute; the | |||
2906 | /// only other checks required are positional restrictions. | |||
2907 | static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, | |||
2908 | const FunctionProtoType::ExtProtoInfo &EPI, | |||
2909 | llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { | |||
2910 | assert(EPI.ExtParameterInfos && "shouldn't get here without param infos")(static_cast <bool> (EPI.ExtParameterInfos && "shouldn't get here without param infos" ) ? void (0) : __assert_fail ("EPI.ExtParameterInfos && \"shouldn't get here without param infos\"" , "clang/lib/Sema/SemaType.cpp", 2910, __extension__ __PRETTY_FUNCTION__ )); | |||
2911 | ||||
2912 | bool emittedError = false; | |||
2913 | auto actualCC = EPI.ExtInfo.getCC(); | |||
2914 | enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync }; | |||
2915 | auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) { | |||
2916 | bool isCompatible = | |||
2917 | (required == RequiredCC::OnlySwift) | |||
2918 | ? (actualCC == CC_Swift) | |||
2919 | : (actualCC == CC_Swift || actualCC == CC_SwiftAsync); | |||
2920 | if (isCompatible || emittedError) | |||
2921 | return; | |||
2922 | S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) | |||
2923 | << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()) | |||
2924 | << (required == RequiredCC::OnlySwift); | |||
2925 | emittedError = true; | |||
2926 | }; | |||
2927 | for (size_t paramIndex = 0, numParams = paramTypes.size(); | |||
2928 | paramIndex != numParams; ++paramIndex) { | |||
2929 | switch (EPI.ExtParameterInfos[paramIndex].getABI()) { | |||
2930 | // Nothing interesting to check for orindary-ABI parameters. | |||
2931 | case ParameterABI::Ordinary: | |||
2932 | continue; | |||
2933 | ||||
2934 | // swift_indirect_result parameters must be a prefix of the function | |||
2935 | // arguments. | |||
2936 | case ParameterABI::SwiftIndirectResult: | |||
2937 | checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync); | |||
2938 | if (paramIndex != 0 && | |||
2939 | EPI.ExtParameterInfos[paramIndex - 1].getABI() | |||
2940 | != ParameterABI::SwiftIndirectResult) { | |||
2941 | S.Diag(getParamLoc(paramIndex), | |||
2942 | diag::err_swift_indirect_result_not_first); | |||
2943 | } | |||
2944 | continue; | |||
2945 | ||||
2946 | case ParameterABI::SwiftContext: | |||
2947 | checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync); | |||
2948 | continue; | |||
2949 | ||||
2950 | // SwiftAsyncContext is not limited to swiftasynccall functions. | |||
2951 | case ParameterABI::SwiftAsyncContext: | |||
2952 | continue; | |||
2953 | ||||
2954 | // swift_error parameters must be preceded by a swift_context parameter. | |||
2955 | case ParameterABI::SwiftErrorResult: | |||
2956 | checkCompatible(paramIndex, RequiredCC::OnlySwift); | |||
2957 | if (paramIndex == 0 || | |||
2958 | EPI.ExtParameterInfos[paramIndex - 1].getABI() != | |||
2959 | ParameterABI::SwiftContext) { | |||
2960 | S.Diag(getParamLoc(paramIndex), | |||
2961 | diag::err_swift_error_result_not_after_swift_context); | |||
2962 | } | |||
2963 | continue; | |||
2964 | } | |||
2965 | llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "clang/lib/Sema/SemaType.cpp" , 2965); | |||
2966 | } | |||
2967 | } | |||
2968 | ||||
2969 | QualType Sema::BuildFunctionType(QualType T, | |||
2970 | MutableArrayRef<QualType> ParamTypes, | |||
2971 | SourceLocation Loc, DeclarationName Entity, | |||
2972 | const FunctionProtoType::ExtProtoInfo &EPI) { | |||
2973 | bool Invalid = false; | |||
2974 | ||||
2975 | Invalid |= CheckFunctionReturnType(T, Loc); | |||
2976 | ||||
2977 | for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { | |||
2978 | // FIXME: Loc is too inprecise here, should use proper locations for args. | |||
2979 | QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); | |||
2980 | if (ParamType->isVoidType()) { | |||
2981 | Diag(Loc, diag::err_param_with_void_type); | |||
2982 | Invalid = true; | |||
2983 | } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns && | |||
2984 | !Context.getTargetInfo().allowHalfArgsAndReturns()) { | |||
2985 | // Disallow half FP arguments. | |||
2986 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << | |||
2987 | FixItHint::CreateInsertion(Loc, "*"); | |||
2988 | Invalid = true; | |||
2989 | } | |||
2990 | ||||
2991 | // C++2a [dcl.fct]p4: | |||
2992 | // A parameter with volatile-qualified type is deprecated | |||
2993 | if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20) | |||
2994 | Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType; | |||
2995 | ||||
2996 | ParamTypes[Idx] = ParamType; | |||
2997 | } | |||
2998 | ||||
2999 | if (EPI.ExtParameterInfos) { | |||
3000 | checkExtParameterInfos(*this, ParamTypes, EPI, | |||
3001 | [=](unsigned i) { return Loc; }); | |||
3002 | } | |||
3003 | ||||
3004 | if (EPI.ExtInfo.getProducesResult()) { | |||
3005 | // This is just a warning, so we can't fail to build if we see it. | |||
3006 | checkNSReturnsRetainedReturnType(Loc, T); | |||
3007 | } | |||
3008 | ||||
3009 | if (Invalid) | |||
3010 | return QualType(); | |||
3011 | ||||
3012 | return Context.getFunctionType(T, ParamTypes, EPI); | |||
3013 | } | |||
3014 | ||||
3015 | /// Build a member pointer type \c T Class::*. | |||
3016 | /// | |||
3017 | /// \param T the type to which the member pointer refers. | |||
3018 | /// \param Class the class type into which the member pointer points. | |||
3019 | /// \param Loc the location where this type begins | |||
3020 | /// \param Entity the name of the entity that will have this member pointer type | |||
3021 | /// | |||
3022 | /// \returns a member pointer type, if successful, or a NULL type if there was | |||
3023 | /// an error. | |||
3024 | QualType Sema::BuildMemberPointerType(QualType T, QualType Class, | |||
3025 | SourceLocation Loc, | |||
3026 | DeclarationName Entity) { | |||
3027 | // Verify that we're not building a pointer to pointer to function with | |||
3028 | // exception specification. | |||
3029 | if (CheckDistantExceptionSpec(T)) { | |||
3030 | Diag(Loc, diag::err_distant_exception_spec); | |||
3031 | return QualType(); | |||
3032 | } | |||
3033 | ||||
3034 | // C++ 8.3.3p3: A pointer to member shall not point to ... a member | |||
3035 | // with reference type, or "cv void." | |||
3036 | if (T->isReferenceType()) { | |||
3037 | Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) | |||
3038 | << getPrintableNameForEntity(Entity) << T; | |||
3039 | return QualType(); | |||
3040 | } | |||
3041 | ||||
3042 | if (T->isVoidType()) { | |||
3043 | Diag(Loc, diag::err_illegal_decl_mempointer_to_void) | |||
3044 | << getPrintableNameForEntity(Entity); | |||
3045 | return QualType(); | |||
3046 | } | |||
3047 | ||||
3048 | if (!Class->isDependentType() && !Class->isRecordType()) { | |||
3049 | Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; | |||
3050 | return QualType(); | |||
3051 | } | |||
3052 | ||||
3053 | if (T->isFunctionType() && getLangOpts().OpenCL && | |||
3054 | !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", | |||
3055 | getLangOpts())) { | |||
3056 | Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0; | |||
3057 | return QualType(); | |||
3058 | } | |||
3059 | ||||
3060 | if (getLangOpts().HLSL && Loc.isValid()) { | |||
3061 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0; | |||
3062 | return QualType(); | |||
3063 | } | |||
3064 | ||||
3065 | // Adjust the default free function calling convention to the default method | |||
3066 | // calling convention. | |||
3067 | bool IsCtorOrDtor = | |||
3068 | (Entity.getNameKind() == DeclarationName::CXXConstructorName) || | |||
3069 | (Entity.getNameKind() == DeclarationName::CXXDestructorName); | |||
3070 | if (T->isFunctionType()) | |||
3071 | adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); | |||
3072 | ||||
3073 | return Context.getMemberPointerType(T, Class.getTypePtr()); | |||
3074 | } | |||
3075 | ||||
3076 | /// Build a block pointer type. | |||
3077 | /// | |||
3078 | /// \param T The type to which we'll be building a block pointer. | |||
3079 | /// | |||
3080 | /// \param Loc The source location, used for diagnostics. | |||
3081 | /// | |||
3082 | /// \param Entity The name of the entity that involves the block pointer | |||
3083 | /// type, if known. | |||
3084 | /// | |||
3085 | /// \returns A suitable block pointer type, if there are no | |||
3086 | /// errors. Otherwise, returns a NULL type. | |||
3087 | QualType Sema::BuildBlockPointerType(QualType T, | |||
3088 | SourceLocation Loc, | |||
3089 | DeclarationName Entity) { | |||
3090 | if (!T->isFunctionType()) { | |||
3091 | Diag(Loc, diag::err_nonfunction_block_type); | |||
3092 | return QualType(); | |||
3093 | } | |||
3094 | ||||
3095 | if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) | |||
3096 | return QualType(); | |||
3097 | ||||
3098 | if (getLangOpts().OpenCL) | |||
3099 | T = deduceOpenCLPointeeAddrSpace(*this, T); | |||
3100 | ||||
3101 | return Context.getBlockPointerType(T); | |||
3102 | } | |||
3103 | ||||
3104 | QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { | |||
3105 | QualType QT = Ty.get(); | |||
3106 | if (QT.isNull()) { | |||
3107 | if (TInfo) *TInfo = nullptr; | |||
3108 | return QualType(); | |||
3109 | } | |||
3110 | ||||
3111 | TypeSourceInfo *DI = nullptr; | |||
3112 | if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { | |||
3113 | QT = LIT->getType(); | |||
3114 | DI = LIT->getTypeSourceInfo(); | |||
3115 | } | |||
3116 | ||||
3117 | if (TInfo) *TInfo = DI; | |||
3118 | return QT; | |||
3119 | } | |||
3120 | ||||
3121 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | |||
3122 | Qualifiers::ObjCLifetime ownership, | |||
3123 | unsigned chunkIndex); | |||
3124 | ||||
3125 | /// Given that this is the declaration of a parameter under ARC, | |||
3126 | /// attempt to infer attributes and such for pointer-to-whatever | |||
3127 | /// types. | |||
3128 | static void inferARCWriteback(TypeProcessingState &state, | |||
3129 | QualType &declSpecType) { | |||
3130 | Sema &S = state.getSema(); | |||
3131 | Declarator &declarator = state.getDeclarator(); | |||
3132 | ||||
3133 | // TODO: should we care about decl qualifiers? | |||
3134 | ||||
3135 | // Check whether the declarator has the expected form. We walk | |||
3136 | // from the inside out in order to make the block logic work. | |||
3137 | unsigned outermostPointerIndex = 0; | |||
3138 | bool isBlockPointer = false; | |||
3139 | unsigned numPointers = 0; | |||
3140 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
3141 | unsigned chunkIndex = i; | |||
3142 | DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); | |||
3143 | switch (chunk.Kind) { | |||
3144 | case DeclaratorChunk::Paren: | |||
3145 | // Ignore parens. | |||
3146 | break; | |||
3147 | ||||
3148 | case DeclaratorChunk::Reference: | |||
3149 | case DeclaratorChunk::Pointer: | |||
3150 | // Count the number of pointers. Treat references | |||
3151 | // interchangeably as pointers; if they're mis-ordered, normal | |||
3152 | // type building will discover that. | |||
3153 | outermostPointerIndex = chunkIndex; | |||
3154 | numPointers++; | |||
3155 | break; | |||
3156 | ||||
3157 | case DeclaratorChunk::BlockPointer: | |||
3158 | // If we have a pointer to block pointer, that's an acceptable | |||
3159 | // indirect reference; anything else is not an application of | |||
3160 | // the rules. | |||
3161 | if (numPointers != 1) return; | |||
3162 | numPointers++; | |||
3163 | outermostPointerIndex = chunkIndex; | |||
3164 | isBlockPointer = true; | |||
3165 | ||||
3166 | // We don't care about pointer structure in return values here. | |||
3167 | goto done; | |||
3168 | ||||
3169 | case DeclaratorChunk::Array: // suppress if written (id[])? | |||
3170 | case DeclaratorChunk::Function: | |||
3171 | case DeclaratorChunk::MemberPointer: | |||
3172 | case DeclaratorChunk::Pipe: | |||
3173 | return; | |||
3174 | } | |||
3175 | } | |||
3176 | done: | |||
3177 | ||||
3178 | // If we have *one* pointer, then we want to throw the qualifier on | |||
3179 | // the declaration-specifiers, which means that it needs to be a | |||
3180 | // retainable object type. | |||
3181 | if (numPointers == 1) { | |||
3182 | // If it's not a retainable object type, the rule doesn't apply. | |||
3183 | if (!declSpecType->isObjCRetainableType()) return; | |||
3184 | ||||
3185 | // If it already has lifetime, don't do anything. | |||
3186 | if (declSpecType.getObjCLifetime()) return; | |||
3187 | ||||
3188 | // Otherwise, modify the type in-place. | |||
3189 | Qualifiers qs; | |||
3190 | ||||
3191 | if (declSpecType->isObjCARCImplicitlyUnretainedType()) | |||
3192 | qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); | |||
3193 | else | |||
3194 | qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); | |||
3195 | declSpecType = S.Context.getQualifiedType(declSpecType, qs); | |||
3196 | ||||
3197 | // If we have *two* pointers, then we want to throw the qualifier on | |||
3198 | // the outermost pointer. | |||
3199 | } else if (numPointers == 2) { | |||
3200 | // If we don't have a block pointer, we need to check whether the | |||
3201 | // declaration-specifiers gave us something that will turn into a | |||
3202 | // retainable object pointer after we slap the first pointer on it. | |||
3203 | if (!isBlockPointer && !declSpecType->isObjCObjectType()) | |||
3204 | return; | |||
3205 | ||||
3206 | // Look for an explicit lifetime attribute there. | |||
3207 | DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); | |||
3208 | if (chunk.Kind != DeclaratorChunk::Pointer && | |||
3209 | chunk.Kind != DeclaratorChunk::BlockPointer) | |||
3210 | return; | |||
3211 | for (const ParsedAttr &AL : chunk.getAttrs()) | |||
3212 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) | |||
3213 | return; | |||
3214 | ||||
3215 | transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, | |||
3216 | outermostPointerIndex); | |||
3217 | ||||
3218 | // Any other number of pointers/references does not trigger the rule. | |||
3219 | } else return; | |||
3220 | ||||
3221 | // TODO: mark whether we did this inference? | |||
3222 | } | |||
3223 | ||||
3224 | void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, | |||
3225 | SourceLocation FallbackLoc, | |||
3226 | SourceLocation ConstQualLoc, | |||
3227 | SourceLocation VolatileQualLoc, | |||
3228 | SourceLocation RestrictQualLoc, | |||
3229 | SourceLocation AtomicQualLoc, | |||
3230 | SourceLocation UnalignedQualLoc) { | |||
3231 | if (!Quals) | |||
3232 | return; | |||
3233 | ||||
3234 | struct Qual { | |||
3235 | const char *Name; | |||
3236 | unsigned Mask; | |||
3237 | SourceLocation Loc; | |||
3238 | } const QualKinds[5] = { | |||
3239 | { "const", DeclSpec::TQ_const, ConstQualLoc }, | |||
3240 | { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, | |||
3241 | { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, | |||
3242 | { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, | |||
3243 | { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } | |||
3244 | }; | |||
3245 | ||||
3246 | SmallString<32> QualStr; | |||
3247 | unsigned NumQuals = 0; | |||
3248 | SourceLocation Loc; | |||
3249 | FixItHint FixIts[5]; | |||
3250 | ||||
3251 | // Build a string naming the redundant qualifiers. | |||
3252 | for (auto &E : QualKinds) { | |||
3253 | if (Quals & E.Mask) { | |||
3254 | if (!QualStr.empty()) QualStr += ' '; | |||
3255 | QualStr += E.Name; | |||
3256 | ||||
3257 | // If we have a location for the qualifier, offer a fixit. | |||
3258 | SourceLocation QualLoc = E.Loc; | |||
3259 | if (QualLoc.isValid()) { | |||
3260 | FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); | |||
3261 | if (Loc.isInvalid() || | |||
3262 | getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) | |||
3263 | Loc = QualLoc; | |||
3264 | } | |||
3265 | ||||
3266 | ++NumQuals; | |||
3267 | } | |||
3268 | } | |||
3269 | ||||
3270 | Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) | |||
3271 | << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; | |||
3272 | } | |||
3273 | ||||
3274 | // Diagnose pointless type qualifiers on the return type of a function. | |||
3275 | static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, | |||
3276 | Declarator &D, | |||
3277 | unsigned FunctionChunkIndex) { | |||
3278 | const DeclaratorChunk::FunctionTypeInfo &FTI = | |||
3279 | D.getTypeObject(FunctionChunkIndex).Fun; | |||
3280 | if (FTI.hasTrailingReturnType()) { | |||
3281 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
3282 | RetTy.getLocalCVRQualifiers(), | |||
3283 | FTI.getTrailingReturnTypeLoc()); | |||
3284 | return; | |||
3285 | } | |||
3286 | ||||
3287 | for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, | |||
3288 | End = D.getNumTypeObjects(); | |||
3289 | OuterChunkIndex != End; ++OuterChunkIndex) { | |||
3290 | DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); | |||
3291 | switch (OuterChunk.Kind) { | |||
3292 | case DeclaratorChunk::Paren: | |||
3293 | continue; | |||
3294 | ||||
3295 | case DeclaratorChunk::Pointer: { | |||
3296 | DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; | |||
3297 | S.diagnoseIgnoredQualifiers( | |||
3298 | diag::warn_qual_return_type, | |||
3299 | PTI.TypeQuals, | |||
3300 | SourceLocation(), | |||
3301 | PTI.ConstQualLoc, | |||
3302 | PTI.VolatileQualLoc, | |||
3303 | PTI.RestrictQualLoc, | |||
3304 | PTI.AtomicQualLoc, | |||
3305 | PTI.UnalignedQualLoc); | |||
3306 | return; | |||
3307 | } | |||
3308 | ||||
3309 | case DeclaratorChunk::Function: | |||
3310 | case DeclaratorChunk::BlockPointer: | |||
3311 | case DeclaratorChunk::Reference: | |||
3312 | case DeclaratorChunk::Array: | |||
3313 | case DeclaratorChunk::MemberPointer: | |||
3314 | case DeclaratorChunk::Pipe: | |||
3315 | // FIXME: We can't currently provide an accurate source location and a | |||
3316 | // fix-it hint for these. | |||
3317 | unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; | |||
3318 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
3319 | RetTy.getCVRQualifiers() | AtomicQual, | |||
3320 | D.getIdentifierLoc()); | |||
3321 | return; | |||
3322 | } | |||
3323 | ||||
3324 | llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind" , "clang/lib/Sema/SemaType.cpp", 3324); | |||
3325 | } | |||
3326 | ||||
3327 | // If the qualifiers come from a conversion function type, don't diagnose | |||
3328 | // them -- they're not necessarily redundant, since such a conversion | |||
3329 | // operator can be explicitly called as "x.operator const int()". | |||
3330 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | |||
3331 | return; | |||
3332 | ||||
3333 | // Just parens all the way out to the decl specifiers. Diagnose any qualifiers | |||
3334 | // which are present there. | |||
3335 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
3336 | D.getDeclSpec().getTypeQualifiers(), | |||
3337 | D.getIdentifierLoc(), | |||
3338 | D.getDeclSpec().getConstSpecLoc(), | |||
3339 | D.getDeclSpec().getVolatileSpecLoc(), | |||
3340 | D.getDeclSpec().getRestrictSpecLoc(), | |||
3341 | D.getDeclSpec().getAtomicSpecLoc(), | |||
3342 | D.getDeclSpec().getUnalignedSpecLoc()); | |||
3343 | } | |||
3344 | ||||
3345 | static std::pair<QualType, TypeSourceInfo *> | |||
3346 | InventTemplateParameter(TypeProcessingState &state, QualType T, | |||
3347 | TypeSourceInfo *TrailingTSI, AutoType *Auto, | |||
3348 | InventedTemplateParameterInfo &Info) { | |||
3349 | Sema &S = state.getSema(); | |||
3350 | Declarator &D = state.getDeclarator(); | |||
3351 | ||||
3352 | const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth; | |||
3353 | const unsigned AutoParameterPosition = Info.TemplateParams.size(); | |||
3354 | const bool IsParameterPack = D.hasEllipsis(); | |||
3355 | ||||
3356 | // If auto is mentioned in a lambda parameter or abbreviated function | |||
3357 | // template context, convert it to a template parameter type. | |||
3358 | ||||
3359 | // Create the TemplateTypeParmDecl here to retrieve the corresponding | |||
3360 | // template parameter type. Template parameters are temporarily added | |||
3361 | // to the TU until the associated TemplateDecl is created. | |||
3362 | TemplateTypeParmDecl *InventedTemplateParam = | |||
3363 | TemplateTypeParmDecl::Create( | |||
3364 | S.Context, S.Context.getTranslationUnitDecl(), | |||
3365 | /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(), | |||
3366 | /*NameLoc=*/D.getIdentifierLoc(), | |||
3367 | TemplateParameterDepth, AutoParameterPosition, | |||
3368 | S.InventAbbreviatedTemplateParameterTypeName( | |||
3369 | D.getIdentifier(), AutoParameterPosition), false, | |||
3370 | IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained()); | |||
3371 | InventedTemplateParam->setImplicit(); | |||
3372 | Info.TemplateParams.push_back(InventedTemplateParam); | |||
3373 | ||||
3374 | // Attach type constraints to the new parameter. | |||
3375 | if (Auto->isConstrained()) { | |||
3376 | if (TrailingTSI) { | |||
3377 | // The 'auto' appears in a trailing return type we've already built; | |||
3378 | // extract its type constraints to attach to the template parameter. | |||
3379 | AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc(); | |||
3380 | TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc()); | |||
3381 | bool Invalid = false; | |||
3382 | for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) { | |||
3383 | if (D.getEllipsisLoc().isInvalid() && !Invalid && | |||
3384 | S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx), | |||
3385 | Sema::UPPC_TypeConstraint)) | |||
3386 | Invalid = true; | |||
3387 | TAL.addArgument(AutoLoc.getArgLoc(Idx)); | |||
3388 | } | |||
3389 | ||||
3390 | if (!Invalid) { | |||
3391 | S.AttachTypeConstraint( | |||
3392 | AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(), | |||
3393 | AutoLoc.getNamedConcept(), | |||
3394 | AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr, | |||
3395 | InventedTemplateParam, D.getEllipsisLoc()); | |||
3396 | } | |||
3397 | } else { | |||
3398 | // The 'auto' appears in the decl-specifiers; we've not finished forming | |||
3399 | // TypeSourceInfo for it yet. | |||
3400 | TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId(); | |||
3401 | TemplateArgumentListInfo TemplateArgsInfo; | |||
3402 | bool Invalid = false; | |||
3403 | if (TemplateId->LAngleLoc.isValid()) { | |||
3404 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
3405 | TemplateId->NumArgs); | |||
3406 | S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | |||
3407 | ||||
3408 | if (D.getEllipsisLoc().isInvalid()) { | |||
3409 | for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) { | |||
3410 | if (S.DiagnoseUnexpandedParameterPack(Arg, | |||
3411 | Sema::UPPC_TypeConstraint)) { | |||
3412 | Invalid = true; | |||
3413 | break; | |||
3414 | } | |||
3415 | } | |||
3416 | } | |||
3417 | } | |||
3418 | if (!Invalid) { | |||
3419 | S.AttachTypeConstraint( | |||
3420 | D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context), | |||
3421 | DeclarationNameInfo(DeclarationName(TemplateId->Name), | |||
3422 | TemplateId->TemplateNameLoc), | |||
3423 | cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()), | |||
3424 | TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr, | |||
3425 | InventedTemplateParam, D.getEllipsisLoc()); | |||
3426 | } | |||
3427 | } | |||
3428 | } | |||
3429 | ||||
3430 | // Replace the 'auto' in the function parameter with this invented | |||
3431 | // template type parameter. | |||
3432 | // FIXME: Retain some type sugar to indicate that this was written | |||
3433 | // as 'auto'? | |||
3434 | QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0); | |||
3435 | QualType NewT = state.ReplaceAutoType(T, Replacement); | |||
3436 | TypeSourceInfo *NewTSI = | |||
3437 | TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement) | |||
3438 | : nullptr; | |||
3439 | return {NewT, NewTSI}; | |||
3440 | } | |||
3441 | ||||
3442 | static TypeSourceInfo * | |||
3443 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, | |||
3444 | QualType T, TypeSourceInfo *ReturnTypeInfo); | |||
3445 | ||||
3446 | static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, | |||
3447 | TypeSourceInfo *&ReturnTypeInfo) { | |||
3448 | Sema &SemaRef = state.getSema(); | |||
3449 | Declarator &D = state.getDeclarator(); | |||
3450 | QualType T; | |||
3451 | ReturnTypeInfo = nullptr; | |||
3452 | ||||
3453 | // The TagDecl owned by the DeclSpec. | |||
3454 | TagDecl *OwnedTagDecl = nullptr; | |||
3455 | ||||
3456 | switch (D.getName().getKind()) { | |||
3457 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
3458 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
3459 | case UnqualifiedIdKind::IK_Identifier: | |||
3460 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
3461 | case UnqualifiedIdKind::IK_TemplateId: | |||
3462 | T = ConvertDeclSpecToType(state); | |||
3463 | ||||
3464 | if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { | |||
3465 | OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
3466 | // Owned declaration is embedded in declarator. | |||
3467 | OwnedTagDecl->setEmbeddedInDeclarator(true); | |||
3468 | } | |||
3469 | break; | |||
3470 | ||||
3471 | case UnqualifiedIdKind::IK_ConstructorName: | |||
3472 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
3473 | case UnqualifiedIdKind::IK_DestructorName: | |||
3474 | // Constructors and destructors don't have return types. Use | |||
3475 | // "void" instead. | |||
3476 | T = SemaRef.Context.VoidTy; | |||
3477 | processTypeAttrs(state, T, TAL_DeclSpec, | |||
3478 | D.getMutableDeclSpec().getAttributes()); | |||
3479 | break; | |||
3480 | ||||
3481 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
3482 | // Deduction guides have a trailing return type and no type in their | |||
3483 | // decl-specifier sequence. Use a placeholder return type for now. | |||
3484 | T = SemaRef.Context.DependentTy; | |||
3485 | break; | |||
3486 | ||||
3487 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
3488 | // The result type of a conversion function is the type that it | |||
3489 | // converts to. | |||
3490 | T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, | |||
3491 | &ReturnTypeInfo); | |||
3492 | break; | |||
3493 | } | |||
3494 | ||||
3495 | // Note: We don't need to distribute declaration attributes (i.e. | |||
3496 | // D.getDeclarationAttributes()) because those are always C++11 attributes, | |||
3497 | // and those don't get distributed. | |||
3498 | distributeTypeAttrsFromDeclarator(state, T); | |||
3499 | ||||
3500 | // Find the deduced type in this type. Look in the trailing return type if we | |||
3501 | // have one, otherwise in the DeclSpec type. | |||
3502 | // FIXME: The standard wording doesn't currently describe this. | |||
3503 | DeducedType *Deduced = T->getContainedDeducedType(); | |||
3504 | bool DeducedIsTrailingReturnType = false; | |||
3505 | if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) { | |||
3506 | QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType()); | |||
3507 | Deduced = T.isNull() ? nullptr : T->getContainedDeducedType(); | |||
3508 | DeducedIsTrailingReturnType = true; | |||
3509 | } | |||
3510 | ||||
3511 | // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. | |||
3512 | if (Deduced) { | |||
3513 | AutoType *Auto = dyn_cast<AutoType>(Deduced); | |||
3514 | int Error = -1; | |||
3515 | ||||
3516 | // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or | |||
3517 | // class template argument deduction)? | |||
3518 | bool IsCXXAutoType = | |||
3519 | (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); | |||
3520 | bool IsDeducedReturnType = false; | |||
3521 | ||||
3522 | switch (D.getContext()) { | |||
3523 | case DeclaratorContext::LambdaExpr: | |||
3524 | // Declared return type of a lambda-declarator is implicit and is always | |||
3525 | // 'auto'. | |||
3526 | break; | |||
3527 | case DeclaratorContext::ObjCParameter: | |||
3528 | case DeclaratorContext::ObjCResult: | |||
3529 | Error = 0; | |||
3530 | break; | |||
3531 | case DeclaratorContext::RequiresExpr: | |||
3532 | Error = 22; | |||
3533 | break; | |||
3534 | case DeclaratorContext::Prototype: | |||
3535 | case DeclaratorContext::LambdaExprParameter: { | |||
3536 | InventedTemplateParameterInfo *Info = nullptr; | |||
3537 | if (D.getContext() == DeclaratorContext::Prototype) { | |||
3538 | // With concepts we allow 'auto' in function parameters. | |||
3539 | if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto || | |||
3540 | Auto->getKeyword() != AutoTypeKeyword::Auto) { | |||
3541 | Error = 0; | |||
3542 | break; | |||
3543 | } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) { | |||
3544 | Error = 21; | |||
3545 | break; | |||
3546 | } | |||
3547 | ||||
3548 | Info = &SemaRef.InventedParameterInfos.back(); | |||
3549 | } else { | |||
3550 | // In C++14, generic lambdas allow 'auto' in their parameters. | |||
3551 | if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto || | |||
3552 | Auto->getKeyword() != AutoTypeKeyword::Auto) { | |||
3553 | Error = 16; | |||
3554 | break; | |||
3555 | } | |||
3556 | Info = SemaRef.getCurLambda(); | |||
3557 | assert(Info && "No LambdaScopeInfo on the stack!")(static_cast <bool> (Info && "No LambdaScopeInfo on the stack!" ) ? void (0) : __assert_fail ("Info && \"No LambdaScopeInfo on the stack!\"" , "clang/lib/Sema/SemaType.cpp", 3557, __extension__ __PRETTY_FUNCTION__ )); | |||
3558 | } | |||
3559 | ||||
3560 | // We'll deal with inventing template parameters for 'auto' in trailing | |||
3561 | // return types when we pick up the trailing return type when processing | |||
3562 | // the function chunk. | |||
3563 | if (!DeducedIsTrailingReturnType) | |||
3564 | T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first; | |||
3565 | break; | |||
3566 | } | |||
3567 | case DeclaratorContext::Member: { | |||
3568 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || | |||
3569 | D.isFunctionDeclarator()) | |||
3570 | break; | |||
3571 | bool Cxx = SemaRef.getLangOpts().CPlusPlus; | |||
3572 | if (isa<ObjCContainerDecl>(SemaRef.CurContext)) { | |||
3573 | Error = 6; // Interface member. | |||
3574 | } else { | |||
3575 | switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { | |||
3576 | case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "clang/lib/Sema/SemaType.cpp" , 3576); | |||
3577 | case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; | |||
3578 | case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; | |||
3579 | case TTK_Class: Error = 5; /* Class member */ break; | |||
3580 | case TTK_Interface: Error = 6; /* Interface member */ break; | |||
3581 | } | |||
3582 | } | |||
3583 | if (D.getDeclSpec().isFriendSpecified()) | |||
3584 | Error = 20; // Friend type | |||
3585 | break; | |||
3586 | } | |||
3587 | case DeclaratorContext::CXXCatch: | |||
3588 | case DeclaratorContext::ObjCCatch: | |||
3589 | Error = 7; // Exception declaration | |||
3590 | break; | |||
3591 | case DeclaratorContext::TemplateParam: | |||
3592 | if (isa<DeducedTemplateSpecializationType>(Deduced) && | |||
3593 | !SemaRef.getLangOpts().CPlusPlus20) | |||
3594 | Error = 19; // Template parameter (until C++20) | |||
3595 | else if (!SemaRef.getLangOpts().CPlusPlus17) | |||
3596 | Error = 8; // Template parameter (until C++17) | |||
3597 | break; | |||
3598 | case DeclaratorContext::BlockLiteral: | |||
3599 | Error = 9; // Block literal | |||
3600 | break; | |||
3601 | case DeclaratorContext::TemplateArg: | |||
3602 | // Within a template argument list, a deduced template specialization | |||
3603 | // type will be reinterpreted as a template template argument. | |||
3604 | if (isa<DeducedTemplateSpecializationType>(Deduced) && | |||
3605 | !D.getNumTypeObjects() && | |||
3606 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) | |||
3607 | break; | |||
3608 | [[fallthrough]]; | |||
3609 | case DeclaratorContext::TemplateTypeArg: | |||
3610 | Error = 10; // Template type argument | |||
3611 | break; | |||
3612 | case DeclaratorContext::AliasDecl: | |||
3613 | case DeclaratorContext::AliasTemplate: | |||
3614 | Error = 12; // Type alias | |||
3615 | break; | |||
3616 | case DeclaratorContext::TrailingReturn: | |||
3617 | case DeclaratorContext::TrailingReturnVar: | |||
3618 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | |||
3619 | Error = 13; // Function return type | |||
3620 | IsDeducedReturnType = true; | |||
3621 | break; | |||
3622 | case DeclaratorContext::ConversionId: | |||
3623 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | |||
3624 | Error = 14; // conversion-type-id | |||
3625 | IsDeducedReturnType = true; | |||
3626 | break; | |||
3627 | case DeclaratorContext::FunctionalCast: | |||
3628 | if (isa<DeducedTemplateSpecializationType>(Deduced)) | |||
3629 | break; | |||
3630 | if (SemaRef.getLangOpts().CPlusPlus2b && IsCXXAutoType && | |||
3631 | !Auto->isDecltypeAuto()) | |||
3632 | break; // auto(x) | |||
3633 | [[fallthrough]]; | |||
3634 | case DeclaratorContext::TypeName: | |||
3635 | case DeclaratorContext::Association: | |||
3636 | Error = 15; // Generic | |||
3637 | break; | |||
3638 | case DeclaratorContext::File: | |||
3639 | case DeclaratorContext::Block: | |||
3640 | case DeclaratorContext::ForInit: | |||
3641 | case DeclaratorContext::SelectionInit: | |||
3642 | case DeclaratorContext::Condition: | |||
3643 | // FIXME: P0091R3 (erroneously) does not permit class template argument | |||
3644 | // deduction in conditions, for-init-statements, and other declarations | |||
3645 | // that are not simple-declarations. | |||
3646 | break; | |||
3647 | case DeclaratorContext::CXXNew: | |||
3648 | // FIXME: P0091R3 does not permit class template argument deduction here, | |||
3649 | // but we follow GCC and allow it anyway. | |||
3650 | if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) | |||
3651 | Error = 17; // 'new' type | |||
3652 | break; | |||
3653 | case DeclaratorContext::KNRTypeList: | |||
3654 | Error = 18; // K&R function parameter | |||
3655 | break; | |||
3656 | } | |||
3657 | ||||
3658 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
3659 | Error = 11; | |||
3660 | ||||
3661 | // In Objective-C it is an error to use 'auto' on a function declarator | |||
3662 | // (and everywhere for '__auto_type'). | |||
3663 | if (D.isFunctionDeclarator() && | |||
3664 | (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) | |||
3665 | Error = 13; | |||
3666 | ||||
3667 | SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); | |||
3668 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | |||
3669 | AutoRange = D.getName().getSourceRange(); | |||
3670 | ||||
3671 | if (Error != -1) { | |||
3672 | unsigned Kind; | |||
3673 | if (Auto) { | |||
3674 | switch (Auto->getKeyword()) { | |||
3675 | case AutoTypeKeyword::Auto: Kind = 0; break; | |||
3676 | case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; | |||
3677 | case AutoTypeKeyword::GNUAutoType: Kind = 2; break; | |||
3678 | } | |||
3679 | } else { | |||
3680 | assert(isa<DeducedTemplateSpecializationType>(Deduced) &&(static_cast <bool> (isa<DeducedTemplateSpecializationType >(Deduced) && "unknown auto type") ? void (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "clang/lib/Sema/SemaType.cpp", 3681, __extension__ __PRETTY_FUNCTION__ )) | |||
3681 | "unknown auto type")(static_cast <bool> (isa<DeducedTemplateSpecializationType >(Deduced) && "unknown auto type") ? void (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "clang/lib/Sema/SemaType.cpp", 3681, __extension__ __PRETTY_FUNCTION__ )); | |||
3682 | Kind = 3; | |||
3683 | } | |||
3684 | ||||
3685 | auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); | |||
3686 | TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); | |||
3687 | ||||
3688 | SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) | |||
3689 | << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) | |||
3690 | << QualType(Deduced, 0) << AutoRange; | |||
3691 | if (auto *TD = TN.getAsTemplateDecl()) | |||
3692 | SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); | |||
3693 | ||||
3694 | T = SemaRef.Context.IntTy; | |||
3695 | D.setInvalidType(true); | |||
3696 | } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) { | |||
3697 | // If there was a trailing return type, we already got | |||
3698 | // warn_cxx98_compat_trailing_return_type in the parser. | |||
3699 | SemaRef.Diag(AutoRange.getBegin(), | |||
3700 | D.getContext() == DeclaratorContext::LambdaExprParameter | |||
3701 | ? diag::warn_cxx11_compat_generic_lambda | |||
3702 | : IsDeducedReturnType | |||
3703 | ? diag::warn_cxx11_compat_deduced_return_type | |||
3704 | : diag::warn_cxx98_compat_auto_type_specifier) | |||
3705 | << AutoRange; | |||
3706 | } | |||
3707 | } | |||
3708 | ||||
3709 | if (SemaRef.getLangOpts().CPlusPlus && | |||
3710 | OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { | |||
3711 | // Check the contexts where C++ forbids the declaration of a new class | |||
3712 | // or enumeration in a type-specifier-seq. | |||
3713 | unsigned DiagID = 0; | |||
3714 | switch (D.getContext()) { | |||
3715 | case DeclaratorContext::TrailingReturn: | |||
3716 | case DeclaratorContext::TrailingReturnVar: | |||
3717 | // Class and enumeration definitions are syntactically not allowed in | |||
3718 | // trailing return types. | |||
3719 | llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this" , "clang/lib/Sema/SemaType.cpp", 3719); | |||
3720 | break; | |||
3721 | case DeclaratorContext::File: | |||
3722 | case DeclaratorContext::Member: | |||
3723 | case DeclaratorContext::Block: | |||
3724 | case DeclaratorContext::ForInit: | |||
3725 | case DeclaratorContext::SelectionInit: | |||
3726 | case DeclaratorContext::BlockLiteral: | |||
3727 | case DeclaratorContext::LambdaExpr: | |||
3728 | // C++11 [dcl.type]p3: | |||
3729 | // A type-specifier-seq shall not define a class or enumeration unless | |||
3730 | // it appears in the type-id of an alias-declaration (7.1.3) that is not | |||
3731 | // the declaration of a template-declaration. | |||
3732 | case DeclaratorContext::AliasDecl: | |||
3733 | break; | |||
3734 | case DeclaratorContext::AliasTemplate: | |||
3735 | DiagID = diag::err_type_defined_in_alias_template; | |||
3736 | break; | |||
3737 | case DeclaratorContext::TypeName: | |||
3738 | case DeclaratorContext::FunctionalCast: | |||
3739 | case DeclaratorContext::ConversionId: | |||
3740 | case DeclaratorContext::TemplateParam: | |||
3741 | case DeclaratorContext::CXXNew: | |||
3742 | case DeclaratorContext::CXXCatch: | |||
3743 | case DeclaratorContext::ObjCCatch: | |||
3744 | case DeclaratorContext::TemplateArg: | |||
3745 | case DeclaratorContext::TemplateTypeArg: | |||
3746 | case DeclaratorContext::Association: | |||
3747 | DiagID = diag::err_type_defined_in_type_specifier; | |||
3748 | break; | |||
3749 | case DeclaratorContext::Prototype: | |||
3750 | case DeclaratorContext::LambdaExprParameter: | |||
3751 | case DeclaratorContext::ObjCParameter: | |||
3752 | case DeclaratorContext::ObjCResult: | |||
3753 | case DeclaratorContext::KNRTypeList: | |||
3754 | case DeclaratorContext::RequiresExpr: | |||
3755 | // C++ [dcl.fct]p6: | |||
3756 | // Types shall not be defined in return or parameter types. | |||
3757 | DiagID = diag::err_type_defined_in_param_type; | |||
3758 | break; | |||
3759 | case DeclaratorContext::Condition: | |||
3760 | // C++ 6.4p2: | |||
3761 | // The type-specifier-seq shall not contain typedef and shall not declare | |||
3762 | // a new class or enumeration. | |||
3763 | DiagID = diag::err_type_defined_in_condition; | |||
3764 | break; | |||
3765 | } | |||
3766 | ||||
3767 | if (DiagID != 0) { | |||
3768 | SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) | |||
3769 | << SemaRef.Context.getTypeDeclType(OwnedTagDecl); | |||
3770 | D.setInvalidType(true); | |||
3771 | } | |||
3772 | } | |||
3773 | ||||
3774 | assert(!T.isNull() && "This function should not return a null type")(static_cast <bool> (!T.isNull() && "This function should not return a null type" ) ? void (0) : __assert_fail ("!T.isNull() && \"This function should not return a null type\"" , "clang/lib/Sema/SemaType.cpp", 3774, __extension__ __PRETTY_FUNCTION__ )); | |||
3775 | return T; | |||
3776 | } | |||
3777 | ||||
3778 | /// Produce an appropriate diagnostic for an ambiguity between a function | |||
3779 | /// declarator and a C++ direct-initializer. | |||
3780 | static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, | |||
3781 | DeclaratorChunk &DeclType, QualType RT) { | |||
3782 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
3783 | assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity")(static_cast <bool> (FTI.isAmbiguous && "no direct-initializer / function ambiguity" ) ? void (0) : __assert_fail ("FTI.isAmbiguous && \"no direct-initializer / function ambiguity\"" , "clang/lib/Sema/SemaType.cpp", 3783, __extension__ __PRETTY_FUNCTION__ )); | |||
3784 | ||||
3785 | // If the return type is void there is no ambiguity. | |||
3786 | if (RT->isVoidType()) | |||
3787 | return; | |||
3788 | ||||
3789 | // An initializer for a non-class type can have at most one argument. | |||
3790 | if (!RT->isRecordType() && FTI.NumParams > 1) | |||
3791 | return; | |||
3792 | ||||
3793 | // An initializer for a reference must have exactly one argument. | |||
3794 | if (RT->isReferenceType() && FTI.NumParams != 1) | |||
3795 | return; | |||
3796 | ||||
3797 | // Only warn if this declarator is declaring a function at block scope, and | |||
3798 | // doesn't have a storage class (such as 'extern') specified. | |||
3799 | if (!D.isFunctionDeclarator() || | |||
3800 | D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration || | |||
3801 | !S.CurContext->isFunctionOrMethod() || | |||
3802 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified) | |||
3803 | return; | |||
3804 | ||||
3805 | // Inside a condition, a direct initializer is not permitted. We allow one to | |||
3806 | // be parsed in order to give better diagnostics in condition parsing. | |||
3807 | if (D.getContext() == DeclaratorContext::Condition) | |||
3808 | return; | |||
3809 | ||||
3810 | SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); | |||
3811 | ||||
3812 | S.Diag(DeclType.Loc, | |||
3813 | FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration | |||
3814 | : diag::warn_empty_parens_are_function_decl) | |||
3815 | << ParenRange; | |||
3816 | ||||
3817 | // If the declaration looks like: | |||
3818 | // T var1, | |||
3819 | // f(); | |||
3820 | // and name lookup finds a function named 'f', then the ',' was | |||
3821 | // probably intended to be a ';'. | |||
3822 | if (!D.isFirstDeclarator() && D.getIdentifier()) { | |||
3823 | FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); | |||
3824 | FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); | |||
3825 | if (Comma.getFileID() != Name.getFileID() || | |||
3826 | Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { | |||
3827 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | |||
3828 | Sema::LookupOrdinaryName); | |||
3829 | if (S.LookupName(Result, S.getCurScope())) | |||
3830 | S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) | |||
3831 | << FixItHint::CreateReplacement(D.getCommaLoc(), ";") | |||
3832 | << D.getIdentifier(); | |||
3833 | Result.suppressDiagnostics(); | |||
3834 | } | |||
3835 | } | |||
3836 | ||||
3837 | if (FTI.NumParams > 0) { | |||
3838 | // For a declaration with parameters, eg. "T var(T());", suggest adding | |||
3839 | // parens around the first parameter to turn the declaration into a | |||
3840 | // variable declaration. | |||
3841 | SourceRange Range = FTI.Params[0].Param->getSourceRange(); | |||
3842 | SourceLocation B = Range.getBegin(); | |||
3843 | SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); | |||
3844 | // FIXME: Maybe we should suggest adding braces instead of parens | |||
3845 | // in C++11 for classes that don't have an initializer_list constructor. | |||
3846 | S.Diag(B, diag::note_additional_parens_for_variable_declaration) | |||
3847 | << FixItHint::CreateInsertion(B, "(") | |||
3848 | << FixItHint::CreateInsertion(E, ")"); | |||
3849 | } else { | |||
3850 | // For a declaration without parameters, eg. "T var();", suggest replacing | |||
3851 | // the parens with an initializer to turn the declaration into a variable | |||
3852 | // declaration. | |||
3853 | const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); | |||
3854 | ||||
3855 | // Empty parens mean value-initialization, and no parens mean | |||
3856 | // default initialization. These are equivalent if the default | |||
3857 | // constructor is user-provided or if zero-initialization is a | |||
3858 | // no-op. | |||
3859 | if (RD && RD->hasDefinition() && | |||
3860 | (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) | |||
3861 | S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) | |||
3862 | << FixItHint::CreateRemoval(ParenRange); | |||
3863 | else { | |||
3864 | std::string Init = | |||
3865 | S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); | |||
3866 | if (Init.empty() && S.LangOpts.CPlusPlus11) | |||
3867 | Init = "{}"; | |||
3868 | if (!Init.empty()) | |||
3869 | S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) | |||
3870 | << FixItHint::CreateReplacement(ParenRange, Init); | |||
3871 | } | |||
3872 | } | |||
3873 | } | |||
3874 | ||||
3875 | /// Produce an appropriate diagnostic for a declarator with top-level | |||
3876 | /// parentheses. | |||
3877 | static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { | |||
3878 | DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); | |||
3879 | assert(Paren.Kind == DeclaratorChunk::Paren &&(static_cast <bool> (Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses") ? void (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "clang/lib/Sema/SemaType.cpp", 3880, __extension__ __PRETTY_FUNCTION__ )) | |||
3880 | "do not have redundant top-level parentheses")(static_cast <bool> (Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses") ? void (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "clang/lib/Sema/SemaType.cpp", 3880, __extension__ __PRETTY_FUNCTION__ )); | |||
3881 | ||||
3882 | // This is a syntactic check; we're not interested in cases that arise | |||
3883 | // during template instantiation. | |||
3884 | if (S.inTemplateInstantiation()) | |||
3885 | return; | |||
3886 | ||||
3887 | // Check whether this could be intended to be a construction of a temporary | |||
3888 | // object in C++ via a function-style cast. | |||
3889 | bool CouldBeTemporaryObject = | |||
3890 | S.getLangOpts().CPlusPlus && D.isExpressionContext() && | |||
3891 | !D.isInvalidType() && D.getIdentifier() && | |||
3892 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && | |||
3893 | (T->isRecordType() || T->isDependentType()) && | |||
3894 | D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); | |||
3895 | ||||
3896 | bool StartsWithDeclaratorId = true; | |||
3897 | for (auto &C : D.type_objects()) { | |||
3898 | switch (C.Kind) { | |||
3899 | case DeclaratorChunk::Paren: | |||
3900 | if (&C == &Paren) | |||
3901 | continue; | |||
3902 | [[fallthrough]]; | |||
3903 | case DeclaratorChunk::Pointer: | |||
3904 | StartsWithDeclaratorId = false; | |||
3905 | continue; | |||
3906 | ||||
3907 | case DeclaratorChunk::Array: | |||
3908 | if (!C.Arr.NumElts) | |||
3909 | CouldBeTemporaryObject = false; | |||
3910 | continue; | |||
3911 | ||||
3912 | case DeclaratorChunk::Reference: | |||
3913 | // FIXME: Suppress the warning here if there is no initializer; we're | |||
3914 | // going to give an error anyway. | |||
3915 | // We assume that something like 'T (&x) = y;' is highly likely to not | |||
3916 | // be intended to be a temporary object. | |||
3917 | CouldBeTemporaryObject = false; | |||
3918 | StartsWithDeclaratorId = false; | |||
3919 | continue; | |||
3920 | ||||
3921 | case DeclaratorChunk::Function: | |||
3922 | // In a new-type-id, function chunks require parentheses. | |||
3923 | if (D.getContext() == DeclaratorContext::CXXNew) | |||
3924 | return; | |||
3925 | // FIXME: "A(f())" deserves a vexing-parse warning, not just a | |||
3926 | // redundant-parens warning, but we don't know whether the function | |||
3927 | // chunk was syntactically valid as an expression here. | |||
3928 | CouldBeTemporaryObject = false; | |||
3929 | continue; | |||
3930 | ||||
3931 | case DeclaratorChunk::BlockPointer: | |||
3932 | case DeclaratorChunk::MemberPointer: | |||
3933 | case DeclaratorChunk::Pipe: | |||
3934 | // These cannot appear in expressions. | |||
3935 | CouldBeTemporaryObject = false; | |||
3936 | StartsWithDeclaratorId = false; | |||
3937 | continue; | |||
3938 | } | |||
3939 | } | |||
3940 | ||||
3941 | // FIXME: If there is an initializer, assume that this is not intended to be | |||
3942 | // a construction of a temporary object. | |||
3943 | ||||
3944 | // Check whether the name has already been declared; if not, this is not a | |||
3945 | // function-style cast. | |||
3946 | if (CouldBeTemporaryObject) { | |||
3947 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | |||
3948 | Sema::LookupOrdinaryName); | |||
3949 | if (!S.LookupName(Result, S.getCurScope())) | |||
3950 | CouldBeTemporaryObject = false; | |||
3951 | Result.suppressDiagnostics(); | |||
3952 | } | |||
3953 | ||||
3954 | SourceRange ParenRange(Paren.Loc, Paren.EndLoc); | |||
3955 | ||||
3956 | if (!CouldBeTemporaryObject) { | |||
3957 | // If we have A (::B), the parentheses affect the meaning of the program. | |||
3958 | // Suppress the warning in that case. Don't bother looking at the DeclSpec | |||
3959 | // here: even (e.g.) "int ::x" is visually ambiguous even though it's | |||
3960 | // formally unambiguous. | |||
3961 | if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { | |||
3962 | for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; | |||
3963 | NNS = NNS->getPrefix()) { | |||
3964 | if (NNS->getKind() == NestedNameSpecifier::Global) | |||
3965 | return; | |||
3966 | } | |||
3967 | } | |||
3968 | ||||
3969 | S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) | |||
3970 | << ParenRange << FixItHint::CreateRemoval(Paren.Loc) | |||
3971 | << FixItHint::CreateRemoval(Paren.EndLoc); | |||
3972 | return; | |||
3973 | } | |||
3974 | ||||
3975 | S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) | |||
3976 | << ParenRange << D.getIdentifier(); | |||
3977 | auto *RD = T->getAsCXXRecordDecl(); | |||
3978 | if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) | |||
3979 | S.Diag(Paren.Loc, diag::note_raii_guard_add_name) | |||
3980 | << FixItHint::CreateInsertion(Paren.Loc, " varname") << T | |||
3981 | << D.getIdentifier(); | |||
3982 | // FIXME: A cast to void is probably a better suggestion in cases where it's | |||
3983 | // valid (when there is no initializer and we're not in a condition). | |||
3984 | S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) | |||
3985 | << FixItHint::CreateInsertion(D.getBeginLoc(), "(") | |||
3986 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); | |||
3987 | S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) | |||
3988 | << FixItHint::CreateRemoval(Paren.Loc) | |||
3989 | << FixItHint::CreateRemoval(Paren.EndLoc); | |||
3990 | } | |||
3991 | ||||
3992 | /// Helper for figuring out the default CC for a function declarator type. If | |||
3993 | /// this is the outermost chunk, then we can determine the CC from the | |||
3994 | /// declarator context. If not, then this could be either a member function | |||
3995 | /// type or normal function type. | |||
3996 | static CallingConv getCCForDeclaratorChunk( | |||
3997 | Sema &S, Declarator &D, const ParsedAttributesView &AttrList, | |||
3998 | const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { | |||
3999 | assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function)(static_cast <bool> (D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function) ? void (0) : __assert_fail ("D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function" , "clang/lib/Sema/SemaType.cpp", 3999, __extension__ __PRETTY_FUNCTION__ )); | |||
4000 | ||||
4001 | // Check for an explicit CC attribute. | |||
4002 | for (const ParsedAttr &AL : AttrList) { | |||
4003 | switch (AL.getKind()) { | |||
4004 | CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_AArch64SVEPcs : case ParsedAttr::AT_AMDGPUKernelCall: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll : { | |||
4005 | // Ignore attributes that don't validate or can't apply to the | |||
4006 | // function type. We'll diagnose the failure to apply them in | |||
4007 | // handleFunctionTypeAttr. | |||
4008 | CallingConv CC; | |||
4009 | if (!S.CheckCallingConvAttr(AL, CC) && | |||
4010 | (!FTI.isVariadic || supportsVariadicCall(CC))) { | |||
4011 | return CC; | |||
4012 | } | |||
4013 | break; | |||
4014 | } | |||
4015 | ||||
4016 | default: | |||
4017 | break; | |||
4018 | } | |||
4019 | } | |||
4020 | ||||
4021 | bool IsCXXInstanceMethod = false; | |||
4022 | ||||
4023 | if (S.getLangOpts().CPlusPlus) { | |||
4024 | // Look inwards through parentheses to see if this chunk will form a | |||
4025 | // member pointer type or if we're the declarator. Any type attributes | |||
4026 | // between here and there will override the CC we choose here. | |||
4027 | unsigned I = ChunkIndex; | |||
4028 | bool FoundNonParen = false; | |||
4029 | while (I && !FoundNonParen) { | |||
4030 | --I; | |||
4031 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) | |||
4032 | FoundNonParen = true; | |||
4033 | } | |||
4034 | ||||
4035 | if (FoundNonParen) { | |||
4036 | // If we're not the declarator, we're a regular function type unless we're | |||
4037 | // in a member pointer. | |||
4038 | IsCXXInstanceMethod = | |||
4039 | D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; | |||
4040 | } else if (D.getContext() == DeclaratorContext::LambdaExpr) { | |||
4041 | // This can only be a call operator for a lambda, which is an instance | |||
4042 | // method. | |||
4043 | IsCXXInstanceMethod = true; | |||
4044 | } else { | |||
4045 | // We're the innermost decl chunk, so must be a function declarator. | |||
4046 | assert(D.isFunctionDeclarator())(static_cast <bool> (D.isFunctionDeclarator()) ? void ( 0) : __assert_fail ("D.isFunctionDeclarator()", "clang/lib/Sema/SemaType.cpp" , 4046, __extension__ __PRETTY_FUNCTION__)); | |||
4047 | ||||
4048 | // If we're inside a record, we're declaring a method, but it could be | |||
4049 | // explicitly or implicitly static. | |||
4050 | IsCXXInstanceMethod = | |||
4051 | D.isFirstDeclarationOfMember() && | |||
4052 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | |||
4053 | !D.isStaticMember(); | |||
4054 | } | |||
4055 | } | |||
4056 | ||||
4057 | CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, | |||
4058 | IsCXXInstanceMethod); | |||
4059 | ||||
4060 | // Attribute AT_OpenCLKernel affects the calling convention for SPIR | |||
4061 | // and AMDGPU targets, hence it cannot be treated as a calling | |||
4062 | // convention attribute. This is the simplest place to infer | |||
4063 | // calling convention for OpenCL kernels. | |||
4064 | if (S.getLangOpts().OpenCL) { | |||
4065 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | |||
4066 | if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { | |||
4067 | CC = CC_OpenCLKernel; | |||
4068 | break; | |||
4069 | } | |||
4070 | } | |||
4071 | } else if (S.getLangOpts().CUDA) { | |||
4072 | // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make | |||
4073 | // sure the kernels will be marked with the right calling convention so that | |||
4074 | // they will be visible by the APIs that ingest SPIR-V. | |||
4075 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); | |||
4076 | if (Triple.getArch() == llvm::Triple::spirv32 || | |||
4077 | Triple.getArch() == llvm::Triple::spirv64) { | |||
4078 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | |||
4079 | if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) { | |||
4080 | CC = CC_OpenCLKernel; | |||
4081 | break; | |||
4082 | } | |||
4083 | } | |||
4084 | } | |||
4085 | } | |||
4086 | ||||
4087 | return CC; | |||
4088 | } | |||
4089 | ||||
4090 | namespace { | |||
4091 | /// A simple notion of pointer kinds, which matches up with the various | |||
4092 | /// pointer declarators. | |||
4093 | enum class SimplePointerKind { | |||
4094 | Pointer, | |||
4095 | BlockPointer, | |||
4096 | MemberPointer, | |||
4097 | Array, | |||
4098 | }; | |||
4099 | } // end anonymous namespace | |||
4100 | ||||
4101 | IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { | |||
4102 | switch (nullability) { | |||
4103 | case NullabilityKind::NonNull: | |||
4104 | if (!Ident__Nonnull) | |||
4105 | Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); | |||
4106 | return Ident__Nonnull; | |||
4107 | ||||
4108 | case NullabilityKind::Nullable: | |||
4109 | if (!Ident__Nullable) | |||
4110 | Ident__Nullable = PP.getIdentifierInfo("_Nullable"); | |||
4111 | return Ident__Nullable; | |||
4112 | ||||
4113 | case NullabilityKind::NullableResult: | |||
4114 | if (!Ident__Nullable_result) | |||
4115 | Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result"); | |||
4116 | return Ident__Nullable_result; | |||
4117 | ||||
4118 | case NullabilityKind::Unspecified: | |||
4119 | if (!Ident__Null_unspecified) | |||
4120 | Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); | |||
4121 | return Ident__Null_unspecified; | |||
4122 | } | |||
4123 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "clang/lib/Sema/SemaType.cpp", 4123); | |||
4124 | } | |||
4125 | ||||
4126 | /// Retrieve the identifier "NSError". | |||
4127 | IdentifierInfo *Sema::getNSErrorIdent() { | |||
4128 | if (!Ident_NSError) | |||
4129 | Ident_NSError = PP.getIdentifierInfo("NSError"); | |||
4130 | ||||
4131 | return Ident_NSError; | |||
4132 | } | |||
4133 | ||||
4134 | /// Check whether there is a nullability attribute of any kind in the given | |||
4135 | /// attribute list. | |||
4136 | static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { | |||
4137 | for (const ParsedAttr &AL : attrs) { | |||
4138 | if (AL.getKind() == ParsedAttr::AT_TypeNonNull || | |||
4139 | AL.getKind() == ParsedAttr::AT_TypeNullable || | |||
4140 | AL.getKind() == ParsedAttr::AT_TypeNullableResult || | |||
4141 | AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) | |||
4142 | return true; | |||
4143 | } | |||
4144 | ||||
4145 | return false; | |||
4146 | } | |||
4147 | ||||
4148 | namespace { | |||
4149 | /// Describes the kind of a pointer a declarator describes. | |||
4150 | enum class PointerDeclaratorKind { | |||
4151 | // Not a pointer. | |||
4152 | NonPointer, | |||
4153 | // Single-level pointer. | |||
4154 | SingleLevelPointer, | |||
4155 | // Multi-level pointer (of any pointer kind). | |||
4156 | MultiLevelPointer, | |||
4157 | // CFFooRef* | |||
4158 | MaybePointerToCFRef, | |||
4159 | // CFErrorRef* | |||
4160 | CFErrorRefPointer, | |||
4161 | // NSError** | |||
4162 | NSErrorPointerPointer, | |||
4163 | }; | |||
4164 | ||||
4165 | /// Describes a declarator chunk wrapping a pointer that marks inference as | |||
4166 | /// unexpected. | |||
4167 | // These values must be kept in sync with diagnostics. | |||
4168 | enum class PointerWrappingDeclaratorKind { | |||
4169 | /// Pointer is top-level. | |||
4170 | None = -1, | |||
4171 | /// Pointer is an array element. | |||
4172 | Array = 0, | |||
4173 | /// Pointer is the referent type of a C++ reference. | |||
4174 | Reference = 1 | |||
4175 | }; | |||
4176 | } // end anonymous namespace | |||
4177 | ||||
4178 | /// Classify the given declarator, whose type-specified is \c type, based on | |||
4179 | /// what kind of pointer it refers to. | |||
4180 | /// | |||
4181 | /// This is used to determine the default nullability. | |||
4182 | static PointerDeclaratorKind | |||
4183 | classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, | |||
4184 | PointerWrappingDeclaratorKind &wrappingKind) { | |||
4185 | unsigned numNormalPointers = 0; | |||
4186 | ||||
4187 | // For any dependent type, we consider it a non-pointer. | |||
4188 | if (type->isDependentType()) | |||
4189 | return PointerDeclaratorKind::NonPointer; | |||
4190 | ||||
4191 | // Look through the declarator chunks to identify pointers. | |||
4192 | for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { | |||
4193 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
4194 | switch (chunk.Kind) { | |||
4195 | case DeclaratorChunk::Array: | |||
4196 | if (numNormalPointers == 0) | |||
4197 | wrappingKind = PointerWrappingDeclaratorKind::Array; | |||
4198 | break; | |||
4199 | ||||
4200 | case DeclaratorChunk::Function: | |||
4201 | case DeclaratorChunk::Pipe: | |||
4202 | break; | |||
4203 | ||||
4204 | case DeclaratorChunk::BlockPointer: | |||
4205 | case DeclaratorChunk::MemberPointer: | |||
4206 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
4207 | : PointerDeclaratorKind::SingleLevelPointer; | |||
4208 | ||||
4209 | case DeclaratorChunk::Paren: | |||
4210 | break; | |||
4211 | ||||
4212 | case DeclaratorChunk::Reference: | |||
4213 | if (numNormalPointers == 0) | |||
4214 | wrappingKind = PointerWrappingDeclaratorKind::Reference; | |||
4215 | break; | |||
4216 | ||||
4217 | case DeclaratorChunk::Pointer: | |||
4218 | ++numNormalPointers; | |||
4219 | if (numNormalPointers > 2) | |||
4220 | return PointerDeclaratorKind::MultiLevelPointer; | |||
4221 | break; | |||
4222 | } | |||
4223 | } | |||
4224 | ||||
4225 | // Then, dig into the type specifier itself. | |||
4226 | unsigned numTypeSpecifierPointers = 0; | |||
4227 | do { | |||
4228 | // Decompose normal pointers. | |||
4229 | if (auto ptrType = type->getAs<PointerType>()) { | |||
4230 | ++numNormalPointers; | |||
4231 | ||||
4232 | if (numNormalPointers > 2) | |||
4233 | return PointerDeclaratorKind::MultiLevelPointer; | |||
4234 | ||||
4235 | type = ptrType->getPointeeType(); | |||
4236 | ++numTypeSpecifierPointers; | |||
4237 | continue; | |||
4238 | } | |||
4239 | ||||
4240 | // Decompose block pointers. | |||
4241 | if (type->getAs<BlockPointerType>()) { | |||
4242 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
4243 | : PointerDeclaratorKind::SingleLevelPointer; | |||
4244 | } | |||
4245 | ||||
4246 | // Decompose member pointers. | |||
4247 | if (type->getAs<MemberPointerType>()) { | |||
4248 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
4249 | : PointerDeclaratorKind::SingleLevelPointer; | |||
4250 | } | |||
4251 | ||||
4252 | // Look at Objective-C object pointers. | |||
4253 | if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { | |||
4254 | ++numNormalPointers; | |||
4255 | ++numTypeSpecifierPointers; | |||
4256 | ||||
4257 | // If this is NSError**, report that. | |||
4258 | if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { | |||
4259 | if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && | |||
4260 | numNormalPointers == 2 && numTypeSpecifierPointers < 2) { | |||
4261 | return PointerDeclaratorKind::NSErrorPointerPointer; | |||
4262 | } | |||
4263 | } | |||
4264 | ||||
4265 | break; | |||
4266 | } | |||
4267 | ||||
4268 | // Look at Objective-C class types. | |||
4269 | if (auto objcClass = type->getAs<ObjCInterfaceType>()) { | |||
4270 | if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { | |||
4271 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) | |||
4272 | return PointerDeclaratorKind::NSErrorPointerPointer; | |||
4273 | } | |||
4274 | ||||
4275 | break; | |||
4276 | } | |||
4277 | ||||
4278 | // If at this point we haven't seen a pointer, we won't see one. | |||
4279 | if (numNormalPointers == 0) | |||
4280 | return PointerDeclaratorKind::NonPointer; | |||
4281 | ||||
4282 | if (auto recordType = type->getAs<RecordType>()) { | |||
4283 | RecordDecl *recordDecl = recordType->getDecl(); | |||
4284 | ||||
4285 | // If this is CFErrorRef*, report it as such. | |||
4286 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 && | |||
4287 | S.isCFError(recordDecl)) { | |||
4288 | return PointerDeclaratorKind::CFErrorRefPointer; | |||
4289 | } | |||
4290 | break; | |||
4291 | } | |||
4292 | ||||
4293 | break; | |||
4294 | } while (true); | |||
4295 | ||||
4296 | switch (numNormalPointers) { | |||
4297 | case 0: | |||
4298 | return PointerDeclaratorKind::NonPointer; | |||
4299 | ||||
4300 | case 1: | |||
4301 | return PointerDeclaratorKind::SingleLevelPointer; | |||
4302 | ||||
4303 | case 2: | |||
4304 | return PointerDeclaratorKind::MaybePointerToCFRef; | |||
4305 | ||||
4306 | default: | |||
4307 | return PointerDeclaratorKind::MultiLevelPointer; | |||
4308 | } | |||
4309 | } | |||
4310 | ||||
4311 | bool Sema::isCFError(RecordDecl *RD) { | |||
4312 | // If we already know about CFError, test it directly. | |||
4313 | if (CFError) | |||
4314 | return CFError == RD; | |||
4315 | ||||
4316 | // Check whether this is CFError, which we identify based on its bridge to | |||
4317 | // NSError. CFErrorRef used to be declared with "objc_bridge" but is now | |||
4318 | // declared with "objc_bridge_mutable", so look for either one of the two | |||
4319 | // attributes. | |||
4320 | if (RD->getTagKind() == TTK_Struct) { | |||
4321 | IdentifierInfo *bridgedType = nullptr; | |||
4322 | if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>()) | |||
4323 | bridgedType = bridgeAttr->getBridgedType(); | |||
4324 | else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>()) | |||
4325 | bridgedType = bridgeAttr->getBridgedType(); | |||
4326 | ||||
4327 | if (bridgedType == getNSErrorIdent()) { | |||
4328 | CFError = RD; | |||
4329 | return true; | |||
4330 | } | |||
4331 | } | |||
4332 | ||||
4333 | return false; | |||
4334 | } | |||
4335 | ||||
4336 | static FileID getNullabilityCompletenessCheckFileID(Sema &S, | |||
4337 | SourceLocation loc) { | |||
4338 | // If we're anywhere in a function, method, or closure context, don't perform | |||
4339 | // completeness checks. | |||
4340 | for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { | |||
4341 | if (ctx->isFunctionOrMethod()) | |||
4342 | return FileID(); | |||
4343 | ||||
4344 | if (ctx->isFileContext()) | |||
4345 | break; | |||
4346 | } | |||
4347 | ||||
4348 | // We only care about the expansion location. | |||
4349 | loc = S.SourceMgr.getExpansionLoc(loc); | |||
4350 | FileID file = S.SourceMgr.getFileID(loc); | |||
4351 | if (file.isInvalid()) | |||
4352 | return FileID(); | |||
4353 | ||||
4354 | // Retrieve file information. | |||
4355 | bool invalid = false; | |||
4356 | const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); | |||
4357 | if (invalid || !sloc.isFile()) | |||
4358 | return FileID(); | |||
4359 | ||||
4360 | // We don't want to perform completeness checks on the main file or in | |||
4361 | // system headers. | |||
4362 | const SrcMgr::FileInfo &fileInfo = sloc.getFile(); | |||
4363 | if (fileInfo.getIncludeLoc().isInvalid()) | |||
4364 | return FileID(); | |||
4365 | if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && | |||
4366 | S.Diags.getSuppressSystemWarnings()) { | |||
4367 | return FileID(); | |||
4368 | } | |||
4369 | ||||
4370 | return file; | |||
4371 | } | |||
4372 | ||||
4373 | /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, | |||
4374 | /// taking into account whitespace before and after. | |||
4375 | template <typename DiagBuilderT> | |||
4376 | static void fixItNullability(Sema &S, DiagBuilderT &Diag, | |||
4377 | SourceLocation PointerLoc, | |||
4378 | NullabilityKind Nullability) { | |||
4379 | assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) : __assert_fail ("PointerLoc.isValid()", "clang/lib/Sema/SemaType.cpp" , 4379, __extension__ __PRETTY_FUNCTION__)); | |||
4380 | if (PointerLoc.isMacroID()) | |||
4381 | return; | |||
4382 | ||||
4383 | SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); | |||
4384 | if (!FixItLoc.isValid() || FixItLoc == PointerLoc) | |||
4385 | return; | |||
4386 | ||||
4387 | const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); | |||
4388 | if (!NextChar) | |||
4389 | return; | |||
4390 | ||||
4391 | SmallString<32> InsertionTextBuf{" "}; | |||
4392 | InsertionTextBuf += getNullabilitySpelling(Nullability); | |||
4393 | InsertionTextBuf += " "; | |||
4394 | StringRef InsertionText = InsertionTextBuf.str(); | |||
4395 | ||||
4396 | if (isWhitespace(*NextChar)) { | |||
4397 | InsertionText = InsertionText.drop_back(); | |||
4398 | } else if (NextChar[-1] == '[') { | |||
4399 | if (NextChar[0] == ']') | |||
4400 | InsertionText = InsertionText.drop_back().drop_front(); | |||
4401 | else | |||
4402 | InsertionText = InsertionText.drop_front(); | |||
4403 | } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) && | |||
4404 | !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) { | |||
4405 | InsertionText = InsertionText.drop_back().drop_front(); | |||
4406 | } | |||
4407 | ||||
4408 | Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); | |||
4409 | } | |||
4410 | ||||
4411 | static void emitNullabilityConsistencyWarning(Sema &S, | |||
4412 | SimplePointerKind PointerKind, | |||
4413 | SourceLocation PointerLoc, | |||
4414 | SourceLocation PointerEndLoc) { | |||
4415 | assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) : __assert_fail ("PointerLoc.isValid()", "clang/lib/Sema/SemaType.cpp" , 4415, __extension__ __PRETTY_FUNCTION__)); | |||
4416 | ||||
4417 | if (PointerKind == SimplePointerKind::Array) { | |||
4418 | S.Diag(PointerLoc, diag::warn_nullability_missing_array); | |||
4419 | } else { | |||
4420 | S.Diag(PointerLoc, diag::warn_nullability_missing) | |||
4421 | << static_cast<unsigned>(PointerKind); | |||
4422 | } | |||
4423 | ||||
4424 | auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; | |||
4425 | if (FixItLoc.isMacroID()) | |||
4426 | return; | |||
4427 | ||||
4428 | auto addFixIt = [&](NullabilityKind Nullability) { | |||
4429 | auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); | |||
4430 | Diag << static_cast<unsigned>(Nullability); | |||
4431 | Diag << static_cast<unsigned>(PointerKind); | |||
4432 | fixItNullability(S, Diag, FixItLoc, Nullability); | |||
4433 | }; | |||
4434 | addFixIt(NullabilityKind::Nullable); | |||
4435 | addFixIt(NullabilityKind::NonNull); | |||
4436 | } | |||
4437 | ||||
4438 | /// Complains about missing nullability if the file containing \p pointerLoc | |||
4439 | /// has other uses of nullability (either the keywords or the \c assume_nonnull | |||
4440 | /// pragma). | |||
4441 | /// | |||
4442 | /// If the file has \e not seen other uses of nullability, this particular | |||
4443 | /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). | |||
4444 | static void | |||
4445 | checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, | |||
4446 | SourceLocation pointerLoc, | |||
4447 | SourceLocation pointerEndLoc = SourceLocation()) { | |||
4448 | // Determine which file we're performing consistency checking for. | |||
4449 | FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); | |||
4450 | if (file.isInvalid()) | |||
4451 | return; | |||
4452 | ||||
4453 | // If we haven't seen any type nullability in this file, we won't warn now | |||
4454 | // about anything. | |||
4455 | FileNullability &fileNullability = S.NullabilityMap[file]; | |||
4456 | if (!fileNullability.SawTypeNullability) { | |||
4457 | // If this is the first pointer declarator in the file, and the appropriate | |||
4458 | // warning is on, record it in case we need to diagnose it retroactively. | |||
4459 | diag::kind diagKind; | |||
4460 | if (pointerKind == SimplePointerKind::Array) | |||
4461 | diagKind = diag::warn_nullability_missing_array; | |||
4462 | else | |||
4463 | diagKind = diag::warn_nullability_missing; | |||
4464 | ||||
4465 | if (fileNullability.PointerLoc.isInvalid() && | |||
4466 | !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { | |||
4467 | fileNullability.PointerLoc = pointerLoc; | |||
4468 | fileNullability.PointerEndLoc = pointerEndLoc; | |||
4469 | fileNullability.PointerKind = static_cast<unsigned>(pointerKind); | |||
4470 | } | |||
4471 | ||||
4472 | return; | |||
4473 | } | |||
4474 | ||||
4475 | // Complain about missing nullability. | |||
4476 | emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); | |||
4477 | } | |||
4478 | ||||
4479 | /// Marks that a nullability feature has been used in the file containing | |||
4480 | /// \p loc. | |||
4481 | /// | |||
4482 | /// If this file already had pointer types in it that were missing nullability, | |||
4483 | /// the first such instance is retroactively diagnosed. | |||
4484 | /// | |||
4485 | /// \sa checkNullabilityConsistency | |||
4486 | static void recordNullabilitySeen(Sema &S, SourceLocation loc) { | |||
4487 | FileID file = getNullabilityCompletenessCheckFileID(S, loc); | |||
4488 | if (file.isInvalid()) | |||
4489 | return; | |||
4490 | ||||
4491 | FileNullability &fileNullability = S.NullabilityMap[file]; | |||
4492 | if (fileNullability.SawTypeNullability) | |||
4493 | return; | |||
4494 | fileNullability.SawTypeNullability = true; | |||
4495 | ||||
4496 | // If we haven't seen any type nullability before, now we have. Retroactively | |||
4497 | // diagnose the first unannotated pointer, if there was one. | |||
4498 | if (fileNullability.PointerLoc.isInvalid()) | |||
4499 | return; | |||
4500 | ||||
4501 | auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); | |||
4502 | emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, | |||
4503 | fileNullability.PointerEndLoc); | |||
4504 | } | |||
4505 | ||||
4506 | /// Returns true if any of the declarator chunks before \p endIndex include a | |||
4507 | /// level of indirection: array, pointer, reference, or pointer-to-member. | |||
4508 | /// | |||
4509 | /// Because declarator chunks are stored in outer-to-inner order, testing | |||
4510 | /// every chunk before \p endIndex is testing all chunks that embed the current | |||
4511 | /// chunk as part of their type. | |||
4512 | /// | |||
4513 | /// It is legal to pass the result of Declarator::getNumTypeObjects() as the | |||
4514 | /// end index, in which case all chunks are tested. | |||
4515 | static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { | |||
4516 | unsigned i = endIndex; | |||
4517 | while (i != 0) { | |||
4518 | // Walk outwards along the declarator chunks. | |||
4519 | --i; | |||
4520 | const DeclaratorChunk &DC = D.getTypeObject(i); | |||
4521 | switch (DC.Kind) { | |||
4522 | case DeclaratorChunk::Paren: | |||
4523 | break; | |||
4524 | case DeclaratorChunk::Array: | |||
4525 | case DeclaratorChunk::Pointer: | |||
4526 | case DeclaratorChunk::Reference: | |||
4527 | case DeclaratorChunk::MemberPointer: | |||
4528 | return true; | |||
4529 | case DeclaratorChunk::Function: | |||
4530 | case DeclaratorChunk::BlockPointer: | |||
4531 | case DeclaratorChunk::Pipe: | |||
4532 | // These are invalid anyway, so just ignore. | |||
4533 | break; | |||
4534 | } | |||
4535 | } | |||
4536 | return false; | |||
4537 | } | |||
4538 | ||||
4539 | static bool IsNoDerefableChunk(DeclaratorChunk Chunk) { | |||
4540 | return (Chunk.Kind == DeclaratorChunk::Pointer || | |||
4541 | Chunk.Kind == DeclaratorChunk::Array); | |||
4542 | } | |||
4543 | ||||
4544 | template<typename AttrT> | |||
4545 | static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) { | |||
4546 | AL.setUsedAsTypeAttr(); | |||
4547 | return ::new (Ctx) AttrT(Ctx, AL); | |||
4548 | } | |||
4549 | ||||
4550 | static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, | |||
4551 | NullabilityKind NK) { | |||
4552 | switch (NK) { | |||
4553 | case NullabilityKind::NonNull: | |||
4554 | return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); | |||
4555 | ||||
4556 | case NullabilityKind::Nullable: | |||
4557 | return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); | |||
4558 | ||||
4559 | case NullabilityKind::NullableResult: | |||
4560 | return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr); | |||
4561 | ||||
4562 | case NullabilityKind::Unspecified: | |||
4563 | return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); | |||
4564 | } | |||
4565 | llvm_unreachable("unknown NullabilityKind")::llvm::llvm_unreachable_internal("unknown NullabilityKind", "clang/lib/Sema/SemaType.cpp" , 4565); | |||
4566 | } | |||
4567 | ||||
4568 | // Diagnose whether this is a case with the multiple addr spaces. | |||
4569 | // Returns true if this is an invalid case. | |||
4570 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified | |||
4571 | // by qualifiers for two or more different address spaces." | |||
4572 | static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, | |||
4573 | LangAS ASNew, | |||
4574 | SourceLocation AttrLoc) { | |||
4575 | if (ASOld != LangAS::Default) { | |||
4576 | if (ASOld != ASNew) { | |||
4577 | S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | |||
4578 | return true; | |||
4579 | } | |||
4580 | // Emit a warning if they are identical; it's likely unintended. | |||
4581 | S.Diag(AttrLoc, | |||
4582 | diag::warn_attribute_address_multiple_identical_qualifiers); | |||
4583 | } | |||
4584 | return false; | |||
4585 | } | |||
4586 | ||||
4587 | static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, | |||
4588 | QualType declSpecType, | |||
4589 | TypeSourceInfo *TInfo) { | |||
4590 | // The TypeSourceInfo that this function returns will not be a null type. | |||
4591 | // If there is an error, this function will fill in a dummy type as fallback. | |||
4592 | QualType T = declSpecType; | |||
4593 | Declarator &D = state.getDeclarator(); | |||
4594 | Sema &S = state.getSema(); | |||
4595 | ASTContext &Context = S.Context; | |||
4596 | const LangOptions &LangOpts = S.getLangOpts(); | |||
4597 | ||||
4598 | // The name we're declaring, if any. | |||
4599 | DeclarationName Name; | |||
4600 | if (D.getIdentifier()) | |||
4601 | Name = D.getIdentifier(); | |||
4602 | ||||
4603 | // Does this declaration declare a typedef-name? | |||
4604 | bool IsTypedefName = | |||
4605 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || | |||
4606 | D.getContext() == DeclaratorContext::AliasDecl || | |||
4607 | D.getContext() == DeclaratorContext::AliasTemplate; | |||
4608 | ||||
4609 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | |||
4610 | bool IsQualifiedFunction = T->isFunctionProtoType() && | |||
4611 | (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || | |||
4612 | T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); | |||
4613 | ||||
4614 | // If T is 'decltype(auto)', the only declarators we can have are parens | |||
4615 | // and at most one function declarator if this is a function declaration. | |||
4616 | // If T is a deduced class template specialization type, we can have no | |||
4617 | // declarator chunks at all. | |||
4618 | if (auto *DT = T->getAs<DeducedType>()) { | |||
4619 | const AutoType *AT = T->getAs<AutoType>(); | |||
4620 | bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); | |||
4621 | if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { | |||
4622 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | |||
4623 | unsigned Index = E - I - 1; | |||
4624 | DeclaratorChunk &DeclChunk = D.getTypeObject(Index); | |||
4625 | unsigned DiagId = IsClassTemplateDeduction | |||
4626 | ? diag::err_deduced_class_template_compound_type | |||
4627 | : diag::err_decltype_auto_compound_type; | |||
4628 | unsigned DiagKind = 0; | |||
4629 | switch (DeclChunk.Kind) { | |||
4630 | case DeclaratorChunk::Paren: | |||
4631 | // FIXME: Rejecting this is a little silly. | |||
4632 | if (IsClassTemplateDeduction) { | |||
4633 | DiagKind = 4; | |||
4634 | break; | |||
4635 | } | |||
4636 | continue; | |||
4637 | case DeclaratorChunk::Function: { | |||
4638 | if (IsClassTemplateDeduction) { | |||
4639 | DiagKind = 3; | |||
4640 | break; | |||
4641 | } | |||
4642 | unsigned FnIndex; | |||
4643 | if (D.isFunctionDeclarationContext() && | |||
4644 | D.isFunctionDeclarator(FnIndex) && FnIndex == Index) | |||
4645 | continue; | |||
4646 | DiagId = diag::err_decltype_auto_function_declarator_not_declaration; | |||
4647 | break; | |||
4648 | } | |||
4649 | case DeclaratorChunk::Pointer: | |||
4650 | case DeclaratorChunk::BlockPointer: | |||
4651 | case DeclaratorChunk::MemberPointer: | |||
4652 | DiagKind = 0; | |||
4653 | break; | |||
4654 | case DeclaratorChunk::Reference: | |||
4655 | DiagKind = 1; | |||
4656 | break; | |||
4657 | case DeclaratorChunk::Array: | |||
4658 | DiagKind = 2; | |||
4659 | break; | |||
4660 | case DeclaratorChunk::Pipe: | |||
4661 | break; | |||
4662 | } | |||
4663 | ||||
4664 | S.Diag(DeclChunk.Loc, DiagId) << DiagKind; | |||
4665 | D.setInvalidType(true); | |||
4666 | break; | |||
4667 | } | |||
4668 | } | |||
4669 | } | |||
4670 | ||||
4671 | // Determine whether we should infer _Nonnull on pointer types. | |||
4672 | Optional<NullabilityKind> inferNullability; | |||
4673 | bool inferNullabilityCS = false; | |||
4674 | bool inferNullabilityInnerOnly = false; | |||
4675 | bool inferNullabilityInnerOnlyComplete = false; | |||
4676 | ||||
4677 | // Are we in an assume-nonnull region? | |||
4678 | bool inAssumeNonNullRegion = false; | |||
4679 | SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); | |||
4680 | if (assumeNonNullLoc.isValid()) { | |||
4681 | inAssumeNonNullRegion = true; | |||
4682 | recordNullabilitySeen(S, assumeNonNullLoc); | |||
4683 | } | |||
4684 | ||||
4685 | // Whether to complain about missing nullability specifiers or not. | |||
4686 | enum { | |||
4687 | /// Never complain. | |||
4688 | CAMN_No, | |||
4689 | /// Complain on the inner pointers (but not the outermost | |||
4690 | /// pointer). | |||
4691 | CAMN_InnerPointers, | |||
4692 | /// Complain about any pointers that don't have nullability | |||
4693 | /// specified or inferred. | |||
4694 | CAMN_Yes | |||
4695 | } complainAboutMissingNullability = CAMN_No; | |||
4696 | unsigned NumPointersRemaining = 0; | |||
4697 | auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; | |||
4698 | ||||
4699 | if (IsTypedefName) { | |||
4700 | // For typedefs, we do not infer any nullability (the default), | |||
4701 | // and we only complain about missing nullability specifiers on | |||
4702 | // inner pointers. | |||
4703 | complainAboutMissingNullability = CAMN_InnerPointers; | |||
4704 | ||||
4705 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | |||
4706 | !T->getNullability(S.Context)) { | |||
4707 | // Note that we allow but don't require nullability on dependent types. | |||
4708 | ++NumPointersRemaining; | |||
4709 | } | |||
4710 | ||||
4711 | for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { | |||
4712 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
4713 | switch (chunk.Kind) { | |||
4714 | case DeclaratorChunk::Array: | |||
4715 | case DeclaratorChunk::Function: | |||
4716 | case DeclaratorChunk::Pipe: | |||
4717 | break; | |||
4718 | ||||
4719 | case DeclaratorChunk::BlockPointer: | |||
4720 | case DeclaratorChunk::MemberPointer: | |||
4721 | ++NumPointersRemaining; | |||
4722 | break; | |||
4723 | ||||
4724 | case DeclaratorChunk::Paren: | |||
4725 | case DeclaratorChunk::Reference: | |||
4726 | continue; | |||
4727 | ||||
4728 | case DeclaratorChunk::Pointer: | |||
4729 | ++NumPointersRemaining; | |||
4730 | continue; | |||
4731 | } | |||
4732 | } | |||
4733 | } else { | |||
4734 | bool isFunctionOrMethod = false; | |||
4735 | switch (auto context = state.getDeclarator().getContext()) { | |||
4736 | case DeclaratorContext::ObjCParameter: | |||
4737 | case DeclaratorContext::ObjCResult: | |||
4738 | case DeclaratorContext::Prototype: | |||
4739 | case DeclaratorContext::TrailingReturn: | |||
4740 | case DeclaratorContext::TrailingReturnVar: | |||
4741 | isFunctionOrMethod = true; | |||
4742 | [[fallthrough]]; | |||
4743 | ||||
4744 | case DeclaratorContext::Member: | |||
4745 | if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { | |||
4746 | complainAboutMissingNullability = CAMN_No; | |||
4747 | break; | |||
4748 | } | |||
4749 | ||||
4750 | // Weak properties are inferred to be nullable. | |||
4751 | if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { | |||
4752 | inferNullability = NullabilityKind::Nullable; | |||
4753 | break; | |||
4754 | } | |||
4755 | ||||
4756 | [[fallthrough]]; | |||
4757 | ||||
4758 | case DeclaratorContext::File: | |||
4759 | case DeclaratorContext::KNRTypeList: { | |||
4760 | complainAboutMissingNullability = CAMN_Yes; | |||
4761 | ||||
4762 | // Nullability inference depends on the type and declarator. | |||
4763 | auto wrappingKind = PointerWrappingDeclaratorKind::None; | |||
4764 | switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { | |||
4765 | case PointerDeclaratorKind::NonPointer: | |||
4766 | case PointerDeclaratorKind::MultiLevelPointer: | |||
4767 | // Cannot infer nullability. | |||
4768 | break; | |||
4769 | ||||
4770 | case PointerDeclaratorKind::SingleLevelPointer: | |||
4771 | // Infer _Nonnull if we are in an assumes-nonnull region. | |||
4772 | if (inAssumeNonNullRegion) { | |||
4773 | complainAboutInferringWithinChunk = wrappingKind; | |||
4774 | inferNullability = NullabilityKind::NonNull; | |||
4775 | inferNullabilityCS = (context == DeclaratorContext::ObjCParameter || | |||
4776 | context == DeclaratorContext::ObjCResult); | |||
4777 | } | |||
4778 | break; | |||
4779 | ||||
4780 | case PointerDeclaratorKind::CFErrorRefPointer: | |||
4781 | case PointerDeclaratorKind::NSErrorPointerPointer: | |||
4782 | // Within a function or method signature, infer _Nullable at both | |||
4783 | // levels. | |||
4784 | if (isFunctionOrMethod && inAssumeNonNullRegion) | |||
4785 | inferNullability = NullabilityKind::Nullable; | |||
4786 | break; | |||
4787 | ||||
4788 | case PointerDeclaratorKind::MaybePointerToCFRef: | |||
4789 | if (isFunctionOrMethod) { | |||
4790 | // On pointer-to-pointer parameters marked cf_returns_retained or | |||
4791 | // cf_returns_not_retained, if the outer pointer is explicit then | |||
4792 | // infer the inner pointer as _Nullable. | |||
4793 | auto hasCFReturnsAttr = | |||
4794 | [](const ParsedAttributesView &AttrList) -> bool { | |||
4795 | return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || | |||
4796 | AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); | |||
4797 | }; | |||
4798 | if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { | |||
4799 | if (hasCFReturnsAttr(D.getDeclarationAttributes()) || | |||
4800 | hasCFReturnsAttr(D.getAttributes()) || | |||
4801 | hasCFReturnsAttr(InnermostChunk->getAttrs()) || | |||
4802 | hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { | |||
4803 | inferNullability = NullabilityKind::Nullable; | |||
4804 | inferNullabilityInnerOnly = true; | |||
4805 | } | |||
4806 | } | |||
4807 | } | |||
4808 | break; | |||
4809 | } | |||
4810 | break; | |||
4811 | } | |||
4812 | ||||
4813 | case DeclaratorContext::ConversionId: | |||
4814 | complainAboutMissingNullability = CAMN_Yes; | |||
4815 | break; | |||
4816 | ||||
4817 | case DeclaratorContext::AliasDecl: | |||
4818 | case DeclaratorContext::AliasTemplate: | |||
4819 | case DeclaratorContext::Block: | |||
4820 | case DeclaratorContext::BlockLiteral: | |||
4821 | case DeclaratorContext::Condition: | |||
4822 | case DeclaratorContext::CXXCatch: | |||
4823 | case DeclaratorContext::CXXNew: | |||
4824 | case DeclaratorContext::ForInit: | |||
4825 | case DeclaratorContext::SelectionInit: | |||
4826 | case DeclaratorContext::LambdaExpr: | |||
4827 | case DeclaratorContext::LambdaExprParameter: | |||
4828 | case DeclaratorContext::ObjCCatch: | |||
4829 | case DeclaratorContext::TemplateParam: | |||
4830 | case DeclaratorContext::TemplateArg: | |||
4831 | case DeclaratorContext::TemplateTypeArg: | |||
4832 | case DeclaratorContext::TypeName: | |||
4833 | case DeclaratorContext::FunctionalCast: | |||
4834 | case DeclaratorContext::RequiresExpr: | |||
4835 | case DeclaratorContext::Association: | |||
4836 | // Don't infer in these contexts. | |||
4837 | break; | |||
4838 | } | |||
4839 | } | |||
4840 | ||||
4841 | // Local function that returns true if its argument looks like a va_list. | |||
4842 | auto isVaList = [&S](QualType T) -> bool { | |||
4843 | auto *typedefTy = T->getAs<TypedefType>(); | |||
4844 | if (!typedefTy) | |||
4845 | return false; | |||
4846 | TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); | |||
4847 | do { | |||
4848 | if (typedefTy->getDecl() == vaListTypedef) | |||
4849 | return true; | |||
4850 | if (auto *name = typedefTy->getDecl()->getIdentifier()) | |||
4851 | if (name->isStr("va_list")) | |||
4852 | return true; | |||
4853 | typedefTy = typedefTy->desugar()->getAs<TypedefType>(); | |||
4854 | } while (typedefTy); | |||
4855 | return false; | |||
4856 | }; | |||
4857 | ||||
4858 | // Local function that checks the nullability for a given pointer declarator. | |||
4859 | // Returns true if _Nonnull was inferred. | |||
4860 | auto inferPointerNullability = | |||
4861 | [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, | |||
4862 | SourceLocation pointerEndLoc, | |||
4863 | ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { | |||
4864 | // We've seen a pointer. | |||
4865 | if (NumPointersRemaining > 0) | |||
4866 | --NumPointersRemaining; | |||
4867 | ||||
4868 | // If a nullability attribute is present, there's nothing to do. | |||
4869 | if (hasNullabilityAttr(attrs)) | |||
4870 | return nullptr; | |||
4871 | ||||
4872 | // If we're supposed to infer nullability, do so now. | |||
4873 | if (inferNullability && !inferNullabilityInnerOnlyComplete) { | |||
4874 | ParsedAttr::Syntax syntax = inferNullabilityCS | |||
4875 | ? ParsedAttr::AS_ContextSensitiveKeyword | |||
4876 | : ParsedAttr::AS_Keyword; | |||
4877 | ParsedAttr *nullabilityAttr = Pool.create( | |||
4878 | S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc), | |||
4879 | nullptr, SourceLocation(), nullptr, 0, syntax); | |||
4880 | ||||
4881 | attrs.addAtEnd(nullabilityAttr); | |||
4882 | ||||
4883 | if (inferNullabilityCS) { | |||
4884 | state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() | |||
4885 | ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); | |||
4886 | } | |||
4887 | ||||
4888 | if (pointerLoc.isValid() && | |||
4889 | complainAboutInferringWithinChunk != | |||
4890 | PointerWrappingDeclaratorKind::None) { | |||
4891 | auto Diag = | |||
4892 | S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); | |||
4893 | Diag << static_cast<int>(complainAboutInferringWithinChunk); | |||
4894 | fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); | |||
4895 | } | |||
4896 | ||||
4897 | if (inferNullabilityInnerOnly) | |||
4898 | inferNullabilityInnerOnlyComplete = true; | |||
4899 | return nullabilityAttr; | |||
4900 | } | |||
4901 | ||||
4902 | // If we're supposed to complain about missing nullability, do so | |||
4903 | // now if it's truly missing. | |||
4904 | switch (complainAboutMissingNullability) { | |||
4905 | case CAMN_No: | |||
4906 | break; | |||
4907 | ||||
4908 | case CAMN_InnerPointers: | |||
4909 | if (NumPointersRemaining == 0) | |||
4910 | break; | |||
4911 | [[fallthrough]]; | |||
4912 | ||||
4913 | case CAMN_Yes: | |||
4914 | checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); | |||
4915 | } | |||
4916 | return nullptr; | |||
4917 | }; | |||
4918 | ||||
4919 | // If the type itself could have nullability but does not, infer pointer | |||
4920 | // nullability and perform consistency checking. | |||
4921 | if (S.CodeSynthesisContexts.empty()) { | |||
4922 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | |||
4923 | !T->getNullability(S.Context)) { | |||
4924 | if (isVaList(T)) { | |||
4925 | // Record that we've seen a pointer, but do nothing else. | |||
4926 | if (NumPointersRemaining > 0) | |||
4927 | --NumPointersRemaining; | |||
4928 | } else { | |||
4929 | SimplePointerKind pointerKind = SimplePointerKind::Pointer; | |||
4930 | if (T->isBlockPointerType()) | |||
4931 | pointerKind = SimplePointerKind::BlockPointer; | |||
4932 | else if (T->isMemberPointerType()) | |||
4933 | pointerKind = SimplePointerKind::MemberPointer; | |||
4934 | ||||
4935 | if (auto *attr = inferPointerNullability( | |||
4936 | pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4937 | D.getDeclSpec().getEndLoc(), | |||
4938 | D.getMutableDeclSpec().getAttributes(), | |||
4939 | D.getMutableDeclSpec().getAttributePool())) { | |||
4940 | T = state.getAttributedType( | |||
4941 | createNullabilityAttr(Context, *attr, *inferNullability), T, T); | |||
4942 | } | |||
4943 | } | |||
4944 | } | |||
4945 | ||||
4946 | if (complainAboutMissingNullability == CAMN_Yes && | |||
4947 | T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && | |||
4948 | D.isPrototypeContext() && | |||
4949 | !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { | |||
4950 | checkNullabilityConsistency(S, SimplePointerKind::Array, | |||
4951 | D.getDeclSpec().getTypeSpecTypeLoc()); | |||
4952 | } | |||
4953 | } | |||
4954 | ||||
4955 | bool ExpectNoDerefChunk = | |||
4956 | state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); | |||
4957 | ||||
4958 | // Walk the DeclTypeInfo, building the recursive type as we go. | |||
4959 | // DeclTypeInfos are ordered from the identifier out, which is | |||
4960 | // opposite of what we want :). | |||
4961 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
4962 | unsigned chunkIndex = e - i - 1; | |||
4963 | state.setCurrentChunkIndex(chunkIndex); | |||
4964 | DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); | |||
4965 | IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; | |||
4966 | switch (DeclType.Kind) { | |||
4967 | case DeclaratorChunk::Paren: | |||
4968 | if (i == 0) | |||
4969 | warnAboutRedundantParens(S, D, T); | |||
4970 | T = S.BuildParenType(T); | |||
4971 | break; | |||
4972 | case DeclaratorChunk::BlockPointer: | |||
4973 | // If blocks are disabled, emit an error. | |||
4974 | if (!LangOpts.Blocks) | |||
4975 | S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; | |||
4976 | ||||
4977 | // Handle pointer nullability. | |||
4978 | inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, | |||
4979 | DeclType.EndLoc, DeclType.getAttrs(), | |||
4980 | state.getDeclarator().getAttributePool()); | |||
4981 | ||||
4982 | T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); | |||
4983 | if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { | |||
4984 | // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly | |||
4985 | // qualified with const. | |||
4986 | if (LangOpts.OpenCL) | |||
4987 | DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; | |||
4988 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); | |||
4989 | } | |||
4990 | break; | |||
4991 | case DeclaratorChunk::Pointer: | |||
4992 | // Verify that we're not building a pointer to pointer to function with | |||
4993 | // exception specification. | |||
4994 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4995 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4996 | D.setInvalidType(true); | |||
4997 | // Build the type anyway. | |||
4998 | } | |||
4999 | ||||
5000 | // Handle pointer nullability | |||
5001 | inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, | |||
5002 | DeclType.EndLoc, DeclType.getAttrs(), | |||
5003 | state.getDeclarator().getAttributePool()); | |||
5004 | ||||
5005 | if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { | |||
5006 | T = Context.getObjCObjectPointerType(T); | |||
5007 | if (DeclType.Ptr.TypeQuals) | |||
5008 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | |||
5009 | break; | |||
5010 | } | |||
5011 | ||||
5012 | // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. | |||
5013 | // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. | |||
5014 | // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. | |||
5015 | if (LangOpts.OpenCL) { | |||
5016 | if (T->isImageType() || T->isSamplerT() || T->isPipeType() || | |||
5017 | T->isBlockPointerType()) { | |||
5018 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; | |||
5019 | D.setInvalidType(true); | |||
5020 | } | |||
5021 | } | |||
5022 | ||||
5023 | T = S.BuildPointerType(T, DeclType.Loc, Name); | |||
5024 | if (DeclType.Ptr.TypeQuals) | |||
5025 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | |||
5026 | break; | |||
5027 | case DeclaratorChunk::Reference: { | |||
5028 | // Verify that we're not building a reference to pointer to function with | |||
5029 | // exception specification. | |||
5030 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
5031 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
5032 | D.setInvalidType(true); | |||
5033 | // Build the type anyway. | |||
5034 | } | |||
5035 | T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); | |||
5036 | ||||
5037 | if (DeclType.Ref.HasRestrict) | |||
5038 | T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); | |||
5039 | break; | |||
5040 | } | |||
5041 | case DeclaratorChunk::Array: { | |||
5042 | // Verify that we're not building an array of pointers to function with | |||
5043 | // exception specification. | |||
5044 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
5045 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
5046 | D.setInvalidType(true); | |||
5047 | // Build the type anyway. | |||
5048 | } | |||
5049 | DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; | |||
5050 | Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); | |||
5051 | ArrayType::ArraySizeModifier ASM; | |||
5052 | if (ATI.isStar) | |||
5053 | ASM = ArrayType::Star; | |||
5054 | else if (ATI.hasStatic) | |||
5055 | ASM = ArrayType::Static; | |||
5056 | else | |||
5057 | ASM = ArrayType::Normal; | |||
5058 | if (ASM == ArrayType::Star && !D.isPrototypeContext()) { | |||
5059 | // FIXME: This check isn't quite right: it allows star in prototypes | |||
5060 | // for function definitions, and disallows some edge cases detailed | |||
5061 | // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html | |||
5062 | S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); | |||
5063 | ASM = ArrayType::Normal; | |||
5064 | D.setInvalidType(true); | |||
5065 | } | |||
5066 | ||||
5067 | // C99 6.7.5.2p1: The optional type qualifiers and the keyword static | |||
5068 | // shall appear only in a declaration of a function parameter with an | |||
5069 | // array type, ... | |||
5070 | if (ASM == ArrayType::Static || ATI.TypeQuals) { | |||
5071 | if (!(D.isPrototypeContext() || | |||
5072 | D.getContext() == DeclaratorContext::KNRTypeList)) { | |||
5073 | S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << | |||
5074 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | |||
5075 | // Remove the 'static' and the type qualifiers. | |||
5076 | if (ASM == ArrayType::Static) | |||
5077 | ASM = ArrayType::Normal; | |||
5078 | ATI.TypeQuals = 0; | |||
5079 | D.setInvalidType(true); | |||
5080 | } | |||
5081 | ||||
5082 | // C99 6.7.5.2p1: ... and then only in the outermost array type | |||
5083 | // derivation. | |||
5084 | if (hasOuterPointerLikeChunk(D, chunkIndex)) { | |||
5085 | S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << | |||
5086 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | |||
5087 | if (ASM == ArrayType::Static) | |||
5088 | ASM = ArrayType::Normal; | |||
5089 | ATI.TypeQuals = 0; | |||
5090 | D.setInvalidType(true); | |||
5091 | } | |||
5092 | } | |||
5093 | const AutoType *AT = T->getContainedAutoType(); | |||
5094 | // Allow arrays of auto if we are a generic lambda parameter. | |||
5095 | // i.e. [](auto (&array)[5]) { return array[0]; }; OK | |||
5096 | if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) { | |||
5097 | // We've already diagnosed this for decltype(auto). | |||
5098 | if (!AT->isDecltypeAuto()) | |||
5099 | S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) | |||
5100 | << getPrintableNameForEntity(Name) << T; | |||
5101 | T = QualType(); | |||
5102 | break; | |||
5103 | } | |||
5104 | ||||
5105 | // Array parameters can be marked nullable as well, although it's not | |||
5106 | // necessary if they're marked 'static'. | |||
5107 | if (complainAboutMissingNullability == CAMN_Yes && | |||
5108 | !hasNullabilityAttr(DeclType.getAttrs()) && | |||
5109 | ASM != ArrayType::Static && | |||
5110 | D.isPrototypeContext() && | |||
5111 | !hasOuterPointerLikeChunk(D, chunkIndex)) { | |||
5112 | checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); | |||
5113 | } | |||
5114 | ||||
5115 | T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, | |||
5116 | SourceRange(DeclType.Loc, DeclType.EndLoc), Name); | |||
5117 | break; | |||
5118 | } | |||
5119 | case DeclaratorChunk::Function: { | |||
5120 | // If the function declarator has a prototype (i.e. it is not () and | |||
5121 | // does not have a K&R-style identifier list), then the arguments are part | |||
5122 | // of the type, otherwise the argument list is (). | |||
5123 | DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
5124 | IsQualifiedFunction = | |||
5125 | FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); | |||
5126 | ||||
5127 | // Check for auto functions and trailing return type and adjust the | |||
5128 | // return type accordingly. | |||
5129 | if (!D.isInvalidType()) { | |||
5130 | // trailing-return-type is only required if we're declaring a function, | |||
5131 | // and not, for instance, a pointer to a function. | |||
5132 | if (D.getDeclSpec().hasAutoTypeSpec() && | |||
5133 | !FTI.hasTrailingReturnType() && chunkIndex == 0) { | |||
5134 | if (!S.getLangOpts().CPlusPlus14) { | |||
5135 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
5136 | D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto | |||
5137 | ? diag::err_auto_missing_trailing_return | |||
5138 | : diag::err_deduced_return_type); | |||
5139 | T = Context.IntTy; | |||
5140 | D.setInvalidType(true); | |||
5141 | } else { | |||
5142 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
5143 | diag::warn_cxx11_compat_deduced_return_type); | |||
5144 | } | |||
5145 | } else if (FTI.hasTrailingReturnType()) { | |||
5146 | // T must be exactly 'auto' at this point. See CWG issue 681. | |||
5147 | if (isa<ParenType>(T)) { | |||
5148 | S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) | |||
5149 | << T << D.getSourceRange(); | |||
5150 | D.setInvalidType(true); | |||
5151 | } else if (D.getName().getKind() == | |||
5152 | UnqualifiedIdKind::IK_DeductionGuideName) { | |||
5153 | if (T != Context.DependentTy) { | |||
5154 | S.Diag(D.getDeclSpec().getBeginLoc(), | |||
5155 | diag::err_deduction_guide_with_complex_decl) | |||
5156 | << D.getSourceRange(); | |||
5157 | D.setInvalidType(true); | |||
5158 | } | |||
5159 | } else if (D.getContext() != DeclaratorContext::LambdaExpr && | |||
5160 | (T.hasQualifiers() || !isa<AutoType>(T) || | |||
5161 | cast<AutoType>(T)->getKeyword() != | |||
5162 | AutoTypeKeyword::Auto || | |||
5163 | cast<AutoType>(T)->isConstrained())) { | |||
5164 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
5165 | diag::err_trailing_return_without_auto) | |||
5166 | << T << D.getDeclSpec().getSourceRange(); | |||
5167 | D.setInvalidType(true); | |||
5168 | } | |||
5169 | T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); | |||
5170 | if (T.isNull()) { | |||
5171 | // An error occurred parsing the trailing return type. | |||
5172 | T = Context.IntTy; | |||
5173 | D.setInvalidType(true); | |||
5174 | } else if (AutoType *Auto = T->getContainedAutoType()) { | |||
5175 | // If the trailing return type contains an `auto`, we may need to | |||
5176 | // invent a template parameter for it, for cases like | |||
5177 | // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`. | |||
5178 | InventedTemplateParameterInfo *InventedParamInfo = nullptr; | |||
5179 | if (D.getContext() == DeclaratorContext::Prototype) | |||
5180 | InventedParamInfo = &S.InventedParameterInfos.back(); | |||
5181 | else if (D.getContext() == DeclaratorContext::LambdaExprParameter) | |||
5182 | InventedParamInfo = S.getCurLambda(); | |||
5183 | if (InventedParamInfo) { | |||
5184 | std::tie(T, TInfo) = InventTemplateParameter( | |||
5185 | state, T, TInfo, Auto, *InventedParamInfo); | |||
5186 | } | |||
5187 | } | |||
5188 | } else { | |||
5189 | // This function type is not the type of the entity being declared, | |||
5190 | // so checking the 'auto' is not the responsibility of this chunk. | |||
5191 | } | |||
5192 | } | |||
5193 | ||||
5194 | // C99 6.7.5.3p1: The return type may not be a function or array type. | |||
5195 | // For conversion functions, we'll diagnose this particular error later. | |||
5196 | if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && | |||
5197 | (D.getName().getKind() != | |||
5198 | UnqualifiedIdKind::IK_ConversionFunctionId)) { | |||
5199 | unsigned diagID = diag::err_func_returning_array_function; | |||
5200 | // Last processing chunk in block context means this function chunk | |||
5201 | // represents the block. | |||
5202 | if (chunkIndex == 0 && | |||
5203 | D.getContext() == DeclaratorContext::BlockLiteral) | |||
5204 | diagID = diag::err_block_returning_array_function; | |||
5205 | S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; | |||
5206 | T = Context.IntTy; | |||
5207 | D.setInvalidType(true); | |||
5208 | } | |||
5209 | ||||
5210 | // Do not allow returning half FP value. | |||
5211 | // FIXME: This really should be in BuildFunctionType. | |||
5212 | if (T->isHalfType()) { | |||
5213 | if (S.getLangOpts().OpenCL) { | |||
5214 | if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", | |||
5215 | S.getLangOpts())) { | |||
5216 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | |||
5217 | << T << 0 /*pointer hint*/; | |||
5218 | D.setInvalidType(true); | |||
5219 | } | |||
5220 | } else if (!S.getLangOpts().NativeHalfArgsAndReturns && | |||
5221 | !S.Context.getTargetInfo().allowHalfArgsAndReturns()) { | |||
5222 | S.Diag(D.getIdentifierLoc(), | |||
5223 | diag::err_parameters_retval_cannot_have_fp16_type) << 1; | |||
5224 | D.setInvalidType(true); | |||
5225 | } | |||
5226 | } | |||
5227 | ||||
5228 | if (LangOpts.OpenCL) { | |||
5229 | // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a | |||
5230 | // function. | |||
5231 | if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || | |||
5232 | T->isPipeType()) { | |||
5233 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | |||
5234 | << T << 1 /*hint off*/; | |||
5235 | D.setInvalidType(true); | |||
5236 | } | |||
5237 | // OpenCL doesn't support variadic functions and blocks | |||
5238 | // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. | |||
5239 | // We also allow here any toolchain reserved identifiers. | |||
5240 | if (FTI.isVariadic && | |||
5241 | !S.getOpenCLOptions().isAvailableOption( | |||
5242 | "__cl_clang_variadic_functions", S.getLangOpts()) && | |||
5243 | !(D.getIdentifier() && | |||
5244 | ((D.getIdentifier()->getName() == "printf" && | |||
5245 | LangOpts.getOpenCLCompatibleVersion() >= 120) || | |||
5246 | D.getIdentifier()->getName().startswith("__")))) { | |||
5247 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); | |||
5248 | D.setInvalidType(true); | |||
5249 | } | |||
5250 | } | |||
5251 | ||||
5252 | // Methods cannot return interface types. All ObjC objects are | |||
5253 | // passed by reference. | |||
5254 | if (T->isObjCObjectType()) { | |||
5255 | SourceLocation DiagLoc, FixitLoc; | |||
5256 | if (TInfo) { | |||
5257 | DiagLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
5258 | FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); | |||
5259 | } else { | |||
5260 | DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); | |||
5261 | FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); | |||
5262 | } | |||
5263 | S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) | |||
5264 | << 0 << T | |||
5265 | << FixItHint::CreateInsertion(FixitLoc, "*"); | |||
5266 | ||||
5267 | T = Context.getObjCObjectPointerType(T); | |||
5268 | if (TInfo) { | |||
5269 | TypeLocBuilder TLB; | |||
5270 | TLB.pushFullCopy(TInfo->getTypeLoc()); | |||
5271 | ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); | |||
5272 | TLoc.setStarLoc(FixitLoc); | |||
5273 | TInfo = TLB.getTypeSourceInfo(Context, T); | |||
5274 | } | |||
5275 | ||||
5276 | D.setInvalidType(true); | |||
5277 | } | |||
5278 | ||||
5279 | // cv-qualifiers on return types are pointless except when the type is a | |||
5280 | // class type in C++. | |||
5281 | if ((T.getCVRQualifiers() || T->isAtomicType()) && | |||
5282 | !(S.getLangOpts().CPlusPlus && | |||
5283 | (T->isDependentType() || T->isRecordType()))) { | |||
5284 | if (T->isVoidType() && !S.getLangOpts().CPlusPlus && | |||
5285 | D.getFunctionDefinitionKind() == | |||
5286 | FunctionDefinitionKind::Definition) { | |||
5287 | // [6.9.1/3] qualified void return is invalid on a C | |||
5288 | // function definition. Apparently ok on declarations and | |||
5289 | // in C++ though (!) | |||
5290 | S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; | |||
5291 | } else | |||
5292 | diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); | |||
5293 | ||||
5294 | // C++2a [dcl.fct]p12: | |||
5295 | // A volatile-qualified return type is deprecated | |||
5296 | if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20) | |||
5297 | S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T; | |||
5298 | } | |||
5299 | ||||
5300 | // Objective-C ARC ownership qualifiers are ignored on the function | |||
5301 | // return type (by type canonicalization). Complain if this attribute | |||
5302 | // was written here. | |||
5303 | if (T.getQualifiers().hasObjCLifetime()) { | |||
5304 | SourceLocation AttrLoc; | |||
5305 | if (chunkIndex + 1 < D.getNumTypeObjects()) { | |||
5306 | DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); | |||
5307 | for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { | |||
5308 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
5309 | AttrLoc = AL.getLoc(); | |||
5310 | break; | |||
5311 | } | |||
5312 | } | |||
5313 | } | |||
5314 | if (AttrLoc.isInvalid()) { | |||
5315 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | |||
5316 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
5317 | AttrLoc = AL.getLoc(); | |||
5318 | break; | |||
5319 | } | |||
5320 | } | |||
5321 | } | |||
5322 | ||||
5323 | if (AttrLoc.isValid()) { | |||
5324 | // The ownership attributes are almost always written via | |||
5325 | // the predefined | |||
5326 | // __strong/__weak/__autoreleasing/__unsafe_unretained. | |||
5327 | if (AttrLoc.isMacroID()) | |||
5328 | AttrLoc = | |||
5329 | S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); | |||
5330 | ||||
5331 | S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) | |||
5332 | << T.getQualifiers().getObjCLifetime(); | |||
5333 | } | |||
5334 | } | |||
5335 | ||||
5336 | if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { | |||
5337 | // C++ [dcl.fct]p6: | |||
5338 | // Types shall not be defined in return or parameter types. | |||
5339 | TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
5340 | S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) | |||
5341 | << Context.getTypeDeclType(Tag); | |||
5342 | } | |||
5343 | ||||
5344 | // Exception specs are not allowed in typedefs. Complain, but add it | |||
5345 | // anyway. | |||
5346 | if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) | |||
5347 | S.Diag(FTI.getExceptionSpecLocBeg(), | |||
5348 | diag::err_exception_spec_in_typedef) | |||
5349 | << (D.getContext() == DeclaratorContext::AliasDecl || | |||
5350 | D.getContext() == DeclaratorContext::AliasTemplate); | |||
5351 | ||||
5352 | // If we see "T var();" or "T var(T());" at block scope, it is probably | |||
5353 | // an attempt to initialize a variable, not a function declaration. | |||
5354 | if (FTI.isAmbiguous) | |||
5355 | warnAboutAmbiguousFunction(S, D, DeclType, T); | |||
5356 | ||||
5357 | FunctionType::ExtInfo EI( | |||
5358 | getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); | |||
5359 | ||||
5360 | // OpenCL disallows functions without a prototype, but it doesn't enforce | |||
5361 | // strict prototypes as in C2x because it allows a function definition to | |||
5362 | // have an identifier list. See OpenCL 3.0 6.11/g for more details. | |||
5363 | if (!FTI.NumParams && !FTI.isVariadic && | |||
5364 | !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) { | |||
5365 | // Simple void foo(), where the incoming T is the result type. | |||
5366 | T = Context.getFunctionNoProtoType(T, EI); | |||
5367 | } else { | |||
5368 | // We allow a zero-parameter variadic function in C if the | |||
5369 | // function is marked with the "overloadable" attribute. Scan | |||
5370 | // for this attribute now. | |||
5371 | if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) | |||
5372 | if (!D.getDeclarationAttributes().hasAttribute( | |||
5373 | ParsedAttr::AT_Overloadable) && | |||
5374 | !D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable) && | |||
5375 | !D.getDeclSpec().getAttributes().hasAttribute( | |||
5376 | ParsedAttr::AT_Overloadable)) | |||
5377 | S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); | |||
5378 | ||||
5379 | if (FTI.NumParams && FTI.Params[0].Param == nullptr) { | |||
5380 | // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function | |||
5381 | // definition. | |||
5382 | S.Diag(FTI.Params[0].IdentLoc, | |||
5383 | diag::err_ident_list_in_fn_declaration); | |||
5384 | D.setInvalidType(true); | |||
5385 | // Recover by creating a K&R-style function type, if possible. | |||
5386 | T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) | |||
5387 | ? Context.getFunctionNoProtoType(T, EI) | |||
5388 | : Context.IntTy; | |||
5389 | break; | |||
5390 | } | |||
5391 | ||||
5392 | FunctionProtoType::ExtProtoInfo EPI; | |||
5393 | EPI.ExtInfo = EI; | |||
5394 | EPI.Variadic = FTI.isVariadic; | |||
5395 | EPI.EllipsisLoc = FTI.getEllipsisLoc(); | |||
5396 | EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); | |||
5397 | EPI.TypeQuals.addCVRUQualifiers( | |||
5398 | FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() | |||
5399 | : 0); | |||
5400 | EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None | |||
5401 | : FTI.RefQualifierIsLValueRef? RQ_LValue | |||
5402 | : RQ_RValue; | |||
5403 | ||||
5404 | // Otherwise, we have a function with a parameter list that is | |||
5405 | // potentially variadic. | |||
5406 | SmallVector<QualType, 16> ParamTys; | |||
5407 | ParamTys.reserve(FTI.NumParams); | |||
5408 | ||||
5409 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> | |||
5410 | ExtParameterInfos(FTI.NumParams); | |||
5411 | bool HasAnyInterestingExtParameterInfos = false; | |||
5412 | ||||
5413 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | |||
5414 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
5415 | QualType ParamTy = Param->getType(); | |||
5416 | assert(!ParamTy.isNull() && "Couldn't parse type?")(static_cast <bool> (!ParamTy.isNull() && "Couldn't parse type?" ) ? void (0) : __assert_fail ("!ParamTy.isNull() && \"Couldn't parse type?\"" , "clang/lib/Sema/SemaType.cpp", 5416, __extension__ __PRETTY_FUNCTION__ )); | |||
5417 | ||||
5418 | // Look for 'void'. void is allowed only as a single parameter to a | |||
5419 | // function with no other parameters (C99 6.7.5.3p10). We record | |||
5420 | // int(void) as a FunctionProtoType with an empty parameter list. | |||
5421 | if (ParamTy->isVoidType()) { | |||
5422 | // If this is something like 'float(int, void)', reject it. 'void' | |||
5423 | // is an incomplete type (C99 6.2.5p19) and function decls cannot | |||
5424 | // have parameters of incomplete type. | |||
5425 | if (FTI.NumParams != 1 || FTI.isVariadic) { | |||
5426 | S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param); | |||
5427 | ParamTy = Context.IntTy; | |||
5428 | Param->setType(ParamTy); | |||
5429 | } else if (FTI.Params[i].Ident) { | |||
5430 | // Reject, but continue to parse 'int(void abc)'. | |||
5431 | S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); | |||
5432 | ParamTy = Context.IntTy; | |||
5433 | Param->setType(ParamTy); | |||
5434 | } else { | |||
5435 | // Reject, but continue to parse 'float(const void)'. | |||
5436 | if (ParamTy.hasQualifiers()) | |||
5437 | S.Diag(DeclType.Loc, diag::err_void_param_qualified); | |||
5438 | ||||
5439 | // Do not add 'void' to the list. | |||
5440 | break; | |||
5441 | } | |||
5442 | } else if (ParamTy->isHalfType()) { | |||
5443 | // Disallow half FP parameters. | |||
5444 | // FIXME: This really should be in BuildFunctionType. | |||
5445 | if (S.getLangOpts().OpenCL) { | |||
5446 | if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", | |||
5447 | S.getLangOpts())) { | |||
5448 | S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) | |||
5449 | << ParamTy << 0; | |||
5450 | D.setInvalidType(); | |||
5451 | Param->setInvalidDecl(); | |||
5452 | } | |||
5453 | } else if (!S.getLangOpts().NativeHalfArgsAndReturns && | |||
5454 | !S.Context.getTargetInfo().allowHalfArgsAndReturns()) { | |||
5455 | S.Diag(Param->getLocation(), | |||
5456 | diag::err_parameters_retval_cannot_have_fp16_type) << 0; | |||
5457 | D.setInvalidType(); | |||
5458 | } | |||
5459 | } else if (!FTI.hasPrototype) { | |||
5460 | if (ParamTy->isPromotableIntegerType()) { | |||
5461 | ParamTy = Context.getPromotedIntegerType(ParamTy); | |||
5462 | Param->setKNRPromoted(true); | |||
5463 | } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { | |||
5464 | if (BTy->getKind() == BuiltinType::Float) { | |||
5465 | ParamTy = Context.DoubleTy; | |||
5466 | Param->setKNRPromoted(true); | |||
5467 | } | |||
5468 | } | |||
5469 | } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) { | |||
5470 | // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function. | |||
5471 | S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) | |||
5472 | << ParamTy << 1 /*hint off*/; | |||
5473 | D.setInvalidType(); | |||
5474 | } | |||
5475 | ||||
5476 | if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { | |||
5477 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); | |||
5478 | HasAnyInterestingExtParameterInfos = true; | |||
5479 | } | |||
5480 | ||||
5481 | if (auto attr = Param->getAttr<ParameterABIAttr>()) { | |||
5482 | ExtParameterInfos[i] = | |||
5483 | ExtParameterInfos[i].withABI(attr->getABI()); | |||
5484 | HasAnyInterestingExtParameterInfos = true; | |||
5485 | } | |||
5486 | ||||
5487 | if (Param->hasAttr<PassObjectSizeAttr>()) { | |||
5488 | ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); | |||
5489 | HasAnyInterestingExtParameterInfos = true; | |||
5490 | } | |||
5491 | ||||
5492 | if (Param->hasAttr<NoEscapeAttr>()) { | |||
5493 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); | |||
5494 | HasAnyInterestingExtParameterInfos = true; | |||
5495 | } | |||
5496 | ||||
5497 | ParamTys.push_back(ParamTy); | |||
5498 | } | |||
5499 | ||||
5500 | if (HasAnyInterestingExtParameterInfos) { | |||
5501 | EPI.ExtParameterInfos = ExtParameterInfos.data(); | |||
5502 | checkExtParameterInfos(S, ParamTys, EPI, | |||
5503 | [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); | |||
5504 | } | |||
5505 | ||||
5506 | SmallVector<QualType, 4> Exceptions; | |||
5507 | SmallVector<ParsedType, 2> DynamicExceptions; | |||
5508 | SmallVector<SourceRange, 2> DynamicExceptionRanges; | |||
5509 | Expr *NoexceptExpr = nullptr; | |||
5510 | ||||
5511 | if (FTI.getExceptionSpecType() == EST_Dynamic) { | |||
5512 | // FIXME: It's rather inefficient to have to split into two vectors | |||
5513 | // here. | |||
5514 | unsigned N = FTI.getNumExceptions(); | |||
5515 | DynamicExceptions.reserve(N); | |||
5516 | DynamicExceptionRanges.reserve(N); | |||
5517 | for (unsigned I = 0; I != N; ++I) { | |||
5518 | DynamicExceptions.push_back(FTI.Exceptions[I].Ty); | |||
5519 | DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); | |||
5520 | } | |||
5521 | } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { | |||
5522 | NoexceptExpr = FTI.NoexceptExpr; | |||
5523 | } | |||
5524 | ||||
5525 | S.checkExceptionSpecification(D.isFunctionDeclarationContext(), | |||
5526 | FTI.getExceptionSpecType(), | |||
5527 | DynamicExceptions, | |||
5528 | DynamicExceptionRanges, | |||
5529 | NoexceptExpr, | |||
5530 | Exceptions, | |||
5531 | EPI.ExceptionSpec); | |||
5532 | ||||
5533 | // FIXME: Set address space from attrs for C++ mode here. | |||
5534 | // OpenCLCPlusPlus: A class member function has an address space. | |||
5535 | auto IsClassMember = [&]() { | |||
5536 | return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && | |||
5537 | state.getDeclarator() | |||
5538 | .getCXXScopeSpec() | |||
5539 | .getScopeRep() | |||
5540 | ->getKind() == NestedNameSpecifier::TypeSpec) || | |||
5541 | state.getDeclarator().getContext() == | |||
5542 | DeclaratorContext::Member || | |||
5543 | state.getDeclarator().getContext() == | |||
5544 | DeclaratorContext::LambdaExpr; | |||
5545 | }; | |||
5546 | ||||
5547 | if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { | |||
5548 | LangAS ASIdx = LangAS::Default; | |||
5549 | // Take address space attr if any and mark as invalid to avoid adding | |||
5550 | // them later while creating QualType. | |||
5551 | if (FTI.MethodQualifiers) | |||
5552 | for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { | |||
5553 | LangAS ASIdxNew = attr.asOpenCLLangAS(); | |||
5554 | if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, | |||
5555 | attr.getLoc())) | |||
5556 | D.setInvalidType(true); | |||
5557 | else | |||
5558 | ASIdx = ASIdxNew; | |||
5559 | } | |||
5560 | // If a class member function's address space is not set, set it to | |||
5561 | // __generic. | |||
5562 | LangAS AS = | |||
5563 | (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace() | |||
5564 | : ASIdx); | |||
5565 | EPI.TypeQuals.addAddressSpace(AS); | |||
5566 | } | |||
5567 | T = Context.getFunctionType(T, ParamTys, EPI); | |||
5568 | } | |||
5569 | break; | |||
5570 | } | |||
5571 | case DeclaratorChunk::MemberPointer: { | |||
5572 | // The scope spec must refer to a class, or be dependent. | |||
5573 | CXXScopeSpec &SS = DeclType.Mem.Scope(); | |||
5574 | QualType ClsType; | |||
5575 | ||||
5576 | // Handle pointer nullability. | |||
5577 | inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, | |||
5578 | DeclType.EndLoc, DeclType.getAttrs(), | |||
5579 | state.getDeclarator().getAttributePool()); | |||
5580 | ||||
5581 | if (SS.isInvalid()) { | |||
5582 | // Avoid emitting extra errors if we already errored on the scope. | |||
5583 | D.setInvalidType(true); | |||
5584 | } else if (S.isDependentScopeSpecifier(SS) || | |||
5585 | isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) { | |||
5586 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
5587 | NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); | |||
5588 | switch (NNS->getKind()) { | |||
5589 | case NestedNameSpecifier::Identifier: | |||
5590 | ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, | |||
5591 | NNS->getAsIdentifier()); | |||
5592 | break; | |||
5593 | ||||
5594 | case NestedNameSpecifier::Namespace: | |||
5595 | case NestedNameSpecifier::NamespaceAlias: | |||
5596 | case NestedNameSpecifier::Global: | |||
5597 | case NestedNameSpecifier::Super: | |||
5598 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "clang/lib/Sema/SemaType.cpp", 5598); | |||
5599 | ||||
5600 | case NestedNameSpecifier::TypeSpec: | |||
5601 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
5602 | ClsType = QualType(NNS->getAsType(), 0); | |||
5603 | // Note: if the NNS has a prefix and ClsType is a nondependent | |||
5604 | // TemplateSpecializationType, then the NNS prefix is NOT included | |||
5605 | // in ClsType; hence we wrap ClsType into an ElaboratedType. | |||
5606 | // NOTE: in particular, no wrap occurs if ClsType already is an | |||
5607 | // Elaborated, DependentName, or DependentTemplateSpecialization. | |||
5608 | if (isa<TemplateSpecializationType>(NNS->getAsType())) | |||
5609 | ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); | |||
5610 | break; | |||
5611 | } | |||
5612 | } else { | |||
5613 | S.Diag(DeclType.Mem.Scope().getBeginLoc(), | |||
5614 | diag::err_illegal_decl_mempointer_in_nonclass) | |||
5615 | << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") | |||
5616 | << DeclType.Mem.Scope().getRange(); | |||
5617 | D.setInvalidType(true); | |||
5618 | } | |||
5619 | ||||
5620 | if (!ClsType.isNull()) | |||
5621 | T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, | |||
5622 | D.getIdentifier()); | |||
5623 | if (T.isNull()) { | |||
5624 | T = Context.IntTy; | |||
5625 | D.setInvalidType(true); | |||
5626 | } else if (DeclType.Mem.TypeQuals) { | |||
5627 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); | |||
5628 | } | |||
5629 | break; | |||
5630 | } | |||
5631 | ||||
5632 | case DeclaratorChunk::Pipe: { | |||
5633 | T = S.BuildReadPipeType(T, DeclType.Loc); | |||
5634 | processTypeAttrs(state, T, TAL_DeclSpec, | |||
5635 | D.getMutableDeclSpec().getAttributes()); | |||
5636 | break; | |||
5637 | } | |||
5638 | } | |||
5639 | ||||
5640 | if (T.isNull()) { | |||
5641 | D.setInvalidType(true); | |||
5642 | T = Context.IntTy; | |||
5643 | } | |||
5644 | ||||
5645 | // See if there are any attributes on this declarator chunk. | |||
5646 | processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); | |||
5647 | ||||
5648 | if (DeclType.Kind != DeclaratorChunk::Paren) { | |||
5649 | if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) | |||
5650 | S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); | |||
5651 | ||||
5652 | ExpectNoDerefChunk = state.didParseNoDeref(); | |||
5653 | } | |||
5654 | } | |||
5655 | ||||
5656 | if (ExpectNoDerefChunk) | |||
5657 | S.Diag(state.getDeclarator().getBeginLoc(), | |||
5658 | diag::warn_noderef_on_non_pointer_or_array); | |||
5659 | ||||
5660 | // GNU warning -Wstrict-prototypes | |||
5661 | // Warn if a function declaration or definition is without a prototype. | |||
5662 | // This warning is issued for all kinds of unprototyped function | |||
5663 | // declarations (i.e. function type typedef, function pointer etc.) | |||
5664 | // C99 6.7.5.3p14: | |||
5665 | // The empty list in a function declarator that is not part of a definition | |||
5666 | // of that function specifies that no information about the number or types | |||
5667 | // of the parameters is supplied. | |||
5668 | // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of | |||
5669 | // function declarations whose behavior changes in C2x. | |||
5670 | if (!LangOpts.requiresStrictPrototypes()) { | |||
5671 | bool IsBlock = false; | |||
5672 | for (const DeclaratorChunk &DeclType : D.type_objects()) { | |||
5673 | switch (DeclType.Kind) { | |||
5674 | case DeclaratorChunk::BlockPointer: | |||
5675 | IsBlock = true; | |||
5676 | break; | |||
5677 | case DeclaratorChunk::Function: { | |||
5678 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
5679 | // We suppress the warning when there's no LParen location, as this | |||
5680 | // indicates the declaration was an implicit declaration, which gets | |||
5681 | // warned about separately via -Wimplicit-function-declaration. We also | |||
5682 | // suppress the warning when we know the function has a prototype. | |||
5683 | if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic && | |||
5684 | FTI.getLParenLoc().isValid()) | |||
5685 | S.Diag(DeclType.Loc, diag::warn_strict_prototypes) | |||
5686 | << IsBlock | |||
5687 | << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); | |||
5688 | IsBlock = false; | |||
5689 | break; | |||
5690 | } | |||
5691 | default: | |||
5692 | break; | |||
5693 | } | |||
5694 | } | |||
5695 | } | |||
5696 | ||||
5697 | assert(!T.isNull() && "T must not be null after this point")(static_cast <bool> (!T.isNull() && "T must not be null after this point" ) ? void (0) : __assert_fail ("!T.isNull() && \"T must not be null after this point\"" , "clang/lib/Sema/SemaType.cpp", 5697, __extension__ __PRETTY_FUNCTION__ )); | |||
5698 | ||||
5699 | if (LangOpts.CPlusPlus && T->isFunctionType()) { | |||
5700 | const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); | |||
5701 | assert(FnTy && "Why oh why is there not a FunctionProtoType here?")(static_cast <bool> (FnTy && "Why oh why is there not a FunctionProtoType here?" ) ? void (0) : __assert_fail ("FnTy && \"Why oh why is there not a FunctionProtoType here?\"" , "clang/lib/Sema/SemaType.cpp", 5701, __extension__ __PRETTY_FUNCTION__ )); | |||
5702 | ||||
5703 | // C++ 8.3.5p4: | |||
5704 | // A cv-qualifier-seq shall only be part of the function type | |||
5705 | // for a nonstatic member function, the function type to which a pointer | |||
5706 | // to member refers, or the top-level function type of a function typedef | |||
5707 | // declaration. | |||
5708 | // | |||
5709 | // Core issue 547 also allows cv-qualifiers on function types that are | |||
5710 | // top-level template type arguments. | |||
5711 | enum { NonMember, Member, DeductionGuide } Kind = NonMember; | |||
5712 | if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) | |||
5713 | Kind = DeductionGuide; | |||
5714 | else if (!D.getCXXScopeSpec().isSet()) { | |||
5715 | if ((D.getContext() == DeclaratorContext::Member || | |||
5716 | D.getContext() == DeclaratorContext::LambdaExpr) && | |||
5717 | !D.getDeclSpec().isFriendSpecified()) | |||
5718 | Kind = Member; | |||
5719 | } else { | |||
5720 | DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); | |||
5721 | if (!DC || DC->isRecord()) | |||
5722 | Kind = Member; | |||
5723 | } | |||
5724 | ||||
5725 | // C++11 [dcl.fct]p6 (w/DR1417): | |||
5726 | // An attempt to specify a function type with a cv-qualifier-seq or a | |||
5727 | // ref-qualifier (including by typedef-name) is ill-formed unless it is: | |||
5728 | // - the function type for a non-static member function, | |||
5729 | // - the function type to which a pointer to member refers, | |||
5730 | // - the top-level function type of a function typedef declaration or | |||
5731 | // alias-declaration, | |||
5732 | // - the type-id in the default argument of a type-parameter, or | |||
5733 | // - the type-id of a template-argument for a type-parameter | |||
5734 | // | |||
5735 | // FIXME: Checking this here is insufficient. We accept-invalid on: | |||
5736 | // | |||
5737 | // template<typename T> struct S { void f(T); }; | |||
5738 | // S<int() const> s; | |||
5739 | // | |||
5740 | // ... for instance. | |||
5741 | if (IsQualifiedFunction && | |||
5742 | !(Kind == Member && | |||
5743 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && | |||
5744 | !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg && | |||
5745 | D.getContext() != DeclaratorContext::TemplateTypeArg) { | |||
5746 | SourceLocation Loc = D.getBeginLoc(); | |||
5747 | SourceRange RemovalRange; | |||
5748 | unsigned I; | |||
5749 | if (D.isFunctionDeclarator(I)) { | |||
5750 | SmallVector<SourceLocation, 4> RemovalLocs; | |||
5751 | const DeclaratorChunk &Chunk = D.getTypeObject(I); | |||
5752 | assert(Chunk.Kind == DeclaratorChunk::Function)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Function ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "clang/lib/Sema/SemaType.cpp", 5752, __extension__ __PRETTY_FUNCTION__ )); | |||
5753 | ||||
5754 | if (Chunk.Fun.hasRefQualifier()) | |||
5755 | RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); | |||
5756 | ||||
5757 | if (Chunk.Fun.hasMethodTypeQualifiers()) | |||
5758 | Chunk.Fun.MethodQualifiers->forEachQualifier( | |||
5759 | [&](DeclSpec::TQ TypeQual, StringRef QualName, | |||
5760 | SourceLocation SL) { RemovalLocs.push_back(SL); }); | |||
5761 | ||||
5762 | if (!RemovalLocs.empty()) { | |||
5763 | llvm::sort(RemovalLocs, | |||
5764 | BeforeThanCompare<SourceLocation>(S.getSourceManager())); | |||
5765 | RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); | |||
5766 | Loc = RemovalLocs.front(); | |||
5767 | } | |||
5768 | } | |||
5769 | ||||
5770 | S.Diag(Loc, diag::err_invalid_qualified_function_type) | |||
5771 | << Kind << D.isFunctionDeclarator() << T | |||
5772 | << getFunctionQualifiersAsString(FnTy) | |||
5773 | << FixItHint::CreateRemoval(RemovalRange); | |||
5774 | ||||
5775 | // Strip the cv-qualifiers and ref-qualifiers from the type. | |||
5776 | FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); | |||
5777 | EPI.TypeQuals.removeCVRQualifiers(); | |||
5778 | EPI.RefQualifier = RQ_None; | |||
5779 | ||||
5780 | T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), | |||
5781 | EPI); | |||
5782 | // Rebuild any parens around the identifier in the function type. | |||
5783 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5784 | if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) | |||
5785 | break; | |||
5786 | T = S.BuildParenType(T); | |||
5787 | } | |||
5788 | } | |||
5789 | } | |||
5790 | ||||
5791 | // Apply any undistributed attributes from the declaration or declarator. | |||
5792 | ParsedAttributesView NonSlidingAttrs; | |||
5793 | for (ParsedAttr &AL : D.getDeclarationAttributes()) { | |||
5794 | if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) { | |||
5795 | NonSlidingAttrs.addAtEnd(&AL); | |||
5796 | } | |||
5797 | } | |||
5798 | processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs); | |||
5799 | processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); | |||
5800 | ||||
5801 | // Diagnose any ignored type attributes. | |||
5802 | state.diagnoseIgnoredTypeAttrs(T); | |||
5803 | ||||
5804 | // C++0x [dcl.constexpr]p9: | |||
5805 | // A constexpr specifier used in an object declaration declares the object | |||
5806 | // as const. | |||
5807 | if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr && | |||
5808 | T->isObjectType()) | |||
5809 | T.addConst(); | |||
5810 | ||||
5811 | // C++2a [dcl.fct]p4: | |||
5812 | // A parameter with volatile-qualified type is deprecated | |||
5813 | if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 && | |||
5814 | (D.getContext() == DeclaratorContext::Prototype || | |||
5815 | D.getContext() == DeclaratorContext::LambdaExprParameter)) | |||
5816 | S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; | |||
5817 | ||||
5818 | // If there was an ellipsis in the declarator, the declaration declares a | |||
5819 | // parameter pack whose type may be a pack expansion type. | |||
5820 | if (D.hasEllipsis()) { | |||
5821 | // C++0x [dcl.fct]p13: | |||
5822 | // A declarator-id or abstract-declarator containing an ellipsis shall | |||
5823 | // only be used in a parameter-declaration. Such a parameter-declaration | |||
5824 | // is a parameter pack (14.5.3). [...] | |||
5825 | switch (D.getContext()) { | |||
5826 | case DeclaratorContext::Prototype: | |||
5827 | case DeclaratorContext::LambdaExprParameter: | |||
5828 | case DeclaratorContext::RequiresExpr: | |||
5829 | // C++0x [dcl.fct]p13: | |||
5830 | // [...] When it is part of a parameter-declaration-clause, the | |||
5831 | // parameter pack is a function parameter pack (14.5.3). The type T | |||
5832 | // of the declarator-id of the function parameter pack shall contain | |||
5833 | // a template parameter pack; each template parameter pack in T is | |||
5834 | // expanded by the function parameter pack. | |||
5835 | // | |||
5836 | // We represent function parameter packs as function parameters whose | |||
5837 | // type is a pack expansion. | |||
5838 | if (!T->containsUnexpandedParameterPack() && | |||
5839 | (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) { | |||
5840 | S.Diag(D.getEllipsisLoc(), | |||
5841 | diag::err_function_parameter_pack_without_parameter_packs) | |||
5842 | << T << D.getSourceRange(); | |||
5843 | D.setEllipsisLoc(SourceLocation()); | |||
5844 | } else { | |||
5845 | T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false); | |||
5846 | } | |||
5847 | break; | |||
5848 | case DeclaratorContext::TemplateParam: | |||
5849 | // C++0x [temp.param]p15: | |||
5850 | // If a template-parameter is a [...] is a parameter-declaration that | |||
5851 | // declares a parameter pack (8.3.5), then the template-parameter is a | |||
5852 | // template parameter pack (14.5.3). | |||
5853 | // | |||
5854 | // Note: core issue 778 clarifies that, if there are any unexpanded | |||
5855 | // parameter packs in the type of the non-type template parameter, then | |||
5856 | // it expands those parameter packs. | |||
5857 | if (T->containsUnexpandedParameterPack()) | |||
5858 | T = Context.getPackExpansionType(T, None); | |||
5859 | else | |||
5860 | S.Diag(D.getEllipsisLoc(), | |||
5861 | LangOpts.CPlusPlus11 | |||
5862 | ? diag::warn_cxx98_compat_variadic_templates | |||
5863 | : diag::ext_variadic_templates); | |||
5864 | break; | |||
5865 | ||||
5866 | case DeclaratorContext::File: | |||
5867 | case DeclaratorContext::KNRTypeList: | |||
5868 | case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here? | |||
5869 | case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here? | |||
5870 | case DeclaratorContext::TypeName: | |||
5871 | case DeclaratorContext::FunctionalCast: | |||
5872 | case DeclaratorContext::CXXNew: | |||
5873 | case DeclaratorContext::AliasDecl: | |||
5874 | case DeclaratorContext::AliasTemplate: | |||
5875 | case DeclaratorContext::Member: | |||
5876 | case DeclaratorContext::Block: | |||
5877 | case DeclaratorContext::ForInit: | |||
5878 | case DeclaratorContext::SelectionInit: | |||
5879 | case DeclaratorContext::Condition: | |||
5880 | case DeclaratorContext::CXXCatch: | |||
5881 | case DeclaratorContext::ObjCCatch: | |||
5882 | case DeclaratorContext::BlockLiteral: | |||
5883 | case DeclaratorContext::LambdaExpr: | |||
5884 | case DeclaratorContext::ConversionId: | |||
5885 | case DeclaratorContext::TrailingReturn: | |||
5886 | case DeclaratorContext::TrailingReturnVar: | |||
5887 | case DeclaratorContext::TemplateArg: | |||
5888 | case DeclaratorContext::TemplateTypeArg: | |||
5889 | case DeclaratorContext::Association: | |||
5890 | // FIXME: We may want to allow parameter packs in block-literal contexts | |||
5891 | // in the future. | |||
5892 | S.Diag(D.getEllipsisLoc(), | |||
5893 | diag::err_ellipsis_in_declarator_not_parameter); | |||
5894 | D.setEllipsisLoc(SourceLocation()); | |||
5895 | break; | |||
5896 | } | |||
5897 | } | |||
5898 | ||||
5899 | assert(!T.isNull() && "T must not be null at the end of this function")(static_cast <bool> (!T.isNull() && "T must not be null at the end of this function" ) ? void (0) : __assert_fail ("!T.isNull() && \"T must not be null at the end of this function\"" , "clang/lib/Sema/SemaType.cpp", 5899, __extension__ __PRETTY_FUNCTION__ )); | |||
5900 | if (D.isInvalidType()) | |||
5901 | return Context.getTrivialTypeSourceInfo(T); | |||
5902 | ||||
5903 | return GetTypeSourceInfoForDeclarator(state, T, TInfo); | |||
5904 | } | |||
5905 | ||||
5906 | /// GetTypeForDeclarator - Convert the type for the specified | |||
5907 | /// declarator to Type instances. | |||
5908 | /// | |||
5909 | /// The result of this call will never be null, but the associated | |||
5910 | /// type may be a null type if there's an unrecoverable error. | |||
5911 | TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { | |||
5912 | // Determine the type of the declarator. Not all forms of declarator | |||
5913 | // have a type. | |||
5914 | ||||
5915 | TypeProcessingState state(*this, D); | |||
5916 | ||||
5917 | TypeSourceInfo *ReturnTypeInfo = nullptr; | |||
5918 | QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | |||
5919 | if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) | |||
5920 | inferARCWriteback(state, T); | |||
5921 | ||||
5922 | return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); | |||
5923 | } | |||
5924 | ||||
5925 | static void transferARCOwnershipToDeclSpec(Sema &S, | |||
5926 | QualType &declSpecTy, | |||
5927 | Qualifiers::ObjCLifetime ownership) { | |||
5928 | if (declSpecTy->isObjCRetainableType() && | |||
5929 | declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { | |||
5930 | Qualifiers qs; | |||
5931 | qs.addObjCLifetime(ownership); | |||
5932 | declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); | |||
5933 | } | |||
5934 | } | |||
5935 | ||||
5936 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | |||
5937 | Qualifiers::ObjCLifetime ownership, | |||
5938 | unsigned chunkIndex) { | |||
5939 | Sema &S = state.getSema(); | |||
5940 | Declarator &D = state.getDeclarator(); | |||
5941 | ||||
5942 | // Look for an explicit lifetime attribute. | |||
5943 | DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); | |||
5944 | if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) | |||
5945 | return; | |||
5946 | ||||
5947 | const char *attrStr = nullptr; | |||
5948 | switch (ownership) { | |||
5949 | case Qualifiers::OCL_None: llvm_unreachable("no ownership!")::llvm::llvm_unreachable_internal("no ownership!", "clang/lib/Sema/SemaType.cpp" , 5949); | |||
5950 | case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; | |||
5951 | case Qualifiers::OCL_Strong: attrStr = "strong"; break; | |||
5952 | case Qualifiers::OCL_Weak: attrStr = "weak"; break; | |||
5953 | case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; | |||
5954 | } | |||
5955 | ||||
5956 | IdentifierLoc *Arg = new (S.Context) IdentifierLoc; | |||
5957 | Arg->Ident = &S.Context.Idents.get(attrStr); | |||
5958 | Arg->Loc = SourceLocation(); | |||
5959 | ||||
5960 | ArgsUnion Args(Arg); | |||
5961 | ||||
5962 | // If there wasn't one, add one (with an invalid source location | |||
5963 | // so that we don't make an AttributedType for it). | |||
5964 | ParsedAttr *attr = D.getAttributePool().create( | |||
5965 | &S.Context.Idents.get("objc_ownership"), SourceLocation(), | |||
5966 | /*scope*/ nullptr, SourceLocation(), | |||
5967 | /*args*/ &Args, 1, ParsedAttr::AS_GNU); | |||
5968 | chunk.getAttrs().addAtEnd(attr); | |||
5969 | // TODO: mark whether we did this inference? | |||
5970 | } | |||
5971 | ||||
5972 | /// Used for transferring ownership in casts resulting in l-values. | |||
5973 | static void transferARCOwnership(TypeProcessingState &state, | |||
5974 | QualType &declSpecTy, | |||
5975 | Qualifiers::ObjCLifetime ownership) { | |||
5976 | Sema &S = state.getSema(); | |||
5977 | Declarator &D = state.getDeclarator(); | |||
5978 | ||||
5979 | int inner = -1; | |||
5980 | bool hasIndirection = false; | |||
5981 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5982 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
5983 | switch (chunk.Kind) { | |||
5984 | case DeclaratorChunk::Paren: | |||
5985 | // Ignore parens. | |||
5986 | break; | |||
5987 | ||||
5988 | case DeclaratorChunk::Array: | |||
5989 | case DeclaratorChunk::Reference: | |||
5990 | case DeclaratorChunk::Pointer: | |||
5991 | if (inner != -1) | |||
5992 | hasIndirection = true; | |||
5993 | inner = i; | |||
5994 | break; | |||
5995 | ||||
5996 | case DeclaratorChunk::BlockPointer: | |||
5997 | if (inner != -1) | |||
5998 | transferARCOwnershipToDeclaratorChunk(state, ownership, i); | |||
5999 | return; | |||
6000 | ||||
6001 | case DeclaratorChunk::Function: | |||
6002 | case DeclaratorChunk::MemberPointer: | |||
6003 | case DeclaratorChunk::Pipe: | |||
6004 | return; | |||
6005 | } | |||
6006 | } | |||
6007 | ||||
6008 | if (inner == -1) | |||
6009 | return; | |||
6010 | ||||
6011 | DeclaratorChunk &chunk = D.getTypeObject(inner); | |||
6012 | if (chunk.Kind == DeclaratorChunk::Pointer) { | |||
6013 | if (declSpecTy->isObjCRetainableType()) | |||
6014 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | |||
6015 | if (declSpecTy->isObjCObjectType() && hasIndirection) | |||
6016 | return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); | |||
6017 | } else { | |||
6018 | assert(chunk.Kind == DeclaratorChunk::Array ||(static_cast <bool> (chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference) ? void (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "clang/lib/Sema/SemaType.cpp", 6019, __extension__ __PRETTY_FUNCTION__ )) | |||
6019 | chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference) ? void (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "clang/lib/Sema/SemaType.cpp", 6019, __extension__ __PRETTY_FUNCTION__ )); | |||
6020 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | |||
6021 | } | |||
6022 | } | |||
6023 | ||||
6024 | TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { | |||
6025 | TypeProcessingState state(*this, D); | |||
6026 | ||||
6027 | TypeSourceInfo *ReturnTypeInfo = nullptr; | |||
6028 | QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | |||
6029 | ||||
6030 | if (getLangOpts().ObjC) { | |||
6031 | Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); | |||
6032 | if (ownership != Qualifiers::OCL_None) | |||
6033 | transferARCOwnership(state, declSpecTy, ownership); | |||
6034 | } | |||
6035 | ||||
6036 | return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); | |||
6037 | } | |||
6038 | ||||
6039 | static void fillAttributedTypeLoc(AttributedTypeLoc TL, | |||
6040 | TypeProcessingState &State) { | |||
6041 | TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); | |||
6042 | } | |||
6043 | ||||
6044 | namespace { | |||
6045 | class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { | |||
6046 | Sema &SemaRef; | |||
6047 | ASTContext &Context; | |||
6048 | TypeProcessingState &State; | |||
6049 | const DeclSpec &DS; | |||
6050 | ||||
6051 | public: | |||
6052 | TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State, | |||
6053 | const DeclSpec &DS) | |||
6054 | : SemaRef(S), Context(Context), State(State), DS(DS) {} | |||
6055 | ||||
6056 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | |||
6057 | Visit(TL.getModifiedLoc()); | |||
6058 | fillAttributedTypeLoc(TL, State); | |||
6059 | } | |||
6060 | void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { | |||
6061 | Visit(TL.getWrappedLoc()); | |||
6062 | } | |||
6063 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { | |||
6064 | Visit(TL.getInnerLoc()); | |||
6065 | TL.setExpansionLoc( | |||
6066 | State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); | |||
6067 | } | |||
6068 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | |||
6069 | Visit(TL.getUnqualifiedLoc()); | |||
6070 | } | |||
6071 | // Allow to fill pointee's type locations, e.g., | |||
6072 | // int __attr * __attr * __attr *p; | |||
6073 | void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); } | |||
6074 | void VisitTypedefTypeLoc(TypedefTypeLoc TL) { | |||
6075 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
6076 | } | |||
6077 | void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { | |||
6078 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
6079 | // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires | |||
6080 | // addition field. What we have is good enough for display of location | |||
6081 | // of 'fixit' on interface name. | |||
6082 | TL.setNameEndLoc(DS.getEndLoc()); | |||
6083 | } | |||
6084 | void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { | |||
6085 | TypeSourceInfo *RepTInfo = nullptr; | |||
6086 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | |||
6087 | TL.copy(RepTInfo->getTypeLoc()); | |||
6088 | } | |||
6089 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | |||
6090 | TypeSourceInfo *RepTInfo = nullptr; | |||
6091 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | |||
6092 | TL.copy(RepTInfo->getTypeLoc()); | |||
6093 | } | |||
6094 | void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { | |||
6095 | TypeSourceInfo *TInfo = nullptr; | |||
6096 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6097 | ||||
6098 | // If we got no declarator info from previous Sema routines, | |||
6099 | // just fill with the typespec loc. | |||
6100 | if (!TInfo) { | |||
6101 | TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); | |||
6102 | return; | |||
6103 | } | |||
6104 | ||||
6105 | TypeLoc OldTL = TInfo->getTypeLoc(); | |||
6106 | if (TInfo->getType()->getAs<ElaboratedType>()) { | |||
6107 | ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); | |||
6108 | TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() | |||
6109 | .castAs<TemplateSpecializationTypeLoc>(); | |||
6110 | TL.copy(NamedTL); | |||
6111 | } else { | |||
6112 | TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); | |||
6113 | assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc())(static_cast <bool> (TL.getRAngleLoc() == OldTL.castAs< TemplateSpecializationTypeLoc>().getRAngleLoc()) ? void (0 ) : __assert_fail ("TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()" , "clang/lib/Sema/SemaType.cpp", 6113, __extension__ __PRETTY_FUNCTION__ )); | |||
6114 | } | |||
6115 | ||||
6116 | } | |||
6117 | void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { | |||
6118 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_typeofExpr || DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofExpr || DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr" , "clang/lib/Sema/SemaType.cpp", 6119, __extension__ __PRETTY_FUNCTION__ )) | |||
6119 | DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_typeofExpr || DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofExpr || DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr" , "clang/lib/Sema/SemaType.cpp", 6119, __extension__ __PRETTY_FUNCTION__ )); | |||
6120 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | |||
6121 | TL.setParensRange(DS.getTypeofParensRange()); | |||
6122 | } | |||
6123 | void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { | |||
6124 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType ||(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_typeofType || DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofType || DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType" , "clang/lib/Sema/SemaType.cpp", 6125, __extension__ __PRETTY_FUNCTION__ )) | |||
6125 | DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_typeofType || DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofType || DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType" , "clang/lib/Sema/SemaType.cpp", 6125, __extension__ __PRETTY_FUNCTION__ )); | |||
6126 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | |||
6127 | TL.setParensRange(DS.getTypeofParensRange()); | |||
6128 | assert(DS.getRepAsType())(static_cast <bool> (DS.getRepAsType()) ? void (0) : __assert_fail ("DS.getRepAsType()", "clang/lib/Sema/SemaType.cpp", 6128, __extension__ __PRETTY_FUNCTION__)); | |||
6129 | TypeSourceInfo *TInfo = nullptr; | |||
6130 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6131 | TL.setUnmodifiedTInfo(TInfo); | |||
6132 | } | |||
6133 | void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { | |||
6134 | assert(DS.getTypeSpecType() == DeclSpec::TST_decltype)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_decltype) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype" , "clang/lib/Sema/SemaType.cpp", 6134, __extension__ __PRETTY_FUNCTION__ )); | |||
6135 | TL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); | |||
6136 | TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); | |||
6137 | } | |||
6138 | void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { | |||
6139 | assert(DS.isTransformTypeTrait(DS.getTypeSpecType()))(static_cast <bool> (DS.isTransformTypeTrait(DS.getTypeSpecType ())) ? void (0) : __assert_fail ("DS.isTransformTypeTrait(DS.getTypeSpecType())" , "clang/lib/Sema/SemaType.cpp", 6139, __extension__ __PRETTY_FUNCTION__ )); | |||
6140 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
6141 | TL.setParensRange(DS.getTypeofParensRange()); | |||
6142 | assert(DS.getRepAsType())(static_cast <bool> (DS.getRepAsType()) ? void (0) : __assert_fail ("DS.getRepAsType()", "clang/lib/Sema/SemaType.cpp", 6142, __extension__ __PRETTY_FUNCTION__)); | |||
6143 | TypeSourceInfo *TInfo = nullptr; | |||
6144 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6145 | TL.setUnderlyingTInfo(TInfo); | |||
6146 | } | |||
6147 | void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { | |||
6148 | // By default, use the source location of the type specifier. | |||
6149 | TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); | |||
6150 | if (TL.needsExtraLocalData()) { | |||
6151 | // Set info for the written builtin specifiers. | |||
6152 | TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); | |||
6153 | // Try to have a meaningful source location. | |||
6154 | if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified) | |||
6155 | TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); | |||
6156 | if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified) | |||
6157 | TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); | |||
6158 | } | |||
6159 | } | |||
6160 | void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { | |||
6161 | if (DS.getTypeSpecType() == TST_typename) { | |||
6162 | TypeSourceInfo *TInfo = nullptr; | |||
6163 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6164 | if (TInfo) | |||
6165 | if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) { | |||
6166 | TL.copy(ETL); | |||
6167 | return; | |||
6168 | } | |||
6169 | } | |||
6170 | const ElaboratedType *T = TL.getTypePtr(); | |||
6171 | TL.setElaboratedKeywordLoc(T->getKeyword() != ETK_None | |||
6172 | ? DS.getTypeSpecTypeLoc() | |||
6173 | : SourceLocation()); | |||
6174 | const CXXScopeSpec& SS = DS.getTypeSpecScope(); | |||
6175 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
6176 | Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); | |||
6177 | } | |||
6178 | void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { | |||
6179 | assert(DS.getTypeSpecType() == TST_typename)(static_cast <bool> (DS.getTypeSpecType() == TST_typename ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "clang/lib/Sema/SemaType.cpp", 6179, __extension__ __PRETTY_FUNCTION__ )); | |||
6180 | TypeSourceInfo *TInfo = nullptr; | |||
6181 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6182 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "clang/lib/Sema/SemaType.cpp", 6182, __extension__ __PRETTY_FUNCTION__ )); | |||
6183 | TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); | |||
6184 | } | |||
6185 | void VisitDependentTemplateSpecializationTypeLoc( | |||
6186 | DependentTemplateSpecializationTypeLoc TL) { | |||
6187 | assert(DS.getTypeSpecType() == TST_typename)(static_cast <bool> (DS.getTypeSpecType() == TST_typename ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "clang/lib/Sema/SemaType.cpp", 6187, __extension__ __PRETTY_FUNCTION__ )); | |||
6188 | TypeSourceInfo *TInfo = nullptr; | |||
6189 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6190 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "clang/lib/Sema/SemaType.cpp", 6190, __extension__ __PRETTY_FUNCTION__ )); | |||
6191 | TL.copy( | |||
6192 | TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); | |||
6193 | } | |||
6194 | void VisitAutoTypeLoc(AutoTypeLoc TL) { | |||
6195 | assert(DS.getTypeSpecType() == TST_auto ||(static_cast <bool> (DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType () == TST_auto_type || DS.getTypeSpecType() == TST_unspecified ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "clang/lib/Sema/SemaType.cpp", 6198, __extension__ __PRETTY_FUNCTION__ )) | |||
6196 | DS.getTypeSpecType() == TST_decltype_auto ||(static_cast <bool> (DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType () == TST_auto_type || DS.getTypeSpecType() == TST_unspecified ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "clang/lib/Sema/SemaType.cpp", 6198, __extension__ __PRETTY_FUNCTION__ )) | |||
6197 | DS.getTypeSpecType() == TST_auto_type ||(static_cast <bool> (DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType () == TST_auto_type || DS.getTypeSpecType() == TST_unspecified ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "clang/lib/Sema/SemaType.cpp", 6198, __extension__ __PRETTY_FUNCTION__ )) | |||
6198 | DS.getTypeSpecType() == TST_unspecified)(static_cast <bool> (DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType () == TST_auto_type || DS.getTypeSpecType() == TST_unspecified ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "clang/lib/Sema/SemaType.cpp", 6198, __extension__ __PRETTY_FUNCTION__ )); | |||
6199 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
6200 | if (DS.getTypeSpecType() == TST_decltype_auto) | |||
6201 | TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); | |||
6202 | if (!DS.isConstrainedAuto()) | |||
6203 | return; | |||
6204 | TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); | |||
6205 | if (!TemplateId) | |||
6206 | return; | |||
6207 | if (DS.getTypeSpecScope().isNotEmpty()) | |||
6208 | TL.setNestedNameSpecifierLoc( | |||
6209 | DS.getTypeSpecScope().getWithLocInContext(Context)); | |||
6210 | else | |||
6211 | TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc()); | |||
6212 | TL.setTemplateKWLoc(TemplateId->TemplateKWLoc); | |||
6213 | TL.setConceptNameLoc(TemplateId->TemplateNameLoc); | |||
6214 | TL.setFoundDecl(nullptr); | |||
6215 | TL.setLAngleLoc(TemplateId->LAngleLoc); | |||
6216 | TL.setRAngleLoc(TemplateId->RAngleLoc); | |||
6217 | if (TemplateId->NumArgs == 0) | |||
6218 | return; | |||
6219 | TemplateArgumentListInfo TemplateArgsInfo; | |||
6220 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
6221 | TemplateId->NumArgs); | |||
6222 | SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | |||
6223 | for (unsigned I = 0; I < TemplateId->NumArgs; ++I) | |||
6224 | TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo()); | |||
6225 | } | |||
6226 | void VisitTagTypeLoc(TagTypeLoc TL) { | |||
6227 | TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); | |||
6228 | } | |||
6229 | void VisitAtomicTypeLoc(AtomicTypeLoc TL) { | |||
6230 | // An AtomicTypeLoc can come from either an _Atomic(...) type specifier | |||
6231 | // or an _Atomic qualifier. | |||
6232 | if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { | |||
6233 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
6234 | TL.setParensRange(DS.getTypeofParensRange()); | |||
6235 | ||||
6236 | TypeSourceInfo *TInfo = nullptr; | |||
6237 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6238 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "clang/lib/Sema/SemaType.cpp", 6238, __extension__ __PRETTY_FUNCTION__ )); | |||
6239 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | |||
6240 | } else { | |||
6241 | TL.setKWLoc(DS.getAtomicSpecLoc()); | |||
6242 | // No parens, to indicate this was spelled as an _Atomic qualifier. | |||
6243 | TL.setParensRange(SourceRange()); | |||
6244 | Visit(TL.getValueLoc()); | |||
6245 | } | |||
6246 | } | |||
6247 | ||||
6248 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | |||
6249 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
6250 | ||||
6251 | TypeSourceInfo *TInfo = nullptr; | |||
6252 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6253 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | |||
6254 | } | |||
6255 | ||||
6256 | void VisitExtIntTypeLoc(BitIntTypeLoc TL) { | |||
6257 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
6258 | } | |||
6259 | ||||
6260 | void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) { | |||
6261 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
6262 | } | |||
6263 | ||||
6264 | void VisitTypeLoc(TypeLoc TL) { | |||
6265 | // FIXME: add other typespec types and change this to an assert. | |||
6266 | TL.initialize(Context, DS.getTypeSpecTypeLoc()); | |||
6267 | } | |||
6268 | }; | |||
6269 | ||||
6270 | class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { | |||
6271 | ASTContext &Context; | |||
6272 | TypeProcessingState &State; | |||
6273 | const DeclaratorChunk &Chunk; | |||
6274 | ||||
6275 | public: | |||
6276 | DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, | |||
6277 | const DeclaratorChunk &Chunk) | |||
6278 | : Context(Context), State(State), Chunk(Chunk) {} | |||
6279 | ||||
6280 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | |||
6281 | llvm_unreachable("qualified type locs not expected here!")::llvm::llvm_unreachable_internal("qualified type locs not expected here!" , "clang/lib/Sema/SemaType.cpp", 6281); | |||
6282 | } | |||
6283 | void VisitDecayedTypeLoc(DecayedTypeLoc TL) { | |||
6284 | llvm_unreachable("decayed type locs not expected here!")::llvm::llvm_unreachable_internal("decayed type locs not expected here!" , "clang/lib/Sema/SemaType.cpp", 6284); | |||
6285 | } | |||
6286 | ||||
6287 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | |||
6288 | fillAttributedTypeLoc(TL, State); | |||
6289 | } | |||
6290 | void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { | |||
6291 | // nothing | |||
6292 | } | |||
6293 | void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { | |||
6294 | // nothing | |||
6295 | } | |||
6296 | void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { | |||
6297 | assert(Chunk.Kind == DeclaratorChunk::BlockPointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::BlockPointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::BlockPointer" , "clang/lib/Sema/SemaType.cpp", 6297, __extension__ __PRETTY_FUNCTION__ )); | |||
6298 | TL.setCaretLoc(Chunk.Loc); | |||
6299 | } | |||
6300 | void VisitPointerTypeLoc(PointerTypeLoc TL) { | |||
6301 | assert(Chunk.Kind == DeclaratorChunk::Pointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "clang/lib/Sema/SemaType.cpp", 6301, __extension__ __PRETTY_FUNCTION__ )); | |||
6302 | TL.setStarLoc(Chunk.Loc); | |||
6303 | } | |||
6304 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | |||
6305 | assert(Chunk.Kind == DeclaratorChunk::Pointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "clang/lib/Sema/SemaType.cpp", 6305, __extension__ __PRETTY_FUNCTION__ )); | |||
6306 | TL.setStarLoc(Chunk.Loc); | |||
6307 | } | |||
6308 | void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { | |||
6309 | assert(Chunk.Kind == DeclaratorChunk::MemberPointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::MemberPointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::MemberPointer" , "clang/lib/Sema/SemaType.cpp", 6309, __extension__ __PRETTY_FUNCTION__ )); | |||
6310 | const CXXScopeSpec& SS = Chunk.Mem.Scope(); | |||
6311 | NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); | |||
6312 | ||||
6313 | const Type* ClsTy = TL.getClass(); | |||
6314 | QualType ClsQT = QualType(ClsTy, 0); | |||
6315 | TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); | |||
6316 | // Now copy source location info into the type loc component. | |||
6317 | TypeLoc ClsTL = ClsTInfo->getTypeLoc(); | |||
6318 | switch (NNSLoc.getNestedNameSpecifier()->getKind()) { | |||
6319 | case NestedNameSpecifier::Identifier: | |||
6320 | assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc")(static_cast <bool> (isa<DependentNameType>(ClsTy ) && "Unexpected TypeLoc") ? void (0) : __assert_fail ("isa<DependentNameType>(ClsTy) && \"Unexpected TypeLoc\"" , "clang/lib/Sema/SemaType.cpp", 6320, __extension__ __PRETTY_FUNCTION__ )); | |||
6321 | { | |||
6322 | DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); | |||
6323 | DNTLoc.setElaboratedKeywordLoc(SourceLocation()); | |||
6324 | DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); | |||
6325 | DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); | |||
6326 | } | |||
6327 | break; | |||
6328 | ||||
6329 | case NestedNameSpecifier::TypeSpec: | |||
6330 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
6331 | if (isa<ElaboratedType>(ClsTy)) { | |||
6332 | ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); | |||
6333 | ETLoc.setElaboratedKeywordLoc(SourceLocation()); | |||
6334 | ETLoc.setQualifierLoc(NNSLoc.getPrefix()); | |||
6335 | TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); | |||
6336 | NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); | |||
6337 | } else { | |||
6338 | ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); | |||
6339 | } | |||
6340 | break; | |||
6341 | ||||
6342 | case NestedNameSpecifier::Namespace: | |||
6343 | case NestedNameSpecifier::NamespaceAlias: | |||
6344 | case NestedNameSpecifier::Global: | |||
6345 | case NestedNameSpecifier::Super: | |||
6346 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "clang/lib/Sema/SemaType.cpp", 6346); | |||
6347 | } | |||
6348 | ||||
6349 | // Finally fill in MemberPointerLocInfo fields. | |||
6350 | TL.setStarLoc(Chunk.Mem.StarLoc); | |||
6351 | TL.setClassTInfo(ClsTInfo); | |||
6352 | } | |||
6353 | void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { | |||
6354 | assert(Chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Reference ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "clang/lib/Sema/SemaType.cpp", 6354, __extension__ __PRETTY_FUNCTION__ )); | |||
6355 | // 'Amp' is misleading: this might have been originally | |||
6356 | /// spelled with AmpAmp. | |||
6357 | TL.setAmpLoc(Chunk.Loc); | |||
6358 | } | |||
6359 | void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { | |||
6360 | assert(Chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Reference ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "clang/lib/Sema/SemaType.cpp", 6360, __extension__ __PRETTY_FUNCTION__ )); | |||
6361 | assert(!Chunk.Ref.LValueRef)(static_cast <bool> (!Chunk.Ref.LValueRef) ? void (0) : __assert_fail ("!Chunk.Ref.LValueRef", "clang/lib/Sema/SemaType.cpp" , 6361, __extension__ __PRETTY_FUNCTION__)); | |||
6362 | TL.setAmpAmpLoc(Chunk.Loc); | |||
6363 | } | |||
6364 | void VisitArrayTypeLoc(ArrayTypeLoc TL) { | |||
6365 | assert(Chunk.Kind == DeclaratorChunk::Array)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Array ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Array" , "clang/lib/Sema/SemaType.cpp", 6365, __extension__ __PRETTY_FUNCTION__ )); | |||
6366 | TL.setLBracketLoc(Chunk.Loc); | |||
6367 | TL.setRBracketLoc(Chunk.EndLoc); | |||
6368 | TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); | |||
6369 | } | |||
6370 | void VisitFunctionTypeLoc(FunctionTypeLoc TL) { | |||
6371 | assert(Chunk.Kind == DeclaratorChunk::Function)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Function ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "clang/lib/Sema/SemaType.cpp", 6371, __extension__ __PRETTY_FUNCTION__ )); | |||
6372 | TL.setLocalRangeBegin(Chunk.Loc); | |||
6373 | TL.setLocalRangeEnd(Chunk.EndLoc); | |||
6374 | ||||
6375 | const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; | |||
6376 | TL.setLParenLoc(FTI.getLParenLoc()); | |||
6377 | TL.setRParenLoc(FTI.getRParenLoc()); | |||
6378 | for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { | |||
6379 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
6380 | TL.setParam(tpi++, Param); | |||
6381 | } | |||
6382 | TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); | |||
6383 | } | |||
6384 | void VisitParenTypeLoc(ParenTypeLoc TL) { | |||
6385 | assert(Chunk.Kind == DeclaratorChunk::Paren)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Paren ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Paren" , "clang/lib/Sema/SemaType.cpp", 6385, __extension__ __PRETTY_FUNCTION__ )); | |||
6386 | TL.setLParenLoc(Chunk.Loc); | |||
6387 | TL.setRParenLoc(Chunk.EndLoc); | |||
6388 | } | |||
6389 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | |||
6390 | assert(Chunk.Kind == DeclaratorChunk::Pipe)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pipe ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pipe" , "clang/lib/Sema/SemaType.cpp", 6390, __extension__ __PRETTY_FUNCTION__ )); | |||
6391 | TL.setKWLoc(Chunk.Loc); | |||
6392 | } | |||
6393 | void VisitBitIntTypeLoc(BitIntTypeLoc TL) { | |||
6394 | TL.setNameLoc(Chunk.Loc); | |||
6395 | } | |||
6396 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { | |||
6397 | TL.setExpansionLoc(Chunk.Loc); | |||
6398 | } | |||
6399 | void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); } | |||
6400 | void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) { | |||
6401 | TL.setNameLoc(Chunk.Loc); | |||
6402 | } | |||
6403 | void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { | |||
6404 | TL.setNameLoc(Chunk.Loc); | |||
6405 | } | |||
6406 | void | |||
6407 | VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) { | |||
6408 | TL.setNameLoc(Chunk.Loc); | |||
6409 | } | |||
6410 | ||||
6411 | void VisitTypeLoc(TypeLoc TL) { | |||
6412 | llvm_unreachable("unsupported TypeLoc kind in declarator!")::llvm::llvm_unreachable_internal("unsupported TypeLoc kind in declarator!" , "clang/lib/Sema/SemaType.cpp", 6412); | |||
6413 | } | |||
6414 | }; | |||
6415 | } // end anonymous namespace | |||
6416 | ||||
6417 | static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { | |||
6418 | SourceLocation Loc; | |||
6419 | switch (Chunk.Kind) { | |||
6420 | case DeclaratorChunk::Function: | |||
6421 | case DeclaratorChunk::Array: | |||
6422 | case DeclaratorChunk::Paren: | |||
6423 | case DeclaratorChunk::Pipe: | |||
6424 | llvm_unreachable("cannot be _Atomic qualified")::llvm::llvm_unreachable_internal("cannot be _Atomic qualified" , "clang/lib/Sema/SemaType.cpp", 6424); | |||
6425 | ||||
6426 | case DeclaratorChunk::Pointer: | |||
6427 | Loc = Chunk.Ptr.AtomicQualLoc; | |||
6428 | break; | |||
6429 | ||||
6430 | case DeclaratorChunk::BlockPointer: | |||
6431 | case DeclaratorChunk::Reference: | |||
6432 | case DeclaratorChunk::MemberPointer: | |||
6433 | // FIXME: Provide a source location for the _Atomic keyword. | |||
6434 | break; | |||
6435 | } | |||
6436 | ||||
6437 | ATL.setKWLoc(Loc); | |||
6438 | ATL.setParensRange(SourceRange()); | |||
6439 | } | |||
6440 | ||||
6441 | static void | |||
6442 | fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, | |||
6443 | const ParsedAttributesView &Attrs) { | |||
6444 | for (const ParsedAttr &AL : Attrs) { | |||
6445 | if (AL.getKind() == ParsedAttr::AT_AddressSpace) { | |||
6446 | DASTL.setAttrNameLoc(AL.getLoc()); | |||
6447 | DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); | |||
6448 | DASTL.setAttrOperandParensRange(SourceRange()); | |||
6449 | return; | |||
6450 | } | |||
6451 | } | |||
6452 | ||||
6453 | llvm_unreachable(::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "clang/lib/Sema/SemaType.cpp", 6454) | |||
6454 | "no address_space attribute found at the expected location!")::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "clang/lib/Sema/SemaType.cpp", 6454); | |||
6455 | } | |||
6456 | ||||
6457 | static void fillMatrixTypeLoc(MatrixTypeLoc MTL, | |||
6458 | const ParsedAttributesView &Attrs) { | |||
6459 | for (const ParsedAttr &AL : Attrs) { | |||
6460 | if (AL.getKind() == ParsedAttr::AT_MatrixType) { | |||
6461 | MTL.setAttrNameLoc(AL.getLoc()); | |||
6462 | MTL.setAttrRowOperand(AL.getArgAsExpr(0)); | |||
6463 | MTL.setAttrColumnOperand(AL.getArgAsExpr(1)); | |||
6464 | MTL.setAttrOperandParensRange(SourceRange()); | |||
6465 | return; | |||
6466 | } | |||
6467 | } | |||
6468 | ||||
6469 | llvm_unreachable("no matrix_type attribute found at the expected location!")::llvm::llvm_unreachable_internal("no matrix_type attribute found at the expected location!" , "clang/lib/Sema/SemaType.cpp", 6469); | |||
6470 | } | |||
6471 | ||||
6472 | /// Create and instantiate a TypeSourceInfo with type source information. | |||
6473 | /// | |||
6474 | /// \param T QualType referring to the type as written in source code. | |||
6475 | /// | |||
6476 | /// \param ReturnTypeInfo For declarators whose return type does not show | |||
6477 | /// up in the normal place in the declaration specifiers (such as a C++ | |||
6478 | /// conversion function), this pointer will refer to a type source information | |||
6479 | /// for that return type. | |||
6480 | static TypeSourceInfo * | |||
6481 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, | |||
6482 | QualType T, TypeSourceInfo *ReturnTypeInfo) { | |||
6483 | Sema &S = State.getSema(); | |||
6484 | Declarator &D = State.getDeclarator(); | |||
6485 | ||||
6486 | TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); | |||
6487 | UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); | |||
6488 | ||||
6489 | // Handle parameter packs whose type is a pack expansion. | |||
6490 | if (isa<PackExpansionType>(T)) { | |||
6491 | CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); | |||
6492 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6493 | } | |||
6494 | ||||
6495 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
6496 | // An AtomicTypeLoc might be produced by an atomic qualifier in this | |||
6497 | // declarator chunk. | |||
6498 | if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { | |||
6499 | fillAtomicQualLoc(ATL, D.getTypeObject(i)); | |||
6500 | CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); | |||
6501 | } | |||
6502 | ||||
6503 | while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) { | |||
6504 | TL.setExpansionLoc( | |||
6505 | State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); | |||
6506 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6507 | } | |||
6508 | ||||
6509 | while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { | |||
6510 | fillAttributedTypeLoc(TL, State); | |||
6511 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6512 | } | |||
6513 | ||||
6514 | while (DependentAddressSpaceTypeLoc TL = | |||
6515 | CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { | |||
6516 | fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); | |||
6517 | CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); | |||
6518 | } | |||
6519 | ||||
6520 | if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>()) | |||
6521 | fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs()); | |||
6522 | ||||
6523 | // FIXME: Ordering here? | |||
6524 | while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) | |||
6525 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6526 | ||||
6527 | DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); | |||
6528 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6529 | } | |||
6530 | ||||
6531 | // If we have different source information for the return type, use | |||
6532 | // that. This really only applies to C++ conversion functions. | |||
6533 | if (ReturnTypeInfo) { | |||
6534 | TypeLoc TL = ReturnTypeInfo->getTypeLoc(); | |||
6535 | assert(TL.getFullDataSize() == CurrTL.getFullDataSize())(static_cast <bool> (TL.getFullDataSize() == CurrTL.getFullDataSize ()) ? void (0) : __assert_fail ("TL.getFullDataSize() == CurrTL.getFullDataSize()" , "clang/lib/Sema/SemaType.cpp", 6535, __extension__ __PRETTY_FUNCTION__ )); | |||
6536 | memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); | |||
6537 | } else { | |||
6538 | TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL); | |||
6539 | } | |||
6540 | ||||
6541 | return TInfo; | |||
6542 | } | |||
6543 | ||||
6544 | /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. | |||
6545 | ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { | |||
6546 | // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser | |||
6547 | // and Sema during declaration parsing. Try deallocating/caching them when | |||
6548 | // it's appropriate, instead of allocating them and keeping them around. | |||
6549 | LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), | |||
6550 | TypeAlignment); | |||
6551 | new (LocT) LocInfoType(T, TInfo); | |||
6552 | assert(LocT->getTypeClass() != T->getTypeClass() &&(static_cast <bool> (LocT->getTypeClass() != T->getTypeClass () && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? void (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "clang/lib/Sema/SemaType.cpp", 6553, __extension__ __PRETTY_FUNCTION__ )) | |||
6553 | "LocInfoType's TypeClass conflicts with an existing Type class")(static_cast <bool> (LocT->getTypeClass() != T->getTypeClass () && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? void (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "clang/lib/Sema/SemaType.cpp", 6553, __extension__ __PRETTY_FUNCTION__ )); | |||
6554 | return ParsedType::make(QualType(LocT, 0)); | |||
6555 | } | |||
6556 | ||||
6557 | void LocInfoType::getAsStringInternal(std::string &Str, | |||
6558 | const PrintingPolicy &Policy) const { | |||
6559 | 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", "clang/lib/Sema/SemaType.cpp", 6561) | |||
6560 | " 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", "clang/lib/Sema/SemaType.cpp", 6561) | |||
6561 | " GetTypeFromParser")::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser", "clang/lib/Sema/SemaType.cpp", 6561); | |||
6562 | } | |||
6563 | ||||
6564 | TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { | |||
6565 | // C99 6.7.6: Type names have no identifier. This is already validated by | |||
6566 | // the parser. | |||
6567 | assert(D.getIdentifier() == nullptr &&(static_cast <bool> (D.getIdentifier() == nullptr && "Type name should have no identifier!") ? void (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "clang/lib/Sema/SemaType.cpp", 6568, __extension__ __PRETTY_FUNCTION__ )) | |||
6568 | "Type name should have no identifier!")(static_cast <bool> (D.getIdentifier() == nullptr && "Type name should have no identifier!") ? void (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "clang/lib/Sema/SemaType.cpp", 6568, __extension__ __PRETTY_FUNCTION__ )); | |||
6569 | ||||
6570 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
6571 | QualType T = TInfo->getType(); | |||
6572 | if (D.isInvalidType()) | |||
6573 | return true; | |||
6574 | ||||
6575 | // Make sure there are no unused decl attributes on the declarator. | |||
6576 | // We don't want to do this for ObjC parameters because we're going | |||
6577 | // to apply them to the actual parameter declaration. | |||
6578 | // Likewise, we don't want to do this for alias declarations, because | |||
6579 | // we are actually going to build a declaration from this eventually. | |||
6580 | if (D.getContext() != DeclaratorContext::ObjCParameter && | |||
6581 | D.getContext() != DeclaratorContext::AliasDecl && | |||
6582 | D.getContext() != DeclaratorContext::AliasTemplate) | |||
6583 | checkUnusedDeclAttributes(D); | |||
6584 | ||||
6585 | if (getLangOpts().CPlusPlus) { | |||
6586 | // Check that there are no default arguments (C++ only). | |||
6587 | CheckExtraCXXDefaultArguments(D); | |||
6588 | } | |||
6589 | ||||
6590 | return CreateParsedType(T, TInfo); | |||
6591 | } | |||
6592 | ||||
6593 | ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { | |||
6594 | QualType T = Context.getObjCInstanceType(); | |||
6595 | TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
6596 | return CreateParsedType(T, TInfo); | |||
6597 | } | |||
6598 | ||||
6599 | //===----------------------------------------------------------------------===// | |||
6600 | // Type Attribute Processing | |||
6601 | //===----------------------------------------------------------------------===// | |||
6602 | ||||
6603 | /// Build an AddressSpace index from a constant expression and diagnose any | |||
6604 | /// errors related to invalid address_spaces. Returns true on successfully | |||
6605 | /// building an AddressSpace index. | |||
6606 | static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, | |||
6607 | const Expr *AddrSpace, | |||
6608 | SourceLocation AttrLoc) { | |||
6609 | if (!AddrSpace->isValueDependent()) { | |||
6610 | Optional<llvm::APSInt> OptAddrSpace = | |||
6611 | AddrSpace->getIntegerConstantExpr(S.Context); | |||
6612 | if (!OptAddrSpace) { | |||
6613 | S.Diag(AttrLoc, diag::err_attribute_argument_type) | |||
6614 | << "'address_space'" << AANT_ArgumentIntegerConstant | |||
6615 | << AddrSpace->getSourceRange(); | |||
6616 | return false; | |||
6617 | } | |||
6618 | llvm::APSInt &addrSpace = *OptAddrSpace; | |||
6619 | ||||
6620 | // Bounds checking. | |||
6621 | if (addrSpace.isSigned()) { | |||
6622 | if (addrSpace.isNegative()) { | |||
6623 | S.Diag(AttrLoc, diag::err_attribute_address_space_negative) | |||
6624 | << AddrSpace->getSourceRange(); | |||
6625 | return false; | |||
6626 | } | |||
6627 | addrSpace.setIsSigned(false); | |||
6628 | } | |||
6629 | ||||
6630 | llvm::APSInt max(addrSpace.getBitWidth()); | |||
6631 | max = | |||
6632 | Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; | |||
6633 | ||||
6634 | if (addrSpace > max) { | |||
6635 | S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) | |||
6636 | << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); | |||
6637 | return false; | |||
6638 | } | |||
6639 | ||||
6640 | ASIdx = | |||
6641 | getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); | |||
6642 | return true; | |||
6643 | } | |||
6644 | ||||
6645 | // Default value for DependentAddressSpaceTypes | |||
6646 | ASIdx = LangAS::Default; | |||
6647 | return true; | |||
6648 | } | |||
6649 | ||||
6650 | /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression | |||
6651 | /// is uninstantiated. If instantiated it will apply the appropriate address | |||
6652 | /// space to the type. This function allows dependent template variables to be | |||
6653 | /// used in conjunction with the address_space attribute | |||
6654 | QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, | |||
6655 | SourceLocation AttrLoc) { | |||
6656 | if (!AddrSpace->isValueDependent()) { | |||
6657 | if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, | |||
6658 | AttrLoc)) | |||
6659 | return QualType(); | |||
6660 | ||||
6661 | return Context.getAddrSpaceQualType(T, ASIdx); | |||
6662 | } | |||
6663 | ||||
6664 | // A check with similar intentions as checking if a type already has an | |||
6665 | // address space except for on a dependent types, basically if the | |||
6666 | // current type is already a DependentAddressSpaceType then its already | |||
6667 | // lined up to have another address space on it and we can't have | |||
6668 | // multiple address spaces on the one pointer indirection | |||
6669 | if (T->getAs<DependentAddressSpaceType>()) { | |||
6670 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | |||
6671 | return QualType(); | |||
6672 | } | |||
6673 | ||||
6674 | return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); | |||
6675 | } | |||
6676 | ||||
6677 | QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, | |||
6678 | SourceLocation AttrLoc) { | |||
6679 | LangAS ASIdx; | |||
6680 | if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) | |||
6681 | return QualType(); | |||
6682 | return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); | |||
6683 | } | |||
6684 | ||||
6685 | static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, | |||
6686 | TypeProcessingState &State) { | |||
6687 | Sema &S = State.getSema(); | |||
6688 | ||||
6689 | // Check the number of attribute arguments. | |||
6690 | if (Attr.getNumArgs() != 1) { | |||
6691 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
6692 | << Attr << 1; | |||
6693 | Attr.setInvalid(); | |||
6694 | return; | |||
6695 | } | |||
6696 | ||||
6697 | // Ensure the argument is a string. | |||
6698 | auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0)); | |||
6699 | if (!StrLiteral) { | |||
6700 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) | |||
6701 | << Attr << AANT_ArgumentString; | |||
6702 | Attr.setInvalid(); | |||
6703 | return; | |||
6704 | } | |||
6705 | ||||
6706 | ASTContext &Ctx = S.Context; | |||
6707 | StringRef BTFTypeTag = StrLiteral->getString(); | |||
6708 | Type = State.getBTFTagAttributedType( | |||
6709 | ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type); | |||
6710 | } | |||
6711 | ||||
6712 | /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the | |||
6713 | /// specified type. The attribute contains 1 argument, the id of the address | |||
6714 | /// space for the type. | |||
6715 | static void HandleAddressSpaceTypeAttribute(QualType &Type, | |||
6716 | const ParsedAttr &Attr, | |||
6717 | TypeProcessingState &State) { | |||
6718 | Sema &S = State.getSema(); | |||
6719 | ||||
6720 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be | |||
6721 | // qualified by an address-space qualifier." | |||
6722 | if (Type->isFunctionType()) { | |||
6723 | S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); | |||
6724 | Attr.setInvalid(); | |||
6725 | return; | |||
6726 | } | |||
6727 | ||||
6728 | LangAS ASIdx; | |||
6729 | if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { | |||
6730 | ||||
6731 | // Check the attribute arguments. | |||
6732 | if (Attr.getNumArgs() != 1) { | |||
6733 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
6734 | << 1; | |||
6735 | Attr.setInvalid(); | |||
6736 | return; | |||
6737 | } | |||
6738 | ||||
6739 | Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); | |||
6740 | LangAS ASIdx; | |||
6741 | if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { | |||
6742 | Attr.setInvalid(); | |||
6743 | return; | |||
6744 | } | |||
6745 | ||||
6746 | ASTContext &Ctx = S.Context; | |||
6747 | auto *ASAttr = | |||
6748 | ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); | |||
6749 | ||||
6750 | // If the expression is not value dependent (not templated), then we can | |||
6751 | // apply the address space qualifiers just to the equivalent type. | |||
6752 | // Otherwise, we make an AttributedType with the modified and equivalent | |||
6753 | // type the same, and wrap it in a DependentAddressSpaceType. When this | |||
6754 | // dependent type is resolved, the qualifier is added to the equivalent type | |||
6755 | // later. | |||
6756 | QualType T; | |||
6757 | if (!ASArgExpr->isValueDependent()) { | |||
6758 | QualType EquivType = | |||
6759 | S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); | |||
6760 | if (EquivType.isNull()) { | |||
6761 | Attr.setInvalid(); | |||
6762 | return; | |||
6763 | } | |||
6764 | T = State.getAttributedType(ASAttr, Type, EquivType); | |||
6765 | } else { | |||
6766 | T = State.getAttributedType(ASAttr, Type, Type); | |||
6767 | T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); | |||
6768 | } | |||
6769 | ||||
6770 | if (!T.isNull()) | |||
6771 | Type = T; | |||
6772 | else | |||
6773 | Attr.setInvalid(); | |||
6774 | } else { | |||
6775 | // The keyword-based type attributes imply which address space to use. | |||
6776 | ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS() | |||
6777 | : Attr.asOpenCLLangAS(); | |||
6778 | ||||
6779 | if (ASIdx == LangAS::Default) | |||
6780 | llvm_unreachable("Invalid address space")::llvm::llvm_unreachable_internal("Invalid address space", "clang/lib/Sema/SemaType.cpp" , 6780); | |||
6781 | ||||
6782 | if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, | |||
6783 | Attr.getLoc())) { | |||
6784 | Attr.setInvalid(); | |||
6785 | return; | |||
6786 | } | |||
6787 | ||||
6788 | Type = S.Context.getAddrSpaceQualType(Type, ASIdx); | |||
6789 | } | |||
6790 | } | |||
6791 | ||||
6792 | /// handleObjCOwnershipTypeAttr - Process an objc_ownership | |||
6793 | /// attribute on the specified type. | |||
6794 | /// | |||
6795 | /// Returns 'true' if the attribute was handled. | |||
6796 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | |||
6797 | ParsedAttr &attr, QualType &type) { | |||
6798 | bool NonObjCPointer = false; | |||
6799 | ||||
6800 | if (!type->isDependentType() && !type->isUndeducedType()) { | |||
6801 | if (const PointerType *ptr = type->getAs<PointerType>()) { | |||
6802 | QualType pointee = ptr->getPointeeType(); | |||
6803 | if (pointee->isObjCRetainableType() || pointee->isPointerType()) | |||
6804 | return false; | |||
6805 | // It is important not to lose the source info that there was an attribute | |||
6806 | // applied to non-objc pointer. We will create an attributed type but | |||
6807 | // its type will be the same as the original type. | |||
6808 | NonObjCPointer = true; | |||
6809 | } else if (!type->isObjCRetainableType()) { | |||
6810 | return false; | |||
6811 | } | |||
6812 | ||||
6813 | // Don't accept an ownership attribute in the declspec if it would | |||
6814 | // just be the return type of a block pointer. | |||
6815 | if (state.isProcessingDeclSpec()) { | |||
6816 | Declarator &D = state.getDeclarator(); | |||
6817 | if (maybeMovePastReturnType(D, D.getNumTypeObjects(), | |||
6818 | /*onlyBlockPointers=*/true)) | |||
6819 | return false; | |||
6820 | } | |||
6821 | } | |||
6822 | ||||
6823 | Sema &S = state.getSema(); | |||
6824 | SourceLocation AttrLoc = attr.getLoc(); | |||
6825 | if (AttrLoc.isMacroID()) | |||
6826 | AttrLoc = | |||
6827 | S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); | |||
6828 | ||||
6829 | if (!attr.isArgIdent(0)) { | |||
6830 | S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr | |||
6831 | << AANT_ArgumentString; | |||
6832 | attr.setInvalid(); | |||
6833 | return true; | |||
6834 | } | |||
6835 | ||||
6836 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | |||
6837 | Qualifiers::ObjCLifetime lifetime; | |||
6838 | if (II->isStr("none")) | |||
6839 | lifetime = Qualifiers::OCL_ExplicitNone; | |||
6840 | else if (II->isStr("strong")) | |||
6841 | lifetime = Qualifiers::OCL_Strong; | |||
6842 | else if (II->isStr("weak")) | |||
6843 | lifetime = Qualifiers::OCL_Weak; | |||
6844 | else if (II->isStr("autoreleasing")) | |||
6845 | lifetime = Qualifiers::OCL_Autoreleasing; | |||
6846 | else { | |||
6847 | S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; | |||
6848 | attr.setInvalid(); | |||
6849 | return true; | |||
6850 | } | |||
6851 | ||||
6852 | // Just ignore lifetime attributes other than __weak and __unsafe_unretained | |||
6853 | // outside of ARC mode. | |||
6854 | if (!S.getLangOpts().ObjCAutoRefCount && | |||
6855 | lifetime != Qualifiers::OCL_Weak && | |||
6856 | lifetime != Qualifiers::OCL_ExplicitNone) { | |||
6857 | return true; | |||
6858 | } | |||
6859 | ||||
6860 | SplitQualType underlyingType = type.split(); | |||
6861 | ||||
6862 | // Check for redundant/conflicting ownership qualifiers. | |||
6863 | if (Qualifiers::ObjCLifetime previousLifetime | |||
6864 | = type.getQualifiers().getObjCLifetime()) { | |||
6865 | // If it's written directly, that's an error. | |||
6866 | if (S.Context.hasDirectOwnershipQualifier(type)) { | |||
6867 | S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) | |||
6868 | << type; | |||
6869 | return true; | |||
6870 | } | |||
6871 | ||||
6872 | // Otherwise, if the qualifiers actually conflict, pull sugar off | |||
6873 | // and remove the ObjCLifetime qualifiers. | |||
6874 | if (previousLifetime != lifetime) { | |||
6875 | // It's possible to have multiple local ObjCLifetime qualifiers. We | |||
6876 | // can't stop after we reach a type that is directly qualified. | |||
6877 | const Type *prevTy = nullptr; | |||
6878 | while (!prevTy || prevTy != underlyingType.Ty) { | |||
6879 | prevTy = underlyingType.Ty; | |||
6880 | underlyingType = underlyingType.getSingleStepDesugaredType(); | |||
6881 | } | |||
6882 | underlyingType.Quals.removeObjCLifetime(); | |||
6883 | } | |||
6884 | } | |||
6885 | ||||
6886 | underlyingType.Quals.addObjCLifetime(lifetime); | |||
6887 | ||||
6888 | if (NonObjCPointer) { | |||
6889 | StringRef name = attr.getAttrName()->getName(); | |||
6890 | switch (lifetime) { | |||
6891 | case Qualifiers::OCL_None: | |||
6892 | case Qualifiers::OCL_ExplicitNone: | |||
6893 | break; | |||
6894 | case Qualifiers::OCL_Strong: name = "__strong"; break; | |||
6895 | case Qualifiers::OCL_Weak: name = "__weak"; break; | |||
6896 | case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; | |||
6897 | } | |||
6898 | S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name | |||
6899 | << TDS_ObjCObjOrBlock << type; | |||
6900 | } | |||
6901 | ||||
6902 | // Don't actually add the __unsafe_unretained qualifier in non-ARC files, | |||
6903 | // because having both 'T' and '__unsafe_unretained T' exist in the type | |||
6904 | // system causes unfortunate widespread consistency problems. (For example, | |||
6905 | // they're not considered compatible types, and we mangle them identicially | |||
6906 | // as template arguments.) These problems are all individually fixable, | |||
6907 | // but it's easier to just not add the qualifier and instead sniff it out | |||
6908 | // in specific places using isObjCInertUnsafeUnretainedType(). | |||
6909 | // | |||
6910 | // Doing this does means we miss some trivial consistency checks that | |||
6911 | // would've triggered in ARC, but that's better than trying to solve all | |||
6912 | // the coexistence problems with __unsafe_unretained. | |||
6913 | if (!S.getLangOpts().ObjCAutoRefCount && | |||
6914 | lifetime == Qualifiers::OCL_ExplicitNone) { | |||
6915 | type = state.getAttributedType( | |||
6916 | createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), | |||
6917 | type, type); | |||
6918 | return true; | |||
6919 | } | |||
6920 | ||||
6921 | QualType origType = type; | |||
6922 | if (!NonObjCPointer) | |||
6923 | type = S.Context.getQualifiedType(underlyingType); | |||
6924 | ||||
6925 | // If we have a valid source location for the attribute, use an | |||
6926 | // AttributedType instead. | |||
6927 | if (AttrLoc.isValid()) { | |||
6928 | type = state.getAttributedType(::new (S.Context) | |||
6929 | ObjCOwnershipAttr(S.Context, attr, II), | |||
6930 | origType, type); | |||
6931 | } | |||
6932 | ||||
6933 | auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, | |||
6934 | unsigned diagnostic, QualType type) { | |||
6935 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | |||
6936 | S.DelayedDiagnostics.add( | |||
6937 | sema::DelayedDiagnostic::makeForbiddenType( | |||
6938 | S.getSourceManager().getExpansionLoc(loc), | |||
6939 | diagnostic, type, /*ignored*/ 0)); | |||
6940 | } else { | |||
6941 | S.Diag(loc, diagnostic); | |||
6942 | } | |||
6943 | }; | |||
6944 | ||||
6945 | // Sometimes, __weak isn't allowed. | |||
6946 | if (lifetime == Qualifiers::OCL_Weak && | |||
6947 | !S.getLangOpts().ObjCWeak && !NonObjCPointer) { | |||
6948 | ||||
6949 | // Use a specialized diagnostic if the runtime just doesn't support them. | |||
6950 | unsigned diagnostic = | |||
6951 | (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled | |||
6952 | : diag::err_arc_weak_no_runtime); | |||
6953 | ||||
6954 | // In any case, delay the diagnostic until we know what we're parsing. | |||
6955 | diagnoseOrDelay(S, AttrLoc, diagnostic, type); | |||
6956 | ||||
6957 | attr.setInvalid(); | |||
6958 | return true; | |||
6959 | } | |||
6960 | ||||
6961 | // Forbid __weak for class objects marked as | |||
6962 | // objc_arc_weak_reference_unavailable | |||
6963 | if (lifetime == Qualifiers::OCL_Weak) { | |||
6964 | if (const ObjCObjectPointerType *ObjT = | |||
6965 | type->getAs<ObjCObjectPointerType>()) { | |||
6966 | if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { | |||
6967 | if (Class->isArcWeakrefUnavailable()) { | |||
6968 | S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); | |||
6969 | S.Diag(ObjT->getInterfaceDecl()->getLocation(), | |||
6970 | diag::note_class_declared); | |||
6971 | } | |||
6972 | } | |||
6973 | } | |||
6974 | } | |||
6975 | ||||
6976 | return true; | |||
6977 | } | |||
6978 | ||||
6979 | /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type | |||
6980 | /// attribute on the specified type. Returns true to indicate that | |||
6981 | /// the attribute was handled, false to indicate that the type does | |||
6982 | /// not permit the attribute. | |||
6983 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
6984 | QualType &type) { | |||
6985 | Sema &S = state.getSema(); | |||
6986 | ||||
6987 | // Delay if this isn't some kind of pointer. | |||
6988 | if (!type->isPointerType() && | |||
6989 | !type->isObjCObjectPointerType() && | |||
6990 | !type->isBlockPointerType()) | |||
6991 | return false; | |||
6992 | ||||
6993 | if (type.getObjCGCAttr() != Qualifiers::GCNone) { | |||
6994 | S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); | |||
6995 | attr.setInvalid(); | |||
6996 | return true; | |||
6997 | } | |||
6998 | ||||
6999 | // Check the attribute arguments. | |||
7000 | if (!attr.isArgIdent(0)) { | |||
7001 | S.Diag(attr.getLoc(), diag::err_attribute_argument_type) | |||
7002 | << attr << AANT_ArgumentString; | |||
7003 | attr.setInvalid(); | |||
7004 | return true; | |||
7005 | } | |||
7006 | Qualifiers::GC GCAttr; | |||
7007 | if (attr.getNumArgs() > 1) { | |||
7008 | S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr | |||
7009 | << 1; | |||
7010 | attr.setInvalid(); | |||
7011 | return true; | |||
7012 | } | |||
7013 | ||||
7014 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | |||
7015 | if (II->isStr("weak")) | |||
7016 | GCAttr = Qualifiers::Weak; | |||
7017 | else if (II->isStr("strong")) | |||
7018 | GCAttr = Qualifiers::Strong; | |||
7019 | else { | |||
7020 | S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) | |||
7021 | << attr << II; | |||
7022 | attr.setInvalid(); | |||
7023 | return true; | |||
7024 | } | |||
7025 | ||||
7026 | QualType origType = type; | |||
7027 | type = S.Context.getObjCGCQualType(origType, GCAttr); | |||
7028 | ||||
7029 | // Make an attributed type to preserve the source information. | |||
7030 | if (attr.getLoc().isValid()) | |||
7031 | type = state.getAttributedType( | |||
7032 | ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); | |||
7033 | ||||
7034 | return true; | |||
7035 | } | |||
7036 | ||||
7037 | namespace { | |||
7038 | /// A helper class to unwrap a type down to a function for the | |||
7039 | /// purposes of applying attributes there. | |||
7040 | /// | |||
7041 | /// Use: | |||
7042 | /// FunctionTypeUnwrapper unwrapped(SemaRef, T); | |||
7043 | /// if (unwrapped.isFunctionType()) { | |||
7044 | /// const FunctionType *fn = unwrapped.get(); | |||
7045 | /// // change fn somehow | |||
7046 | /// T = unwrapped.wrap(fn); | |||
7047 | /// } | |||
7048 | struct FunctionTypeUnwrapper { | |||
7049 | enum WrapKind { | |||
7050 | Desugar, | |||
7051 | Attributed, | |||
7052 | Parens, | |||
7053 | Array, | |||
7054 | Pointer, | |||
7055 | BlockPointer, | |||
7056 | Reference, | |||
7057 | MemberPointer, | |||
7058 | MacroQualified, | |||
7059 | }; | |||
7060 | ||||
7061 | QualType Original; | |||
7062 | const FunctionType *Fn; | |||
7063 | SmallVector<unsigned char /*WrapKind*/, 8> Stack; | |||
7064 | ||||
7065 | FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { | |||
7066 | while (true) { | |||
7067 | const Type *Ty = T.getTypePtr(); | |||
7068 | if (isa<FunctionType>(Ty)) { | |||
7069 | Fn = cast<FunctionType>(Ty); | |||
7070 | return; | |||
7071 | } else if (isa<ParenType>(Ty)) { | |||
7072 | T = cast<ParenType>(Ty)->getInnerType(); | |||
7073 | Stack.push_back(Parens); | |||
7074 | } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) || | |||
7075 | isa<IncompleteArrayType>(Ty)) { | |||
7076 | T = cast<ArrayType>(Ty)->getElementType(); | |||
7077 | Stack.push_back(Array); | |||
7078 | } else if (isa<PointerType>(Ty)) { | |||
7079 | T = cast<PointerType>(Ty)->getPointeeType(); | |||
7080 | Stack.push_back(Pointer); | |||
7081 | } else if (isa<BlockPointerType>(Ty)) { | |||
7082 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | |||
7083 | Stack.push_back(BlockPointer); | |||
7084 | } else if (isa<MemberPointerType>(Ty)) { | |||
7085 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | |||
7086 | Stack.push_back(MemberPointer); | |||
7087 | } else if (isa<ReferenceType>(Ty)) { | |||
7088 | T = cast<ReferenceType>(Ty)->getPointeeType(); | |||
7089 | Stack.push_back(Reference); | |||
7090 | } else if (isa<AttributedType>(Ty)) { | |||
7091 | T = cast<AttributedType>(Ty)->getEquivalentType(); | |||
7092 | Stack.push_back(Attributed); | |||
7093 | } else if (isa<MacroQualifiedType>(Ty)) { | |||
7094 | T = cast<MacroQualifiedType>(Ty)->getUnderlyingType(); | |||
7095 | Stack.push_back(MacroQualified); | |||
7096 | } else { | |||
7097 | const Type *DTy = Ty->getUnqualifiedDesugaredType(); | |||
7098 | if (Ty == DTy) { | |||
7099 | Fn = nullptr; | |||
7100 | return; | |||
7101 | } | |||
7102 | ||||
7103 | T = QualType(DTy, 0); | |||
7104 | Stack.push_back(Desugar); | |||
7105 | } | |||
7106 | } | |||
7107 | } | |||
7108 | ||||
7109 | bool isFunctionType() const { return (Fn != nullptr); } | |||
7110 | const FunctionType *get() const { return Fn; } | |||
7111 | ||||
7112 | QualType wrap(Sema &S, const FunctionType *New) { | |||
7113 | // If T wasn't modified from the unwrapped type, do nothing. | |||
7114 | if (New == get()) return Original; | |||
7115 | ||||
7116 | Fn = New; | |||
7117 | return wrap(S.Context, Original, 0); | |||
7118 | } | |||
7119 | ||||
7120 | private: | |||
7121 | QualType wrap(ASTContext &C, QualType Old, unsigned I) { | |||
7122 | if (I == Stack.size()) | |||
7123 | return C.getQualifiedType(Fn, Old.getQualifiers()); | |||
7124 | ||||
7125 | // Build up the inner type, applying the qualifiers from the old | |||
7126 | // type to the new type. | |||
7127 | SplitQualType SplitOld = Old.split(); | |||
7128 | ||||
7129 | // As a special case, tail-recurse if there are no qualifiers. | |||
7130 | if (SplitOld.Quals.empty()) | |||
7131 | return wrap(C, SplitOld.Ty, I); | |||
7132 | return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); | |||
7133 | } | |||
7134 | ||||
7135 | QualType wrap(ASTContext &C, const Type *Old, unsigned I) { | |||
7136 | if (I == Stack.size()) return QualType(Fn, 0); | |||
7137 | ||||
7138 | switch (static_cast<WrapKind>(Stack[I++])) { | |||
7139 | case Desugar: | |||
7140 | // This is the point at which we potentially lose source | |||
7141 | // information. | |||
7142 | return wrap(C, Old->getUnqualifiedDesugaredType(), I); | |||
7143 | ||||
7144 | case Attributed: | |||
7145 | return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); | |||
7146 | ||||
7147 | case Parens: { | |||
7148 | QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); | |||
7149 | return C.getParenType(New); | |||
7150 | } | |||
7151 | ||||
7152 | case MacroQualified: | |||
7153 | return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I); | |||
7154 | ||||
7155 | case Array: { | |||
7156 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) { | |||
7157 | QualType New = wrap(C, CAT->getElementType(), I); | |||
7158 | return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(), | |||
7159 | CAT->getSizeModifier(), | |||
7160 | CAT->getIndexTypeCVRQualifiers()); | |||
7161 | } | |||
7162 | ||||
7163 | if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) { | |||
7164 | QualType New = wrap(C, VAT->getElementType(), I); | |||
7165 | return C.getVariableArrayType( | |||
7166 | New, VAT->getSizeExpr(), VAT->getSizeModifier(), | |||
7167 | VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); | |||
7168 | } | |||
7169 | ||||
7170 | const auto *IAT = cast<IncompleteArrayType>(Old); | |||
7171 | QualType New = wrap(C, IAT->getElementType(), I); | |||
7172 | return C.getIncompleteArrayType(New, IAT->getSizeModifier(), | |||
7173 | IAT->getIndexTypeCVRQualifiers()); | |||
7174 | } | |||
7175 | ||||
7176 | case Pointer: { | |||
7177 | QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); | |||
7178 | return C.getPointerType(New); | |||
7179 | } | |||
7180 | ||||
7181 | case BlockPointer: { | |||
7182 | QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); | |||
7183 | return C.getBlockPointerType(New); | |||
7184 | } | |||
7185 | ||||
7186 | case MemberPointer: { | |||
7187 | const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); | |||
7188 | QualType New = wrap(C, OldMPT->getPointeeType(), I); | |||
7189 | return C.getMemberPointerType(New, OldMPT->getClass()); | |||
7190 | } | |||
7191 | ||||
7192 | case Reference: { | |||
7193 | const ReferenceType *OldRef = cast<ReferenceType>(Old); | |||
7194 | QualType New = wrap(C, OldRef->getPointeeType(), I); | |||
7195 | if (isa<LValueReferenceType>(OldRef)) | |||
7196 | return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); | |||
7197 | else | |||
7198 | return C.getRValueReferenceType(New); | |||
7199 | } | |||
7200 | } | |||
7201 | ||||
7202 | llvm_unreachable("unknown wrapping kind")::llvm::llvm_unreachable_internal("unknown wrapping kind", "clang/lib/Sema/SemaType.cpp" , 7202); | |||
7203 | } | |||
7204 | }; | |||
7205 | } // end anonymous namespace | |||
7206 | ||||
7207 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, | |||
7208 | ParsedAttr &PAttr, QualType &Type) { | |||
7209 | Sema &S = State.getSema(); | |||
7210 | ||||
7211 | Attr *A; | |||
7212 | switch (PAttr.getKind()) { | |||
7213 | default: llvm_unreachable("Unknown attribute kind")::llvm::llvm_unreachable_internal("Unknown attribute kind", "clang/lib/Sema/SemaType.cpp" , 7213); | |||
7214 | case ParsedAttr::AT_Ptr32: | |||
7215 | A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); | |||
7216 | break; | |||
7217 | case ParsedAttr::AT_Ptr64: | |||
7218 | A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); | |||
7219 | break; | |||
7220 | case ParsedAttr::AT_SPtr: | |||
7221 | A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); | |||
7222 | break; | |||
7223 | case ParsedAttr::AT_UPtr: | |||
7224 | A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); | |||
7225 | break; | |||
7226 | } | |||
7227 | ||||
7228 | std::bitset<attr::LastAttr> Attrs; | |||
7229 | QualType Desugared = Type; | |||
7230 | for (;;) { | |||
7231 | if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) { | |||
7232 | Desugared = TT->desugar(); | |||
7233 | continue; | |||
7234 | } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) { | |||
7235 | Desugared = ET->desugar(); | |||
7236 | continue; | |||
7237 | } | |||
7238 | const AttributedType *AT = dyn_cast<AttributedType>(Desugared); | |||
7239 | if (!AT) | |||
7240 | break; | |||
7241 | Attrs[AT->getAttrKind()] = true; | |||
7242 | Desugared = AT->getModifiedType(); | |||
7243 | } | |||
7244 | ||||
7245 | // You cannot specify duplicate type attributes, so if the attribute has | |||
7246 | // already been applied, flag it. | |||
7247 | attr::Kind NewAttrKind = A->getKind(); | |||
7248 | if (Attrs[NewAttrKind]) { | |||
7249 | S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; | |||
7250 | return true; | |||
7251 | } | |||
7252 | Attrs[NewAttrKind] = true; | |||
7253 | ||||
7254 | // You cannot have both __sptr and __uptr on the same type, nor can you | |||
7255 | // have __ptr32 and __ptr64. | |||
7256 | if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) { | |||
7257 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7258 | << "'__ptr32'" | |||
7259 | << "'__ptr64'"; | |||
7260 | return true; | |||
7261 | } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) { | |||
7262 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7263 | << "'__sptr'" | |||
7264 | << "'__uptr'"; | |||
7265 | return true; | |||
7266 | } | |||
7267 | ||||
7268 | // Check the raw (i.e., desugared) Canonical type to see if it | |||
7269 | // is a pointer type. | |||
7270 | if (!isa<PointerType>(Desugared)) { | |||
7271 | // Pointer type qualifiers can only operate on pointer types, but not | |||
7272 | // pointer-to-member types. | |||
7273 | if (Type->isMemberPointerType()) | |||
7274 | S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; | |||
7275 | else | |||
7276 | S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; | |||
7277 | return true; | |||
7278 | } | |||
7279 | ||||
7280 | // Add address space to type based on its attributes. | |||
7281 | LangAS ASIdx = LangAS::Default; | |||
7282 | uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0); | |||
7283 | if (PtrWidth == 32) { | |||
7284 | if (Attrs[attr::Ptr64]) | |||
7285 | ASIdx = LangAS::ptr64; | |||
7286 | else if (Attrs[attr::UPtr]) | |||
7287 | ASIdx = LangAS::ptr32_uptr; | |||
7288 | } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) { | |||
7289 | if (Attrs[attr::UPtr]) | |||
7290 | ASIdx = LangAS::ptr32_uptr; | |||
7291 | else | |||
7292 | ASIdx = LangAS::ptr32_sptr; | |||
7293 | } | |||
7294 | ||||
7295 | QualType Pointee = Type->getPointeeType(); | |||
7296 | if (ASIdx != LangAS::Default) | |||
7297 | Pointee = S.Context.getAddrSpaceQualType( | |||
7298 | S.Context.removeAddrSpaceQualType(Pointee), ASIdx); | |||
7299 | Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee)); | |||
7300 | return false; | |||
7301 | } | |||
7302 | ||||
7303 | /// Map a nullability attribute kind to a nullability kind. | |||
7304 | static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { | |||
7305 | switch (kind) { | |||
7306 | case ParsedAttr::AT_TypeNonNull: | |||
7307 | return NullabilityKind::NonNull; | |||
7308 | ||||
7309 | case ParsedAttr::AT_TypeNullable: | |||
7310 | return NullabilityKind::Nullable; | |||
7311 | ||||
7312 | case ParsedAttr::AT_TypeNullableResult: | |||
7313 | return NullabilityKind::NullableResult; | |||
7314 | ||||
7315 | case ParsedAttr::AT_TypeNullUnspecified: | |||
7316 | return NullabilityKind::Unspecified; | |||
7317 | ||||
7318 | default: | |||
7319 | llvm_unreachable("not a nullability attribute kind")::llvm::llvm_unreachable_internal("not a nullability attribute kind" , "clang/lib/Sema/SemaType.cpp", 7319); | |||
7320 | } | |||
7321 | } | |||
7322 | ||||
7323 | /// Applies a nullability type specifier to the given type, if possible. | |||
7324 | /// | |||
7325 | /// \param state The type processing state. | |||
7326 | /// | |||
7327 | /// \param type The type to which the nullability specifier will be | |||
7328 | /// added. On success, this type will be updated appropriately. | |||
7329 | /// | |||
7330 | /// \param attr The attribute as written on the type. | |||
7331 | /// | |||
7332 | /// \param allowOnArrayType Whether to accept nullability specifiers on an | |||
7333 | /// array type (e.g., because it will decay to a pointer). | |||
7334 | /// | |||
7335 | /// \returns true if a problem has been diagnosed, false on success. | |||
7336 | static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, | |||
7337 | QualType &type, | |||
7338 | ParsedAttr &attr, | |||
7339 | bool allowOnArrayType) { | |||
7340 | Sema &S = state.getSema(); | |||
7341 | ||||
7342 | NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); | |||
7343 | SourceLocation nullabilityLoc = attr.getLoc(); | |||
7344 | bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); | |||
7345 | ||||
7346 | recordNullabilitySeen(S, nullabilityLoc); | |||
7347 | ||||
7348 | // Check for existing nullability attributes on the type. | |||
7349 | QualType desugared = type; | |||
7350 | while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { | |||
7351 | // Check whether there is already a null | |||
7352 | if (auto existingNullability = attributed->getImmediateNullability()) { | |||
7353 | // Duplicated nullability. | |||
7354 | if (nullability == *existingNullability) { | |||
7355 | S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) | |||
7356 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
7357 | << FixItHint::CreateRemoval(nullabilityLoc); | |||
7358 | ||||
7359 | break; | |||
7360 | } | |||
7361 | ||||
7362 | // Conflicting nullability. | |||
7363 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) | |||
7364 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
7365 | << DiagNullabilityKind(*existingNullability, false); | |||
7366 | return true; | |||
7367 | } | |||
7368 | ||||
7369 | desugared = attributed->getModifiedType(); | |||
7370 | } | |||
7371 | ||||
7372 | // If there is already a different nullability specifier, complain. | |||
7373 | // This (unlike the code above) looks through typedefs that might | |||
7374 | // have nullability specifiers on them, which means we cannot | |||
7375 | // provide a useful Fix-It. | |||
7376 | if (auto existingNullability = desugared->getNullability(S.Context)) { | |||
7377 | if (nullability != *existingNullability) { | |||
7378 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) | |||
7379 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
7380 | << DiagNullabilityKind(*existingNullability, false); | |||
7381 | ||||
7382 | // Try to find the typedef with the existing nullability specifier. | |||
7383 | if (auto typedefType = desugared->getAs<TypedefType>()) { | |||
7384 | TypedefNameDecl *typedefDecl = typedefType->getDecl(); | |||
7385 | QualType underlyingType = typedefDecl->getUnderlyingType(); | |||
7386 | if (auto typedefNullability | |||
7387 | = AttributedType::stripOuterNullability(underlyingType)) { | |||
7388 | if (*typedefNullability == *existingNullability) { | |||
7389 | S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) | |||
7390 | << DiagNullabilityKind(*existingNullability, false); | |||
7391 | } | |||
7392 | } | |||
7393 | } | |||
7394 | ||||
7395 | return true; | |||
7396 | } | |||
7397 | } | |||
7398 | ||||
7399 | // If this definitely isn't a pointer type, reject the specifier. | |||
7400 | if (!desugared->canHaveNullability() && | |||
7401 | !(allowOnArrayType && desugared->isArrayType())) { | |||
7402 | S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) | |||
7403 | << DiagNullabilityKind(nullability, isContextSensitive) << type; | |||
7404 | return true; | |||
7405 | } | |||
7406 | ||||
7407 | // For the context-sensitive keywords/Objective-C property | |||
7408 | // attributes, require that the type be a single-level pointer. | |||
7409 | if (isContextSensitive) { | |||
7410 | // Make sure that the pointee isn't itself a pointer type. | |||
7411 | const Type *pointeeType = nullptr; | |||
7412 | if (desugared->isArrayType()) | |||
7413 | pointeeType = desugared->getArrayElementTypeNoTypeQual(); | |||
7414 | else if (desugared->isAnyPointerType()) | |||
7415 | pointeeType = desugared->getPointeeType().getTypePtr(); | |||
7416 | ||||
7417 | if (pointeeType && (pointeeType->isAnyPointerType() || | |||
7418 | pointeeType->isObjCObjectPointerType() || | |||
7419 | pointeeType->isMemberPointerType())) { | |||
7420 | S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) | |||
7421 | << DiagNullabilityKind(nullability, true) | |||
7422 | << type; | |||
7423 | S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) | |||
7424 | << DiagNullabilityKind(nullability, false) | |||
7425 | << type | |||
7426 | << FixItHint::CreateReplacement(nullabilityLoc, | |||
7427 | getNullabilitySpelling(nullability)); | |||
7428 | return true; | |||
7429 | } | |||
7430 | } | |||
7431 | ||||
7432 | // Form the attributed type. | |||
7433 | type = state.getAttributedType( | |||
7434 | createNullabilityAttr(S.Context, attr, nullability), type, type); | |||
7435 | return false; | |||
7436 | } | |||
7437 | ||||
7438 | /// Check the application of the Objective-C '__kindof' qualifier to | |||
7439 | /// the given type. | |||
7440 | static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, | |||
7441 | ParsedAttr &attr) { | |||
7442 | Sema &S = state.getSema(); | |||
7443 | ||||
7444 | if (isa<ObjCTypeParamType>(type)) { | |||
7445 | // Build the attributed type to record where __kindof occurred. | |||
7446 | type = state.getAttributedType( | |||
7447 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); | |||
7448 | return false; | |||
7449 | } | |||
7450 | ||||
7451 | // Find out if it's an Objective-C object or object pointer type; | |||
7452 | const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); | |||
7453 | const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() | |||
7454 | : type->getAs<ObjCObjectType>(); | |||
7455 | ||||
7456 | // If not, we can't apply __kindof. | |||
7457 | if (!objType) { | |||
7458 | // FIXME: Handle dependent types that aren't yet object types. | |||
7459 | S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) | |||
7460 | << type; | |||
7461 | return true; | |||
7462 | } | |||
7463 | ||||
7464 | // Rebuild the "equivalent" type, which pushes __kindof down into | |||
7465 | // the object type. | |||
7466 | // There is no need to apply kindof on an unqualified id type. | |||
7467 | QualType equivType = S.Context.getObjCObjectType( | |||
7468 | objType->getBaseType(), objType->getTypeArgsAsWritten(), | |||
7469 | objType->getProtocols(), | |||
7470 | /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); | |||
7471 | ||||
7472 | // If we started with an object pointer type, rebuild it. | |||
7473 | if (ptrType) { | |||
7474 | equivType = S.Context.getObjCObjectPointerType(equivType); | |||
7475 | if (auto nullability = type->getNullability(S.Context)) { | |||
7476 | // We create a nullability attribute from the __kindof attribute. | |||
7477 | // Make sure that will make sense. | |||
7478 | assert(attr.getAttributeSpellingListIndex() == 0 &&(static_cast <bool> (attr.getAttributeSpellingListIndex () == 0 && "multiple spellings for __kindof?") ? void (0) : __assert_fail ("attr.getAttributeSpellingListIndex() == 0 && \"multiple spellings for __kindof?\"" , "clang/lib/Sema/SemaType.cpp", 7479, __extension__ __PRETTY_FUNCTION__ )) | |||
7479 | "multiple spellings for __kindof?")(static_cast <bool> (attr.getAttributeSpellingListIndex () == 0 && "multiple spellings for __kindof?") ? void (0) : __assert_fail ("attr.getAttributeSpellingListIndex() == 0 && \"multiple spellings for __kindof?\"" , "clang/lib/Sema/SemaType.cpp", 7479, __extension__ __PRETTY_FUNCTION__ )); | |||
7480 | Attr *A = createNullabilityAttr(S.Context, attr, *nullability); | |||
7481 | A->setImplicit(true); | |||
7482 | equivType = state.getAttributedType(A, equivType, equivType); | |||
7483 | } | |||
7484 | } | |||
7485 | ||||
7486 | // Build the attributed type to record where __kindof occurred. | |||
7487 | type = state.getAttributedType( | |||
7488 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); | |||
7489 | return false; | |||
7490 | } | |||
7491 | ||||
7492 | /// Distribute a nullability type attribute that cannot be applied to | |||
7493 | /// the type specifier to a pointer, block pointer, or member pointer | |||
7494 | /// declarator, complaining if necessary. | |||
7495 | /// | |||
7496 | /// \returns true if the nullability annotation was distributed, false | |||
7497 | /// otherwise. | |||
7498 | static bool distributeNullabilityTypeAttr(TypeProcessingState &state, | |||
7499 | QualType type, ParsedAttr &attr) { | |||
7500 | Declarator &declarator = state.getDeclarator(); | |||
7501 | ||||
7502 | /// Attempt to move the attribute to the specified chunk. | |||
7503 | auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { | |||
7504 | // If there is already a nullability attribute there, don't add | |||
7505 | // one. | |||
7506 | if (hasNullabilityAttr(chunk.getAttrs())) | |||
7507 | return false; | |||
7508 | ||||
7509 | // Complain about the nullability qualifier being in the wrong | |||
7510 | // place. | |||
7511 | enum { | |||
7512 | PK_Pointer, | |||
7513 | PK_BlockPointer, | |||
7514 | PK_MemberPointer, | |||
7515 | PK_FunctionPointer, | |||
7516 | PK_MemberFunctionPointer, | |||
7517 | } pointerKind | |||
7518 | = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer | |||
7519 | : PK_Pointer) | |||
7520 | : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer | |||
7521 | : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; | |||
7522 | ||||
7523 | auto diag = state.getSema().Diag(attr.getLoc(), | |||
7524 | diag::warn_nullability_declspec) | |||
7525 | << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), | |||
7526 | attr.isContextSensitiveKeywordAttribute()) | |||
7527 | << type | |||
7528 | << static_cast<unsigned>(pointerKind); | |||
7529 | ||||
7530 | // FIXME: MemberPointer chunks don't carry the location of the *. | |||
7531 | if (chunk.Kind != DeclaratorChunk::MemberPointer) { | |||
7532 | diag << FixItHint::CreateRemoval(attr.getLoc()) | |||
7533 | << FixItHint::CreateInsertion( | |||
7534 | state.getSema().getPreprocessor().getLocForEndOfToken( | |||
7535 | chunk.Loc), | |||
7536 | " " + attr.getAttrName()->getName().str() + " "); | |||
7537 | } | |||
7538 | ||||
7539 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
7540 | chunk.getAttrs()); | |||
7541 | return true; | |||
7542 | }; | |||
7543 | ||||
7544 | // Move it to the outermost pointer, member pointer, or block | |||
7545 | // pointer declarator. | |||
7546 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
7547 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
7548 | switch (chunk.Kind) { | |||
7549 | case DeclaratorChunk::Pointer: | |||
7550 | case DeclaratorChunk::BlockPointer: | |||
7551 | case DeclaratorChunk::MemberPointer: | |||
7552 | return moveToChunk(chunk, false); | |||
7553 | ||||
7554 | case DeclaratorChunk::Paren: | |||
7555 | case DeclaratorChunk::Array: | |||
7556 | continue; | |||
7557 | ||||
7558 | case DeclaratorChunk::Function: | |||
7559 | // Try to move past the return type to a function/block/member | |||
7560 | // function pointer. | |||
7561 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | |||
7562 | declarator, i, | |||
7563 | /*onlyBlockPointers=*/false)) { | |||
7564 | return moveToChunk(*dest, true); | |||
7565 | } | |||
7566 | ||||
7567 | return false; | |||
7568 | ||||
7569 | // Don't walk through these. | |||
7570 | case DeclaratorChunk::Reference: | |||
7571 | case DeclaratorChunk::Pipe: | |||
7572 | return false; | |||
7573 | } | |||
7574 | } | |||
7575 | ||||
7576 | return false; | |||
7577 | } | |||
7578 | ||||
7579 | static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { | |||
7580 | assert(!Attr.isInvalid())(static_cast <bool> (!Attr.isInvalid()) ? void (0) : __assert_fail ("!Attr.isInvalid()", "clang/lib/Sema/SemaType.cpp", 7580, __extension__ __PRETTY_FUNCTION__)); | |||
7581 | switch (Attr.getKind()) { | |||
7582 | default: | |||
7583 | llvm_unreachable("not a calling convention attribute")::llvm::llvm_unreachable_internal("not a calling convention attribute" , "clang/lib/Sema/SemaType.cpp", 7583); | |||
7584 | case ParsedAttr::AT_CDecl: | |||
7585 | return createSimpleAttr<CDeclAttr>(Ctx, Attr); | |||
7586 | case ParsedAttr::AT_FastCall: | |||
7587 | return createSimpleAttr<FastCallAttr>(Ctx, Attr); | |||
7588 | case ParsedAttr::AT_StdCall: | |||
7589 | return createSimpleAttr<StdCallAttr>(Ctx, Attr); | |||
7590 | case ParsedAttr::AT_ThisCall: | |||
7591 | return createSimpleAttr<ThisCallAttr>(Ctx, Attr); | |||
7592 | case ParsedAttr::AT_RegCall: | |||
7593 | return createSimpleAttr<RegCallAttr>(Ctx, Attr); | |||
7594 | case ParsedAttr::AT_Pascal: | |||
7595 | return createSimpleAttr<PascalAttr>(Ctx, Attr); | |||
7596 | case ParsedAttr::AT_SwiftCall: | |||
7597 | return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); | |||
7598 | case ParsedAttr::AT_SwiftAsyncCall: | |||
7599 | return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr); | |||
7600 | case ParsedAttr::AT_VectorCall: | |||
7601 | return createSimpleAttr<VectorCallAttr>(Ctx, Attr); | |||
7602 | case ParsedAttr::AT_AArch64VectorPcs: | |||
7603 | return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); | |||
7604 | case ParsedAttr::AT_AArch64SVEPcs: | |||
7605 | return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr); | |||
7606 | case ParsedAttr::AT_AMDGPUKernelCall: | |||
7607 | return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr); | |||
7608 | case ParsedAttr::AT_Pcs: { | |||
7609 | // The attribute may have had a fixit applied where we treated an | |||
7610 | // identifier as a string literal. The contents of the string are valid, | |||
7611 | // but the form may not be. | |||
7612 | StringRef Str; | |||
7613 | if (Attr.isArgExpr(0)) | |||
7614 | Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); | |||
7615 | else | |||
7616 | Str = Attr.getArgAsIdent(0)->Ident->getName(); | |||
7617 | PcsAttr::PCSType Type; | |||
7618 | if (!PcsAttr::ConvertStrToPCSType(Str, Type)) | |||
7619 | llvm_unreachable("already validated the attribute")::llvm::llvm_unreachable_internal("already validated the attribute" , "clang/lib/Sema/SemaType.cpp", 7619); | |||
7620 | return ::new (Ctx) PcsAttr(Ctx, Attr, Type); | |||
7621 | } | |||
7622 | case ParsedAttr::AT_IntelOclBicc: | |||
7623 | return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); | |||
7624 | case ParsedAttr::AT_MSABI: | |||
7625 | return createSimpleAttr<MSABIAttr>(Ctx, Attr); | |||
7626 | case ParsedAttr::AT_SysVABI: | |||
7627 | return createSimpleAttr<SysVABIAttr>(Ctx, Attr); | |||
7628 | case ParsedAttr::AT_PreserveMost: | |||
7629 | return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); | |||
7630 | case ParsedAttr::AT_PreserveAll: | |||
7631 | return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); | |||
7632 | } | |||
7633 | llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!" , "clang/lib/Sema/SemaType.cpp", 7633); | |||
7634 | } | |||
7635 | ||||
7636 | /// Process an individual function attribute. Returns true to | |||
7637 | /// indicate that the attribute was handled, false if it wasn't. | |||
7638 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
7639 | QualType &type) { | |||
7640 | Sema &S = state.getSema(); | |||
7641 | ||||
7642 | FunctionTypeUnwrapper unwrapped(S, type); | |||
7643 | ||||
7644 | if (attr.getKind() == ParsedAttr::AT_NoReturn) { | |||
7645 | if (S.CheckAttrNoArgs(attr)) | |||
7646 | return true; | |||
7647 | ||||
7648 | // Delay if this is not a function type. | |||
7649 | if (!unwrapped.isFunctionType()) | |||
7650 | return false; | |||
7651 | ||||
7652 | // Otherwise we can process right away. | |||
7653 | FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); | |||
7654 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7655 | return true; | |||
7656 | } | |||
7657 | ||||
7658 | if (attr.getKind() == ParsedAttr::AT_CmseNSCall) { | |||
7659 | // Delay if this is not a function type. | |||
7660 | if (!unwrapped.isFunctionType()) | |||
7661 | return false; | |||
7662 | ||||
7663 | // Ignore if we don't have CMSE enabled. | |||
7664 | if (!S.getLangOpts().Cmse) { | |||
7665 | S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr; | |||
7666 | attr.setInvalid(); | |||
7667 | return true; | |||
7668 | } | |||
7669 | ||||
7670 | // Otherwise we can process right away. | |||
7671 | FunctionType::ExtInfo EI = | |||
7672 | unwrapped.get()->getExtInfo().withCmseNSCall(true); | |||
7673 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7674 | return true; | |||
7675 | } | |||
7676 | ||||
7677 | // ns_returns_retained is not always a type attribute, but if we got | |||
7678 | // here, we're treating it as one right now. | |||
7679 | if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { | |||
7680 | if (attr.getNumArgs()) return true; | |||
7681 | ||||
7682 | // Delay if this is not a function type. | |||
7683 | if (!unwrapped.isFunctionType()) | |||
7684 | return false; | |||
7685 | ||||
7686 | // Check whether the return type is reasonable. | |||
7687 | if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), | |||
7688 | unwrapped.get()->getReturnType())) | |||
7689 | return true; | |||
7690 | ||||
7691 | // Only actually change the underlying type in ARC builds. | |||
7692 | QualType origType = type; | |||
7693 | if (state.getSema().getLangOpts().ObjCAutoRefCount) { | |||
7694 | FunctionType::ExtInfo EI | |||
7695 | = unwrapped.get()->getExtInfo().withProducesResult(true); | |||
7696 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7697 | } | |||
7698 | type = state.getAttributedType( | |||
7699 | createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), | |||
7700 | origType, type); | |||
7701 | return true; | |||
7702 | } | |||
7703 | ||||
7704 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { | |||
7705 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) | |||
7706 | return true; | |||
7707 | ||||
7708 | // Delay if this is not a function type. | |||
7709 | if (!unwrapped.isFunctionType()) | |||
7710 | return false; | |||
7711 | ||||
7712 | FunctionType::ExtInfo EI = | |||
7713 | unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); | |||
7714 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7715 | return true; | |||
7716 | } | |||
7717 | ||||
7718 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { | |||
7719 | if (!S.getLangOpts().CFProtectionBranch) { | |||
7720 | S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); | |||
7721 | attr.setInvalid(); | |||
7722 | return true; | |||
7723 | } | |||
7724 | ||||
7725 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) | |||
7726 | return true; | |||
7727 | ||||
7728 | // If this is not a function type, warning will be asserted by subject | |||
7729 | // check. | |||
7730 | if (!unwrapped.isFunctionType()) | |||
7731 | return true; | |||
7732 | ||||
7733 | FunctionType::ExtInfo EI = | |||
7734 | unwrapped.get()->getExtInfo().withNoCfCheck(true); | |||
7735 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7736 | return true; | |||
7737 | } | |||
7738 | ||||
7739 | if (attr.getKind() == ParsedAttr::AT_Regparm) { | |||
7740 | unsigned value; | |||
7741 | if (S.CheckRegparmAttr(attr, value)) | |||
7742 | return true; | |||
7743 | ||||
7744 | // Delay if this is not a function type. | |||
7745 | if (!unwrapped.isFunctionType()) | |||
7746 | return false; | |||
7747 | ||||
7748 | // Diagnose regparm with fastcall. | |||
7749 | const FunctionType *fn = unwrapped.get(); | |||
7750 | CallingConv CC = fn->getCallConv(); | |||
7751 | if (CC == CC_X86FastCall) { | |||
7752 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7753 | << FunctionType::getNameForCallConv(CC) | |||
7754 | << "regparm"; | |||
7755 | attr.setInvalid(); | |||
7756 | return true; | |||
7757 | } | |||
7758 | ||||
7759 | FunctionType::ExtInfo EI = | |||
7760 | unwrapped.get()->getExtInfo().withRegParm(value); | |||
7761 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7762 | return true; | |||
7763 | } | |||
7764 | ||||
7765 | if (attr.getKind() == ParsedAttr::AT_NoThrow) { | |||
7766 | // Delay if this is not a function type. | |||
7767 | if (!unwrapped.isFunctionType()) | |||
7768 | return false; | |||
7769 | ||||
7770 | if (S.CheckAttrNoArgs(attr)) { | |||
7771 | attr.setInvalid(); | |||
7772 | return true; | |||
7773 | } | |||
7774 | ||||
7775 | // Otherwise we can process right away. | |||
7776 | auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); | |||
7777 | ||||
7778 | // MSVC ignores nothrow if it is in conflict with an explicit exception | |||
7779 | // specification. | |||
7780 | if (Proto->hasExceptionSpec()) { | |||
7781 | switch (Proto->getExceptionSpecType()) { | |||
7782 | case EST_None: | |||
7783 | llvm_unreachable("This doesn't have an exception spec!")::llvm::llvm_unreachable_internal("This doesn't have an exception spec!" , "clang/lib/Sema/SemaType.cpp", 7783); | |||
7784 | ||||
7785 | case EST_DynamicNone: | |||
7786 | case EST_BasicNoexcept: | |||
7787 | case EST_NoexceptTrue: | |||
7788 | case EST_NoThrow: | |||
7789 | // Exception spec doesn't conflict with nothrow, so don't warn. | |||
7790 | [[fallthrough]]; | |||
7791 | case EST_Unparsed: | |||
7792 | case EST_Uninstantiated: | |||
7793 | case EST_DependentNoexcept: | |||
7794 | case EST_Unevaluated: | |||
7795 | // We don't have enough information to properly determine if there is a | |||
7796 | // conflict, so suppress the warning. | |||
7797 | break; | |||
7798 | case EST_Dynamic: | |||
7799 | case EST_MSAny: | |||
7800 | case EST_NoexceptFalse: | |||
7801 | S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); | |||
7802 | break; | |||
7803 | } | |||
7804 | return true; | |||
7805 | } | |||
7806 | ||||
7807 | type = unwrapped.wrap( | |||
7808 | S, S.Context | |||
7809 | .getFunctionTypeWithExceptionSpec( | |||
7810 | QualType{Proto, 0}, | |||
7811 | FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) | |||
7812 | ->getAs<FunctionType>()); | |||
7813 | return true; | |||
7814 | } | |||
7815 | ||||
7816 | // Delay if the type didn't work out to a function. | |||
7817 | if (!unwrapped.isFunctionType()) return false; | |||
7818 | ||||
7819 | // Otherwise, a calling convention. | |||
7820 | CallingConv CC; | |||
7821 | if (S.CheckCallingConvAttr(attr, CC)) | |||
7822 | return true; | |||
7823 | ||||
7824 | const FunctionType *fn = unwrapped.get(); | |||
7825 | CallingConv CCOld = fn->getCallConv(); | |||
7826 | Attr *CCAttr = getCCTypeAttr(S.Context, attr); | |||
7827 | ||||
7828 | if (CCOld != CC) { | |||
7829 | // Error out on when there's already an attribute on the type | |||
7830 | // and the CCs don't match. | |||
7831 | if (S.getCallingConvAttributedType(type)) { | |||
7832 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7833 | << FunctionType::getNameForCallConv(CC) | |||
7834 | << FunctionType::getNameForCallConv(CCOld); | |||
7835 | attr.setInvalid(); | |||
7836 | return true; | |||
7837 | } | |||
7838 | } | |||
7839 | ||||
7840 | // Diagnose use of variadic functions with calling conventions that | |||
7841 | // don't support them (e.g. because they're callee-cleanup). | |||
7842 | // We delay warning about this on unprototyped function declarations | |||
7843 | // until after redeclaration checking, just in case we pick up a | |||
7844 | // prototype that way. And apparently we also "delay" warning about | |||
7845 | // unprototyped function types in general, despite not necessarily having | |||
7846 | // much ability to diagnose it later. | |||
7847 | if (!supportsVariadicCall(CC)) { | |||
7848 | const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); | |||
7849 | if (FnP && FnP->isVariadic()) { | |||
7850 | // stdcall and fastcall are ignored with a warning for GCC and MS | |||
7851 | // compatibility. | |||
7852 | if (CC == CC_X86StdCall || CC == CC_X86FastCall) | |||
7853 | return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) | |||
7854 | << FunctionType::getNameForCallConv(CC) | |||
7855 | << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; | |||
7856 | ||||
7857 | attr.setInvalid(); | |||
7858 | return S.Diag(attr.getLoc(), diag::err_cconv_varargs) | |||
7859 | << FunctionType::getNameForCallConv(CC); | |||
7860 | } | |||
7861 | } | |||
7862 | ||||
7863 | // Also diagnose fastcall with regparm. | |||
7864 | if (CC == CC_X86FastCall && fn->getHasRegParm()) { | |||
7865 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7866 | << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); | |||
7867 | attr.setInvalid(); | |||
7868 | return true; | |||
7869 | } | |||
7870 | ||||
7871 | // Modify the CC from the wrapped function type, wrap it all back, and then | |||
7872 | // wrap the whole thing in an AttributedType as written. The modified type | |||
7873 | // might have a different CC if we ignored the attribute. | |||
7874 | QualType Equivalent; | |||
7875 | if (CCOld == CC) { | |||
7876 | Equivalent = type; | |||
7877 | } else { | |||
7878 | auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); | |||
7879 | Equivalent = | |||
7880 | unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7881 | } | |||
7882 | type = state.getAttributedType(CCAttr, type, Equivalent); | |||
7883 | return true; | |||
7884 | } | |||
7885 | ||||
7886 | bool Sema::hasExplicitCallingConv(QualType T) { | |||
7887 | const AttributedType *AT; | |||
7888 | ||||
7889 | // Stop if we'd be stripping off a typedef sugar node to reach the | |||
7890 | // AttributedType. | |||
7891 | while ((AT = T->getAs<AttributedType>()) && | |||
7892 | AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { | |||
7893 | if (AT->isCallingConv()) | |||
7894 | return true; | |||
7895 | T = AT->getModifiedType(); | |||
7896 | } | |||
7897 | return false; | |||
7898 | } | |||
7899 | ||||
7900 | void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, | |||
7901 | SourceLocation Loc) { | |||
7902 | FunctionTypeUnwrapper Unwrapped(*this, T); | |||
7903 | const FunctionType *FT = Unwrapped.get(); | |||
7904 | bool IsVariadic = (isa<FunctionProtoType>(FT) && | |||
7905 | cast<FunctionProtoType>(FT)->isVariadic()); | |||
7906 | CallingConv CurCC = FT->getCallConv(); | |||
7907 | CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); | |||
7908 | ||||
7909 | if (CurCC == ToCC) | |||
7910 | return; | |||
7911 | ||||
7912 | // MS compiler ignores explicit calling convention attributes on structors. We | |||
7913 | // should do the same. | |||
7914 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { | |||
7915 | // Issue a warning on ignored calling convention -- except of __stdcall. | |||
7916 | // Again, this is what MS compiler does. | |||
7917 | if (CurCC != CC_X86StdCall) | |||
7918 | Diag(Loc, diag::warn_cconv_unsupported) | |||
7919 | << FunctionType::getNameForCallConv(CurCC) | |||
7920 | << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; | |||
7921 | // Default adjustment. | |||
7922 | } else { | |||
7923 | // Only adjust types with the default convention. For example, on Windows | |||
7924 | // we should adjust a __cdecl type to __thiscall for instance methods, and a | |||
7925 | // __thiscall type to __cdecl for static methods. | |||
7926 | CallingConv DefaultCC = | |||
7927 | Context.getDefaultCallingConvention(IsVariadic, IsStatic); | |||
7928 | ||||
7929 | if (CurCC != DefaultCC || DefaultCC == ToCC) | |||
7930 | return; | |||
7931 | ||||
7932 | if (hasExplicitCallingConv(T)) | |||
7933 | return; | |||
7934 | } | |||
7935 | ||||
7936 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); | |||
7937 | QualType Wrapped = Unwrapped.wrap(*this, FT); | |||
7938 | T = Context.getAdjustedType(T, Wrapped); | |||
7939 | } | |||
7940 | ||||
7941 | /// HandleVectorSizeAttribute - this attribute is only applicable to integral | |||
7942 | /// and float scalars, although arrays, pointers, and function return values are | |||
7943 | /// allowed in conjunction with this construct. Aggregates with this attribute | |||
7944 | /// are invalid, even if they are of the same size as a corresponding scalar. | |||
7945 | /// The raw attribute should contain precisely 1 argument, the vector size for | |||
7946 | /// the variable, measured in bytes. If curType and rawAttr are well formed, | |||
7947 | /// this routine will return a new vector type. | |||
7948 | static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7949 | Sema &S) { | |||
7950 | // Check the attribute arguments. | |||
7951 | if (Attr.getNumArgs() != 1) { | |||
7952 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
7953 | << 1; | |||
7954 | Attr.setInvalid(); | |||
7955 | return; | |||
7956 | } | |||
7957 | ||||
7958 | Expr *SizeExpr = Attr.getArgAsExpr(0); | |||
7959 | QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); | |||
7960 | if (!T.isNull()) | |||
7961 | CurType = T; | |||
7962 | else | |||
7963 | Attr.setInvalid(); | |||
7964 | } | |||
7965 | ||||
7966 | /// Process the OpenCL-like ext_vector_type attribute when it occurs on | |||
7967 | /// a type. | |||
7968 | static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7969 | Sema &S) { | |||
7970 | // check the attribute arguments. | |||
7971 | if (Attr.getNumArgs() != 1) { | |||
7972 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
7973 | << 1; | |||
7974 | return; | |||
7975 | } | |||
7976 | ||||
7977 | Expr *SizeExpr = Attr.getArgAsExpr(0); | |||
7978 | QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc()); | |||
7979 | if (!T.isNull()) | |||
7980 | CurType = T; | |||
7981 | } | |||
7982 | ||||
7983 | static bool isPermittedNeonBaseType(QualType &Ty, | |||
7984 | VectorType::VectorKind VecKind, Sema &S) { | |||
7985 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
7986 | if (!BTy) | |||
7987 | return false; | |||
7988 | ||||
7989 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); | |||
7990 | ||||
7991 | // Signed poly is mathematically wrong, but has been baked into some ABIs by | |||
7992 | // now. | |||
7993 | bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || | |||
7994 | Triple.getArch() == llvm::Triple::aarch64_32 || | |||
7995 | Triple.getArch() == llvm::Triple::aarch64_be; | |||
7996 | if (VecKind == VectorType::NeonPolyVector) { | |||
7997 | if (IsPolyUnsigned) { | |||
7998 | // AArch64 polynomial vectors are unsigned. | |||
7999 | return BTy->getKind() == BuiltinType::UChar || | |||
8000 | BTy->getKind() == BuiltinType::UShort || | |||
8001 | BTy->getKind() == BuiltinType::ULong || | |||
8002 | BTy->getKind() == BuiltinType::ULongLong; | |||
8003 | } else { | |||
8004 | // AArch32 polynomial vectors are signed. | |||
8005 | return BTy->getKind() == BuiltinType::SChar || | |||
8006 | BTy->getKind() == BuiltinType::Short || | |||
8007 | BTy->getKind() == BuiltinType::LongLong; | |||
8008 | } | |||
8009 | } | |||
8010 | ||||
8011 | // Non-polynomial vector types: the usual suspects are allowed, as well as | |||
8012 | // float64_t on AArch64. | |||
8013 | if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) && | |||
8014 | BTy->getKind() == BuiltinType::Double) | |||
8015 | return true; | |||
8016 | ||||
8017 | return BTy->getKind() == BuiltinType::SChar || | |||
8018 | BTy->getKind() == BuiltinType::UChar || | |||
8019 | BTy->getKind() == BuiltinType::Short || | |||
8020 | BTy->getKind() == BuiltinType::UShort || | |||
8021 | BTy->getKind() == BuiltinType::Int || | |||
8022 | BTy->getKind() == BuiltinType::UInt || | |||
8023 | BTy->getKind() == BuiltinType::Long || | |||
8024 | BTy->getKind() == BuiltinType::ULong || | |||
8025 | BTy->getKind() == BuiltinType::LongLong || | |||
8026 | BTy->getKind() == BuiltinType::ULongLong || | |||
8027 | BTy->getKind() == BuiltinType::Float || | |||
8028 | BTy->getKind() == BuiltinType::Half || | |||
8029 | BTy->getKind() == BuiltinType::BFloat16; | |||
8030 | } | |||
8031 | ||||
8032 | static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, | |||
8033 | llvm::APSInt &Result) { | |||
8034 | const auto *AttrExpr = Attr.getArgAsExpr(0); | |||
8035 | if (!AttrExpr->isTypeDependent()) { | |||
8036 | if (Optional<llvm::APSInt> Res = | |||
8037 | AttrExpr->getIntegerConstantExpr(S.Context)) { | |||
8038 | Result = *Res; | |||
8039 | return true; | |||
8040 | } | |||
8041 | } | |||
8042 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) | |||
8043 | << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange(); | |||
8044 | Attr.setInvalid(); | |||
8045 | return false; | |||
8046 | } | |||
8047 | ||||
8048 | /// HandleNeonVectorTypeAttr - The "neon_vector_type" and | |||
8049 | /// "neon_polyvector_type" attributes are used to create vector types that | |||
8050 | /// are mangled according to ARM's ABI. Otherwise, these types are identical | |||
8051 | /// to those created with the "vector_size" attribute. Unlike "vector_size" | |||
8052 | /// the argument to these Neon attributes is the number of vector elements, | |||
8053 | /// not the vector size in bytes. The vector width and element type must | |||
8054 | /// match one of the standard Neon vector types. | |||
8055 | static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
8056 | Sema &S, VectorType::VectorKind VecKind) { | |||
8057 | // Target must have NEON (or MVE, whose vectors are similar enough | |||
8058 | // not to need a separate attribute) | |||
8059 | if (!S.Context.getTargetInfo().hasFeature("neon") && | |||
8060 | !S.Context.getTargetInfo().hasFeature("mve")) { | |||
8061 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) | |||
8062 | << Attr << "'neon' or 'mve'"; | |||
8063 | Attr.setInvalid(); | |||
8064 | return; | |||
8065 | } | |||
8066 | // Check the attribute arguments. | |||
8067 | if (Attr.getNumArgs() != 1) { | |||
8068 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
8069 | << 1; | |||
8070 | Attr.setInvalid(); | |||
8071 | return; | |||
8072 | } | |||
8073 | // The number of elements must be an ICE. | |||
8074 | llvm::APSInt numEltsInt(32); | |||
8075 | if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt)) | |||
8076 | return; | |||
8077 | ||||
8078 | // Only certain element types are supported for Neon vectors. | |||
8079 | if (!isPermittedNeonBaseType(CurType, VecKind, S)) { | |||
8080 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; | |||
8081 | Attr.setInvalid(); | |||
8082 | return; | |||
8083 | } | |||
8084 | ||||
8085 | // The total size of the vector must be 64 or 128 bits. | |||
8086 | unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); | |||
8087 | unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); | |||
8088 | unsigned vecSize = typeSize * numElts; | |||
8089 | if (vecSize != 64 && vecSize != 128) { | |||
8090 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; | |||
8091 | Attr.setInvalid(); | |||
8092 | return; | |||
8093 | } | |||
8094 | ||||
8095 | CurType = S.Context.getVectorType(CurType, numElts, VecKind); | |||
8096 | } | |||
8097 | ||||
8098 | /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is | |||
8099 | /// used to create fixed-length versions of sizeless SVE types defined by | |||
8100 | /// the ACLE, such as svint32_t and svbool_t. | |||
8101 | static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, | |||
8102 | Sema &S) { | |||
8103 | // Target must have SVE. | |||
8104 | if (!S.Context.getTargetInfo().hasFeature("sve")) { | |||
8105 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'"; | |||
8106 | Attr.setInvalid(); | |||
8107 | return; | |||
8108 | } | |||
8109 | ||||
8110 | // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or | |||
8111 | // if <bits>+ syntax is used. | |||
8112 | if (!S.getLangOpts().VScaleMin || | |||
8113 | S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) { | |||
8114 | S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported) | |||
8115 | << Attr; | |||
8116 | Attr.setInvalid(); | |||
8117 | return; | |||
8118 | } | |||
8119 | ||||
8120 | // Check the attribute arguments. | |||
8121 | if (Attr.getNumArgs() != 1) { | |||
8122 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
8123 | << Attr << 1; | |||
8124 | Attr.setInvalid(); | |||
8125 | return; | |||
8126 | } | |||
8127 | ||||
8128 | // The vector size must be an integer constant expression. | |||
8129 | llvm::APSInt SveVectorSizeInBits(32); | |||
8130 | if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits)) | |||
8131 | return; | |||
8132 | ||||
8133 | unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue()); | |||
8134 | ||||
8135 | // The attribute vector size must match -msve-vector-bits. | |||
8136 | if (VecSize != S.getLangOpts().VScaleMin * 128) { | |||
8137 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size) | |||
8138 | << VecSize << S.getLangOpts().VScaleMin * 128; | |||
8139 | Attr.setInvalid(); | |||
8140 | return; | |||
8141 | } | |||
8142 | ||||
8143 | // Attribute can only be attached to a single SVE vector or predicate type. | |||
8144 | if (!CurType->isVLSTBuiltinType()) { | |||
8145 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type) | |||
8146 | << Attr << CurType; | |||
8147 | Attr.setInvalid(); | |||
8148 | return; | |||
8149 | } | |||
8150 | ||||
8151 | const auto *BT = CurType->castAs<BuiltinType>(); | |||
8152 | ||||
8153 | QualType EltType = CurType->getSveEltType(S.Context); | |||
8154 | unsigned TypeSize = S.Context.getTypeSize(EltType); | |||
8155 | VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector; | |||
8156 | if (BT->getKind() == BuiltinType::SveBool) { | |||
8157 | // Predicates are represented as i8. | |||
8158 | VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth(); | |||
8159 | VecKind = VectorType::SveFixedLengthPredicateVector; | |||
8160 | } else | |||
8161 | VecSize /= TypeSize; | |||
8162 | CurType = S.Context.getVectorType(EltType, VecSize, VecKind); | |||
8163 | } | |||
8164 | ||||
8165 | static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, | |||
8166 | QualType &CurType, | |||
8167 | ParsedAttr &Attr) { | |||
8168 | const VectorType *VT = dyn_cast<VectorType>(CurType); | |||
8169 | if (!VT || VT->getVectorKind() != VectorType::NeonVector) { | |||
8170 | State.getSema().Diag(Attr.getLoc(), | |||
8171 | diag::err_attribute_arm_mve_polymorphism); | |||
8172 | Attr.setInvalid(); | |||
8173 | return; | |||
8174 | } | |||
8175 | ||||
8176 | CurType = | |||
8177 | State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>( | |||
8178 | State.getSema().Context, Attr), | |||
8179 | CurType, CurType); | |||
8180 | } | |||
8181 | ||||
8182 | /// Handle OpenCL Access Qualifier Attribute. | |||
8183 | static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, | |||
8184 | Sema &S) { | |||
8185 | // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. | |||
8186 | if (!(CurType->isImageType() || CurType->isPipeType())) { | |||
8187 | S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); | |||
8188 | Attr.setInvalid(); | |||
8189 | return; | |||
8190 | } | |||
8191 | ||||
8192 | if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { | |||
8193 | QualType BaseTy = TypedefTy->desugar(); | |||
8194 | ||||
8195 | std::string PrevAccessQual; | |||
8196 | if (BaseTy->isPipeType()) { | |||
8197 | if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { | |||
8198 | OpenCLAccessAttr *Attr = | |||
8199 | TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); | |||
8200 | PrevAccessQual = Attr->getSpelling(); | |||
8201 | } else { | |||
8202 | PrevAccessQual = "read_only"; | |||
8203 | } | |||
8204 | } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { | |||
8205 | ||||
8206 | switch (ImgType->getKind()) { | |||
8207 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
8208 | case BuiltinType::Id: \ | |||
8209 | PrevAccessQual = #Access; \ | |||
8210 | break; | |||
8211 | #include "clang/Basic/OpenCLImageTypes.def" | |||
8212 | default: | |||
8213 | llvm_unreachable("Unable to find corresponding image type.")::llvm::llvm_unreachable_internal("Unable to find corresponding image type." , "clang/lib/Sema/SemaType.cpp", 8213); | |||
8214 | } | |||
8215 | } else { | |||
8216 | llvm_unreachable("unexpected type")::llvm::llvm_unreachable_internal("unexpected type", "clang/lib/Sema/SemaType.cpp" , 8216); | |||
8217 | } | |||
8218 | StringRef AttrName = Attr.getAttrName()->getName(); | |||
8219 | if (PrevAccessQual == AttrName.ltrim("_")) { | |||
8220 | // Duplicated qualifiers | |||
8221 | S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) | |||
8222 | << AttrName << Attr.getRange(); | |||
8223 | } else { | |||
8224 | // Contradicting qualifiers | |||
8225 | S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); | |||
8226 | } | |||
8227 | ||||
8228 | S.Diag(TypedefTy->getDecl()->getBeginLoc(), | |||
8229 | diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; | |||
8230 | } else if (CurType->isPipeType()) { | |||
8231 | if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { | |||
8232 | QualType ElemType = CurType->castAs<PipeType>()->getElementType(); | |||
8233 | CurType = S.Context.getWritePipeType(ElemType); | |||
8234 | } | |||
8235 | } | |||
8236 | } | |||
8237 | ||||
8238 | /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type | |||
8239 | static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
8240 | Sema &S) { | |||
8241 | if (!S.getLangOpts().MatrixTypes) { | |||
8242 | S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled); | |||
8243 | return; | |||
8244 | } | |||
8245 | ||||
8246 | if (Attr.getNumArgs() != 2) { | |||
8247 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
8248 | << Attr << 2; | |||
8249 | return; | |||
8250 | } | |||
8251 | ||||
8252 | Expr *RowsExpr = Attr.getArgAsExpr(0); | |||
8253 | Expr *ColsExpr = Attr.getArgAsExpr(1); | |||
8254 | QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc()); | |||
8255 | if (!T.isNull()) | |||
8256 | CurType = T; | |||
8257 | } | |||
8258 | ||||
8259 | static void HandleAnnotateTypeAttr(TypeProcessingState &State, | |||
8260 | QualType &CurType, const ParsedAttr &PA) { | |||
8261 | Sema &S = State.getSema(); | |||
8262 | ||||
8263 | if (PA.getNumArgs() < 1) { | |||
8264 | S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1; | |||
8265 | return; | |||
8266 | } | |||
8267 | ||||
8268 | // Make sure that there is a string literal as the annotation's first | |||
8269 | // argument. | |||
8270 | StringRef Str; | |||
8271 | if (!S.checkStringLiteralArgumentAttr(PA, 0, Str)) | |||
8272 | return; | |||
8273 | ||||
8274 | llvm::SmallVector<Expr *, 4> Args; | |||
8275 | Args.reserve(PA.getNumArgs() - 1); | |||
8276 | for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) { | |||
8277 | assert(!PA.isArgIdent(Idx))(static_cast <bool> (!PA.isArgIdent(Idx)) ? void (0) : __assert_fail ("!PA.isArgIdent(Idx)", "clang/lib/Sema/SemaType.cpp", 8277, __extension__ __PRETTY_FUNCTION__)); | |||
8278 | Args.push_back(PA.getArgAsExpr(Idx)); | |||
8279 | } | |||
8280 | if (!S.ConstantFoldAttrArgs(PA, Args)) | |||
8281 | return; | |||
8282 | auto *AnnotateTypeAttr = | |||
8283 | AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA); | |||
8284 | CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType); | |||
8285 | } | |||
8286 | ||||
8287 | static void HandleLifetimeBoundAttr(TypeProcessingState &State, | |||
8288 | QualType &CurType, | |||
8289 | ParsedAttr &Attr) { | |||
8290 | if (State.getDeclarator().isDeclarationOfFunction()) { | |||
8291 | CurType = State.getAttributedType( | |||
8292 | createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), | |||
8293 | CurType, CurType); | |||
8294 | } | |||
8295 | } | |||
8296 | ||||
8297 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, | |||
8298 | TypeAttrLocation TAL, | |||
8299 | const ParsedAttributesView &attrs) { | |||
8300 | ||||
8301 | state.setParsedNoDeref(false); | |||
8302 | if (attrs.empty()) | |||
8303 | return; | |||
8304 | ||||
8305 | // Scan through and apply attributes to this type where it makes sense. Some | |||
8306 | // attributes (such as __address_space__, __vector_size__, etc) apply to the | |||
8307 | // type, but others can be present in the type specifiers even though they | |||
8308 | // apply to the decl. Here we apply type attributes and ignore the rest. | |||
8309 | ||||
8310 | // This loop modifies the list pretty frequently, but we still need to make | |||
8311 | // sure we visit every element once. Copy the attributes list, and iterate | |||
8312 | // over that. | |||
8313 | ParsedAttributesView AttrsCopy{attrs}; | |||
8314 | for (ParsedAttr &attr : AttrsCopy) { | |||
8315 | ||||
8316 | // Skip attributes that were marked to be invalid. | |||
8317 | if (attr.isInvalid()) | |||
8318 | continue; | |||
8319 | ||||
8320 | if (attr.isStandardAttributeSyntax()) { | |||
8321 | // [[gnu::...]] attributes are treated as declaration attributes, so may | |||
8322 | // not appertain to a DeclaratorChunk. If we handle them as type | |||
8323 | // attributes, accept them in that position and diagnose the GCC | |||
8324 | // incompatibility. | |||
8325 | if (attr.isGNUScope()) { | |||
8326 | bool IsTypeAttr = attr.isTypeAttr(); | |||
8327 | if (TAL == TAL_DeclChunk) { | |||
8328 | state.getSema().Diag(attr.getLoc(), | |||
8329 | IsTypeAttr | |||
8330 | ? diag::warn_gcc_ignores_type_attr | |||
8331 | : diag::warn_cxx11_gnu_attribute_on_type) | |||
8332 | << attr; | |||
8333 | if (!IsTypeAttr) | |||
8334 | continue; | |||
8335 | } | |||
8336 | } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk && | |||
8337 | !attr.isTypeAttr()) { | |||
8338 | // Otherwise, only consider type processing for a C++11 attribute if | |||
8339 | // - it has actually been applied to a type (decl-specifier-seq or | |||
8340 | // declarator chunk), or | |||
8341 | // - it is a type attribute, irrespective of where it was applied (so | |||
8342 | // that we can support the legacy behavior of some type attributes | |||
8343 | // that can be applied to the declaration name). | |||
8344 | continue; | |||
8345 | } | |||
8346 | } | |||
8347 | ||||
8348 | // If this is an attribute we can handle, do so now, | |||
8349 | // otherwise, add it to the FnAttrs list for rechaining. | |||
8350 | switch (attr.getKind()) { | |||
8351 | default: | |||
8352 | // A [[]] attribute on a declarator chunk must appertain to a type. | |||
8353 | if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) { | |||
8354 | state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) | |||
8355 | << attr; | |||
8356 | attr.setUsedAsTypeAttr(); | |||
8357 | } | |||
8358 | break; | |||
8359 | ||||
8360 | case ParsedAttr::UnknownAttribute: | |||
8361 | if (attr.isStandardAttributeSyntax()) { | |||
8362 | state.getSema().Diag(attr.getLoc(), | |||
8363 | diag::warn_unknown_attribute_ignored) | |||
8364 | << attr << attr.getRange(); | |||
8365 | // Mark the attribute as invalid so we don't emit the same diagnostic | |||
8366 | // multiple times. | |||
8367 | attr.setInvalid(); | |||
8368 | } | |||
8369 | break; | |||
8370 | ||||
8371 | case ParsedAttr::IgnoredAttribute: | |||
8372 | break; | |||
8373 | ||||
8374 | case ParsedAttr::AT_BTFTypeTag: | |||
8375 | HandleBTFTypeTagAttribute(type, attr, state); | |||
8376 | attr.setUsedAsTypeAttr(); | |||
8377 | break; | |||
8378 | ||||
8379 | case ParsedAttr::AT_MayAlias: | |||
8380 | // FIXME: This attribute needs to actually be handled, but if we ignore | |||
8381 | // it it breaks large amounts of Linux software. | |||
8382 | attr.setUsedAsTypeAttr(); | |||
8383 | break; | |||
8384 | case ParsedAttr::AT_OpenCLPrivateAddressSpace: | |||
8385 | case ParsedAttr::AT_OpenCLGlobalAddressSpace: | |||
8386 | case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace: | |||
8387 | case ParsedAttr::AT_OpenCLGlobalHostAddressSpace: | |||
8388 | case ParsedAttr::AT_OpenCLLocalAddressSpace: | |||
8389 | case ParsedAttr::AT_OpenCLConstantAddressSpace: | |||
8390 | case ParsedAttr::AT_OpenCLGenericAddressSpace: | |||
8391 | case ParsedAttr::AT_AddressSpace: | |||
8392 | HandleAddressSpaceTypeAttribute(type, attr, state); | |||
8393 | attr.setUsedAsTypeAttr(); | |||
8394 | break; | |||
8395 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: | |||
8396 | if (!handleObjCPointerTypeAttr(state, attr, type)) | |||
8397 | distributeObjCPointerTypeAttr(state, attr, type); | |||
8398 | attr.setUsedAsTypeAttr(); | |||
8399 | break; | |||
8400 | case ParsedAttr::AT_VectorSize: | |||
8401 | HandleVectorSizeAttr(type, attr, state.getSema()); | |||
8402 | attr.setUsedAsTypeAttr(); | |||
8403 | break; | |||
8404 | case ParsedAttr::AT_ExtVectorType: | |||
8405 | HandleExtVectorTypeAttr(type, attr, state.getSema()); | |||
8406 | attr.setUsedAsTypeAttr(); | |||
8407 | break; | |||
8408 | case ParsedAttr::AT_NeonVectorType: | |||
8409 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | |||
8410 | VectorType::NeonVector); | |||
8411 | attr.setUsedAsTypeAttr(); | |||
8412 | break; | |||
8413 | case ParsedAttr::AT_NeonPolyVectorType: | |||
8414 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | |||
8415 | VectorType::NeonPolyVector); | |||
8416 | attr.setUsedAsTypeAttr(); | |||
8417 | break; | |||
8418 | case ParsedAttr::AT_ArmSveVectorBits: | |||
8419 | HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema()); | |||
8420 | attr.setUsedAsTypeAttr(); | |||
8421 | break; | |||
8422 | case ParsedAttr::AT_ArmMveStrictPolymorphism: { | |||
8423 | HandleArmMveStrictPolymorphismAttr(state, type, attr); | |||
8424 | attr.setUsedAsTypeAttr(); | |||
8425 | break; | |||
8426 | } | |||
8427 | case ParsedAttr::AT_OpenCLAccess: | |||
8428 | HandleOpenCLAccessAttr(type, attr, state.getSema()); | |||
8429 | attr.setUsedAsTypeAttr(); | |||
8430 | break; | |||
8431 | case ParsedAttr::AT_LifetimeBound: | |||
8432 | if (TAL == TAL_DeclChunk) | |||
8433 | HandleLifetimeBoundAttr(state, type, attr); | |||
8434 | break; | |||
8435 | ||||
8436 | case ParsedAttr::AT_NoDeref: { | |||
8437 | // FIXME: `noderef` currently doesn't work correctly in [[]] syntax. | |||
8438 | // See https://github.com/llvm/llvm-project/issues/55790 for details. | |||
8439 | // For the time being, we simply emit a warning that the attribute is | |||
8440 | // ignored. | |||
8441 | if (attr.isStandardAttributeSyntax()) { | |||
8442 | state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored) | |||
8443 | << attr; | |||
8444 | break; | |||
8445 | } | |||
8446 | ASTContext &Ctx = state.getSema().Context; | |||
8447 | type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), | |||
8448 | type, type); | |||
8449 | attr.setUsedAsTypeAttr(); | |||
8450 | state.setParsedNoDeref(true); | |||
8451 | break; | |||
8452 | } | |||
8453 | ||||
8454 | case ParsedAttr::AT_MatrixType: | |||
8455 | HandleMatrixTypeAttr(type, attr, state.getSema()); | |||
8456 | attr.setUsedAsTypeAttr(); | |||
8457 | break; | |||
8458 | ||||
8459 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: | |||
8460 | if (!handleMSPointerTypeQualifierAttr(state, attr, type)) | |||
8461 | attr.setUsedAsTypeAttr(); | |||
8462 | break; | |||
8463 | ||||
8464 | ||||
8465 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified: | |||
8466 | // Either add nullability here or try to distribute it. We | |||
8467 | // don't want to distribute the nullability specifier past any | |||
8468 | // dependent type, because that complicates the user model. | |||
8469 | if (type->canHaveNullability() || type->isDependentType() || | |||
8470 | type->isArrayType() || | |||
8471 | !distributeNullabilityTypeAttr(state, type, attr)) { | |||
8472 | unsigned endIndex; | |||
8473 | if (TAL == TAL_DeclChunk) | |||
8474 | endIndex = state.getCurrentChunkIndex(); | |||
8475 | else | |||
8476 | endIndex = state.getDeclarator().getNumTypeObjects(); | |||
8477 | bool allowOnArrayType = | |||
8478 | state.getDeclarator().isPrototypeContext() && | |||
8479 | !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); | |||
8480 | if (checkNullabilityTypeSpecifier( | |||
8481 | state, | |||
8482 | type, | |||
8483 | attr, | |||
8484 | allowOnArrayType)) { | |||
8485 | attr.setInvalid(); | |||
8486 | } | |||
8487 | ||||
8488 | attr.setUsedAsTypeAttr(); | |||
8489 | } | |||
8490 | break; | |||
8491 | ||||
8492 | case ParsedAttr::AT_ObjCKindOf: | |||
8493 | // '__kindof' must be part of the decl-specifiers. | |||
8494 | switch (TAL) { | |||
8495 | case TAL_DeclSpec: | |||
8496 | break; | |||
8497 | ||||
8498 | case TAL_DeclChunk: | |||
8499 | case TAL_DeclName: | |||
8500 | state.getSema().Diag(attr.getLoc(), | |||
8501 | diag::err_objc_kindof_wrong_position) | |||
8502 | << FixItHint::CreateRemoval(attr.getLoc()) | |||
8503 | << FixItHint::CreateInsertion( | |||
8504 | state.getDeclarator().getDeclSpec().getBeginLoc(), | |||
8505 | "__kindof "); | |||
8506 | break; | |||
8507 | } | |||
8508 | ||||
8509 | // Apply it regardless. | |||
8510 | if (checkObjCKindOfType(state, type, attr)) | |||
8511 | attr.setInvalid(); | |||
8512 | break; | |||
8513 | ||||
8514 | case ParsedAttr::AT_NoThrow: | |||
8515 | // Exception Specifications aren't generally supported in C mode throughout | |||
8516 | // clang, so revert to attribute-based handling for C. | |||
8517 | if (!state.getSema().getLangOpts().CPlusPlus) | |||
8518 | break; | |||
8519 | [[fallthrough]]; | |||
8520 | FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_SwiftAsyncCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_AArch64SVEPcs: case ParsedAttr::AT_AMDGPUKernelCall : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll: | |||
8521 | attr.setUsedAsTypeAttr(); | |||
8522 | ||||
8523 | // Attributes with standard syntax have strict rules for what they | |||
8524 | // appertain to and hence should not use the "distribution" logic below. | |||
8525 | if (attr.isStandardAttributeSyntax()) { | |||
8526 | if (!handleFunctionTypeAttr(state, attr, type)) { | |||
8527 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
8528 | attr.setInvalid(); | |||
8529 | } | |||
8530 | break; | |||
8531 | } | |||
8532 | ||||
8533 | // Never process function type attributes as part of the | |||
8534 | // declaration-specifiers. | |||
8535 | if (TAL == TAL_DeclSpec) | |||
8536 | distributeFunctionTypeAttrFromDeclSpec(state, attr, type); | |||
8537 | ||||
8538 | // Otherwise, handle the possible delays. | |||
8539 | else if (!handleFunctionTypeAttr(state, attr, type)) | |||
8540 | distributeFunctionTypeAttr(state, attr, type); | |||
8541 | break; | |||
8542 | case ParsedAttr::AT_AcquireHandle: { | |||
8543 | if (!type->isFunctionType()) | |||
8544 | return; | |||
8545 | ||||
8546 | if (attr.getNumArgs() != 1) { | |||
8547 | state.getSema().Diag(attr.getLoc(), | |||
8548 | diag::err_attribute_wrong_number_arguments) | |||
8549 | << attr << 1; | |||
8550 | attr.setInvalid(); | |||
8551 | return; | |||
8552 | } | |||
8553 | ||||
8554 | StringRef HandleType; | |||
8555 | if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType)) | |||
8556 | return; | |||
8557 | type = state.getAttributedType( | |||
8558 | AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr), | |||
8559 | type, type); | |||
8560 | attr.setUsedAsTypeAttr(); | |||
8561 | break; | |||
8562 | } | |||
8563 | case ParsedAttr::AT_AnnotateType: { | |||
8564 | HandleAnnotateTypeAttr(state, type, attr); | |||
8565 | attr.setUsedAsTypeAttr(); | |||
8566 | break; | |||
8567 | } | |||
8568 | } | |||
8569 | ||||
8570 | // Handle attributes that are defined in a macro. We do not want this to be | |||
8571 | // applied to ObjC builtin attributes. | |||
8572 | if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && | |||
8573 | !type.getQualifiers().hasObjCLifetime() && | |||
8574 | !type.getQualifiers().hasObjCGCAttr() && | |||
8575 | attr.getKind() != ParsedAttr::AT_ObjCGC && | |||
8576 | attr.getKind() != ParsedAttr::AT_ObjCOwnership) { | |||
8577 | const IdentifierInfo *MacroII = attr.getMacroIdentifier(); | |||
8578 | type = state.getSema().Context.getMacroQualifiedType(type, MacroII); | |||
8579 | state.setExpansionLocForMacroQualifiedType( | |||
8580 | cast<MacroQualifiedType>(type.getTypePtr()), | |||
8581 | attr.getMacroExpansionLoc()); | |||
8582 | } | |||
8583 | } | |||
8584 | } | |||
8585 | ||||
8586 | void Sema::completeExprArrayBound(Expr *E) { | |||
8587 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
8588 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
8589 | if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { | |||
8590 | auto *Def = Var->getDefinition(); | |||
8591 | if (!Def) { | |||
8592 | SourceLocation PointOfInstantiation = E->getExprLoc(); | |||
8593 | runWithSufficientStackSpace(PointOfInstantiation, [&] { | |||
8594 | InstantiateVariableDefinition(PointOfInstantiation, Var); | |||
8595 | }); | |||
8596 | Def = Var->getDefinition(); | |||
8597 | ||||
8598 | // If we don't already have a point of instantiation, and we managed | |||
8599 | // to instantiate a definition, this is the point of instantiation. | |||
8600 | // Otherwise, we don't request an end-of-TU instantiation, so this is | |||
8601 | // not a point of instantiation. | |||
8602 | // FIXME: Is this really the right behavior? | |||
8603 | if (Var->getPointOfInstantiation().isInvalid() && Def) { | |||
8604 | assert(Var->getTemplateSpecializationKind() ==(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "clang/lib/Sema/SemaType.cpp", 8606, __extension__ __PRETTY_FUNCTION__ )) | |||
8605 | TSK_ImplicitInstantiation &&(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "clang/lib/Sema/SemaType.cpp", 8606, __extension__ __PRETTY_FUNCTION__ )) | |||
8606 | "explicit instantiation with no point of instantiation")(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "clang/lib/Sema/SemaType.cpp", 8606, __extension__ __PRETTY_FUNCTION__ )); | |||
8607 | Var->setTemplateSpecializationKind( | |||
8608 | Var->getTemplateSpecializationKind(), PointOfInstantiation); | |||
8609 | } | |||
8610 | } | |||
8611 | ||||
8612 | // Update the type to the definition's type both here and within the | |||
8613 | // expression. | |||
8614 | if (Def) { | |||
8615 | DRE->setDecl(Def); | |||
8616 | QualType T = Def->getType(); | |||
8617 | DRE->setType(T); | |||
8618 | // FIXME: Update the type on all intervening expressions. | |||
8619 | E->setType(T); | |||
8620 | } | |||
8621 | ||||
8622 | // We still go on to try to complete the type independently, as it | |||
8623 | // may also require instantiations or diagnostics if it remains | |||
8624 | // incomplete. | |||
8625 | } | |||
8626 | } | |||
8627 | } | |||
8628 | } | |||
8629 | ||||
8630 | QualType Sema::getCompletedType(Expr *E) { | |||
8631 | // Incomplete array types may be completed by the initializer attached to | |||
8632 | // their definitions. For static data members of class templates and for | |||
8633 | // variable templates, we need to instantiate the definition to get this | |||
8634 | // initializer and complete the type. | |||
8635 | if (E->getType()->isIncompleteArrayType()) | |||
8636 | completeExprArrayBound(E); | |||
8637 | ||||
8638 | // FIXME: Are there other cases which require instantiating something other | |||
8639 | // than the type to complete the type of an expression? | |||
8640 | ||||
8641 | return E->getType(); | |||
8642 | } | |||
8643 | ||||
8644 | /// Ensure that the type of the given expression is complete. | |||
8645 | /// | |||
8646 | /// This routine checks whether the expression \p E has a complete type. If the | |||
8647 | /// expression refers to an instantiable construct, that instantiation is | |||
8648 | /// performed as needed to complete its type. Furthermore | |||
8649 | /// Sema::RequireCompleteType is called for the expression's type (or in the | |||
8650 | /// case of a reference type, the referred-to type). | |||
8651 | /// | |||
8652 | /// \param E The expression whose type is required to be complete. | |||
8653 | /// \param Kind Selects which completeness rules should be applied. | |||
8654 | /// \param Diagnoser The object that will emit a diagnostic if the type is | |||
8655 | /// incomplete. | |||
8656 | /// | |||
8657 | /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false | |||
8658 | /// otherwise. | |||
8659 | bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, | |||
8660 | TypeDiagnoser &Diagnoser) { | |||
8661 | return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind, | |||
8662 | Diagnoser); | |||
8663 | } | |||
8664 | ||||
8665 | bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { | |||
8666 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
8667 | return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); | |||
8668 | } | |||
8669 | ||||
8670 | /// Ensure that the type T is a complete type. | |||
8671 | /// | |||
8672 | /// This routine checks whether the type @p T is complete in any | |||
8673 | /// context where a complete type is required. If @p T is a complete | |||
8674 | /// type, returns false. If @p T is a class template specialization, | |||
8675 | /// this routine then attempts to perform class template | |||
8676 | /// instantiation. If instantiation fails, or if @p T is incomplete | |||
8677 | /// and cannot be completed, issues the diagnostic @p diag (giving it | |||
8678 | /// the type @p T) and returns true. | |||
8679 | /// | |||
8680 | /// @param Loc The location in the source that the incomplete type | |||
8681 | /// diagnostic should refer to. | |||
8682 | /// | |||
8683 | /// @param T The type that this routine is examining for completeness. | |||
8684 | /// | |||
8685 | /// @param Kind Selects which completeness rules should be applied. | |||
8686 | /// | |||
8687 | /// @returns @c true if @p T is incomplete and a diagnostic was emitted, | |||
8688 | /// @c false otherwise. | |||
8689 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | |||
8690 | CompleteTypeKind Kind, | |||
8691 | TypeDiagnoser &Diagnoser) { | |||
8692 | if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser)) | |||
8693 | return true; | |||
8694 | if (const TagType *Tag = T->getAs<TagType>()) { | |||
8695 | if (!Tag->getDecl()->isCompleteDefinitionRequired()) { | |||
8696 | Tag->getDecl()->setCompleteDefinitionRequired(); | |||
8697 | Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); | |||
8698 | } | |||
8699 | } | |||
8700 | return false; | |||
8701 | } | |||
8702 | ||||
8703 | bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { | |||
8704 | llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; | |||
8705 | if (!Suggested) | |||
8706 | return false; | |||
8707 | ||||
8708 | // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext | |||
8709 | // and isolate from other C++ specific checks. | |||
8710 | StructuralEquivalenceContext Ctx( | |||
8711 | D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, | |||
8712 | StructuralEquivalenceKind::Default, | |||
8713 | false /*StrictTypeSpelling*/, true /*Complain*/, | |||
8714 | true /*ErrorOnTagTypeMismatch*/); | |||
8715 | return Ctx.IsEquivalent(D, Suggested); | |||
8716 | } | |||
8717 | ||||
8718 | bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, | |||
8719 | AcceptableKind Kind, bool OnlyNeedComplete) { | |||
8720 | // Easy case: if we don't have modules, all declarations are visible. | |||
8721 | if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) | |||
8722 | return true; | |||
8723 | ||||
8724 | // If this definition was instantiated from a template, map back to the | |||
8725 | // pattern from which it was instantiated. | |||
8726 | if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { | |||
8727 | // We're in the middle of defining it; this definition should be treated | |||
8728 | // as visible. | |||
8729 | return true; | |||
8730 | } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { | |||
8731 | if (auto *Pattern = RD->getTemplateInstantiationPattern()) | |||
8732 | RD = Pattern; | |||
8733 | D = RD->getDefinition(); | |||
8734 | } else if (auto *ED = dyn_cast<EnumDecl>(D)) { | |||
8735 | if (auto *Pattern = ED->getTemplateInstantiationPattern()) | |||
8736 | ED = Pattern; | |||
8737 | if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) { | |||
8738 | // If the enum has a fixed underlying type, it may have been forward | |||
8739 | // declared. In -fms-compatibility, `enum Foo;` will also forward declare | |||
8740 | // the enum and assign it the underlying type of `int`. Since we're only | |||
8741 | // looking for a complete type (not a definition), any visible declaration | |||
8742 | // of it will do. | |||
8743 | *Suggested = nullptr; | |||
8744 | for (auto *Redecl : ED->redecls()) { | |||
8745 | if (isAcceptable(Redecl, Kind)) | |||
8746 | return true; | |||
8747 | if (Redecl->isThisDeclarationADefinition() || | |||
8748 | (Redecl->isCanonicalDecl() && !*Suggested)) | |||
8749 | *Suggested = Redecl; | |||
8750 | } | |||
8751 | ||||
8752 | return false; | |||
8753 | } | |||
8754 | D = ED->getDefinition(); | |||
8755 | } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
8756 | if (auto *Pattern = FD->getTemplateInstantiationPattern()) | |||
8757 | FD = Pattern; | |||
8758 | D = FD->getDefinition(); | |||
8759 | } else if (auto *VD = dyn_cast<VarDecl>(D)) { | |||
8760 | if (auto *Pattern = VD->getTemplateInstantiationPattern()) | |||
8761 | VD = Pattern; | |||
8762 | D = VD->getDefinition(); | |||
8763 | } | |||
8764 | ||||
8765 | assert(D && "missing definition for pattern of instantiated definition")(static_cast <bool> (D && "missing definition for pattern of instantiated definition" ) ? void (0) : __assert_fail ("D && \"missing definition for pattern of instantiated definition\"" , "clang/lib/Sema/SemaType.cpp", 8765, __extension__ __PRETTY_FUNCTION__ )); | |||
8766 | ||||
8767 | *Suggested = D; | |||
8768 | ||||
8769 | auto DefinitionIsAcceptable = [&] { | |||
8770 | // The (primary) definition might be in a visible module. | |||
8771 | if (isAcceptable(D, Kind)) | |||
8772 | return true; | |||
8773 | ||||
8774 | // A visible module might have a merged definition instead. | |||
8775 | if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) | |||
8776 | : hasVisibleMergedDefinition(D)) { | |||
8777 | if (CodeSynthesisContexts.empty() && | |||
8778 | !getLangOpts().ModulesLocalVisibility) { | |||
8779 | // Cache the fact that this definition is implicitly visible because | |||
8780 | // there is a visible merged definition. | |||
8781 | D->setVisibleDespiteOwningModule(); | |||
8782 | } | |||
8783 | return true; | |||
8784 | } | |||
8785 | ||||
8786 | return false; | |||
8787 | }; | |||
8788 | ||||
8789 | if (DefinitionIsAcceptable()) | |||
8790 | return true; | |||
8791 | ||||
8792 | // The external source may have additional definitions of this entity that are | |||
8793 | // visible, so complete the redeclaration chain now and ask again. | |||
8794 | if (auto *Source = Context.getExternalSource()) { | |||
8795 | Source->CompleteRedeclChain(D); | |||
8796 | return DefinitionIsAcceptable(); | |||
8797 | } | |||
8798 | ||||
8799 | return false; | |||
8800 | } | |||
8801 | ||||
8802 | /// Determine whether there is any declaration of \p D that was ever a | |||
8803 | /// definition (perhaps before module merging) and is currently visible. | |||
8804 | /// \param D The definition of the entity. | |||
8805 | /// \param Suggested Filled in with the declaration that should be made visible | |||
8806 | /// in order to provide a definition of this entity. | |||
8807 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, | |||
8808 | /// not defined. This only matters for enums with a fixed underlying | |||
8809 | /// type, since in all other cases, a type is complete if and only if it | |||
8810 | /// is defined. | |||
8811 | bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, | |||
8812 | bool OnlyNeedComplete) { | |||
8813 | return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Visible, | |||
8814 | OnlyNeedComplete); | |||
8815 | } | |||
8816 | ||||
8817 | /// Determine whether there is any declaration of \p D that was ever a | |||
8818 | /// definition (perhaps before module merging) and is currently | |||
8819 | /// reachable. | |||
8820 | /// \param D The definition of the entity. | |||
8821 | /// \param Suggested Filled in with the declaration that should be made | |||
8822 | /// reachable | |||
8823 | /// in order to provide a definition of this entity. | |||
8824 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, | |||
8825 | /// not defined. This only matters for enums with a fixed underlying | |||
8826 | /// type, since in all other cases, a type is complete if and only if it | |||
8827 | /// is defined. | |||
8828 | bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, | |||
8829 | bool OnlyNeedComplete) { | |||
8830 | return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Reachable, | |||
8831 | OnlyNeedComplete); | |||
8832 | } | |||
8833 | ||||
8834 | /// Locks in the inheritance model for the given class and all of its bases. | |||
8835 | static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { | |||
8836 | RD = RD->getMostRecentNonInjectedDecl(); | |||
8837 | if (!RD->hasAttr<MSInheritanceAttr>()) { | |||
8838 | MSInheritanceModel IM; | |||
8839 | bool BestCase = false; | |||
8840 | switch (S.MSPointerToMemberRepresentationMethod) { | |||
8841 | case LangOptions::PPTMK_BestCase: | |||
8842 | BestCase = true; | |||
8843 | IM = RD->calculateInheritanceModel(); | |||
8844 | break; | |||
8845 | case LangOptions::PPTMK_FullGeneralitySingleInheritance: | |||
8846 | IM = MSInheritanceModel::Single; | |||
8847 | break; | |||
8848 | case LangOptions::PPTMK_FullGeneralityMultipleInheritance: | |||
8849 | IM = MSInheritanceModel::Multiple; | |||
8850 | break; | |||
8851 | case LangOptions::PPTMK_FullGeneralityVirtualInheritance: | |||
8852 | IM = MSInheritanceModel::Unspecified; | |||
8853 | break; | |||
8854 | } | |||
8855 | ||||
8856 | SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() | |||
8857 | ? S.ImplicitMSInheritanceAttrLoc | |||
8858 | : RD->getSourceRange(); | |||
8859 | RD->addAttr(MSInheritanceAttr::CreateImplicit( | |||
8860 | S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft, | |||
8861 | MSInheritanceAttr::Spelling(IM))); | |||
8862 | S.Consumer.AssignInheritanceModel(RD); | |||
8863 | } | |||
8864 | } | |||
8865 | ||||
8866 | /// The implementation of RequireCompleteType | |||
8867 | bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, | |||
8868 | CompleteTypeKind Kind, | |||
8869 | TypeDiagnoser *Diagnoser) { | |||
8870 | // FIXME: Add this assertion to make sure we always get instantiation points. | |||
8871 | // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); | |||
8872 | // FIXME: Add this assertion to help us flush out problems with | |||
8873 | // checking for dependent types and type-dependent expressions. | |||
8874 | // | |||
8875 | // assert(!T->isDependentType() && | |||
8876 | // "Can't ask whether a dependent type is complete"); | |||
8877 | ||||
8878 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { | |||
8879 | if (!MPTy->getClass()->isDependentType()) { | |||
8880 | if (getLangOpts().CompleteMemberPointers && | |||
8881 | !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && | |||
8882 | RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind, | |||
8883 | diag::err_memptr_incomplete)) | |||
8884 | return true; | |||
8885 | ||||
8886 | // We lock in the inheritance model once somebody has asked us to ensure | |||
8887 | // that a pointer-to-member type is complete. | |||
8888 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
8889 | (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); | |||
8890 | assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); | |||
8891 | } | |||
8892 | } | |||
8893 | } | |||
8894 | ||||
8895 | NamedDecl *Def = nullptr; | |||
8896 | bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless); | |||
8897 | bool Incomplete = (T->isIncompleteType(&Def) || | |||
8898 | (!AcceptSizeless && T->isSizelessBuiltinType())); | |||
8899 | ||||
8900 | // Check that any necessary explicit specializations are visible. For an | |||
8901 | // enum, we just need the declaration, so don't check this. | |||
8902 | if (Def && !isa<EnumDecl>(Def)) | |||
8903 | checkSpecializationReachability(Loc, Def); | |||
8904 | ||||
8905 | // If we have a complete type, we're done. | |||
8906 | if (!Incomplete) { | |||
8907 | NamedDecl *Suggested = nullptr; | |||
8908 | if (Def && | |||
8909 | !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) { | |||
8910 | // If the user is going to see an error here, recover by making the | |||
8911 | // definition visible. | |||
8912 | bool TreatAsComplete = Diagnoser && !isSFINAEContext(); | |||
8913 | if (Diagnoser && Suggested) | |||
8914 | diagnoseMissingImport(Loc, Suggested, MissingImportKind::Definition, | |||
8915 | /*Recover*/ TreatAsComplete); | |||
8916 | return !TreatAsComplete; | |||
8917 | } else if (Def && !TemplateInstCallbacks.empty()) { | |||
8918 | CodeSynthesisContext TempInst; | |||
8919 | TempInst.Kind = CodeSynthesisContext::Memoization; | |||
8920 | TempInst.Template = Def; | |||
8921 | TempInst.Entity = Def; | |||
8922 | TempInst.PointOfInstantiation = Loc; | |||
8923 | atTemplateBegin(TemplateInstCallbacks, *this, TempInst); | |||
8924 | atTemplateEnd(TemplateInstCallbacks, *this, TempInst); | |||
8925 | } | |||
8926 | ||||
8927 | return false; | |||
8928 | } | |||
8929 | ||||
8930 | TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); | |||
8931 | ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); | |||
8932 | ||||
8933 | // Give the external source a chance to provide a definition of the type. | |||
8934 | // This is kept separate from completing the redeclaration chain so that | |||
8935 | // external sources such as LLDB can avoid synthesizing a type definition | |||
8936 | // unless it's actually needed. | |||
8937 | if (Tag || IFace) { | |||
8938 | // Avoid diagnosing invalid decls as incomplete. | |||
8939 | if (Def->isInvalidDecl()) | |||
8940 | return true; | |||
8941 | ||||
8942 | // Give the external AST source a chance to complete the type. | |||
8943 | if (auto *Source = Context.getExternalSource()) { | |||
8944 | if (Tag && Tag->hasExternalLexicalStorage()) | |||
8945 | Source->CompleteType(Tag); | |||
8946 | if (IFace && IFace->hasExternalLexicalStorage()) | |||
8947 | Source->CompleteType(IFace); | |||
8948 | // If the external source completed the type, go through the motions | |||
8949 | // again to ensure we're allowed to use the completed type. | |||
8950 | if (!T->isIncompleteType()) | |||
8951 | return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); | |||
8952 | } | |||
8953 | } | |||
8954 | ||||
8955 | // If we have a class template specialization or a class member of a | |||
8956 | // class template specialization, or an array with known size of such, | |||
8957 | // try to instantiate it. | |||
8958 | if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { | |||
8959 | bool Instantiated = false; | |||
8960 | bool Diagnosed = false; | |||
8961 | if (RD->isDependentContext()) { | |||
8962 | // Don't try to instantiate a dependent class (eg, a member template of | |||
8963 | // an instantiated class template specialization). | |||
8964 | // FIXME: Can this ever happen? | |||
8965 | } else if (auto *ClassTemplateSpec = | |||
8966 | dyn_cast<ClassTemplateSpecializationDecl>(RD)) { | |||
8967 | if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { | |||
8968 | runWithSufficientStackSpace(Loc, [&] { | |||
8969 | Diagnosed = InstantiateClassTemplateSpecialization( | |||
8970 | Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, | |||
8971 | /*Complain=*/Diagnoser); | |||
8972 | }); | |||
8973 | Instantiated = true; | |||
8974 | } | |||
8975 | } else { | |||
8976 | CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); | |||
8977 | if (!RD->isBeingDefined() && Pattern) { | |||
8978 | MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); | |||
8979 | assert(MSI && "Missing member specialization information?")(static_cast <bool> (MSI && "Missing member specialization information?" ) ? void (0) : __assert_fail ("MSI && \"Missing member specialization information?\"" , "clang/lib/Sema/SemaType.cpp", 8979, __extension__ __PRETTY_FUNCTION__ )); | |||
8980 | // This record was instantiated from a class within a template. | |||
8981 | if (MSI->getTemplateSpecializationKind() != | |||
8982 | TSK_ExplicitSpecialization) { | |||
8983 | runWithSufficientStackSpace(Loc, [&] { | |||
8984 | Diagnosed = InstantiateClass(Loc, RD, Pattern, | |||
8985 | getTemplateInstantiationArgs(RD), | |||
8986 | TSK_ImplicitInstantiation, | |||
8987 | /*Complain=*/Diagnoser); | |||
8988 | }); | |||
8989 | Instantiated = true; | |||
8990 | } | |||
8991 | } | |||
8992 | } | |||
8993 | ||||
8994 | if (Instantiated) { | |||
8995 | // Instantiate* might have already complained that the template is not | |||
8996 | // defined, if we asked it to. | |||
8997 | if (Diagnoser && Diagnosed) | |||
8998 | return true; | |||
8999 | // If we instantiated a definition, check that it's usable, even if | |||
9000 | // instantiation produced an error, so that repeated calls to this | |||
9001 | // function give consistent answers. | |||
9002 | if (!T->isIncompleteType()) | |||
9003 | return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); | |||
9004 | } | |||
9005 | } | |||
9006 | ||||
9007 | // FIXME: If we didn't instantiate a definition because of an explicit | |||
9008 | // specialization declaration, check that it's visible. | |||
9009 | ||||
9010 | if (!Diagnoser) | |||
9011 | return true; | |||
9012 | ||||
9013 | Diagnoser->diagnose(*this, Loc, T); | |||
9014 | ||||
9015 | // If the type was a forward declaration of a class/struct/union | |||
9016 | // type, produce a note. | |||
9017 | if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid()) | |||
9018 | Diag(Tag->getLocation(), | |||
9019 | Tag->isBeingDefined() ? diag::note_type_being_defined | |||
9020 | : diag::note_forward_declaration) | |||
9021 | << Context.getTagDeclType(Tag); | |||
9022 | ||||
9023 | // If the Objective-C class was a forward declaration, produce a note. | |||
9024 | if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid()) | |||
9025 | Diag(IFace->getLocation(), diag::note_forward_class); | |||
9026 | ||||
9027 | // If we have external information that we can use to suggest a fix, | |||
9028 | // produce a note. | |||
9029 | if (ExternalSource) | |||
9030 | ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); | |||
9031 | ||||
9032 | return true; | |||
9033 | } | |||
9034 | ||||
9035 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | |||
9036 | CompleteTypeKind Kind, unsigned DiagID) { | |||
9037 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
9038 | return RequireCompleteType(Loc, T, Kind, Diagnoser); | |||
9039 | } | |||
9040 | ||||
9041 | /// Get diagnostic %select index for tag kind for | |||
9042 | /// literal type diagnostic message. | |||
9043 | /// WARNING: Indexes apply to particular diagnostics only! | |||
9044 | /// | |||
9045 | /// \returns diagnostic %select index. | |||
9046 | static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { | |||
9047 | switch (Tag) { | |||
9048 | case TTK_Struct: return 0; | |||
9049 | case TTK_Interface: return 1; | |||
9050 | case TTK_Class: return 2; | |||
9051 | default: llvm_unreachable("Invalid tag kind for literal type diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for literal type diagnostic!" , "clang/lib/Sema/SemaType.cpp", 9051); | |||
9052 | } | |||
9053 | } | |||
9054 | ||||
9055 | /// Ensure that the type T is a literal type. | |||
9056 | /// | |||
9057 | /// This routine checks whether the type @p T is a literal type. If @p T is an | |||
9058 | /// incomplete type, an attempt is made to complete it. If @p T is a literal | |||
9059 | /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, | |||
9060 | /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving | |||
9061 | /// it the type @p T), along with notes explaining why the type is not a | |||
9062 | /// literal type, and returns true. | |||
9063 | /// | |||
9064 | /// @param Loc The location in the source that the non-literal type | |||
9065 | /// diagnostic should refer to. | |||
9066 | /// | |||
9067 | /// @param T The type that this routine is examining for literalness. | |||
9068 | /// | |||
9069 | /// @param Diagnoser Emits a diagnostic if T is not a literal type. | |||
9070 | /// | |||
9071 | /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, | |||
9072 | /// @c false otherwise. | |||
9073 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, | |||
9074 | TypeDiagnoser &Diagnoser) { | |||
9075 | assert(!T->isDependentType() && "type should not be dependent")(static_cast <bool> (!T->isDependentType() && "type should not be dependent") ? void (0) : __assert_fail ( "!T->isDependentType() && \"type should not be dependent\"" , "clang/lib/Sema/SemaType.cpp", 9075, __extension__ __PRETTY_FUNCTION__ )); | |||
9076 | ||||
9077 | QualType ElemType = Context.getBaseElementType(T); | |||
9078 | if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && | |||
9079 | T->isLiteralType(Context)) | |||
9080 | return false; | |||
9081 | ||||
9082 | Diagnoser.diagnose(*this, Loc, T); | |||
9083 | ||||
9084 | if (T->isVariableArrayType()) | |||
9085 | return true; | |||
9086 | ||||
9087 | const RecordType *RT = ElemType->getAs<RecordType>(); | |||
9088 | if (!RT) | |||
9089 | return true; | |||
9090 | ||||
9091 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
9092 | ||||
9093 | // A partially-defined class type can't be a literal type, because a literal | |||
9094 | // class type must have a trivial destructor (which can't be checked until | |||
9095 | // the class definition is complete). | |||
9096 | if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) | |||
9097 | return true; | |||
9098 | ||||
9099 | // [expr.prim.lambda]p3: | |||
9100 | // This class type is [not] a literal type. | |||
9101 | if (RD->isLambda() && !getLangOpts().CPlusPlus17) { | |||
9102 | Diag(RD->getLocation(), diag::note_non_literal_lambda); | |||
9103 | return true; | |||
9104 | } | |||
9105 | ||||
9106 | // If the class has virtual base classes, then it's not an aggregate, and | |||
9107 | // cannot have any constexpr constructors or a trivial default constructor, | |||
9108 | // so is non-literal. This is better to diagnose than the resulting absence | |||
9109 | // of constexpr constructors. | |||
9110 | if (RD->getNumVBases()) { | |||
9111 | Diag(RD->getLocation(), diag::note_non_literal_virtual_base) | |||
9112 | << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); | |||
9113 | for (const auto &I : RD->vbases()) | |||
9114 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) | |||
9115 | << I.getSourceRange(); | |||
9116 | } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && | |||
9117 | !RD->hasTrivialDefaultConstructor()) { | |||
9118 | Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; | |||
9119 | } else if (RD->hasNonLiteralTypeFieldsOrBases()) { | |||
9120 | for (const auto &I : RD->bases()) { | |||
9121 | if (!I.getType()->isLiteralType(Context)) { | |||
9122 | Diag(I.getBeginLoc(), diag::note_non_literal_base_class) | |||
9123 | << RD << I.getType() << I.getSourceRange(); | |||
9124 | return true; | |||
9125 | } | |||
9126 | } | |||
9127 | for (const auto *I : RD->fields()) { | |||
9128 | if (!I->getType()->isLiteralType(Context) || | |||
9129 | I->getType().isVolatileQualified()) { | |||
9130 | Diag(I->getLocation(), diag::note_non_literal_field) | |||
9131 | << RD << I << I->getType() | |||
9132 | << I->getType().isVolatileQualified(); | |||
9133 | return true; | |||
9134 | } | |||
9135 | } | |||
9136 | } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor() | |||
9137 | : !RD->hasTrivialDestructor()) { | |||
9138 | // All fields and bases are of literal types, so have trivial or constexpr | |||
9139 | // destructors. If this class's destructor is non-trivial / non-constexpr, | |||
9140 | // it must be user-declared. | |||
9141 | CXXDestructorDecl *Dtor = RD->getDestructor(); | |||
9142 | assert(Dtor && "class has literal fields and bases but no dtor?")(static_cast <bool> (Dtor && "class has literal fields and bases but no dtor?" ) ? void (0) : __assert_fail ("Dtor && \"class has literal fields and bases but no dtor?\"" , "clang/lib/Sema/SemaType.cpp", 9142, __extension__ __PRETTY_FUNCTION__ )); | |||
9143 | if (!Dtor) | |||
9144 | return true; | |||
9145 | ||||
9146 | if (getLangOpts().CPlusPlus20) { | |||
9147 | Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) | |||
9148 | << RD; | |||
9149 | } else { | |||
9150 | Diag(Dtor->getLocation(), Dtor->isUserProvided() | |||
9151 | ? diag::note_non_literal_user_provided_dtor | |||
9152 | : diag::note_non_literal_nontrivial_dtor) | |||
9153 | << RD; | |||
9154 | if (!Dtor->isUserProvided()) | |||
9155 | SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, | |||
9156 | /*Diagnose*/ true); | |||
9157 | } | |||
9158 | } | |||
9159 | ||||
9160 | return true; | |||
9161 | } | |||
9162 | ||||
9163 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { | |||
9164 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
9165 | return RequireLiteralType(Loc, T, Diagnoser); | |||
9166 | } | |||
9167 | ||||
9168 | /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified | |||
9169 | /// by the nested-name-specifier contained in SS, and that is (re)declared by | |||
9170 | /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. | |||
9171 | QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, | |||
9172 | const CXXScopeSpec &SS, QualType T, | |||
9173 | TagDecl *OwnedTagDecl) { | |||
9174 | if (T.isNull()) | |||
9175 | return T; | |||
9176 | return Context.getElaboratedType( | |||
9177 | Keyword, SS.isValid() ? SS.getScopeRep() : nullptr, T, OwnedTagDecl); | |||
9178 | } | |||
9179 | ||||
9180 | QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) { | |||
9181 | assert(!E->hasPlaceholderType() && "unexpected placeholder")(static_cast <bool> (!E->hasPlaceholderType() && "unexpected placeholder") ? void (0) : __assert_fail ("!E->hasPlaceholderType() && \"unexpected placeholder\"" , "clang/lib/Sema/SemaType.cpp", 9181, __extension__ __PRETTY_FUNCTION__ )); | |||
9182 | ||||
9183 | if (!getLangOpts().CPlusPlus && E->refersToBitField()) | |||
9184 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) | |||
9185 | << (Kind == TypeOfKind::Unqualified ? 3 : 2); | |||
9186 | ||||
9187 | if (!E->isTypeDependent()) { | |||
9188 | QualType T = E->getType(); | |||
9189 | if (const TagType *TT = T->getAs<TagType>()) | |||
9190 | DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); | |||
9191 | } | |||
9192 | return Context.getTypeOfExprType(E, Kind); | |||
9193 | } | |||
9194 | ||||
9195 | /// getDecltypeForExpr - Given an expr, will return the decltype for | |||
9196 | /// that expression, according to the rules in C++11 | |||
9197 | /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. | |||
9198 | QualType Sema::getDecltypeForExpr(Expr *E) { | |||
9199 | if (E->isTypeDependent()) | |||
9200 | return Context.DependentTy; | |||
9201 | ||||
9202 | Expr *IDExpr = E; | |||
9203 | if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E)) | |||
9204 | IDExpr = ImplCastExpr->getSubExpr(); | |||
9205 | ||||
9206 | // C++11 [dcl.type.simple]p4: | |||
9207 | // The type denoted by decltype(e) is defined as follows: | |||
9208 | ||||
9209 | // C++20: | |||
9210 | // - if E is an unparenthesized id-expression naming a non-type | |||
9211 | // template-parameter (13.2), decltype(E) is the type of the | |||
9212 | // template-parameter after performing any necessary type deduction | |||
9213 | // Note that this does not pick up the implicit 'const' for a template | |||
9214 | // parameter object. This rule makes no difference before C++20 so we apply | |||
9215 | // it unconditionally. | |||
9216 | if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr)) | |||
9217 | return SNTTPE->getParameterType(Context); | |||
9218 | ||||
9219 | // - if e is an unparenthesized id-expression or an unparenthesized class | |||
9220 | // member access (5.2.5), decltype(e) is the type of the entity named | |||
9221 | // by e. If there is no such entity, or if e names a set of overloaded | |||
9222 | // functions, the program is ill-formed; | |||
9223 | // | |||
9224 | // We apply the same rules for Objective-C ivar and property references. | |||
9225 | if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) { | |||
9226 | const ValueDecl *VD = DRE->getDecl(); | |||
9227 | QualType T = VD->getType(); | |||
9228 | return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T; | |||
9229 | } | |||
9230 | if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) { | |||
9231 | if (const auto *VD = ME->getMemberDecl()) | |||
9232 | if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) | |||
9233 | return VD->getType(); | |||
9234 | } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) { | |||
9235 | return IR->getDecl()->getType(); | |||
9236 | } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) { | |||
9237 | if (PR->isExplicitProperty()) | |||
9238 | return PR->getExplicitProperty()->getType(); | |||
9239 | } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) { | |||
9240 | return PE->getType(); | |||
9241 | } | |||
9242 | ||||
9243 | // C++11 [expr.lambda.prim]p18: | |||
9244 | // Every occurrence of decltype((x)) where x is a possibly | |||
9245 | // parenthesized id-expression that names an entity of automatic | |||
9246 | // storage duration is treated as if x were transformed into an | |||
9247 | // access to a corresponding data member of the closure type that | |||
9248 | // would have been declared if x were an odr-use of the denoted | |||
9249 | // entity. | |||
9250 | if (getCurLambda() && isa<ParenExpr>(IDExpr)) { | |||
9251 | if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) { | |||
9252 | if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
9253 | QualType T = getCapturedDeclRefType(Var, DRE->getLocation()); | |||
9254 | if (!T.isNull()) | |||
9255 | return Context.getLValueReferenceType(T); | |||
9256 | } | |||
9257 | } | |||
9258 | } | |||
9259 | ||||
9260 | return Context.getReferenceQualifiedType(E); | |||
9261 | } | |||
9262 | ||||
9263 | QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) { | |||
9264 | assert(!E->hasPlaceholderType() && "unexpected placeholder")(static_cast <bool> (!E->hasPlaceholderType() && "unexpected placeholder") ? void (0) : __assert_fail ("!E->hasPlaceholderType() && \"unexpected placeholder\"" , "clang/lib/Sema/SemaType.cpp", 9264, __extension__ __PRETTY_FUNCTION__ )); | |||
9265 | ||||
9266 | if (AsUnevaluated && CodeSynthesisContexts.empty() && | |||
9267 | !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) { | |||
9268 | // The expression operand for decltype is in an unevaluated expression | |||
9269 | // context, so side effects could result in unintended consequences. | |||
9270 | // Exclude instantiation-dependent expressions, because 'decltype' is often | |||
9271 | // used to build SFINAE gadgets. | |||
9272 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
9273 | } | |||
9274 | return Context.getDecltypeType(E, getDecltypeForExpr(E)); | |||
9275 | } | |||
9276 | ||||
9277 | static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, | |||
9278 | SourceLocation Loc) { | |||
9279 | assert(BaseType->isEnumeralType())(static_cast <bool> (BaseType->isEnumeralType()) ? void (0) : __assert_fail ("BaseType->isEnumeralType()", "clang/lib/Sema/SemaType.cpp" , 9279, __extension__ __PRETTY_FUNCTION__)); | |||
9280 | EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl(); | |||
9281 | assert(ED && "EnumType has no EnumDecl")(static_cast <bool> (ED && "EnumType has no EnumDecl" ) ? void (0) : __assert_fail ("ED && \"EnumType has no EnumDecl\"" , "clang/lib/Sema/SemaType.cpp", 9281, __extension__ __PRETTY_FUNCTION__ )); | |||
9282 | ||||
9283 | S.DiagnoseUseOfDecl(ED, Loc); | |||
9284 | ||||
9285 | QualType Underlying = ED->getIntegerType(); | |||
9286 | assert(!Underlying.isNull())(static_cast <bool> (!Underlying.isNull()) ? void (0) : __assert_fail ("!Underlying.isNull()", "clang/lib/Sema/SemaType.cpp" , 9286, __extension__ __PRETTY_FUNCTION__)); | |||
9287 | ||||
9288 | return Underlying; | |||
9289 | } | |||
9290 | ||||
9291 | QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType, | |||
9292 | SourceLocation Loc) { | |||
9293 | if (!BaseType->isEnumeralType()) { | |||
9294 | Diag(Loc, diag::err_only_enums_have_underlying_types); | |||
9295 | return QualType(); | |||
9296 | } | |||
9297 | ||||
9298 | // The enum could be incomplete if we're parsing its definition or | |||
9299 | // recovering from an error. | |||
9300 | NamedDecl *FwdDecl = nullptr; | |||
9301 | if (BaseType->isIncompleteType(&FwdDecl)) { | |||
9302 | Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; | |||
9303 | Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; | |||
9304 | return QualType(); | |||
9305 | } | |||
9306 | ||||
9307 | return GetEnumUnderlyingType(*this, BaseType, Loc); | |||
9308 | } | |||
9309 | ||||
9310 | QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) { | |||
9311 | QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType() | |||
9312 | ? BuildPointerType(BaseType.getNonReferenceType(), Loc, | |||
9313 | DeclarationName()) | |||
9314 | : BaseType; | |||
9315 | ||||
9316 | return Pointer.isNull() ? QualType() : Pointer; | |||
9317 | } | |||
9318 | ||||
9319 | QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) { | |||
9320 | // We don't want block pointers or ObjectiveC's id type. | |||
9321 | if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType()) | |||
9322 | return BaseType; | |||
9323 | ||||
9324 | return BaseType->getPointeeType(); | |||
9325 | } | |||
9326 | ||||
9327 | QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) { | |||
9328 | QualType Underlying = BaseType.getNonReferenceType(); | |||
9329 | if (Underlying->isArrayType()) | |||
9330 | return Context.getDecayedType(Underlying); | |||
9331 | ||||
9332 | if (Underlying->isFunctionType()) | |||
9333 | return BuiltinAddPointer(BaseType, Loc); | |||
9334 | ||||
9335 | SplitQualType Split = Underlying.getSplitUnqualifiedType(); | |||
9336 | // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is | |||
9337 | // in the same group of qualifiers as 'const' and 'volatile', we're extending | |||
9338 | // '__decay(T)' so that it removes all qualifiers. | |||
9339 | Split.Quals.removeCVRQualifiers(); | |||
9340 | return Context.getQualifiedType(Split); | |||
9341 | } | |||
9342 | ||||
9343 | QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind, | |||
9344 | SourceLocation Loc) { | |||
9345 | assert(LangOpts.CPlusPlus)(static_cast <bool> (LangOpts.CPlusPlus) ? void (0) : __assert_fail ("LangOpts.CPlusPlus", "clang/lib/Sema/SemaType.cpp", 9345, __extension__ __PRETTY_FUNCTION__)); | |||
9346 | QualType Reference = | |||
9347 | BaseType.isReferenceable() | |||
9348 | ? BuildReferenceType(BaseType, | |||
9349 | UKind == UnaryTransformType::AddLvalueReference, | |||
9350 | Loc, DeclarationName()) | |||
9351 | : BaseType; | |||
9352 | return Reference.isNull() ? QualType() : Reference; | |||
9353 | } | |||
9354 | ||||
9355 | QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, | |||
9356 | SourceLocation Loc) { | |||
9357 | if (UKind == UnaryTransformType::RemoveAllExtents) | |||
9358 | return Context.getBaseElementType(BaseType); | |||
9359 | ||||
9360 | if (const auto *AT = Context.getAsArrayType(BaseType)) | |||
9361 | return AT->getElementType(); | |||
9362 | ||||
9363 | return BaseType; | |||
9364 | } | |||
9365 | ||||
9366 | QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind, | |||
9367 | SourceLocation Loc) { | |||
9368 | assert(LangOpts.CPlusPlus)(static_cast <bool> (LangOpts.CPlusPlus) ? void (0) : __assert_fail ("LangOpts.CPlusPlus", "clang/lib/Sema/SemaType.cpp", 9368, __extension__ __PRETTY_FUNCTION__)); | |||
9369 | QualType T = BaseType.getNonReferenceType(); | |||
9370 | if (UKind == UTTKind::RemoveCVRef && | |||
9371 | (T.isConstQualified() || T.isVolatileQualified())) { | |||
9372 | Qualifiers Quals; | |||
9373 | QualType Unqual = Context.getUnqualifiedArrayType(T, Quals); | |||
9374 | Quals.removeConst(); | |||
9375 | Quals.removeVolatile(); | |||
9376 | T = Context.getQualifiedType(Unqual, Quals); | |||
9377 | } | |||
9378 | return T; | |||
9379 | } | |||
9380 | ||||
9381 | QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, | |||
9382 | SourceLocation Loc) { | |||
9383 | if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) || | |||
9384 | BaseType->isFunctionType()) | |||
9385 | return BaseType; | |||
9386 | ||||
9387 | Qualifiers Quals; | |||
9388 | QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals); | |||
9389 | ||||
9390 | if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV) | |||
9391 | Quals.removeConst(); | |||
9392 | if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV) | |||
9393 | Quals.removeVolatile(); | |||
9394 | if (UKind == UTTKind::RemoveRestrict) | |||
9395 | Quals.removeRestrict(); | |||
9396 | ||||
9397 | return Context.getQualifiedType(Unqual, Quals); | |||
9398 | } | |||
9399 | ||||
9400 | static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType, | |||
9401 | bool IsMakeSigned, | |||
9402 | SourceLocation Loc) { | |||
9403 | if (BaseType->isEnumeralType()) { | |||
9404 | QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc); | |||
9405 | if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) { | |||
9406 | unsigned int Bits = BitInt->getNumBits(); | |||
9407 | if (Bits > 1) | |||
9408 | return S.Context.getBitIntType(!IsMakeSigned, Bits); | |||
9409 | ||||
9410 | S.Diag(Loc, diag::err_make_signed_integral_only) | |||
9411 | << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying; | |||
9412 | return QualType(); | |||
9413 | } | |||
9414 | if (Underlying->isBooleanType()) { | |||
9415 | S.Diag(Loc, diag::err_make_signed_integral_only) | |||
9416 | << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1 | |||
9417 | << Underlying; | |||
9418 | return QualType(); | |||
9419 | } | |||
9420 | } | |||
9421 | ||||
9422 | bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type(); | |||
9423 | std::array<CanQualType *, 6> AllSignedIntegers = { | |||
9424 | &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy, | |||
9425 | &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty}; | |||
9426 | ArrayRef<CanQualType *> AvailableSignedIntegers( | |||
9427 | AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported); | |||
9428 | std::array<CanQualType *, 6> AllUnsignedIntegers = { | |||
9429 | &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy, | |||
9430 | &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy, | |||
9431 | &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty}; | |||
9432 | ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(), | |||
9433 | AllUnsignedIntegers.size() - | |||
9434 | Int128Unsupported); | |||
9435 | ArrayRef<CanQualType *> *Consider = | |||
9436 | IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers; | |||
9437 | ||||
9438 | uint64_t BaseSize = S.Context.getTypeSize(BaseType); | |||
9439 | auto *Result = | |||
9440 | llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) { | |||
9441 | return BaseSize == S.Context.getTypeSize(T->getTypePtr()); | |||
9442 | }); | |||
9443 | ||||
9444 | assert(Result != Consider->end())(static_cast <bool> (Result != Consider->end()) ? void (0) : __assert_fail ("Result != Consider->end()", "clang/lib/Sema/SemaType.cpp" , 9444, __extension__ __PRETTY_FUNCTION__)); | |||
9445 | return QualType((*Result)->getTypePtr(), 0); | |||
9446 | } | |||
9447 | ||||
9448 | QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, | |||
9449 | SourceLocation Loc) { | |||
9450 | bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned; | |||
9451 | if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) || | |||
9452 | BaseType->isBooleanType() || | |||
9453 | (BaseType->isBitIntType() && | |||
9454 | BaseType->getAs<BitIntType>()->getNumBits() < 2)) { | |||
9455 | Diag(Loc, diag::err_make_signed_integral_only) | |||
9456 | << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0; | |||
9457 | return QualType(); | |||
9458 | } | |||
9459 | ||||
9460 | bool IsNonIntIntegral = | |||
9461 | BaseType->isChar16Type() || BaseType->isChar32Type() || | |||
9462 | BaseType->isWideCharType() || BaseType->isEnumeralType(); | |||
9463 | ||||
9464 | QualType Underlying = | |||
9465 | IsNonIntIntegral | |||
9466 | ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc) | |||
9467 | : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType) | |||
9468 | : Context.getCorrespondingUnsignedType(BaseType); | |||
9469 | if (Underlying.isNull()) | |||
9470 | return Underlying; | |||
9471 | return Context.getQualifiedType(Underlying, BaseType.getQualifiers()); | |||
9472 | } | |||
9473 | ||||
9474 | QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind, | |||
9475 | SourceLocation Loc) { | |||
9476 | if (BaseType->isDependentType()) | |||
9477 | return Context.getUnaryTransformType(BaseType, BaseType, UKind); | |||
9478 | QualType Result; | |||
9479 | switch (UKind) { | |||
9480 | case UnaryTransformType::EnumUnderlyingType: { | |||
9481 | Result = BuiltinEnumUnderlyingType(BaseType, Loc); | |||
9482 | break; | |||
9483 | } | |||
9484 | case UnaryTransformType::AddPointer: { | |||
9485 | Result = BuiltinAddPointer(BaseType, Loc); | |||
9486 | break; | |||
9487 | } | |||
9488 | case UnaryTransformType::RemovePointer: { | |||
9489 | Result = BuiltinRemovePointer(BaseType, Loc); | |||
9490 | break; | |||
9491 | } | |||
9492 | case UnaryTransformType::Decay: { | |||
9493 | Result = BuiltinDecay(BaseType, Loc); | |||
9494 | break; | |||
9495 | } | |||
9496 | case UnaryTransformType::AddLvalueReference: | |||
9497 | case UnaryTransformType::AddRvalueReference: { | |||
9498 | Result = BuiltinAddReference(BaseType, UKind, Loc); | |||
9499 | break; | |||
9500 | } | |||
9501 | case UnaryTransformType::RemoveAllExtents: | |||
9502 | case UnaryTransformType::RemoveExtent: { | |||
9503 | Result = BuiltinRemoveExtent(BaseType, UKind, Loc); | |||
9504 | break; | |||
9505 | } | |||
9506 | case UnaryTransformType::RemoveCVRef: | |||
9507 | case UnaryTransformType::RemoveReference: { | |||
9508 | Result = BuiltinRemoveReference(BaseType, UKind, Loc); | |||
9509 | break; | |||
9510 | } | |||
9511 | case UnaryTransformType::RemoveConst: | |||
9512 | case UnaryTransformType::RemoveCV: | |||
9513 | case UnaryTransformType::RemoveRestrict: | |||
9514 | case UnaryTransformType::RemoveVolatile: { | |||
9515 | Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc); | |||
9516 | break; | |||
9517 | } | |||
9518 | case UnaryTransformType::MakeSigned: | |||
9519 | case UnaryTransformType::MakeUnsigned: { | |||
9520 | Result = BuiltinChangeSignedness(BaseType, UKind, Loc); | |||
9521 | break; | |||
9522 | } | |||
9523 | } | |||
9524 | ||||
9525 | return !Result.isNull() | |||
9526 | ? Context.getUnaryTransformType(BaseType, Result, UKind) | |||
9527 | : Result; | |||
9528 | } | |||
9529 | ||||
9530 | QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { | |||
9531 | if (!isDependentOrGNUAutoType(T)) { | |||
9532 | // FIXME: It isn't entirely clear whether incomplete atomic types | |||
9533 | // are allowed or not; for simplicity, ban them for the moment. | |||
9534 | if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) | |||
9535 | return QualType(); | |||
9536 | ||||
9537 | int DisallowedKind = -1; | |||
9538 | if (T->isArrayType()) | |||
9539 | DisallowedKind = 1; | |||
9540 | else if (T->isFunctionType()) | |||
9541 | DisallowedKind = 2; | |||
9542 | else if (T->isReferenceType()) | |||
9543 | DisallowedKind = 3; | |||
9544 | else if (T->isAtomicType()) | |||
9545 | DisallowedKind = 4; | |||
9546 | else if (T.hasQualifiers()) | |||
9547 | DisallowedKind = 5; | |||
9548 | else if (T->isSizelessType()) | |||
9549 | DisallowedKind = 6; | |||
9550 | else if (!T.isTriviallyCopyableType(Context)) | |||
9551 | // Some other non-trivially-copyable type (probably a C++ class) | |||
9552 | DisallowedKind = 7; | |||
9553 | else if (T->isBitIntType()) | |||
9554 | DisallowedKind = 8; | |||
9555 | ||||
9556 | if (DisallowedKind != -1) { | |||
9557 | Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; | |||
9558 | return QualType(); | |||
9559 | } | |||
9560 | ||||
9561 | // FIXME: Do we need any handling for ARC here? | |||
9562 | } | |||
9563 | ||||
9564 | // Build the pointer type. | |||
9565 | return Context.getAtomicType(T); | |||
9566 | } |