File: | clang/lib/Analysis/CalledOnceCheck.cpp |
Warning: | line 934, column 12 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- CalledOnceCheck.cpp - Check 'called once' parameters ---------------===// | ||||
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 | #include "clang/Analysis/Analyses/CalledOnceCheck.h" | ||||
10 | #include "clang/AST/Attr.h" | ||||
11 | #include "clang/AST/Decl.h" | ||||
12 | #include "clang/AST/DeclBase.h" | ||||
13 | #include "clang/AST/Expr.h" | ||||
14 | #include "clang/AST/ExprObjC.h" | ||||
15 | #include "clang/AST/OperationKinds.h" | ||||
16 | #include "clang/AST/ParentMap.h" | ||||
17 | #include "clang/AST/RecursiveASTVisitor.h" | ||||
18 | #include "clang/AST/Stmt.h" | ||||
19 | #include "clang/AST/StmtObjC.h" | ||||
20 | #include "clang/AST/StmtVisitor.h" | ||||
21 | #include "clang/AST/Type.h" | ||||
22 | #include "clang/Analysis/AnalysisDeclContext.h" | ||||
23 | #include "clang/Analysis/CFG.h" | ||||
24 | #include "clang/Analysis/FlowSensitive/DataflowWorklist.h" | ||||
25 | #include "clang/Basic/IdentifierTable.h" | ||||
26 | #include "clang/Basic/LLVM.h" | ||||
27 | #include "llvm/ADT/BitVector.h" | ||||
28 | #include "llvm/ADT/BitmaskEnum.h" | ||||
29 | #include "llvm/ADT/Optional.h" | ||||
30 | #include "llvm/ADT/PointerIntPair.h" | ||||
31 | #include "llvm/ADT/STLExtras.h" | ||||
32 | #include "llvm/ADT/Sequence.h" | ||||
33 | #include "llvm/ADT/SmallVector.h" | ||||
34 | #include "llvm/ADT/StringRef.h" | ||||
35 | #include "llvm/Support/Casting.h" | ||||
36 | #include "llvm/Support/Compiler.h" | ||||
37 | #include "llvm/Support/ErrorHandling.h" | ||||
38 | #include <memory> | ||||
39 | |||||
40 | using namespace clang; | ||||
41 | |||||
42 | namespace { | ||||
43 | static constexpr unsigned EXPECTED_MAX_NUMBER_OF_PARAMS = 2; | ||||
44 | template <class T> | ||||
45 | using ParamSizedVector = llvm::SmallVector<T, EXPECTED_MAX_NUMBER_OF_PARAMS>; | ||||
46 | static constexpr unsigned EXPECTED_NUMBER_OF_BASIC_BLOCKS = 8; | ||||
47 | template <class T> | ||||
48 | using CFGSizedVector = llvm::SmallVector<T, EXPECTED_NUMBER_OF_BASIC_BLOCKS>; | ||||
49 | constexpr llvm::StringLiteral CONVENTIONAL_NAMES[] = { | ||||
50 | "completionHandler", "completion", "withCompletionHandler"}; | ||||
51 | constexpr llvm::StringLiteral CONVENTIONAL_SUFFIXES[] = { | ||||
52 | "WithCompletionHandler", "WithCompletion"}; | ||||
53 | constexpr llvm::StringLiteral CONVENTIONAL_CONDITIONS[] = { | ||||
54 | "error", "cancel", "shouldCall", "done", "OK", "success"}; | ||||
55 | |||||
56 | class ParameterStatus { | ||||
57 | public: | ||||
58 | // Status kind is basically the main part of parameter's status. | ||||
59 | // The kind represents our knowledge (so far) about a tracked parameter | ||||
60 | // in the context of this analysis. | ||||
61 | // | ||||
62 | // Since we want to report on missing and extraneous calls, we need to | ||||
63 | // track the fact whether paramater was called or not. This automatically | ||||
64 | // decides two kinds: `NotCalled` and `Called`. | ||||
65 | // | ||||
66 | // One of the erroneous situations is the case when parameter is called only | ||||
67 | // on some of the paths. We could've considered it `NotCalled`, but we want | ||||
68 | // to report double call warnings even if these two calls are not guaranteed | ||||
69 | // to happen in every execution. We also don't want to have it as `Called` | ||||
70 | // because not calling tracked parameter on all of the paths is an error | ||||
71 | // on its own. For these reasons, we need to have a separate kind, | ||||
72 | // `MaybeCalled`, and change `Called` to `DefinitelyCalled` to avoid | ||||
73 | // confusion. | ||||
74 | // | ||||
75 | // Two violations of calling parameter more than once and not calling it on | ||||
76 | // every path are not, however, mutually exclusive. In situations where both | ||||
77 | // violations take place, we prefer to report ONLY double call. It's always | ||||
78 | // harder to pinpoint a bug that has arisen when a user neglects to take the | ||||
79 | // right action (and therefore, no action is taken), than when a user takes | ||||
80 | // the wrong action. And, in order to remember that we already reported | ||||
81 | // a double call, we need another kind: `Reported`. | ||||
82 | // | ||||
83 | // Our analysis is intra-procedural and, while in the perfect world, | ||||
84 | // developers only use tracked parameters to call them, in the real world, | ||||
85 | // the picture might be different. Parameters can be stored in global | ||||
86 | // variables or leaked into other functions that we know nothing about. | ||||
87 | // We try to be lenient and trust users. Another kind `Escaped` reflects | ||||
88 | // such situations. We don't know if it gets called there or not, but we | ||||
89 | // should always think of `Escaped` as the best possible option. | ||||
90 | // | ||||
91 | // Some of the paths in the analyzed functions might end with a call | ||||
92 | // to noreturn functions. Such paths are not required to have parameter | ||||
93 | // calls and we want to track that. For the purposes of better diagnostics, | ||||
94 | // we don't want to reuse `Escaped` and, thus, have another kind `NoReturn`. | ||||
95 | // | ||||
96 | // Additionally, we have `NotVisited` kind that tells us nothing about | ||||
97 | // a tracked parameter, but is used for tracking analyzed (aka visited) | ||||
98 | // basic blocks. | ||||
99 | // | ||||
100 | // If we consider `|` to be a JOIN operation of two kinds coming from | ||||
101 | // two different paths, the following properties must hold: | ||||
102 | // | ||||
103 | // 1. for any Kind K: K | K == K | ||||
104 | // Joining two identical kinds should result in the same kind. | ||||
105 | // | ||||
106 | // 2. for any Kind K: Reported | K == Reported | ||||
107 | // Doesn't matter on which path it was reported, it still is. | ||||
108 | // | ||||
109 | // 3. for any Kind K: NoReturn | K == K | ||||
110 | // We can totally ignore noreturn paths during merges. | ||||
111 | // | ||||
112 | // 4. DefinitelyCalled | NotCalled == MaybeCalled | ||||
113 | // Called on one path, not called on another - that's simply | ||||
114 | // a definition for MaybeCalled. | ||||
115 | // | ||||
116 | // 5. for any Kind K in [DefinitelyCalled, NotCalled, MaybeCalled]: | ||||
117 | // Escaped | K == K | ||||
118 | // Escaped mirrors other statuses after joins. | ||||
119 | // Every situation, when we join any of the listed kinds K, | ||||
120 | // is a violation. For this reason, in order to assume the | ||||
121 | // best outcome for this escape, we consider it to be the | ||||
122 | // same as the other path. | ||||
123 | // | ||||
124 | // 6. for any Kind K in [DefinitelyCalled, NotCalled]: | ||||
125 | // MaybeCalled | K == MaybeCalled | ||||
126 | // MaybeCalled should basically stay after almost every join. | ||||
127 | enum Kind { | ||||
128 | // No-return paths should be absolutely transparent for the analysis. | ||||
129 | // 0x0 is the identity element for selected join operation (binary or). | ||||
130 | NoReturn = 0x0, /* 0000 */ | ||||
131 | // Escaped marks situations when marked parameter escaped into | ||||
132 | // another function (so we can assume that it was possibly called there). | ||||
133 | Escaped = 0x1, /* 0001 */ | ||||
134 | // Parameter was definitely called once at this point. | ||||
135 | DefinitelyCalled = 0x3, /* 0011 */ | ||||
136 | // Kinds less or equal to NON_ERROR_STATUS are not considered errors. | ||||
137 | NON_ERROR_STATUS = DefinitelyCalled, | ||||
138 | // Parameter was not yet called. | ||||
139 | NotCalled = 0x5, /* 0101 */ | ||||
140 | // Parameter was not called at least on one path leading to this point, | ||||
141 | // while there is also at least one path that it gets called. | ||||
142 | MaybeCalled = 0x7, /* 0111 */ | ||||
143 | // Parameter was not yet analyzed. | ||||
144 | NotVisited = 0x8, /* 1000 */ | ||||
145 | // We already reported a violation and stopped tracking calls for this | ||||
146 | // parameter. | ||||
147 | Reported = 0x15, /* 1111 */ | ||||
148 | LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ Reported)LLVM_BITMASK_LARGEST_ENUMERATOR = Reported | ||||
149 | }; | ||||
150 | |||||
151 | constexpr ParameterStatus() = default; | ||||
152 | /* implicit */ ParameterStatus(Kind K) : StatusKind(K) { | ||||
153 | assert(!seenAnyCalls(K) && "Can't initialize status without a call")((!seenAnyCalls(K) && "Can't initialize status without a call" ) ? static_cast<void> (0) : __assert_fail ("!seenAnyCalls(K) && \"Can't initialize status without a call\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 153, __PRETTY_FUNCTION__)); | ||||
154 | } | ||||
155 | ParameterStatus(Kind K, const Expr *Call) : StatusKind(K), Call(Call) { | ||||
156 | assert(seenAnyCalls(K) && "This kind is not supposed to have a call")((seenAnyCalls(K) && "This kind is not supposed to have a call" ) ? static_cast<void> (0) : __assert_fail ("seenAnyCalls(K) && \"This kind is not supposed to have a call\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 156, __PRETTY_FUNCTION__)); | ||||
157 | } | ||||
158 | |||||
159 | const Expr &getCall() const { | ||||
160 | assert(seenAnyCalls(getKind()) && "ParameterStatus doesn't have a call")((seenAnyCalls(getKind()) && "ParameterStatus doesn't have a call" ) ? static_cast<void> (0) : __assert_fail ("seenAnyCalls(getKind()) && \"ParameterStatus doesn't have a call\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 160, __PRETTY_FUNCTION__)); | ||||
161 | return *Call; | ||||
162 | } | ||||
163 | static bool seenAnyCalls(Kind K) { | ||||
164 | return (K & DefinitelyCalled) == DefinitelyCalled && K != Reported; | ||||
165 | } | ||||
166 | bool seenAnyCalls() const { return seenAnyCalls(getKind()); } | ||||
167 | |||||
168 | static bool isErrorStatus(Kind K) { return K > NON_ERROR_STATUS; } | ||||
169 | bool isErrorStatus() const { return isErrorStatus(getKind()); } | ||||
170 | |||||
171 | Kind getKind() const { return StatusKind; } | ||||
172 | |||||
173 | void join(const ParameterStatus &Other) { | ||||
174 | // If we have a pointer already, let's keep it. | ||||
175 | // For the purposes of the analysis, it doesn't really matter | ||||
176 | // which call we report. | ||||
177 | // | ||||
178 | // If we don't have a pointer, let's take whatever gets joined. | ||||
179 | if (!Call) { | ||||
180 | Call = Other.Call; | ||||
181 | } | ||||
182 | // Join kinds. | ||||
183 | StatusKind |= Other.getKind(); | ||||
184 | } | ||||
185 | |||||
186 | bool operator==(const ParameterStatus &Other) const { | ||||
187 | // We compare only kinds, pointers on their own is only additional | ||||
188 | // information. | ||||
189 | return getKind() == Other.getKind(); | ||||
190 | } | ||||
191 | |||||
192 | private: | ||||
193 | // It would've been a perfect place to use llvm::PointerIntPair, but | ||||
194 | // unfortunately NumLowBitsAvailable for clang::Expr had been reduced to 2. | ||||
195 | Kind StatusKind = NotVisited; | ||||
196 | const Expr *Call = nullptr; | ||||
197 | }; | ||||
198 | |||||
199 | /// State aggregates statuses of all tracked parameters. | ||||
200 | class State { | ||||
201 | public: | ||||
202 | State(unsigned Size, ParameterStatus::Kind K = ParameterStatus::NotVisited) | ||||
203 | : ParamData(Size, K) {} | ||||
204 | |||||
205 | /// Return status of a parameter with the given index. | ||||
206 | /// \{ | ||||
207 | ParameterStatus &getStatusFor(unsigned Index) { return ParamData[Index]; } | ||||
208 | const ParameterStatus &getStatusFor(unsigned Index) const { | ||||
209 | return ParamData[Index]; | ||||
210 | } | ||||
211 | /// \} | ||||
212 | |||||
213 | /// Return true if parameter with the given index can be called. | ||||
214 | bool seenAnyCalls(unsigned Index) const { | ||||
215 | return getStatusFor(Index).seenAnyCalls(); | ||||
216 | } | ||||
217 | /// Return a reference that we consider a call. | ||||
218 | /// | ||||
219 | /// Should only be used for parameters that can be called. | ||||
220 | const Expr &getCallFor(unsigned Index) const { | ||||
221 | return getStatusFor(Index).getCall(); | ||||
222 | } | ||||
223 | /// Return status kind of parameter with the given index. | ||||
224 | ParameterStatus::Kind getKindFor(unsigned Index) const { | ||||
225 | return getStatusFor(Index).getKind(); | ||||
226 | } | ||||
227 | |||||
228 | bool isVisited() const { | ||||
229 | return llvm::all_of(ParamData, [](const ParameterStatus &S) { | ||||
230 | return S.getKind() != ParameterStatus::NotVisited; | ||||
231 | }); | ||||
232 | } | ||||
233 | |||||
234 | // Join other state into the current state. | ||||
235 | void join(const State &Other) { | ||||
236 | assert(ParamData.size() == Other.ParamData.size() &&((ParamData.size() == Other.ParamData.size() && "Couldn't join statuses with different sizes" ) ? static_cast<void> (0) : __assert_fail ("ParamData.size() == Other.ParamData.size() && \"Couldn't join statuses with different sizes\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 237, __PRETTY_FUNCTION__)) | ||||
237 | "Couldn't join statuses with different sizes")((ParamData.size() == Other.ParamData.size() && "Couldn't join statuses with different sizes" ) ? static_cast<void> (0) : __assert_fail ("ParamData.size() == Other.ParamData.size() && \"Couldn't join statuses with different sizes\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 237, __PRETTY_FUNCTION__)); | ||||
238 | for (auto Pair : llvm::zip(ParamData, Other.ParamData)) { | ||||
239 | std::get<0>(Pair).join(std::get<1>(Pair)); | ||||
240 | } | ||||
241 | } | ||||
242 | |||||
243 | using iterator = ParamSizedVector<ParameterStatus>::iterator; | ||||
244 | using const_iterator = ParamSizedVector<ParameterStatus>::const_iterator; | ||||
245 | |||||
246 | iterator begin() { return ParamData.begin(); } | ||||
247 | iterator end() { return ParamData.end(); } | ||||
248 | |||||
249 | const_iterator begin() const { return ParamData.begin(); } | ||||
250 | const_iterator end() const { return ParamData.end(); } | ||||
251 | |||||
252 | bool operator==(const State &Other) const { | ||||
253 | return ParamData == Other.ParamData; | ||||
254 | } | ||||
255 | |||||
256 | private: | ||||
257 | ParamSizedVector<ParameterStatus> ParamData; | ||||
258 | }; | ||||
259 | |||||
260 | /// A simple class that finds DeclRefExpr in the given expression. | ||||
261 | /// | ||||
262 | /// However, we don't want to find ANY nested DeclRefExpr skipping whatever | ||||
263 | /// expressions on our way. Only certain expressions considered "no-op" | ||||
264 | /// for our task are indeed skipped. | ||||
265 | class DeclRefFinder | ||||
266 | : public ConstStmtVisitor<DeclRefFinder, const DeclRefExpr *> { | ||||
267 | public: | ||||
268 | /// Find a DeclRefExpr in the given expression. | ||||
269 | /// | ||||
270 | /// In its most basic form (ShouldRetrieveFromComparisons == false), | ||||
271 | /// this function can be simply reduced to the following question: | ||||
272 | /// | ||||
273 | /// - If expression E is used as a function argument, could we say | ||||
274 | /// that DeclRefExpr nested in E is used as an argument? | ||||
275 | /// | ||||
276 | /// According to this rule, we can say that parens, casts and dereferencing | ||||
277 | /// (dereferencing only applied to function pointers, but this is our case) | ||||
278 | /// can be skipped. | ||||
279 | /// | ||||
280 | /// When we should look into comparisons the question changes to: | ||||
281 | /// | ||||
282 | /// - If expression E is used as a condition, could we say that | ||||
283 | /// DeclRefExpr is being checked? | ||||
284 | /// | ||||
285 | /// And even though, these are two different questions, they have quite a lot | ||||
286 | /// in common. Actually, we can say that whatever expression answers | ||||
287 | /// positively the first question also fits the second question as well. | ||||
288 | /// | ||||
289 | /// In addition, we skip binary operators == and !=, and unary opeartor !. | ||||
290 | static const DeclRefExpr *find(const Expr *E, | ||||
291 | bool ShouldRetrieveFromComparisons = false) { | ||||
292 | return DeclRefFinder(ShouldRetrieveFromComparisons).Visit(E); | ||||
293 | } | ||||
294 | |||||
295 | const DeclRefExpr *VisitDeclRefExpr(const DeclRefExpr *DR) { return DR; } | ||||
296 | |||||
297 | const DeclRefExpr *VisitUnaryOperator(const UnaryOperator *UO) { | ||||
298 | switch (UO->getOpcode()) { | ||||
299 | case UO_LNot: | ||||
300 | // We care about logical not only if we care about comparisons. | ||||
301 | if (!ShouldRetrieveFromComparisons) | ||||
302 | return nullptr; | ||||
303 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
304 | // Function pointer/references can be dereferenced before a call. | ||||
305 | // That doesn't make it, however, any different from a regular call. | ||||
306 | // For this reason, dereference operation is a "no-op". | ||||
307 | case UO_Deref: | ||||
308 | return Visit(UO->getSubExpr()); | ||||
309 | default: | ||||
310 | return nullptr; | ||||
311 | } | ||||
312 | } | ||||
313 | |||||
314 | const DeclRefExpr *VisitBinaryOperator(const BinaryOperator *BO) { | ||||
315 | if (!ShouldRetrieveFromComparisons) | ||||
316 | return nullptr; | ||||
317 | |||||
318 | switch (BO->getOpcode()) { | ||||
319 | case BO_EQ: | ||||
320 | case BO_NE: { | ||||
321 | const DeclRefExpr *LHS = Visit(BO->getLHS()); | ||||
322 | return LHS ? LHS : Visit(BO->getRHS()); | ||||
323 | } | ||||
324 | default: | ||||
325 | return nullptr; | ||||
326 | } | ||||
327 | } | ||||
328 | |||||
329 | const DeclRefExpr *VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) { | ||||
330 | return Visit(OVE->getSourceExpr()); | ||||
331 | } | ||||
332 | |||||
333 | const DeclRefExpr *VisitExpr(const Expr *E) { | ||||
334 | // It is a fallback method that gets called whenever the actual type | ||||
335 | // of the given expression is not covered. | ||||
336 | // | ||||
337 | // We first check if we have anything to skip. And then repeat the whole | ||||
338 | // procedure for a nested expression instead. | ||||
339 | const Expr *DeclutteredExpr = E->IgnoreParenCasts(); | ||||
340 | return E != DeclutteredExpr ? Visit(DeclutteredExpr) : nullptr; | ||||
341 | } | ||||
342 | |||||
343 | private: | ||||
344 | DeclRefFinder(bool ShouldRetrieveFromComparisons) | ||||
345 | : ShouldRetrieveFromComparisons(ShouldRetrieveFromComparisons) {} | ||||
346 | |||||
347 | bool ShouldRetrieveFromComparisons; | ||||
348 | }; | ||||
349 | |||||
350 | const DeclRefExpr *findDeclRefExpr(const Expr *In, | ||||
351 | bool ShouldRetrieveFromComparisons = false) { | ||||
352 | return DeclRefFinder::find(In, ShouldRetrieveFromComparisons); | ||||
353 | } | ||||
354 | |||||
355 | const ParmVarDecl * | ||||
356 | findReferencedParmVarDecl(const Expr *In, | ||||
357 | bool ShouldRetrieveFromComparisons = false) { | ||||
358 | if (const DeclRefExpr *DR = | ||||
359 | findDeclRefExpr(In, ShouldRetrieveFromComparisons)) { | ||||
360 | return dyn_cast<ParmVarDecl>(DR->getDecl()); | ||||
361 | } | ||||
362 | |||||
363 | return nullptr; | ||||
364 | } | ||||
365 | |||||
366 | /// Return conditions expression of a statement if it has one. | ||||
367 | const Expr *getCondition(const Stmt *S) { | ||||
368 | if (!S) { | ||||
369 | return nullptr; | ||||
370 | } | ||||
371 | |||||
372 | if (const auto *If = dyn_cast<IfStmt>(S)) { | ||||
373 | return If->getCond(); | ||||
374 | } | ||||
375 | if (const auto *Ternary = dyn_cast<AbstractConditionalOperator>(S)) { | ||||
376 | return Ternary->getCond(); | ||||
377 | } | ||||
378 | |||||
379 | return nullptr; | ||||
380 | } | ||||
381 | |||||
382 | /// A small helper class that collects all named identifiers in the given | ||||
383 | /// expression. It traverses it recursively, so names from deeper levels | ||||
384 | /// of the AST will end up in the results. | ||||
385 | /// Results might have duplicate names, if this is a problem, convert to | ||||
386 | /// string sets afterwards. | ||||
387 | class NamesCollector : public RecursiveASTVisitor<NamesCollector> { | ||||
388 | public: | ||||
389 | static constexpr unsigned EXPECTED_NUMBER_OF_NAMES = 5; | ||||
390 | using NameCollection = | ||||
391 | llvm::SmallVector<llvm::StringRef, EXPECTED_NUMBER_OF_NAMES>; | ||||
392 | |||||
393 | static NameCollection collect(const Expr *From) { | ||||
394 | NamesCollector Impl; | ||||
395 | Impl.TraverseStmt(const_cast<Expr *>(From)); | ||||
396 | return Impl.Result; | ||||
397 | } | ||||
398 | |||||
399 | bool VisitDeclRefExpr(const DeclRefExpr *E) { | ||||
400 | Result.push_back(E->getDecl()->getName()); | ||||
401 | return true; | ||||
402 | } | ||||
403 | |||||
404 | bool VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) { | ||||
405 | llvm::StringRef Name; | ||||
406 | |||||
407 | if (E->isImplicitProperty()) { | ||||
408 | ObjCMethodDecl *PropertyMethodDecl = nullptr; | ||||
409 | if (E->isMessagingGetter()) { | ||||
410 | PropertyMethodDecl = E->getImplicitPropertyGetter(); | ||||
411 | } else { | ||||
412 | PropertyMethodDecl = E->getImplicitPropertySetter(); | ||||
413 | } | ||||
414 | assert(PropertyMethodDecl &&((PropertyMethodDecl && "Implicit property must have associated declaration" ) ? static_cast<void> (0) : __assert_fail ("PropertyMethodDecl && \"Implicit property must have associated declaration\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 415, __PRETTY_FUNCTION__)) | ||||
415 | "Implicit property must have associated declaration")((PropertyMethodDecl && "Implicit property must have associated declaration" ) ? static_cast<void> (0) : __assert_fail ("PropertyMethodDecl && \"Implicit property must have associated declaration\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 415, __PRETTY_FUNCTION__)); | ||||
416 | Name = PropertyMethodDecl->getSelector().getNameForSlot(0); | ||||
417 | } else { | ||||
418 | assert(E->isExplicitProperty())((E->isExplicitProperty()) ? static_cast<void> (0) : __assert_fail ("E->isExplicitProperty()", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 418, __PRETTY_FUNCTION__)); | ||||
419 | Name = E->getExplicitProperty()->getName(); | ||||
420 | } | ||||
421 | |||||
422 | Result.push_back(Name); | ||||
423 | return true; | ||||
424 | } | ||||
425 | |||||
426 | private: | ||||
427 | NamesCollector() = default; | ||||
428 | NameCollection Result; | ||||
429 | }; | ||||
430 | |||||
431 | /// Check whether the given expression mentions any of conventional names. | ||||
432 | bool mentionsAnyOfConventionalNames(const Expr *E) { | ||||
433 | NamesCollector::NameCollection MentionedNames = NamesCollector::collect(E); | ||||
434 | |||||
435 | return llvm::any_of(MentionedNames, [](llvm::StringRef ConditionName) { | ||||
436 | return llvm::any_of( | ||||
437 | CONVENTIONAL_CONDITIONS, | ||||
438 | [ConditionName](const llvm::StringLiteral &Conventional) { | ||||
439 | return ConditionName.contains_lower(Conventional); | ||||
440 | }); | ||||
441 | }); | ||||
442 | } | ||||
443 | |||||
444 | /// Clarification is a simple pair of a reason why parameter is not called | ||||
445 | /// on every path and a statement to blame. | ||||
446 | struct Clarification { | ||||
447 | NeverCalledReason Reason; | ||||
448 | const Stmt *Location; | ||||
449 | }; | ||||
450 | |||||
451 | /// A helper class that can produce a clarification based on the given pair | ||||
452 | /// of basic blocks. | ||||
453 | class NotCalledClarifier | ||||
454 | : public ConstStmtVisitor<NotCalledClarifier, | ||||
455 | llvm::Optional<Clarification>> { | ||||
456 | public: | ||||
457 | /// The main entrypoint for the class, the function that tries to find the | ||||
458 | /// clarification of how to explain which sub-path starts with a CFG edge | ||||
459 | /// from Conditional to SuccWithoutCall. | ||||
460 | /// | ||||
461 | /// This means that this function has one precondition: | ||||
462 | /// SuccWithoutCall should be a successor block for Conditional. | ||||
463 | /// | ||||
464 | /// Because clarification is not needed for non-trivial pairs of blocks | ||||
465 | /// (i.e. SuccWithoutCall is not the only successor), it returns meaningful | ||||
466 | /// results only for such cases. For this very reason, the parent basic | ||||
467 | /// block, Conditional, is named that way, so it is clear what kind of | ||||
468 | /// block is expected. | ||||
469 | static llvm::Optional<Clarification> | ||||
470 | clarify(const CFGBlock *Conditional, const CFGBlock *SuccWithoutCall) { | ||||
471 | if (const Stmt *Terminator = Conditional->getTerminatorStmt()) { | ||||
472 | return NotCalledClarifier{Conditional, SuccWithoutCall}.Visit(Terminator); | ||||
473 | } | ||||
474 | return llvm::None; | ||||
475 | } | ||||
476 | |||||
477 | llvm::Optional<Clarification> VisitIfStmt(const IfStmt *If) { | ||||
478 | return VisitBranchingBlock(If, NeverCalledReason::IfThen); | ||||
479 | } | ||||
480 | |||||
481 | llvm::Optional<Clarification> | ||||
482 | VisitAbstractConditionalOperator(const AbstractConditionalOperator *Ternary) { | ||||
483 | return VisitBranchingBlock(Ternary, NeverCalledReason::IfThen); | ||||
484 | } | ||||
485 | |||||
486 | llvm::Optional<Clarification> VisitSwitchStmt(const SwitchStmt *Switch) { | ||||
487 | const Stmt *CaseToBlame = SuccInQuestion->getLabel(); | ||||
488 | if (!CaseToBlame) { | ||||
489 | // If interesting basic block is not labeled, it means that this | ||||
490 | // basic block does not represent any of the cases. | ||||
491 | return Clarification{NeverCalledReason::SwitchSkipped, Switch}; | ||||
492 | } | ||||
493 | |||||
494 | for (const SwitchCase *Case = Switch->getSwitchCaseList(); Case; | ||||
495 | Case = Case->getNextSwitchCase()) { | ||||
496 | if (Case == CaseToBlame) { | ||||
497 | return Clarification{NeverCalledReason::Switch, Case}; | ||||
498 | } | ||||
499 | } | ||||
500 | |||||
501 | llvm_unreachable("Found unexpected switch structure")::llvm::llvm_unreachable_internal("Found unexpected switch structure" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 501); | ||||
502 | } | ||||
503 | |||||
504 | llvm::Optional<Clarification> VisitForStmt(const ForStmt *For) { | ||||
505 | return VisitBranchingBlock(For, NeverCalledReason::LoopEntered); | ||||
506 | } | ||||
507 | |||||
508 | llvm::Optional<Clarification> VisitWhileStmt(const WhileStmt *While) { | ||||
509 | return VisitBranchingBlock(While, NeverCalledReason::LoopEntered); | ||||
510 | } | ||||
511 | |||||
512 | llvm::Optional<Clarification> | ||||
513 | VisitBranchingBlock(const Stmt *Terminator, NeverCalledReason DefaultReason) { | ||||
514 | assert(Parent->succ_size() == 2 &&((Parent->succ_size() == 2 && "Branching block should have exactly two successors" ) ? static_cast<void> (0) : __assert_fail ("Parent->succ_size() == 2 && \"Branching block should have exactly two successors\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 515, __PRETTY_FUNCTION__)) | ||||
515 | "Branching block should have exactly two successors")((Parent->succ_size() == 2 && "Branching block should have exactly two successors" ) ? static_cast<void> (0) : __assert_fail ("Parent->succ_size() == 2 && \"Branching block should have exactly two successors\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 515, __PRETTY_FUNCTION__)); | ||||
516 | unsigned SuccessorIndex = getSuccessorIndex(Parent, SuccInQuestion); | ||||
517 | NeverCalledReason ActualReason = | ||||
518 | updateForSuccessor(DefaultReason, SuccessorIndex); | ||||
519 | return Clarification{ActualReason, Terminator}; | ||||
520 | } | ||||
521 | |||||
522 | llvm::Optional<Clarification> VisitBinaryOperator(const BinaryOperator *) { | ||||
523 | // We don't want to report on short-curcuit logical operations. | ||||
524 | return llvm::None; | ||||
525 | } | ||||
526 | |||||
527 | llvm::Optional<Clarification> VisitStmt(const Stmt *Terminator) { | ||||
528 | // If we got here, we didn't have a visit function for more derived | ||||
529 | // classes of statement that this terminator actually belongs to. | ||||
530 | // | ||||
531 | // This is not a good scenario and should not happen in practice, but | ||||
532 | // at least we'll warn the user. | ||||
533 | return Clarification{NeverCalledReason::FallbackReason, Terminator}; | ||||
534 | } | ||||
535 | |||||
536 | static unsigned getSuccessorIndex(const CFGBlock *Parent, | ||||
537 | const CFGBlock *Child) { | ||||
538 | CFGBlock::const_succ_iterator It = llvm::find(Parent->succs(), Child); | ||||
539 | assert(It != Parent->succ_end() &&((It != Parent->succ_end() && "Given blocks should be in parent-child relationship" ) ? static_cast<void> (0) : __assert_fail ("It != Parent->succ_end() && \"Given blocks should be in parent-child relationship\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 540, __PRETTY_FUNCTION__)) | ||||
540 | "Given blocks should be in parent-child relationship")((It != Parent->succ_end() && "Given blocks should be in parent-child relationship" ) ? static_cast<void> (0) : __assert_fail ("It != Parent->succ_end() && \"Given blocks should be in parent-child relationship\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 540, __PRETTY_FUNCTION__)); | ||||
541 | return It - Parent->succ_begin(); | ||||
542 | } | ||||
543 | |||||
544 | static NeverCalledReason | ||||
545 | updateForSuccessor(NeverCalledReason ReasonForTrueBranch, | ||||
546 | unsigned SuccessorIndex) { | ||||
547 | assert(SuccessorIndex <= 1)((SuccessorIndex <= 1) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex <= 1", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 547, __PRETTY_FUNCTION__)); | ||||
548 | unsigned RawReason = | ||||
549 | static_cast<unsigned>(ReasonForTrueBranch) + SuccessorIndex; | ||||
550 | assert(RawReason <=((RawReason <= static_cast<unsigned>(NeverCalledReason ::LARGEST_VALUE)) ? static_cast<void> (0) : __assert_fail ("RawReason <= static_cast<unsigned>(NeverCalledReason::LARGEST_VALUE)" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 551, __PRETTY_FUNCTION__)) | ||||
551 | static_cast<unsigned>(NeverCalledReason::LARGEST_VALUE))((RawReason <= static_cast<unsigned>(NeverCalledReason ::LARGEST_VALUE)) ? static_cast<void> (0) : __assert_fail ("RawReason <= static_cast<unsigned>(NeverCalledReason::LARGEST_VALUE)" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 551, __PRETTY_FUNCTION__)); | ||||
552 | return static_cast<NeverCalledReason>(RawReason); | ||||
553 | } | ||||
554 | |||||
555 | private: | ||||
556 | NotCalledClarifier(const CFGBlock *Parent, const CFGBlock *SuccInQuestion) | ||||
557 | : Parent(Parent), SuccInQuestion(SuccInQuestion) {} | ||||
558 | |||||
559 | const CFGBlock *Parent, *SuccInQuestion; | ||||
560 | }; | ||||
561 | |||||
562 | class CalledOnceChecker : public ConstStmtVisitor<CalledOnceChecker> { | ||||
563 | public: | ||||
564 | static void check(AnalysisDeclContext &AC, CalledOnceCheckHandler &Handler, | ||||
565 | bool CheckConventionalParameters) { | ||||
566 | CalledOnceChecker(AC, Handler, CheckConventionalParameters).check(); | ||||
567 | } | ||||
568 | |||||
569 | private: | ||||
570 | CalledOnceChecker(AnalysisDeclContext &AC, CalledOnceCheckHandler &Handler, | ||||
571 | bool CheckConventionalParameters) | ||||
572 | : FunctionCFG(*AC.getCFG()), AC(AC), Handler(Handler), | ||||
573 | CheckConventionalParameters(CheckConventionalParameters), | ||||
574 | CurrentState(0) { | ||||
575 | initDataStructures(); | ||||
576 | assert((size() == 0 || !States.empty()) &&(((size() == 0 || !States.empty()) && "Data structures are inconsistent" ) ? static_cast<void> (0) : __assert_fail ("(size() == 0 || !States.empty()) && \"Data structures are inconsistent\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 577, __PRETTY_FUNCTION__)) | ||||
577 | "Data structures are inconsistent")(((size() == 0 || !States.empty()) && "Data structures are inconsistent" ) ? static_cast<void> (0) : __assert_fail ("(size() == 0 || !States.empty()) && \"Data structures are inconsistent\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 577, __PRETTY_FUNCTION__)); | ||||
578 | } | ||||
579 | |||||
580 | //===----------------------------------------------------------------------===// | ||||
581 | // Initializing functions | ||||
582 | //===----------------------------------------------------------------------===// | ||||
583 | |||||
584 | void initDataStructures() { | ||||
585 | const Decl *AnalyzedDecl = AC.getDecl(); | ||||
586 | |||||
587 | if (const auto *Function = dyn_cast<FunctionDecl>(AnalyzedDecl)) { | ||||
588 | findParamsToTrack(Function); | ||||
589 | } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(AnalyzedDecl)) { | ||||
590 | findParamsToTrack(Method); | ||||
591 | } else if (const auto *Block = dyn_cast<BlockDecl>(AnalyzedDecl)) { | ||||
592 | findCapturesToTrack(Block); | ||||
593 | findParamsToTrack(Block); | ||||
594 | } | ||||
595 | |||||
596 | // Have something to track, let's init states for every block from the CFG. | ||||
597 | if (size() != 0) { | ||||
598 | States = | ||||
599 | CFGSizedVector<State>(FunctionCFG.getNumBlockIDs(), State(size())); | ||||
600 | } | ||||
601 | } | ||||
602 | |||||
603 | void findCapturesToTrack(const BlockDecl *Block) { | ||||
604 | for (const auto &Capture : Block->captures()) { | ||||
605 | if (const auto *P = dyn_cast<ParmVarDecl>(Capture.getVariable())) { | ||||
606 | // Parameter DeclContext is its owning function or method. | ||||
607 | const DeclContext *ParamContext = P->getDeclContext(); | ||||
608 | if (shouldBeCalledOnce(ParamContext, P)) { | ||||
609 | TrackedParams.push_back(P); | ||||
610 | } | ||||
611 | } | ||||
612 | } | ||||
613 | } | ||||
614 | |||||
615 | template <class FunctionLikeDecl> | ||||
616 | void findParamsToTrack(const FunctionLikeDecl *Function) { | ||||
617 | for (unsigned Index : llvm::seq<unsigned>(0u, Function->param_size())) { | ||||
618 | if (shouldBeCalledOnce(Function, Index)) { | ||||
619 | TrackedParams.push_back(Function->getParamDecl(Index)); | ||||
620 | } | ||||
621 | } | ||||
622 | } | ||||
623 | |||||
624 | //===----------------------------------------------------------------------===// | ||||
625 | // Main logic 'check' functions | ||||
626 | //===----------------------------------------------------------------------===// | ||||
627 | |||||
628 | void check() { | ||||
629 | // Nothing to check here: we don't have marked parameters. | ||||
630 | if (size() == 0 || isPossiblyEmptyImpl()) | ||||
631 | return; | ||||
632 | |||||
633 | assert(((llvm::none_of(States, [](const State &S) { return S.isVisited (); }) && "None of the blocks should be 'visited' before the analysis" ) ? static_cast<void> (0) : __assert_fail ("llvm::none_of(States, [](const State &S) { return S.isVisited(); }) && \"None of the blocks should be 'visited' before the analysis\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 635, __PRETTY_FUNCTION__)) | ||||
634 | llvm::none_of(States, [](const State &S) { return S.isVisited(); }) &&((llvm::none_of(States, [](const State &S) { return S.isVisited (); }) && "None of the blocks should be 'visited' before the analysis" ) ? static_cast<void> (0) : __assert_fail ("llvm::none_of(States, [](const State &S) { return S.isVisited(); }) && \"None of the blocks should be 'visited' before the analysis\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 635, __PRETTY_FUNCTION__)) | ||||
635 | "None of the blocks should be 'visited' before the analysis")((llvm::none_of(States, [](const State &S) { return S.isVisited (); }) && "None of the blocks should be 'visited' before the analysis" ) ? static_cast<void> (0) : __assert_fail ("llvm::none_of(States, [](const State &S) { return S.isVisited(); }) && \"None of the blocks should be 'visited' before the analysis\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 635, __PRETTY_FUNCTION__)); | ||||
636 | |||||
637 | // For our task, both backward and forward approaches suite well. | ||||
638 | // However, in order to report better diagnostics, we decided to go with | ||||
639 | // backward analysis. | ||||
640 | // | ||||
641 | // Let's consider the following CFG and how forward and backward analyses | ||||
642 | // will work for it. | ||||
643 | // | ||||
644 | // FORWARD: | BACKWARD: | ||||
645 | // #1 | #1 | ||||
646 | // +---------+ | +-----------+ | ||||
647 | // | if | | |MaybeCalled| | ||||
648 | // +---------+ | +-----------+ | ||||
649 | // |NotCalled| | | if | | ||||
650 | // +---------+ | +-----------+ | ||||
651 | // / \ | / \ | ||||
652 | // #2 / \ #3 | #2 / \ #3 | ||||
653 | // +----------------+ +---------+ | +----------------+ +---------+ | ||||
654 | // | foo() | | ... | | |DefinitelyCalled| |NotCalled| | ||||
655 | // +----------------+ +---------+ | +----------------+ +---------+ | ||||
656 | // |DefinitelyCalled| |NotCalled| | | foo() | | ... | | ||||
657 | // +----------------+ +---------+ | +----------------+ +---------+ | ||||
658 | // \ / | \ / | ||||
659 | // \ #4 / | \ #4 / | ||||
660 | // +-----------+ | +---------+ | ||||
661 | // | ... | | |NotCalled| | ||||
662 | // +-----------+ | +---------+ | ||||
663 | // |MaybeCalled| | | ... | | ||||
664 | // +-----------+ | +---------+ | ||||
665 | // | ||||
666 | // The most natural way to report lacking call in the block #3 would be to | ||||
667 | // message that the false branch of the if statement in the block #1 doesn't | ||||
668 | // have a call. And while with the forward approach we'll need to find a | ||||
669 | // least common ancestor or something like that to find the 'if' to blame, | ||||
670 | // backward analysis gives it to us out of the box. | ||||
671 | BackwardDataflowWorklist Worklist(FunctionCFG, AC); | ||||
672 | |||||
673 | // Let's visit EXIT. | ||||
674 | const CFGBlock *Exit = &FunctionCFG.getExit(); | ||||
675 | assignState(Exit, State(size(), ParameterStatus::NotCalled)); | ||||
676 | Worklist.enqueuePredecessors(Exit); | ||||
677 | |||||
678 | while (const CFGBlock *BB = Worklist.dequeue()) { | ||||
679 | assert(BB && "Worklist should filter out null blocks")((BB && "Worklist should filter out null blocks") ? static_cast <void> (0) : __assert_fail ("BB && \"Worklist should filter out null blocks\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 679, __PRETTY_FUNCTION__)); | ||||
680 | check(BB); | ||||
681 | assert(CurrentState.isVisited() &&((CurrentState.isVisited() && "After the check, basic block should be visited" ) ? static_cast<void> (0) : __assert_fail ("CurrentState.isVisited() && \"After the check, basic block should be visited\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 682, __PRETTY_FUNCTION__)) | ||||
682 | "After the check, basic block should be visited")((CurrentState.isVisited() && "After the check, basic block should be visited" ) ? static_cast<void> (0) : __assert_fail ("CurrentState.isVisited() && \"After the check, basic block should be visited\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 682, __PRETTY_FUNCTION__)); | ||||
683 | |||||
684 | // Traverse successor basic blocks if the status of this block | ||||
685 | // has changed. | ||||
686 | if (assignState(BB, CurrentState)) { | ||||
687 | Worklist.enqueuePredecessors(BB); | ||||
688 | } | ||||
689 | } | ||||
690 | |||||
691 | // Check that we have all tracked parameters at the last block. | ||||
692 | // As we are performing a backward version of the analysis, | ||||
693 | // it should be the ENTRY block. | ||||
694 | checkEntry(&FunctionCFG.getEntry()); | ||||
695 | } | ||||
696 | |||||
697 | void check(const CFGBlock *BB) { | ||||
698 | // We start with a state 'inherited' from all the successors. | ||||
699 | CurrentState = joinSuccessors(BB); | ||||
700 | assert(CurrentState.isVisited() &&((CurrentState.isVisited() && "Shouldn't start with a 'not visited' state" ) ? static_cast<void> (0) : __assert_fail ("CurrentState.isVisited() && \"Shouldn't start with a 'not visited' state\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 701, __PRETTY_FUNCTION__)) | ||||
701 | "Shouldn't start with a 'not visited' state")((CurrentState.isVisited() && "Shouldn't start with a 'not visited' state" ) ? static_cast<void> (0) : __assert_fail ("CurrentState.isVisited() && \"Shouldn't start with a 'not visited' state\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 701, __PRETTY_FUNCTION__)); | ||||
702 | |||||
703 | // This is the 'exit' situation, broken promises are probably OK | ||||
704 | // in such scenarios. | ||||
705 | if (BB->hasNoReturnElement()) { | ||||
706 | markNoReturn(); | ||||
707 | // This block still can have calls (even multiple calls) and | ||||
708 | // for this reason there is no early return here. | ||||
709 | } | ||||
710 | |||||
711 | // We use a backward dataflow propagation and for this reason we | ||||
712 | // should traverse basic blocks bottom-up. | ||||
713 | for (const CFGElement &Element : llvm::reverse(*BB)) { | ||||
714 | if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) { | ||||
715 | check(S->getStmt()); | ||||
716 | } | ||||
717 | } | ||||
718 | } | ||||
719 | void check(const Stmt *S) { Visit(S); } | ||||
720 | |||||
721 | void checkEntry(const CFGBlock *Entry) { | ||||
722 | // We finalize this algorithm with the ENTRY block because | ||||
723 | // we use a backward version of the analysis. This is where | ||||
724 | // we can judge that some of the tracked parameters are not called on | ||||
725 | // every path from ENTRY to EXIT. | ||||
726 | |||||
727 | const State &EntryStatus = getState(Entry); | ||||
728 | llvm::BitVector NotCalledOnEveryPath(size(), false); | ||||
729 | llvm::BitVector NotUsedOnEveryPath(size(), false); | ||||
730 | |||||
731 | // Check if there are no calls of the marked parameter at all | ||||
732 | for (const auto &IndexedStatus : llvm::enumerate(EntryStatus)) { | ||||
733 | const ParmVarDecl *Parameter = getParameter(IndexedStatus.index()); | ||||
734 | |||||
735 | switch (IndexedStatus.value().getKind()) { | ||||
736 | case ParameterStatus::NotCalled: | ||||
737 | // If there were places where this parameter escapes (aka being used), | ||||
738 | // we can provide a more useful diagnostic by pointing at the exact | ||||
739 | // branches where it is not even mentioned. | ||||
740 | if (!hasEverEscaped(IndexedStatus.index())) { | ||||
741 | // This parameter is was not used at all, so we should report the | ||||
742 | // most generic version of the warning. | ||||
743 | if (isCaptured(Parameter)) { | ||||
744 | // We want to specify that it was captured by the block. | ||||
745 | Handler.handleCapturedNeverCalled(Parameter, AC.getDecl(), | ||||
746 | !isExplicitlyMarked(Parameter)); | ||||
747 | } else { | ||||
748 | Handler.handleNeverCalled(Parameter, | ||||
749 | !isExplicitlyMarked(Parameter)); | ||||
750 | } | ||||
751 | } else { | ||||
752 | // Mark it as 'interesting' to figure out which paths don't even | ||||
753 | // have escapes. | ||||
754 | NotUsedOnEveryPath[IndexedStatus.index()] = true; | ||||
755 | } | ||||
756 | |||||
757 | break; | ||||
758 | case ParameterStatus::MaybeCalled: | ||||
759 | // If we have 'maybe called' at this point, we have an error | ||||
760 | // that there is at least one path where this parameter | ||||
761 | // is not called. | ||||
762 | // | ||||
763 | // However, reporting the warning with only that information can be | ||||
764 | // too vague for the users. For this reason, we mark such parameters | ||||
765 | // as "interesting" for further analysis. | ||||
766 | NotCalledOnEveryPath[IndexedStatus.index()] = true; | ||||
767 | break; | ||||
768 | default: | ||||
769 | break; | ||||
770 | } | ||||
771 | } | ||||
772 | |||||
773 | // Early exit if we don't have parameters for extra analysis. | ||||
774 | if (NotCalledOnEveryPath.none() && NotUsedOnEveryPath.none()) | ||||
775 | return; | ||||
776 | |||||
777 | // We are looking for a pair of blocks A, B so that the following is true: | ||||
778 | // * A is a predecessor of B | ||||
779 | // * B is marked as NotCalled | ||||
780 | // * A has at least one successor marked as either | ||||
781 | // Escaped or DefinitelyCalled | ||||
782 | // | ||||
783 | // In that situation, it is guaranteed that B is the first block of the path | ||||
784 | // where the user doesn't call or use parameter in question. | ||||
785 | // | ||||
786 | // For this reason, branch A -> B can be used for reporting. | ||||
787 | // | ||||
788 | // This part of the algorithm is guarded by a condition that the function | ||||
789 | // does indeed have a violation of contract. For this reason, we can | ||||
790 | // spend more time to find a good spot to place the warning. | ||||
791 | // | ||||
792 | // The following algorithm has the worst case complexity of O(V + E), | ||||
793 | // where V is the number of basic blocks in FunctionCFG, | ||||
794 | // E is the number of edges between blocks in FunctionCFG. | ||||
795 | for (const CFGBlock *BB : FunctionCFG) { | ||||
796 | if (!BB) | ||||
797 | continue; | ||||
798 | |||||
799 | const State &BlockState = getState(BB); | ||||
800 | |||||
801 | for (unsigned Index : llvm::seq(0u, size())) { | ||||
802 | // We don't want to use 'isLosingCall' here because we want to report | ||||
803 | // the following situation as well: | ||||
804 | // | ||||
805 | // MaybeCalled | ||||
806 | // | ... | | ||||
807 | // MaybeCalled NotCalled | ||||
808 | // | ||||
809 | // Even though successor is not 'DefinitelyCalled', it is still useful | ||||
810 | // to report it, it is still a path without a call. | ||||
811 | if (NotCalledOnEveryPath[Index] && | ||||
812 | BlockState.getKindFor(Index) == ParameterStatus::MaybeCalled) { | ||||
813 | |||||
814 | findAndReportNotCalledBranches(BB, Index); | ||||
815 | } else if (NotUsedOnEveryPath[Index] && | ||||
816 | isLosingEscape(BlockState, BB, Index)) { | ||||
817 | |||||
818 | findAndReportNotCalledBranches(BB, Index, /* IsEscape = */ true); | ||||
819 | } | ||||
820 | } | ||||
821 | } | ||||
822 | } | ||||
823 | |||||
824 | /// Check potential call of a tracked parameter. | ||||
825 | void checkDirectCall(const CallExpr *Call) { | ||||
826 | if (auto Index = getIndexOfCallee(Call)) { | ||||
827 | processCallFor(*Index, Call); | ||||
828 | } | ||||
829 | } | ||||
830 | |||||
831 | /// Check the call expression for being an indirect call of one of the tracked | ||||
832 | /// parameters. It is indirect in the sense that this particular call is not | ||||
833 | /// calling the parameter itself, but rather uses it as the argument. | ||||
834 | template <class CallLikeExpr> | ||||
835 | void checkIndirectCall(const CallLikeExpr *CallOrMessage) { | ||||
836 | // CallExpr::arguments does not interact nicely with llvm::enumerate. | ||||
837 | llvm::ArrayRef<const Expr *> Arguments = llvm::makeArrayRef( | ||||
838 | CallOrMessage->getArgs(), CallOrMessage->getNumArgs()); | ||||
839 | |||||
840 | // Let's check if any of the call arguments is a point of interest. | ||||
841 | for (const auto &Argument : llvm::enumerate(Arguments)) { | ||||
842 | if (auto Index = getIndexOfExpression(Argument.value())) { | ||||
843 | ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(*Index); | ||||
844 | |||||
845 | if (shouldBeCalledOnce(CallOrMessage, Argument.index())) { | ||||
846 | // If the corresponding parameter is marked as 'called_once' we should | ||||
847 | // consider it as a call. | ||||
848 | processCallFor(*Index, CallOrMessage); | ||||
849 | } else if (CurrentParamStatus.getKind() == ParameterStatus::NotCalled) { | ||||
850 | // Otherwise, we mark this parameter as escaped, which can be | ||||
851 | // interpreted both as called or not called depending on the context. | ||||
852 | CurrentParamStatus = ParameterStatus::Escaped; | ||||
853 | } | ||||
854 | // Otherwise, let's keep the state as it is. | ||||
855 | } | ||||
856 | } | ||||
857 | } | ||||
858 | |||||
859 | /// Process call of the parameter with the given index | ||||
860 | void processCallFor(unsigned Index, const Expr *Call) { | ||||
861 | ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(Index); | ||||
862 | |||||
863 | if (CurrentParamStatus.seenAnyCalls()) { | ||||
864 | |||||
865 | // At this point, this parameter was called, so this is a second call. | ||||
866 | const ParmVarDecl *Parameter = getParameter(Index); | ||||
867 | Handler.handleDoubleCall( | ||||
868 | Parameter, &CurrentState.getCallFor(Index), Call, | ||||
869 | !isExplicitlyMarked(Parameter), | ||||
870 | // We are sure that the second call is definitely | ||||
871 | // going to happen if the status is 'DefinitelyCalled'. | ||||
872 | CurrentParamStatus.getKind() == ParameterStatus::DefinitelyCalled); | ||||
873 | |||||
874 | // Mark this parameter as already reported on, so we don't repeat | ||||
875 | // warnings. | ||||
876 | CurrentParamStatus = ParameterStatus::Reported; | ||||
877 | |||||
878 | } else if (CurrentParamStatus.getKind() != ParameterStatus::Reported) { | ||||
879 | // If we didn't report anything yet, let's mark this parameter | ||||
880 | // as called. | ||||
881 | ParameterStatus Called(ParameterStatus::DefinitelyCalled, Call); | ||||
882 | CurrentParamStatus = Called; | ||||
883 | } | ||||
884 | } | ||||
885 | |||||
886 | void findAndReportNotCalledBranches(const CFGBlock *Parent, unsigned Index, | ||||
887 | bool IsEscape = false) { | ||||
888 | for (const CFGBlock *Succ : Parent->succs()) { | ||||
889 | if (!Succ) | ||||
890 | continue; | ||||
891 | |||||
892 | if (getState(Succ).getKindFor(Index) == ParameterStatus::NotCalled) { | ||||
893 | assert(Parent->succ_size() >= 2 &&((Parent->succ_size() >= 2 && "Block should have at least two successors at this point" ) ? static_cast<void> (0) : __assert_fail ("Parent->succ_size() >= 2 && \"Block should have at least two successors at this point\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 894, __PRETTY_FUNCTION__)) | ||||
894 | "Block should have at least two successors at this point")((Parent->succ_size() >= 2 && "Block should have at least two successors at this point" ) ? static_cast<void> (0) : __assert_fail ("Parent->succ_size() >= 2 && \"Block should have at least two successors at this point\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 894, __PRETTY_FUNCTION__)); | ||||
895 | if (auto Clarification = NotCalledClarifier::clarify(Parent, Succ)) { | ||||
896 | const ParmVarDecl *Parameter = getParameter(Index); | ||||
897 | Handler.handleNeverCalled(Parameter, Clarification->Location, | ||||
898 | Clarification->Reason, !IsEscape, | ||||
899 | !isExplicitlyMarked(Parameter)); | ||||
900 | } | ||||
901 | } | ||||
902 | } | ||||
903 | } | ||||
904 | |||||
905 | //===----------------------------------------------------------------------===// | ||||
906 | // Predicate functions to check parameters | ||||
907 | //===----------------------------------------------------------------------===// | ||||
908 | |||||
909 | /// Return true if parameter is explicitly marked as 'called_once'. | ||||
910 | static bool isExplicitlyMarked(const ParmVarDecl *Parameter) { | ||||
911 | return Parameter->hasAttr<CalledOnceAttr>(); | ||||
912 | } | ||||
913 | |||||
914 | /// Return true if the given name matches conventional pattens. | ||||
915 | static bool isConventional(llvm::StringRef Name) { | ||||
916 | return llvm::count(CONVENTIONAL_NAMES, Name) != 0; | ||||
917 | } | ||||
918 | |||||
919 | /// Return true if the given name has conventional suffixes. | ||||
920 | static bool hasConventionalSuffix(llvm::StringRef Name) { | ||||
921 | return llvm::any_of(CONVENTIONAL_SUFFIXES, [Name](llvm::StringRef Suffix) { | ||||
922 | return Name.endswith(Suffix); | ||||
923 | }); | ||||
924 | } | ||||
925 | |||||
926 | /// Return true if the given type can be used for conventional parameters. | ||||
927 | static bool isConventional(QualType Ty) { | ||||
928 | if (!Ty->isBlockPointerType()) { | ||||
929 | return false; | ||||
930 | } | ||||
931 | |||||
932 | QualType BlockType = Ty->getAs<BlockPointerType>()->getPointeeType(); | ||||
933 | // Completion handlers should have a block type with void return type. | ||||
934 | return BlockType->getAs<FunctionType>()->getReturnType()->isVoidType(); | ||||
| |||||
935 | } | ||||
936 | |||||
937 | /// Return true if the only parameter of the function is conventional. | ||||
938 | static bool isOnlyParameterConventional(const FunctionDecl *Function) { | ||||
939 | return Function->getNumParams() == 1 && | ||||
940 | hasConventionalSuffix(Function->getName()); | ||||
941 | } | ||||
942 | |||||
943 | /// Return true/false if 'swift_async' attribute states that the given | ||||
944 | /// parameter is conventionally called once. | ||||
945 | /// Return llvm::None if the given declaration doesn't have 'swift_async' | ||||
946 | /// attribute. | ||||
947 | static llvm::Optional<bool> isConventionalSwiftAsync(const Decl *D, | ||||
948 | unsigned ParamIndex) { | ||||
949 | if (const SwiftAsyncAttr *A = D->getAttr<SwiftAsyncAttr>()) { | ||||
950 | if (A->getKind() == SwiftAsyncAttr::None) { | ||||
951 | return false; | ||||
952 | } | ||||
953 | |||||
954 | return A->getCompletionHandlerIndex().getASTIndex() == ParamIndex; | ||||
955 | } | ||||
956 | return llvm::None; | ||||
957 | } | ||||
958 | |||||
959 | /// Return true if the specified selector piece matches conventions. | ||||
960 | static bool isConventionalSelectorPiece(Selector MethodSelector, | ||||
961 | unsigned PieceIndex, | ||||
962 | QualType PieceType) { | ||||
963 | if (!isConventional(PieceType)) { | ||||
964 | return false; | ||||
965 | } | ||||
966 | |||||
967 | if (MethodSelector.getNumArgs() == 1) { | ||||
968 | assert(PieceIndex == 0)((PieceIndex == 0) ? static_cast<void> (0) : __assert_fail ("PieceIndex == 0", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 968, __PRETTY_FUNCTION__)); | ||||
969 | return hasConventionalSuffix(MethodSelector.getNameForSlot(0)); | ||||
970 | } | ||||
971 | |||||
972 | return isConventional(MethodSelector.getNameForSlot(PieceIndex)); | ||||
973 | } | ||||
974 | |||||
975 | bool shouldBeCalledOnce(const ParmVarDecl *Parameter) const { | ||||
976 | return isExplicitlyMarked(Parameter) || | ||||
977 | (CheckConventionalParameters && | ||||
978 | isConventional(Parameter->getName()) && | ||||
979 | isConventional(Parameter->getType())); | ||||
980 | } | ||||
981 | |||||
982 | bool shouldBeCalledOnce(const DeclContext *ParamContext, | ||||
983 | const ParmVarDecl *Param) { | ||||
984 | unsigned ParamIndex = Param->getFunctionScopeIndex(); | ||||
985 | if (const auto *Function = dyn_cast<FunctionDecl>(ParamContext)) { | ||||
986 | return shouldBeCalledOnce(Function, ParamIndex); | ||||
987 | } | ||||
988 | if (const auto *Method = dyn_cast<ObjCMethodDecl>(ParamContext)) { | ||||
989 | return shouldBeCalledOnce(Method, ParamIndex); | ||||
990 | } | ||||
991 | return shouldBeCalledOnce(Param); | ||||
992 | } | ||||
993 | |||||
994 | bool shouldBeCalledOnce(const BlockDecl *Block, unsigned ParamIndex) const { | ||||
995 | return shouldBeCalledOnce(Block->getParamDecl(ParamIndex)); | ||||
996 | } | ||||
997 | |||||
998 | bool shouldBeCalledOnce(const FunctionDecl *Function, | ||||
999 | unsigned ParamIndex) const { | ||||
1000 | if (ParamIndex >= Function->getNumParams()) { | ||||
1001 | return false; | ||||
1002 | } | ||||
1003 | // 'swift_async' goes first and overrides anything else. | ||||
1004 | if (auto ConventionalAsync = | ||||
1005 | isConventionalSwiftAsync(Function, ParamIndex)) { | ||||
1006 | return ConventionalAsync.getValue(); | ||||
1007 | } | ||||
1008 | |||||
1009 | return shouldBeCalledOnce(Function->getParamDecl(ParamIndex)) || | ||||
1010 | (CheckConventionalParameters && | ||||
1011 | isOnlyParameterConventional(Function)); | ||||
1012 | } | ||||
1013 | |||||
1014 | bool shouldBeCalledOnce(const ObjCMethodDecl *Method, | ||||
1015 | unsigned ParamIndex) const { | ||||
1016 | Selector MethodSelector = Method->getSelector(); | ||||
1017 | if (ParamIndex >= MethodSelector.getNumArgs()) { | ||||
1018 | return false; | ||||
1019 | } | ||||
1020 | |||||
1021 | // 'swift_async' goes first and overrides anything else. | ||||
1022 | if (auto ConventionalAsync = isConventionalSwiftAsync(Method, ParamIndex)) { | ||||
1023 | return ConventionalAsync.getValue(); | ||||
1024 | } | ||||
1025 | |||||
1026 | const ParmVarDecl *Parameter = Method->getParamDecl(ParamIndex); | ||||
1027 | return shouldBeCalledOnce(Parameter) || | ||||
1028 | (CheckConventionalParameters && | ||||
1029 | isConventionalSelectorPiece(MethodSelector, ParamIndex, | ||||
1030 | Parameter->getType())); | ||||
1031 | } | ||||
1032 | |||||
1033 | bool shouldBeCalledOnce(const CallExpr *Call, unsigned ParamIndex) const { | ||||
1034 | const FunctionDecl *Function = Call->getDirectCallee(); | ||||
1035 | return Function
| ||||
1036 | } | ||||
1037 | |||||
1038 | bool shouldBeCalledOnce(const ObjCMessageExpr *Message, | ||||
1039 | unsigned ParamIndex) const { | ||||
1040 | const ObjCMethodDecl *Method = Message->getMethodDecl(); | ||||
1041 | return Method && ParamIndex < Method->param_size() && | ||||
1042 | shouldBeCalledOnce(Method, ParamIndex); | ||||
1043 | } | ||||
1044 | |||||
1045 | //===----------------------------------------------------------------------===// | ||||
1046 | // Utility methods | ||||
1047 | //===----------------------------------------------------------------------===// | ||||
1048 | |||||
1049 | bool isCaptured(const ParmVarDecl *Parameter) const { | ||||
1050 | if (const BlockDecl *Block = dyn_cast<BlockDecl>(AC.getDecl())) { | ||||
1051 | return Block->capturesVariable(Parameter); | ||||
1052 | } | ||||
1053 | return false; | ||||
1054 | } | ||||
1055 | |||||
1056 | /// Return true if the analyzed function is actually a default implementation | ||||
1057 | /// of the method that has to be overriden. | ||||
1058 | /// | ||||
1059 | /// These functions can have tracked parameters, but wouldn't call them | ||||
1060 | /// because they are not designed to perform any meaningful actions. | ||||
1061 | /// | ||||
1062 | /// There are a couple of flavors of such default implementations: | ||||
1063 | /// 1. Empty methods or methods with a single return statement | ||||
1064 | /// 2. Methods that have one block with a call to no return function | ||||
1065 | /// 3. Methods with only assertion-like operations | ||||
1066 | bool isPossiblyEmptyImpl() const { | ||||
1067 | if (!isa<ObjCMethodDecl>(AC.getDecl())) { | ||||
1068 | // We care only about functions that are not supposed to be called. | ||||
1069 | // Only methods can be overriden. | ||||
1070 | return false; | ||||
1071 | } | ||||
1072 | |||||
1073 | // Case #1 (without return statements) | ||||
1074 | if (FunctionCFG.size() == 2) { | ||||
1075 | // Method has only two blocks: ENTRY and EXIT. | ||||
1076 | // This is equivalent to empty function. | ||||
1077 | return true; | ||||
1078 | } | ||||
1079 | |||||
1080 | // Case #2 | ||||
1081 | if (FunctionCFG.size() == 3) { | ||||
1082 | const CFGBlock &Entry = FunctionCFG.getEntry(); | ||||
1083 | if (Entry.succ_empty()) { | ||||
1084 | return false; | ||||
1085 | } | ||||
1086 | |||||
1087 | const CFGBlock *OnlyBlock = *Entry.succ_begin(); | ||||
1088 | // Method has only one block, let's see if it has a no-return | ||||
1089 | // element. | ||||
1090 | if (OnlyBlock && OnlyBlock->hasNoReturnElement()) { | ||||
1091 | return true; | ||||
1092 | } | ||||
1093 | // Fallthrough, CFGs with only one block can fall into #1 and #3 as well. | ||||
1094 | } | ||||
1095 | |||||
1096 | // Cases #1 (return statements) and #3. | ||||
1097 | // | ||||
1098 | // It is hard to detect that something is an assertion or came | ||||
1099 | // from assertion. Here we use a simple heuristic: | ||||
1100 | // | ||||
1101 | // - If it came from a macro, it can be an assertion. | ||||
1102 | // | ||||
1103 | // Additionally, we can't assume a number of basic blocks or the CFG's | ||||
1104 | // structure because assertions might include loops and conditions. | ||||
1105 | return llvm::all_of(FunctionCFG, [](const CFGBlock *BB) { | ||||
1106 | if (!BB) { | ||||
1107 | // Unreachable blocks are totally fine. | ||||
1108 | return true; | ||||
1109 | } | ||||
1110 | |||||
1111 | // Return statements can have sub-expressions that are represented as | ||||
1112 | // separate statements of a basic block. We should allow this. | ||||
1113 | // This parent map will be initialized with a parent tree for all | ||||
1114 | // subexpressions of the block's return statement (if it has one). | ||||
1115 | std::unique_ptr<ParentMap> ReturnChildren; | ||||
1116 | |||||
1117 | return llvm::all_of( | ||||
1118 | llvm::reverse(*BB), // we should start with return statements, if we | ||||
1119 | // have any, i.e. from the bottom of the block | ||||
1120 | [&ReturnChildren](const CFGElement &Element) { | ||||
1121 | if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) { | ||||
1122 | const Stmt *SuspiciousStmt = S->getStmt(); | ||||
1123 | |||||
1124 | if (isa<ReturnStmt>(SuspiciousStmt)) { | ||||
1125 | // Let's initialize this structure to test whether | ||||
1126 | // some further statement is a part of this return. | ||||
1127 | ReturnChildren = std::make_unique<ParentMap>( | ||||
1128 | const_cast<Stmt *>(SuspiciousStmt)); | ||||
1129 | // Return statements are allowed as part of #1. | ||||
1130 | return true; | ||||
1131 | } | ||||
1132 | |||||
1133 | return SuspiciousStmt->getBeginLoc().isMacroID() || | ||||
1134 | (ReturnChildren && | ||||
1135 | ReturnChildren->hasParent(SuspiciousStmt)); | ||||
1136 | } | ||||
1137 | return true; | ||||
1138 | }); | ||||
1139 | }); | ||||
1140 | } | ||||
1141 | |||||
1142 | /// Check if parameter with the given index has ever escaped. | ||||
1143 | bool hasEverEscaped(unsigned Index) const { | ||||
1144 | return llvm::any_of(States, [Index](const State &StateForOneBB) { | ||||
1145 | return StateForOneBB.getKindFor(Index) == ParameterStatus::Escaped; | ||||
1146 | }); | ||||
1147 | } | ||||
1148 | |||||
1149 | /// Return status stored for the given basic block. | ||||
1150 | /// \{ | ||||
1151 | State &getState(const CFGBlock *BB) { | ||||
1152 | assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1152, __PRETTY_FUNCTION__)); | ||||
1153 | return States[BB->getBlockID()]; | ||||
1154 | } | ||||
1155 | const State &getState(const CFGBlock *BB) const { | ||||
1156 | assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1156, __PRETTY_FUNCTION__)); | ||||
1157 | return States[BB->getBlockID()]; | ||||
1158 | } | ||||
1159 | /// \} | ||||
1160 | |||||
1161 | /// Assign status to the given basic block. | ||||
1162 | /// | ||||
1163 | /// Returns true when the stored status changed. | ||||
1164 | bool assignState(const CFGBlock *BB, const State &ToAssign) { | ||||
1165 | State &Current = getState(BB); | ||||
1166 | if (Current == ToAssign) { | ||||
1167 | return false; | ||||
1168 | } | ||||
1169 | |||||
1170 | Current = ToAssign; | ||||
1171 | return true; | ||||
1172 | } | ||||
1173 | |||||
1174 | /// Join all incoming statuses for the given basic block. | ||||
1175 | State joinSuccessors(const CFGBlock *BB) const { | ||||
1176 | auto Succs = | ||||
1177 | llvm::make_filter_range(BB->succs(), [this](const CFGBlock *Succ) { | ||||
1178 | return Succ && this->getState(Succ).isVisited(); | ||||
1179 | }); | ||||
1180 | // We came to this block from somewhere after all. | ||||
1181 | assert(!Succs.empty() &&((!Succs.empty() && "Basic block should have at least one visited successor" ) ? static_cast<void> (0) : __assert_fail ("!Succs.empty() && \"Basic block should have at least one visited successor\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1182, __PRETTY_FUNCTION__)) | ||||
1182 | "Basic block should have at least one visited successor")((!Succs.empty() && "Basic block should have at least one visited successor" ) ? static_cast<void> (0) : __assert_fail ("!Succs.empty() && \"Basic block should have at least one visited successor\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1182, __PRETTY_FUNCTION__)); | ||||
1183 | |||||
1184 | State Result = getState(*Succs.begin()); | ||||
1185 | |||||
1186 | for (const CFGBlock *Succ : llvm::drop_begin(Succs, 1)) { | ||||
1187 | Result.join(getState(Succ)); | ||||
1188 | } | ||||
1189 | |||||
1190 | if (const Expr *Condition = getCondition(BB->getTerminatorStmt())) { | ||||
1191 | handleConditional(BB, Condition, Result); | ||||
1192 | } | ||||
1193 | |||||
1194 | return Result; | ||||
1195 | } | ||||
1196 | |||||
1197 | void handleConditional(const CFGBlock *BB, const Expr *Condition, | ||||
1198 | State &ToAlter) const { | ||||
1199 | handleParameterCheck(BB, Condition, ToAlter); | ||||
1200 | if (SuppressOnConventionalErrorPaths) { | ||||
1201 | handleConventionalCheck(BB, Condition, ToAlter); | ||||
1202 | } | ||||
1203 | } | ||||
1204 | |||||
1205 | void handleParameterCheck(const CFGBlock *BB, const Expr *Condition, | ||||
1206 | State &ToAlter) const { | ||||
1207 | // In this function, we try to deal with the following pattern: | ||||
1208 | // | ||||
1209 | // if (parameter) | ||||
1210 | // parameter(...); | ||||
1211 | // | ||||
1212 | // It's not good to show a warning here because clearly 'parameter' | ||||
1213 | // couldn't and shouldn't be called on the 'else' path. | ||||
1214 | // | ||||
1215 | // Let's check if this if statement has a check involving one of | ||||
1216 | // the tracked parameters. | ||||
1217 | if (const ParmVarDecl *Parameter = findReferencedParmVarDecl( | ||||
1218 | Condition, | ||||
1219 | /* ShouldRetrieveFromComparisons = */ true)) { | ||||
1220 | if (const auto Index = getIndex(*Parameter)) { | ||||
1221 | ParameterStatus &CurrentStatus = ToAlter.getStatusFor(*Index); | ||||
1222 | |||||
1223 | // We don't want to deep dive into semantics of the check and | ||||
1224 | // figure out if that check was for null or something else. | ||||
1225 | // We simply trust the user that they know what they are doing. | ||||
1226 | // | ||||
1227 | // For this reason, in the following loop we look for the | ||||
1228 | // best-looking option. | ||||
1229 | for (const CFGBlock *Succ : BB->succs()) { | ||||
1230 | if (!Succ) | ||||
1231 | continue; | ||||
1232 | |||||
1233 | const ParameterStatus &StatusInSucc = | ||||
1234 | getState(Succ).getStatusFor(*Index); | ||||
1235 | |||||
1236 | if (StatusInSucc.isErrorStatus()) { | ||||
1237 | continue; | ||||
1238 | } | ||||
1239 | |||||
1240 | // Let's use this status instead. | ||||
1241 | CurrentStatus = StatusInSucc; | ||||
1242 | |||||
1243 | if (StatusInSucc.getKind() == ParameterStatus::DefinitelyCalled) { | ||||
1244 | // This is the best option to have and we already found it. | ||||
1245 | break; | ||||
1246 | } | ||||
1247 | |||||
1248 | // If we found 'Escaped' first, we still might find 'DefinitelyCalled' | ||||
1249 | // on the other branch. And we prefer the latter. | ||||
1250 | } | ||||
1251 | } | ||||
1252 | } | ||||
1253 | } | ||||
1254 | |||||
1255 | void handleConventionalCheck(const CFGBlock *BB, const Expr *Condition, | ||||
1256 | State &ToAlter) const { | ||||
1257 | // Even when the analysis is technically correct, it is a widespread pattern | ||||
1258 | // not to call completion handlers in some scenarios. These usually have | ||||
1259 | // typical conditional names, such as 'error' or 'cancel'. | ||||
1260 | if (!mentionsAnyOfConventionalNames(Condition)) { | ||||
1261 | return; | ||||
1262 | } | ||||
1263 | |||||
1264 | for (const auto &IndexedStatus : llvm::enumerate(ToAlter)) { | ||||
1265 | const ParmVarDecl *Parameter = getParameter(IndexedStatus.index()); | ||||
1266 | // Conventions do not apply to explicitly marked parameters. | ||||
1267 | if (isExplicitlyMarked(Parameter)) { | ||||
1268 | continue; | ||||
1269 | } | ||||
1270 | |||||
1271 | ParameterStatus &CurrentStatus = IndexedStatus.value(); | ||||
1272 | // If we did find that on one of the branches the user uses the callback | ||||
1273 | // and doesn't on the other path, we believe that they know what they are | ||||
1274 | // doing and trust them. | ||||
1275 | // | ||||
1276 | // There are two possible scenarios for that: | ||||
1277 | // 1. Current status is 'MaybeCalled' and one of the branches is | ||||
1278 | // 'DefinitelyCalled' | ||||
1279 | // 2. Current status is 'NotCalled' and one of the branches is 'Escaped' | ||||
1280 | if (isLosingCall(ToAlter, BB, IndexedStatus.index()) || | ||||
1281 | isLosingEscape(ToAlter, BB, IndexedStatus.index())) { | ||||
1282 | CurrentStatus = ParameterStatus::Escaped; | ||||
1283 | } | ||||
1284 | } | ||||
1285 | } | ||||
1286 | |||||
1287 | bool isLosingCall(const State &StateAfterJoin, const CFGBlock *JoinBlock, | ||||
1288 | unsigned ParameterIndex) const { | ||||
1289 | // Let's check if the block represents DefinitelyCalled -> MaybeCalled | ||||
1290 | // transition. | ||||
1291 | return isLosingJoin(StateAfterJoin, JoinBlock, ParameterIndex, | ||||
1292 | ParameterStatus::MaybeCalled, | ||||
1293 | ParameterStatus::DefinitelyCalled); | ||||
1294 | } | ||||
1295 | |||||
1296 | bool isLosingEscape(const State &StateAfterJoin, const CFGBlock *JoinBlock, | ||||
1297 | unsigned ParameterIndex) const { | ||||
1298 | // Let's check if the block represents Escaped -> NotCalled transition. | ||||
1299 | return isLosingJoin(StateAfterJoin, JoinBlock, ParameterIndex, | ||||
1300 | ParameterStatus::NotCalled, ParameterStatus::Escaped); | ||||
1301 | } | ||||
1302 | |||||
1303 | bool isLosingJoin(const State &StateAfterJoin, const CFGBlock *JoinBlock, | ||||
1304 | unsigned ParameterIndex, ParameterStatus::Kind AfterJoin, | ||||
1305 | ParameterStatus::Kind BeforeJoin) const { | ||||
1306 | assert(!ParameterStatus::isErrorStatus(BeforeJoin) &&((!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus ::isErrorStatus(AfterJoin) && "It's not a losing join if statuses do not represent " "correct-to-error transition") ? static_cast<void> (0) : __assert_fail ("!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus::isErrorStatus(AfterJoin) && \"It's not a losing join if statuses do not represent \" \"correct-to-error transition\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1309, __PRETTY_FUNCTION__)) | ||||
1307 | ParameterStatus::isErrorStatus(AfterJoin) &&((!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus ::isErrorStatus(AfterJoin) && "It's not a losing join if statuses do not represent " "correct-to-error transition") ? static_cast<void> (0) : __assert_fail ("!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus::isErrorStatus(AfterJoin) && \"It's not a losing join if statuses do not represent \" \"correct-to-error transition\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1309, __PRETTY_FUNCTION__)) | ||||
1308 | "It's not a losing join if statuses do not represent "((!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus ::isErrorStatus(AfterJoin) && "It's not a losing join if statuses do not represent " "correct-to-error transition") ? static_cast<void> (0) : __assert_fail ("!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus::isErrorStatus(AfterJoin) && \"It's not a losing join if statuses do not represent \" \"correct-to-error transition\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1309, __PRETTY_FUNCTION__)) | ||||
1309 | "correct-to-error transition")((!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus ::isErrorStatus(AfterJoin) && "It's not a losing join if statuses do not represent " "correct-to-error transition") ? static_cast<void> (0) : __assert_fail ("!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus::isErrorStatus(AfterJoin) && \"It's not a losing join if statuses do not represent \" \"correct-to-error transition\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1309, __PRETTY_FUNCTION__)); | ||||
1310 | |||||
1311 | const ParameterStatus &CurrentStatus = | ||||
1312 | StateAfterJoin.getStatusFor(ParameterIndex); | ||||
1313 | |||||
1314 | return CurrentStatus.getKind() == AfterJoin && | ||||
1315 | anySuccessorHasStatus(JoinBlock, ParameterIndex, BeforeJoin); | ||||
1316 | } | ||||
1317 | |||||
1318 | /// Return true if any of the successors of the given basic block has | ||||
1319 | /// a specified status for the given parameter. | ||||
1320 | bool anySuccessorHasStatus(const CFGBlock *Parent, unsigned ParameterIndex, | ||||
1321 | ParameterStatus::Kind ToFind) const { | ||||
1322 | return llvm::any_of( | ||||
1323 | Parent->succs(), [this, ParameterIndex, ToFind](const CFGBlock *Succ) { | ||||
1324 | return Succ && getState(Succ).getKindFor(ParameterIndex) == ToFind; | ||||
1325 | }); | ||||
1326 | } | ||||
1327 | |||||
1328 | /// Check given expression that was discovered to escape. | ||||
1329 | void checkEscapee(const Expr *E) { | ||||
1330 | if (const ParmVarDecl *Parameter = findReferencedParmVarDecl(E)) { | ||||
1331 | checkEscapee(*Parameter); | ||||
1332 | } | ||||
1333 | } | ||||
1334 | |||||
1335 | /// Check given parameter that was discovered to escape. | ||||
1336 | void checkEscapee(const ParmVarDecl &Parameter) { | ||||
1337 | if (auto Index = getIndex(Parameter)) { | ||||
1338 | ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(*Index); | ||||
1339 | |||||
1340 | if (CurrentParamStatus.getKind() == ParameterStatus::NotCalled) { | ||||
1341 | CurrentParamStatus = ParameterStatus::Escaped; | ||||
1342 | } | ||||
1343 | } | ||||
1344 | } | ||||
1345 | |||||
1346 | /// Mark all parameters in the current state as 'no-return'. | ||||
1347 | void markNoReturn() { | ||||
1348 | for (ParameterStatus &PS : CurrentState) { | ||||
1349 | PS = ParameterStatus::NoReturn; | ||||
1350 | } | ||||
1351 | } | ||||
1352 | |||||
1353 | /// Check if the given assignment represents suppression and act on it. | ||||
1354 | void checkSuppression(const BinaryOperator *Assignment) { | ||||
1355 | // Suppression has the following form: | ||||
1356 | // parameter = 0; | ||||
1357 | // 0 can be of any form (NULL, nil, etc.) | ||||
1358 | if (auto Index = getIndexOfExpression(Assignment->getLHS())) { | ||||
1359 | |||||
1360 | // We don't care what is written in the RHS, it could be whatever | ||||
1361 | // we can interpret as 0. | ||||
1362 | if (auto Constant = | ||||
1363 | Assignment->getRHS()->IgnoreParenCasts()->getIntegerConstantExpr( | ||||
1364 | AC.getASTContext())) { | ||||
1365 | |||||
1366 | ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(*Index); | ||||
1367 | |||||
1368 | if (0 == *Constant && CurrentParamStatus.seenAnyCalls()) { | ||||
1369 | // Even though this suppression mechanism is introduced to tackle | ||||
1370 | // false positives for multiple calls, the fact that the user has | ||||
1371 | // to use suppression can also tell us that we couldn't figure out | ||||
1372 | // how different paths cancel each other out. And if that is true, | ||||
1373 | // we will most certainly have false positives about parameters not | ||||
1374 | // being called on certain paths. | ||||
1375 | // | ||||
1376 | // For this reason, we abandon tracking this parameter altogether. | ||||
1377 | CurrentParamStatus = ParameterStatus::Reported; | ||||
1378 | } | ||||
1379 | } | ||||
1380 | } | ||||
1381 | } | ||||
1382 | |||||
1383 | public: | ||||
1384 | //===----------------------------------------------------------------------===// | ||||
1385 | // Tree traversal methods | ||||
1386 | //===----------------------------------------------------------------------===// | ||||
1387 | |||||
1388 | void VisitCallExpr(const CallExpr *Call) { | ||||
1389 | // This call might be a direct call, i.e. a parameter call... | ||||
1390 | checkDirectCall(Call); | ||||
1391 | // ... or an indirect call, i.e. when parameter is an argument. | ||||
1392 | checkIndirectCall(Call); | ||||
| |||||
1393 | } | ||||
1394 | |||||
1395 | void VisitObjCMessageExpr(const ObjCMessageExpr *Message) { | ||||
1396 | // The most common situation that we are defending against here is | ||||
1397 | // copying a tracked parameter. | ||||
1398 | if (const Expr *Receiver = Message->getInstanceReceiver()) { | ||||
1399 | checkEscapee(Receiver); | ||||
1400 | } | ||||
1401 | // Message expressions unlike calls, could not be direct. | ||||
1402 | checkIndirectCall(Message); | ||||
1403 | } | ||||
1404 | |||||
1405 | void VisitBlockExpr(const BlockExpr *Block) { | ||||
1406 | for (const auto &Capture : Block->getBlockDecl()->captures()) { | ||||
1407 | // If a block captures a tracked parameter, it should be | ||||
1408 | // considered escaped. | ||||
1409 | // On one hand, blocks that do that should definitely call it on | ||||
1410 | // every path. However, it is not guaranteed that the block | ||||
1411 | // itself gets called whenever it gets created. | ||||
1412 | // | ||||
1413 | // Because we don't want to track blocks and whether they get called, | ||||
1414 | // we consider such parameters simply escaped. | ||||
1415 | if (const auto *Param = dyn_cast<ParmVarDecl>(Capture.getVariable())) { | ||||
1416 | checkEscapee(*Param); | ||||
1417 | } | ||||
1418 | } | ||||
1419 | } | ||||
1420 | |||||
1421 | void VisitBinaryOperator(const BinaryOperator *Op) { | ||||
1422 | if (Op->getOpcode() == clang::BO_Assign) { | ||||
1423 | // Let's check if one of the tracked parameters is assigned into | ||||
1424 | // something, and if it is we don't want to track extra variables, so we | ||||
1425 | // consider it as an escapee. | ||||
1426 | checkEscapee(Op->getRHS()); | ||||
1427 | |||||
1428 | // Let's check whether this assignment is a suppression. | ||||
1429 | checkSuppression(Op); | ||||
1430 | } | ||||
1431 | } | ||||
1432 | |||||
1433 | void VisitDeclStmt(const DeclStmt *DS) { | ||||
1434 | // Variable initialization is not assignment and should be handled | ||||
1435 | // separately. | ||||
1436 | // | ||||
1437 | // Multiple declarations can be a part of declaration statement. | ||||
1438 | for (const auto *Declaration : DS->getDeclGroup()) { | ||||
1439 | if (const auto *Var = dyn_cast<VarDecl>(Declaration)) { | ||||
1440 | if (Var->getInit()) { | ||||
1441 | checkEscapee(Var->getInit()); | ||||
1442 | } | ||||
1443 | } | ||||
1444 | } | ||||
1445 | } | ||||
1446 | |||||
1447 | void VisitCStyleCastExpr(const CStyleCastExpr *Cast) { | ||||
1448 | // We consider '(void)parameter' as a manual no-op escape. | ||||
1449 | // It should be used to explicitly tell the analysis that this parameter | ||||
1450 | // is intentionally not called on this path. | ||||
1451 | if (Cast->getType().getCanonicalType()->isVoidType()) { | ||||
1452 | checkEscapee(Cast->getSubExpr()); | ||||
1453 | } | ||||
1454 | } | ||||
1455 | |||||
1456 | void VisitObjCAtThrowStmt(const ObjCAtThrowStmt *) { | ||||
1457 | // It is OK not to call marked parameters on exceptional paths. | ||||
1458 | markNoReturn(); | ||||
1459 | } | ||||
1460 | |||||
1461 | private: | ||||
1462 | unsigned size() const { return TrackedParams.size(); } | ||||
1463 | |||||
1464 | llvm::Optional<unsigned> getIndexOfCallee(const CallExpr *Call) const { | ||||
1465 | return getIndexOfExpression(Call->getCallee()); | ||||
1466 | } | ||||
1467 | |||||
1468 | llvm::Optional<unsigned> getIndexOfExpression(const Expr *E) const { | ||||
1469 | if (const ParmVarDecl *Parameter = findReferencedParmVarDecl(E)) { | ||||
1470 | return getIndex(*Parameter); | ||||
1471 | } | ||||
1472 | |||||
1473 | return llvm::None; | ||||
1474 | } | ||||
1475 | |||||
1476 | llvm::Optional<unsigned> getIndex(const ParmVarDecl &Parameter) const { | ||||
1477 | // Expected number of parameters that we actually track is 1. | ||||
1478 | // | ||||
1479 | // Also, the maximum number of declared parameters could not be on a scale | ||||
1480 | // of hundreds of thousands. | ||||
1481 | // | ||||
1482 | // In this setting, linear search seems reasonable and even performs better | ||||
1483 | // than bisection. | ||||
1484 | ParamSizedVector<const ParmVarDecl *>::const_iterator It = | ||||
1485 | llvm::find(TrackedParams, &Parameter); | ||||
1486 | |||||
1487 | if (It != TrackedParams.end()) { | ||||
1488 | return It - TrackedParams.begin(); | ||||
1489 | } | ||||
1490 | |||||
1491 | return llvm::None; | ||||
1492 | } | ||||
1493 | |||||
1494 | const ParmVarDecl *getParameter(unsigned Index) const { | ||||
1495 | assert(Index < TrackedParams.size())((Index < TrackedParams.size()) ? static_cast<void> ( 0) : __assert_fail ("Index < TrackedParams.size()", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Analysis/CalledOnceCheck.cpp" , 1495, __PRETTY_FUNCTION__)); | ||||
1496 | return TrackedParams[Index]; | ||||
1497 | } | ||||
1498 | |||||
1499 | const CFG &FunctionCFG; | ||||
1500 | AnalysisDeclContext &AC; | ||||
1501 | CalledOnceCheckHandler &Handler; | ||||
1502 | bool CheckConventionalParameters; | ||||
1503 | // As of now, we turn this behavior off. So, we still are going to report | ||||
1504 | // missing calls on paths that look like it was intentional. | ||||
1505 | // Technically such reports are true positives, but they can make some users | ||||
1506 | // grumpy because of the sheer number of warnings. | ||||
1507 | // It can be turned back on if we decide that we want to have the other way | ||||
1508 | // around. | ||||
1509 | bool SuppressOnConventionalErrorPaths = false; | ||||
1510 | |||||
1511 | State CurrentState; | ||||
1512 | ParamSizedVector<const ParmVarDecl *> TrackedParams; | ||||
1513 | CFGSizedVector<State> States; | ||||
1514 | }; | ||||
1515 | |||||
1516 | } // end anonymous namespace | ||||
1517 | |||||
1518 | namespace clang { | ||||
1519 | void checkCalledOnceParameters(AnalysisDeclContext &AC, | ||||
1520 | CalledOnceCheckHandler &Handler, | ||||
1521 | bool CheckConventionalParameters) { | ||||
1522 | CalledOnceChecker::check(AC, Handler, CheckConventionalParameters); | ||||
1523 | } | ||||
1524 | } // end namespace clang |
1 | //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | /// \file |
10 | /// C Language Family Type Representation |
11 | /// |
12 | /// This file defines the clang::Type interface and subclasses, used to |
13 | /// represent types for languages in the C family. |
14 | // |
15 | //===----------------------------------------------------------------------===// |
16 | |
17 | #ifndef LLVM_CLANG_AST_TYPE_H |
18 | #define LLVM_CLANG_AST_TYPE_H |
19 | |
20 | #include "clang/AST/DependenceFlags.h" |
21 | #include "clang/AST/NestedNameSpecifier.h" |
22 | #include "clang/AST/TemplateName.h" |
23 | #include "clang/Basic/AddressSpaces.h" |
24 | #include "clang/Basic/AttrKinds.h" |
25 | #include "clang/Basic/Diagnostic.h" |
26 | #include "clang/Basic/ExceptionSpecificationType.h" |
27 | #include "clang/Basic/LLVM.h" |
28 | #include "clang/Basic/Linkage.h" |
29 | #include "clang/Basic/PartialDiagnostic.h" |
30 | #include "clang/Basic/SourceLocation.h" |
31 | #include "clang/Basic/Specifiers.h" |
32 | #include "clang/Basic/Visibility.h" |
33 | #include "llvm/ADT/APInt.h" |
34 | #include "llvm/ADT/APSInt.h" |
35 | #include "llvm/ADT/ArrayRef.h" |
36 | #include "llvm/ADT/FoldingSet.h" |
37 | #include "llvm/ADT/None.h" |
38 | #include "llvm/ADT/Optional.h" |
39 | #include "llvm/ADT/PointerIntPair.h" |
40 | #include "llvm/ADT/PointerUnion.h" |
41 | #include "llvm/ADT/StringRef.h" |
42 | #include "llvm/ADT/Twine.h" |
43 | #include "llvm/ADT/iterator_range.h" |
44 | #include "llvm/Support/Casting.h" |
45 | #include "llvm/Support/Compiler.h" |
46 | #include "llvm/Support/ErrorHandling.h" |
47 | #include "llvm/Support/PointerLikeTypeTraits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include "llvm/Support/type_traits.h" |
50 | #include <cassert> |
51 | #include <cstddef> |
52 | #include <cstdint> |
53 | #include <cstring> |
54 | #include <string> |
55 | #include <type_traits> |
56 | #include <utility> |
57 | |
58 | namespace clang { |
59 | |
60 | class ExtQuals; |
61 | class QualType; |
62 | class ConceptDecl; |
63 | class TagDecl; |
64 | class TemplateParameterList; |
65 | class Type; |
66 | |
67 | enum { |
68 | TypeAlignmentInBits = 4, |
69 | TypeAlignment = 1 << TypeAlignmentInBits |
70 | }; |
71 | |
72 | namespace serialization { |
73 | template <class T> class AbstractTypeReader; |
74 | template <class T> class AbstractTypeWriter; |
75 | } |
76 | |
77 | } // namespace clang |
78 | |
79 | namespace llvm { |
80 | |
81 | template <typename T> |
82 | struct PointerLikeTypeTraits; |
83 | template<> |
84 | struct PointerLikeTypeTraits< ::clang::Type*> { |
85 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
86 | |
87 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
88 | return static_cast< ::clang::Type*>(P); |
89 | } |
90 | |
91 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
92 | }; |
93 | |
94 | template<> |
95 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
96 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
97 | |
98 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
99 | return static_cast< ::clang::ExtQuals*>(P); |
100 | } |
101 | |
102 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
103 | }; |
104 | |
105 | } // namespace llvm |
106 | |
107 | namespace clang { |
108 | |
109 | class ASTContext; |
110 | template <typename> class CanQual; |
111 | class CXXRecordDecl; |
112 | class DeclContext; |
113 | class EnumDecl; |
114 | class Expr; |
115 | class ExtQualsTypeCommonBase; |
116 | class FunctionDecl; |
117 | class IdentifierInfo; |
118 | class NamedDecl; |
119 | class ObjCInterfaceDecl; |
120 | class ObjCProtocolDecl; |
121 | class ObjCTypeParamDecl; |
122 | struct PrintingPolicy; |
123 | class RecordDecl; |
124 | class Stmt; |
125 | class TagDecl; |
126 | class TemplateArgument; |
127 | class TemplateArgumentListInfo; |
128 | class TemplateArgumentLoc; |
129 | class TemplateTypeParmDecl; |
130 | class TypedefNameDecl; |
131 | class UnresolvedUsingTypenameDecl; |
132 | |
133 | using CanQualType = CanQual<Type>; |
134 | |
135 | // Provide forward declarations for all of the *Type classes. |
136 | #define TYPE(Class, Base) class Class##Type; |
137 | #include "clang/AST/TypeNodes.inc" |
138 | |
139 | /// The collection of all-type qualifiers we support. |
140 | /// Clang supports five independent qualifiers: |
141 | /// * C99: const, volatile, and restrict |
142 | /// * MS: __unaligned |
143 | /// * Embedded C (TR18037): address spaces |
144 | /// * Objective C: the GC attributes (none, weak, or strong) |
145 | class Qualifiers { |
146 | public: |
147 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
148 | Const = 0x1, |
149 | Restrict = 0x2, |
150 | Volatile = 0x4, |
151 | CVRMask = Const | Volatile | Restrict |
152 | }; |
153 | |
154 | enum GC { |
155 | GCNone = 0, |
156 | Weak, |
157 | Strong |
158 | }; |
159 | |
160 | enum ObjCLifetime { |
161 | /// There is no lifetime qualification on this type. |
162 | OCL_None, |
163 | |
164 | /// This object can be modified without requiring retains or |
165 | /// releases. |
166 | OCL_ExplicitNone, |
167 | |
168 | /// Assigning into this object requires the old value to be |
169 | /// released and the new value to be retained. The timing of the |
170 | /// release of the old value is inexact: it may be moved to |
171 | /// immediately after the last known point where the value is |
172 | /// live. |
173 | OCL_Strong, |
174 | |
175 | /// Reading or writing from this object requires a barrier call. |
176 | OCL_Weak, |
177 | |
178 | /// Assigning into this object requires a lifetime extension. |
179 | OCL_Autoreleasing |
180 | }; |
181 | |
182 | enum { |
183 | /// The maximum supported address space number. |
184 | /// 23 bits should be enough for anyone. |
185 | MaxAddressSpace = 0x7fffffu, |
186 | |
187 | /// The width of the "fast" qualifier mask. |
188 | FastWidth = 3, |
189 | |
190 | /// The fast qualifier mask. |
191 | FastMask = (1 << FastWidth) - 1 |
192 | }; |
193 | |
194 | /// Returns the common set of qualifiers while removing them from |
195 | /// the given sets. |
196 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
197 | // If both are only CVR-qualified, bit operations are sufficient. |
198 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
199 | Qualifiers Q; |
200 | Q.Mask = L.Mask & R.Mask; |
201 | L.Mask &= ~Q.Mask; |
202 | R.Mask &= ~Q.Mask; |
203 | return Q; |
204 | } |
205 | |
206 | Qualifiers Q; |
207 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
208 | Q.addCVRQualifiers(CommonCRV); |
209 | L.removeCVRQualifiers(CommonCRV); |
210 | R.removeCVRQualifiers(CommonCRV); |
211 | |
212 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
213 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
214 | L.removeObjCGCAttr(); |
215 | R.removeObjCGCAttr(); |
216 | } |
217 | |
218 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
219 | Q.setObjCLifetime(L.getObjCLifetime()); |
220 | L.removeObjCLifetime(); |
221 | R.removeObjCLifetime(); |
222 | } |
223 | |
224 | if (L.getAddressSpace() == R.getAddressSpace()) { |
225 | Q.setAddressSpace(L.getAddressSpace()); |
226 | L.removeAddressSpace(); |
227 | R.removeAddressSpace(); |
228 | } |
229 | return Q; |
230 | } |
231 | |
232 | static Qualifiers fromFastMask(unsigned Mask) { |
233 | Qualifiers Qs; |
234 | Qs.addFastQualifiers(Mask); |
235 | return Qs; |
236 | } |
237 | |
238 | static Qualifiers fromCVRMask(unsigned CVR) { |
239 | Qualifiers Qs; |
240 | Qs.addCVRQualifiers(CVR); |
241 | return Qs; |
242 | } |
243 | |
244 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
245 | Qualifiers Qs; |
246 | Qs.addCVRUQualifiers(CVRU); |
247 | return Qs; |
248 | } |
249 | |
250 | // Deserialize qualifiers from an opaque representation. |
251 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
252 | Qualifiers Qs; |
253 | Qs.Mask = opaque; |
254 | return Qs; |
255 | } |
256 | |
257 | // Serialize these qualifiers into an opaque representation. |
258 | unsigned getAsOpaqueValue() const { |
259 | return Mask; |
260 | } |
261 | |
262 | bool hasConst() const { return Mask & Const; } |
263 | bool hasOnlyConst() const { return Mask == Const; } |
264 | void removeConst() { Mask &= ~Const; } |
265 | void addConst() { Mask |= Const; } |
266 | |
267 | bool hasVolatile() const { return Mask & Volatile; } |
268 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
269 | void removeVolatile() { Mask &= ~Volatile; } |
270 | void addVolatile() { Mask |= Volatile; } |
271 | |
272 | bool hasRestrict() const { return Mask & Restrict; } |
273 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
274 | void removeRestrict() { Mask &= ~Restrict; } |
275 | void addRestrict() { Mask |= Restrict; } |
276 | |
277 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
278 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
279 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
280 | |
281 | void setCVRQualifiers(unsigned mask) { |
282 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 282, __PRETTY_FUNCTION__)); |
283 | Mask = (Mask & ~CVRMask) | mask; |
284 | } |
285 | void removeCVRQualifiers(unsigned mask) { |
286 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 286, __PRETTY_FUNCTION__)); |
287 | Mask &= ~mask; |
288 | } |
289 | void removeCVRQualifiers() { |
290 | removeCVRQualifiers(CVRMask); |
291 | } |
292 | void addCVRQualifiers(unsigned mask) { |
293 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 293, __PRETTY_FUNCTION__)); |
294 | Mask |= mask; |
295 | } |
296 | void addCVRUQualifiers(unsigned mask) { |
297 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 297, __PRETTY_FUNCTION__)); |
298 | Mask |= mask; |
299 | } |
300 | |
301 | bool hasUnaligned() const { return Mask & UMask; } |
302 | void setUnaligned(bool flag) { |
303 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
304 | } |
305 | void removeUnaligned() { Mask &= ~UMask; } |
306 | void addUnaligned() { Mask |= UMask; } |
307 | |
308 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
309 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
310 | void setObjCGCAttr(GC type) { |
311 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
312 | } |
313 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
314 | void addObjCGCAttr(GC type) { |
315 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 315, __PRETTY_FUNCTION__)); |
316 | setObjCGCAttr(type); |
317 | } |
318 | Qualifiers withoutObjCGCAttr() const { |
319 | Qualifiers qs = *this; |
320 | qs.removeObjCGCAttr(); |
321 | return qs; |
322 | } |
323 | Qualifiers withoutObjCLifetime() const { |
324 | Qualifiers qs = *this; |
325 | qs.removeObjCLifetime(); |
326 | return qs; |
327 | } |
328 | Qualifiers withoutAddressSpace() const { |
329 | Qualifiers qs = *this; |
330 | qs.removeAddressSpace(); |
331 | return qs; |
332 | } |
333 | |
334 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
335 | ObjCLifetime getObjCLifetime() const { |
336 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
337 | } |
338 | void setObjCLifetime(ObjCLifetime type) { |
339 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
340 | } |
341 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
342 | void addObjCLifetime(ObjCLifetime type) { |
343 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 343, __PRETTY_FUNCTION__)); |
344 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 344, __PRETTY_FUNCTION__)); |
345 | Mask |= (type << LifetimeShift); |
346 | } |
347 | |
348 | /// True if the lifetime is neither None or ExplicitNone. |
349 | bool hasNonTrivialObjCLifetime() const { |
350 | ObjCLifetime lifetime = getObjCLifetime(); |
351 | return (lifetime > OCL_ExplicitNone); |
352 | } |
353 | |
354 | /// True if the lifetime is either strong or weak. |
355 | bool hasStrongOrWeakObjCLifetime() const { |
356 | ObjCLifetime lifetime = getObjCLifetime(); |
357 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
358 | } |
359 | |
360 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
361 | LangAS getAddressSpace() const { |
362 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
363 | } |
364 | bool hasTargetSpecificAddressSpace() const { |
365 | return isTargetAddressSpace(getAddressSpace()); |
366 | } |
367 | /// Get the address space attribute value to be printed by diagnostics. |
368 | unsigned getAddressSpaceAttributePrintValue() const { |
369 | auto Addr = getAddressSpace(); |
370 | // This function is not supposed to be used with language specific |
371 | // address spaces. If that happens, the diagnostic message should consider |
372 | // printing the QualType instead of the address space value. |
373 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 373, __PRETTY_FUNCTION__)); |
374 | if (Addr != LangAS::Default) |
375 | return toTargetAddressSpace(Addr); |
376 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
377 | // since it cannot differentiate the situation where 0 denotes the default |
378 | // address space or user specified __attribute__((address_space(0))). |
379 | return 0; |
380 | } |
381 | void setAddressSpace(LangAS space) { |
382 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 382, __PRETTY_FUNCTION__)); |
383 | Mask = (Mask & ~AddressSpaceMask) |
384 | | (((uint32_t) space) << AddressSpaceShift); |
385 | } |
386 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
387 | void addAddressSpace(LangAS space) { |
388 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 388, __PRETTY_FUNCTION__)); |
389 | setAddressSpace(space); |
390 | } |
391 | |
392 | // Fast qualifiers are those that can be allocated directly |
393 | // on a QualType object. |
394 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
395 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
396 | void setFastQualifiers(unsigned mask) { |
397 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 397, __PRETTY_FUNCTION__)); |
398 | Mask = (Mask & ~FastMask) | mask; |
399 | } |
400 | void removeFastQualifiers(unsigned mask) { |
401 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 401, __PRETTY_FUNCTION__)); |
402 | Mask &= ~mask; |
403 | } |
404 | void removeFastQualifiers() { |
405 | removeFastQualifiers(FastMask); |
406 | } |
407 | void addFastQualifiers(unsigned mask) { |
408 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 408, __PRETTY_FUNCTION__)); |
409 | Mask |= mask; |
410 | } |
411 | |
412 | /// Return true if the set contains any qualifiers which require an ExtQuals |
413 | /// node to be allocated. |
414 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
415 | Qualifiers getNonFastQualifiers() const { |
416 | Qualifiers Quals = *this; |
417 | Quals.setFastQualifiers(0); |
418 | return Quals; |
419 | } |
420 | |
421 | /// Return true if the set contains any qualifiers. |
422 | bool hasQualifiers() const { return Mask; } |
423 | bool empty() const { return !Mask; } |
424 | |
425 | /// Add the qualifiers from the given set to this set. |
426 | void addQualifiers(Qualifiers Q) { |
427 | // If the other set doesn't have any non-boolean qualifiers, just |
428 | // bit-or it in. |
429 | if (!(Q.Mask & ~CVRMask)) |
430 | Mask |= Q.Mask; |
431 | else { |
432 | Mask |= (Q.Mask & CVRMask); |
433 | if (Q.hasAddressSpace()) |
434 | addAddressSpace(Q.getAddressSpace()); |
435 | if (Q.hasObjCGCAttr()) |
436 | addObjCGCAttr(Q.getObjCGCAttr()); |
437 | if (Q.hasObjCLifetime()) |
438 | addObjCLifetime(Q.getObjCLifetime()); |
439 | } |
440 | } |
441 | |
442 | /// Remove the qualifiers from the given set from this set. |
443 | void removeQualifiers(Qualifiers Q) { |
444 | // If the other set doesn't have any non-boolean qualifiers, just |
445 | // bit-and the inverse in. |
446 | if (!(Q.Mask & ~CVRMask)) |
447 | Mask &= ~Q.Mask; |
448 | else { |
449 | Mask &= ~(Q.Mask & CVRMask); |
450 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
451 | removeObjCGCAttr(); |
452 | if (getObjCLifetime() == Q.getObjCLifetime()) |
453 | removeObjCLifetime(); |
454 | if (getAddressSpace() == Q.getAddressSpace()) |
455 | removeAddressSpace(); |
456 | } |
457 | } |
458 | |
459 | /// Add the qualifiers from the given set to this set, given that |
460 | /// they don't conflict. |
461 | void addConsistentQualifiers(Qualifiers qs) { |
462 | assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 463, __PRETTY_FUNCTION__)) |
463 | !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 463, __PRETTY_FUNCTION__)); |
464 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 465, __PRETTY_FUNCTION__)) |
465 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 465, __PRETTY_FUNCTION__)); |
466 | assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 467, __PRETTY_FUNCTION__)) |
467 | !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 467, __PRETTY_FUNCTION__)); |
468 | Mask |= qs.Mask; |
469 | } |
470 | |
471 | /// Returns true if address space A is equal to or a superset of B. |
472 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
473 | /// overlapping address spaces. |
474 | /// CL1.1 or CL1.2: |
475 | /// every address space is a superset of itself. |
476 | /// CL2.0 adds: |
477 | /// __generic is a superset of any address space except for __constant. |
478 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
479 | // Address spaces must match exactly. |
480 | return A == B || |
481 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
482 | // for __constant can be used as __generic. |
483 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant) || |
484 | // We also define global_device and global_host address spaces, |
485 | // to distinguish global pointers allocated on host from pointers |
486 | // allocated on device, which are a subset of __global. |
487 | (A == LangAS::opencl_global && (B == LangAS::opencl_global_device || |
488 | B == LangAS::opencl_global_host)) || |
489 | // Consider pointer size address spaces to be equivalent to default. |
490 | ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && |
491 | (isPtrSizeAddressSpace(B) || B == LangAS::Default)); |
492 | } |
493 | |
494 | /// Returns true if the address space in these qualifiers is equal to or |
495 | /// a superset of the address space in the argument qualifiers. |
496 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
497 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
498 | } |
499 | |
500 | /// Determines if these qualifiers compatibly include another set. |
501 | /// Generally this answers the question of whether an object with the other |
502 | /// qualifiers can be safely used as an object with these qualifiers. |
503 | bool compatiblyIncludes(Qualifiers other) const { |
504 | return isAddressSpaceSupersetOf(other) && |
505 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
506 | // be changed. |
507 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
508 | !other.hasObjCGCAttr()) && |
509 | // ObjC lifetime qualifiers must match exactly. |
510 | getObjCLifetime() == other.getObjCLifetime() && |
511 | // CVR qualifiers may subset. |
512 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
513 | // U qualifier may superset. |
514 | (!other.hasUnaligned() || hasUnaligned()); |
515 | } |
516 | |
517 | /// Determines if these qualifiers compatibly include another set of |
518 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
519 | /// |
520 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
521 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
522 | /// including set also contains the 'const' qualifier, or both are non-__weak |
523 | /// and one is None (which can only happen in non-ARC modes). |
524 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
525 | if (getObjCLifetime() == other.getObjCLifetime()) |
526 | return true; |
527 | |
528 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
529 | return false; |
530 | |
531 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
532 | return true; |
533 | |
534 | return hasConst(); |
535 | } |
536 | |
537 | /// Determine whether this set of qualifiers is a strict superset of |
538 | /// another set of qualifiers, not considering qualifier compatibility. |
539 | bool isStrictSupersetOf(Qualifiers Other) const; |
540 | |
541 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
542 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
543 | |
544 | explicit operator bool() const { return hasQualifiers(); } |
545 | |
546 | Qualifiers &operator+=(Qualifiers R) { |
547 | addQualifiers(R); |
548 | return *this; |
549 | } |
550 | |
551 | // Union two qualifier sets. If an enumerated qualifier appears |
552 | // in both sets, use the one from the right. |
553 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
554 | L += R; |
555 | return L; |
556 | } |
557 | |
558 | Qualifiers &operator-=(Qualifiers R) { |
559 | removeQualifiers(R); |
560 | return *this; |
561 | } |
562 | |
563 | /// Compute the difference between two qualifier sets. |
564 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
565 | L -= R; |
566 | return L; |
567 | } |
568 | |
569 | std::string getAsString() const; |
570 | std::string getAsString(const PrintingPolicy &Policy) const; |
571 | |
572 | static std::string getAddrSpaceAsString(LangAS AS); |
573 | |
574 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
575 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
576 | bool appendSpaceIfNonEmpty = false) const; |
577 | |
578 | void Profile(llvm::FoldingSetNodeID &ID) const { |
579 | ID.AddInteger(Mask); |
580 | } |
581 | |
582 | private: |
583 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
584 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
585 | uint32_t Mask = 0; |
586 | |
587 | static const uint32_t UMask = 0x8; |
588 | static const uint32_t UShift = 3; |
589 | static const uint32_t GCAttrMask = 0x30; |
590 | static const uint32_t GCAttrShift = 4; |
591 | static const uint32_t LifetimeMask = 0x1C0; |
592 | static const uint32_t LifetimeShift = 6; |
593 | static const uint32_t AddressSpaceMask = |
594 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
595 | static const uint32_t AddressSpaceShift = 9; |
596 | }; |
597 | |
598 | /// A std::pair-like structure for storing a qualified type split |
599 | /// into its local qualifiers and its locally-unqualified type. |
600 | struct SplitQualType { |
601 | /// The locally-unqualified type. |
602 | const Type *Ty = nullptr; |
603 | |
604 | /// The local qualifiers. |
605 | Qualifiers Quals; |
606 | |
607 | SplitQualType() = default; |
608 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
609 | |
610 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
611 | |
612 | // Make std::tie work. |
613 | std::pair<const Type *,Qualifiers> asPair() const { |
614 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
615 | } |
616 | |
617 | friend bool operator==(SplitQualType a, SplitQualType b) { |
618 | return a.Ty == b.Ty && a.Quals == b.Quals; |
619 | } |
620 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
621 | return a.Ty != b.Ty || a.Quals != b.Quals; |
622 | } |
623 | }; |
624 | |
625 | /// The kind of type we are substituting Objective-C type arguments into. |
626 | /// |
627 | /// The kind of substitution affects the replacement of type parameters when |
628 | /// no concrete type information is provided, e.g., when dealing with an |
629 | /// unspecialized type. |
630 | enum class ObjCSubstitutionContext { |
631 | /// An ordinary type. |
632 | Ordinary, |
633 | |
634 | /// The result type of a method or function. |
635 | Result, |
636 | |
637 | /// The parameter type of a method or function. |
638 | Parameter, |
639 | |
640 | /// The type of a property. |
641 | Property, |
642 | |
643 | /// The superclass of a type. |
644 | Superclass, |
645 | }; |
646 | |
647 | /// A (possibly-)qualified type. |
648 | /// |
649 | /// For efficiency, we don't store CV-qualified types as nodes on their |
650 | /// own: instead each reference to a type stores the qualifiers. This |
651 | /// greatly reduces the number of nodes we need to allocate for types (for |
652 | /// example we only need one for 'int', 'const int', 'volatile int', |
653 | /// 'const volatile int', etc). |
654 | /// |
655 | /// As an added efficiency bonus, instead of making this a pair, we |
656 | /// just store the two bits we care about in the low bits of the |
657 | /// pointer. To handle the packing/unpacking, we make QualType be a |
658 | /// simple wrapper class that acts like a smart pointer. A third bit |
659 | /// indicates whether there are extended qualifiers present, in which |
660 | /// case the pointer points to a special structure. |
661 | class QualType { |
662 | friend class QualifierCollector; |
663 | |
664 | // Thankfully, these are efficiently composable. |
665 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
666 | Qualifiers::FastWidth> Value; |
667 | |
668 | const ExtQuals *getExtQualsUnsafe() const { |
669 | return Value.getPointer().get<const ExtQuals*>(); |
670 | } |
671 | |
672 | const Type *getTypePtrUnsafe() const { |
673 | return Value.getPointer().get<const Type*>(); |
674 | } |
675 | |
676 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
677 | assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer") ? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 677, __PRETTY_FUNCTION__)); |
678 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
679 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
680 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
681 | } |
682 | |
683 | public: |
684 | QualType() = default; |
685 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
686 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
687 | |
688 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
689 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
690 | |
691 | /// Retrieves a pointer to the underlying (unqualified) type. |
692 | /// |
693 | /// This function requires that the type not be NULL. If the type might be |
694 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
695 | const Type *getTypePtr() const; |
696 | |
697 | const Type *getTypePtrOrNull() const; |
698 | |
699 | /// Retrieves a pointer to the name of the base type. |
700 | const IdentifierInfo *getBaseTypeIdentifier() const; |
701 | |
702 | /// Divides a QualType into its unqualified type and a set of local |
703 | /// qualifiers. |
704 | SplitQualType split() const; |
705 | |
706 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
707 | |
708 | static QualType getFromOpaquePtr(const void *Ptr) { |
709 | QualType T; |
710 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
711 | return T; |
712 | } |
713 | |
714 | const Type &operator*() const { |
715 | return *getTypePtr(); |
716 | } |
717 | |
718 | const Type *operator->() const { |
719 | return getTypePtr(); |
720 | } |
721 | |
722 | bool isCanonical() const; |
723 | bool isCanonicalAsParam() const; |
724 | |
725 | /// Return true if this QualType doesn't point to a type yet. |
726 | bool isNull() const { |
727 | return Value.getPointer().isNull(); |
728 | } |
729 | |
730 | /// Determine whether this particular QualType instance has the |
731 | /// "const" qualifier set, without looking through typedefs that may have |
732 | /// added "const" at a different level. |
733 | bool isLocalConstQualified() const { |
734 | return (getLocalFastQualifiers() & Qualifiers::Const); |
735 | } |
736 | |
737 | /// Determine whether this type is const-qualified. |
738 | bool isConstQualified() const; |
739 | |
740 | /// Determine whether this particular QualType instance has the |
741 | /// "restrict" qualifier set, without looking through typedefs that may have |
742 | /// added "restrict" at a different level. |
743 | bool isLocalRestrictQualified() const { |
744 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
745 | } |
746 | |
747 | /// Determine whether this type is restrict-qualified. |
748 | bool isRestrictQualified() const; |
749 | |
750 | /// Determine whether this particular QualType instance has the |
751 | /// "volatile" qualifier set, without looking through typedefs that may have |
752 | /// added "volatile" at a different level. |
753 | bool isLocalVolatileQualified() const { |
754 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
755 | } |
756 | |
757 | /// Determine whether this type is volatile-qualified. |
758 | bool isVolatileQualified() const; |
759 | |
760 | /// Determine whether this particular QualType instance has any |
761 | /// qualifiers, without looking through any typedefs that might add |
762 | /// qualifiers at a different level. |
763 | bool hasLocalQualifiers() const { |
764 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
765 | } |
766 | |
767 | /// Determine whether this type has any qualifiers. |
768 | bool hasQualifiers() const; |
769 | |
770 | /// Determine whether this particular QualType instance has any |
771 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
772 | /// instance. |
773 | bool hasLocalNonFastQualifiers() const { |
774 | return Value.getPointer().is<const ExtQuals*>(); |
775 | } |
776 | |
777 | /// Retrieve the set of qualifiers local to this particular QualType |
778 | /// instance, not including any qualifiers acquired through typedefs or |
779 | /// other sugar. |
780 | Qualifiers getLocalQualifiers() const; |
781 | |
782 | /// Retrieve the set of qualifiers applied to this type. |
783 | Qualifiers getQualifiers() const; |
784 | |
785 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
786 | /// local to this particular QualType instance, not including any qualifiers |
787 | /// acquired through typedefs or other sugar. |
788 | unsigned getLocalCVRQualifiers() const { |
789 | return getLocalFastQualifiers(); |
790 | } |
791 | |
792 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
793 | /// applied to this type. |
794 | unsigned getCVRQualifiers() const; |
795 | |
796 | bool isConstant(const ASTContext& Ctx) const { |
797 | return QualType::isConstant(*this, Ctx); |
798 | } |
799 | |
800 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
801 | bool isPODType(const ASTContext &Context) const; |
802 | |
803 | /// Return true if this is a POD type according to the rules of the C++98 |
804 | /// standard, regardless of the current compilation's language. |
805 | bool isCXX98PODType(const ASTContext &Context) const; |
806 | |
807 | /// Return true if this is a POD type according to the more relaxed rules |
808 | /// of the C++11 standard, regardless of the current compilation's language. |
809 | /// (C++0x [basic.types]p9). Note that, unlike |
810 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
811 | bool isCXX11PODType(const ASTContext &Context) const; |
812 | |
813 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
814 | bool isTrivialType(const ASTContext &Context) const; |
815 | |
816 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
817 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
818 | |
819 | |
820 | /// Returns true if it is a class and it might be dynamic. |
821 | bool mayBeDynamicClass() const; |
822 | |
823 | /// Returns true if it is not a class or if the class might not be dynamic. |
824 | bool mayBeNotDynamicClass() const; |
825 | |
826 | // Don't promise in the API that anything besides 'const' can be |
827 | // easily added. |
828 | |
829 | /// Add the `const` type qualifier to this QualType. |
830 | void addConst() { |
831 | addFastQualifiers(Qualifiers::Const); |
832 | } |
833 | QualType withConst() const { |
834 | return withFastQualifiers(Qualifiers::Const); |
835 | } |
836 | |
837 | /// Add the `volatile` type qualifier to this QualType. |
838 | void addVolatile() { |
839 | addFastQualifiers(Qualifiers::Volatile); |
840 | } |
841 | QualType withVolatile() const { |
842 | return withFastQualifiers(Qualifiers::Volatile); |
843 | } |
844 | |
845 | /// Add the `restrict` qualifier to this QualType. |
846 | void addRestrict() { |
847 | addFastQualifiers(Qualifiers::Restrict); |
848 | } |
849 | QualType withRestrict() const { |
850 | return withFastQualifiers(Qualifiers::Restrict); |
851 | } |
852 | |
853 | QualType withCVRQualifiers(unsigned CVR) const { |
854 | return withFastQualifiers(CVR); |
855 | } |
856 | |
857 | void addFastQualifiers(unsigned TQs) { |
858 | assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 859, __PRETTY_FUNCTION__)) |
859 | && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 859, __PRETTY_FUNCTION__)); |
860 | Value.setInt(Value.getInt() | TQs); |
861 | } |
862 | |
863 | void removeLocalConst(); |
864 | void removeLocalVolatile(); |
865 | void removeLocalRestrict(); |
866 | void removeLocalCVRQualifiers(unsigned Mask); |
867 | |
868 | void removeLocalFastQualifiers() { Value.setInt(0); } |
869 | void removeLocalFastQualifiers(unsigned Mask) { |
870 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 870, __PRETTY_FUNCTION__)); |
871 | Value.setInt(Value.getInt() & ~Mask); |
872 | } |
873 | |
874 | // Creates a type with the given qualifiers in addition to any |
875 | // qualifiers already on this type. |
876 | QualType withFastQualifiers(unsigned TQs) const { |
877 | QualType T = *this; |
878 | T.addFastQualifiers(TQs); |
879 | return T; |
880 | } |
881 | |
882 | // Creates a type with exactly the given fast qualifiers, removing |
883 | // any existing fast qualifiers. |
884 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
885 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
886 | } |
887 | |
888 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
889 | QualType withoutLocalFastQualifiers() const { |
890 | QualType T = *this; |
891 | T.removeLocalFastQualifiers(); |
892 | return T; |
893 | } |
894 | |
895 | QualType getCanonicalType() const; |
896 | |
897 | /// Return this type with all of the instance-specific qualifiers |
898 | /// removed, but without removing any qualifiers that may have been applied |
899 | /// through typedefs. |
900 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
901 | |
902 | /// Retrieve the unqualified variant of the given type, |
903 | /// removing as little sugar as possible. |
904 | /// |
905 | /// This routine looks through various kinds of sugar to find the |
906 | /// least-desugared type that is unqualified. For example, given: |
907 | /// |
908 | /// \code |
909 | /// typedef int Integer; |
910 | /// typedef const Integer CInteger; |
911 | /// typedef CInteger DifferenceType; |
912 | /// \endcode |
913 | /// |
914 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
915 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
916 | /// |
917 | /// The resulting type might still be qualified if it's sugar for an array |
918 | /// type. To strip qualifiers even from within a sugared array type, use |
919 | /// ASTContext::getUnqualifiedArrayType. |
920 | inline QualType getUnqualifiedType() const; |
921 | |
922 | /// Retrieve the unqualified variant of the given type, removing as little |
923 | /// sugar as possible. |
924 | /// |
925 | /// Like getUnqualifiedType(), but also returns the set of |
926 | /// qualifiers that were built up. |
927 | /// |
928 | /// The resulting type might still be qualified if it's sugar for an array |
929 | /// type. To strip qualifiers even from within a sugared array type, use |
930 | /// ASTContext::getUnqualifiedArrayType. |
931 | inline SplitQualType getSplitUnqualifiedType() const; |
932 | |
933 | /// Determine whether this type is more qualified than the other |
934 | /// given type, requiring exact equality for non-CVR qualifiers. |
935 | bool isMoreQualifiedThan(QualType Other) const; |
936 | |
937 | /// Determine whether this type is at least as qualified as the other |
938 | /// given type, requiring exact equality for non-CVR qualifiers. |
939 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
940 | |
941 | QualType getNonReferenceType() const; |
942 | |
943 | /// Determine the type of a (typically non-lvalue) expression with the |
944 | /// specified result type. |
945 | /// |
946 | /// This routine should be used for expressions for which the return type is |
947 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
948 | /// an lvalue. It removes a top-level reference (since there are no |
949 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
950 | /// from non-class types (in C++) or all types (in C). |
951 | QualType getNonLValueExprType(const ASTContext &Context) const; |
952 | |
953 | /// Remove an outer pack expansion type (if any) from this type. Used as part |
954 | /// of converting the type of a declaration to the type of an expression that |
955 | /// references that expression. It's meaningless for an expression to have a |
956 | /// pack expansion type. |
957 | QualType getNonPackExpansionType() const; |
958 | |
959 | /// Return the specified type with any "sugar" removed from |
960 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
961 | /// the type is already concrete, it returns it unmodified. This is similar |
962 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
963 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
964 | /// concrete. |
965 | /// |
966 | /// Qualifiers are left in place. |
967 | QualType getDesugaredType(const ASTContext &Context) const { |
968 | return getDesugaredType(*this, Context); |
969 | } |
970 | |
971 | SplitQualType getSplitDesugaredType() const { |
972 | return getSplitDesugaredType(*this); |
973 | } |
974 | |
975 | /// Return the specified type with one level of "sugar" removed from |
976 | /// the type. |
977 | /// |
978 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
979 | /// of the type is already concrete, it returns it unmodified. |
980 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
981 | return getSingleStepDesugaredTypeImpl(*this, Context); |
982 | } |
983 | |
984 | /// Returns the specified type after dropping any |
985 | /// outer-level parentheses. |
986 | QualType IgnoreParens() const { |
987 | if (isa<ParenType>(*this)) |
988 | return QualType::IgnoreParens(*this); |
989 | return *this; |
990 | } |
991 | |
992 | /// Indicate whether the specified types and qualifiers are identical. |
993 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
994 | return LHS.Value == RHS.Value; |
995 | } |
996 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
997 | return LHS.Value != RHS.Value; |
998 | } |
999 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
1000 | return LHS.Value < RHS.Value; |
1001 | } |
1002 | |
1003 | static std::string getAsString(SplitQualType split, |
1004 | const PrintingPolicy &Policy) { |
1005 | return getAsString(split.Ty, split.Quals, Policy); |
1006 | } |
1007 | static std::string getAsString(const Type *ty, Qualifiers qs, |
1008 | const PrintingPolicy &Policy); |
1009 | |
1010 | std::string getAsString() const; |
1011 | std::string getAsString(const PrintingPolicy &Policy) const; |
1012 | |
1013 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
1014 | const Twine &PlaceHolder = Twine(), |
1015 | unsigned Indentation = 0) const; |
1016 | |
1017 | static void print(SplitQualType split, raw_ostream &OS, |
1018 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
1019 | unsigned Indentation = 0) { |
1020 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
1021 | } |
1022 | |
1023 | static void print(const Type *ty, Qualifiers qs, |
1024 | raw_ostream &OS, const PrintingPolicy &policy, |
1025 | const Twine &PlaceHolder, |
1026 | unsigned Indentation = 0); |
1027 | |
1028 | void getAsStringInternal(std::string &Str, |
1029 | const PrintingPolicy &Policy) const; |
1030 | |
1031 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1032 | const PrintingPolicy &policy) { |
1033 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1034 | } |
1035 | |
1036 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1037 | std::string &out, |
1038 | const PrintingPolicy &policy); |
1039 | |
1040 | class StreamedQualTypeHelper { |
1041 | const QualType &T; |
1042 | const PrintingPolicy &Policy; |
1043 | const Twine &PlaceHolder; |
1044 | unsigned Indentation; |
1045 | |
1046 | public: |
1047 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1048 | const Twine &PlaceHolder, unsigned Indentation) |
1049 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1050 | Indentation(Indentation) {} |
1051 | |
1052 | friend raw_ostream &operator<<(raw_ostream &OS, |
1053 | const StreamedQualTypeHelper &SQT) { |
1054 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1055 | return OS; |
1056 | } |
1057 | }; |
1058 | |
1059 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1060 | const Twine &PlaceHolder = Twine(), |
1061 | unsigned Indentation = 0) const { |
1062 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1063 | } |
1064 | |
1065 | void dump(const char *s) const; |
1066 | void dump() const; |
1067 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
1068 | |
1069 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1070 | ID.AddPointer(getAsOpaquePtr()); |
1071 | } |
1072 | |
1073 | /// Check if this type has any address space qualifier. |
1074 | inline bool hasAddressSpace() const; |
1075 | |
1076 | /// Return the address space of this type. |
1077 | inline LangAS getAddressSpace() const; |
1078 | |
1079 | /// Returns true if address space qualifiers overlap with T address space |
1080 | /// qualifiers. |
1081 | /// OpenCL C defines conversion rules for pointers to different address spaces |
1082 | /// and notion of overlapping address spaces. |
1083 | /// CL1.1 or CL1.2: |
1084 | /// address spaces overlap iff they are they same. |
1085 | /// OpenCL C v2.0 s6.5.5 adds: |
1086 | /// __generic overlaps with any address space except for __constant. |
1087 | bool isAddressSpaceOverlapping(QualType T) const { |
1088 | Qualifiers Q = getQualifiers(); |
1089 | Qualifiers TQ = T.getQualifiers(); |
1090 | // Address spaces overlap if at least one of them is a superset of another |
1091 | return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q); |
1092 | } |
1093 | |
1094 | /// Returns gc attribute of this type. |
1095 | inline Qualifiers::GC getObjCGCAttr() const; |
1096 | |
1097 | /// true when Type is objc's weak. |
1098 | bool isObjCGCWeak() const { |
1099 | return getObjCGCAttr() == Qualifiers::Weak; |
1100 | } |
1101 | |
1102 | /// true when Type is objc's strong. |
1103 | bool isObjCGCStrong() const { |
1104 | return getObjCGCAttr() == Qualifiers::Strong; |
1105 | } |
1106 | |
1107 | /// Returns lifetime attribute of this type. |
1108 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1109 | return getQualifiers().getObjCLifetime(); |
1110 | } |
1111 | |
1112 | bool hasNonTrivialObjCLifetime() const { |
1113 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1114 | } |
1115 | |
1116 | bool hasStrongOrWeakObjCLifetime() const { |
1117 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1118 | } |
1119 | |
1120 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1121 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1122 | |
1123 | enum PrimitiveDefaultInitializeKind { |
1124 | /// The type does not fall into any of the following categories. Note that |
1125 | /// this case is zero-valued so that values of this enum can be used as a |
1126 | /// boolean condition for non-triviality. |
1127 | PDIK_Trivial, |
1128 | |
1129 | /// The type is an Objective-C retainable pointer type that is qualified |
1130 | /// with the ARC __strong qualifier. |
1131 | PDIK_ARCStrong, |
1132 | |
1133 | /// The type is an Objective-C retainable pointer type that is qualified |
1134 | /// with the ARC __weak qualifier. |
1135 | PDIK_ARCWeak, |
1136 | |
1137 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1138 | PDIK_Struct |
1139 | }; |
1140 | |
1141 | /// Functions to query basic properties of non-trivial C struct types. |
1142 | |
1143 | /// Check if this is a non-trivial type that would cause a C struct |
1144 | /// transitively containing this type to be non-trivial to default initialize |
1145 | /// and return the kind. |
1146 | PrimitiveDefaultInitializeKind |
1147 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1148 | |
1149 | enum PrimitiveCopyKind { |
1150 | /// The type does not fall into any of the following categories. Note that |
1151 | /// this case is zero-valued so that values of this enum can be used as a |
1152 | /// boolean condition for non-triviality. |
1153 | PCK_Trivial, |
1154 | |
1155 | /// The type would be trivial except that it is volatile-qualified. Types |
1156 | /// that fall into one of the other non-trivial cases may additionally be |
1157 | /// volatile-qualified. |
1158 | PCK_VolatileTrivial, |
1159 | |
1160 | /// The type is an Objective-C retainable pointer type that is qualified |
1161 | /// with the ARC __strong qualifier. |
1162 | PCK_ARCStrong, |
1163 | |
1164 | /// The type is an Objective-C retainable pointer type that is qualified |
1165 | /// with the ARC __weak qualifier. |
1166 | PCK_ARCWeak, |
1167 | |
1168 | /// The type is a struct containing a field whose type is neither |
1169 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1170 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1171 | /// semantics are too complex to express here, in part because they depend |
1172 | /// on the exact constructor or assignment operator that is chosen by |
1173 | /// overload resolution to do the copy. |
1174 | PCK_Struct |
1175 | }; |
1176 | |
1177 | /// Check if this is a non-trivial type that would cause a C struct |
1178 | /// transitively containing this type to be non-trivial to copy and return the |
1179 | /// kind. |
1180 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1181 | |
1182 | /// Check if this is a non-trivial type that would cause a C struct |
1183 | /// transitively containing this type to be non-trivial to destructively |
1184 | /// move and return the kind. Destructive move in this context is a C++-style |
1185 | /// move in which the source object is placed in a valid but unspecified state |
1186 | /// after it is moved, as opposed to a truly destructive move in which the |
1187 | /// source object is placed in an uninitialized state. |
1188 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1189 | |
1190 | enum DestructionKind { |
1191 | DK_none, |
1192 | DK_cxx_destructor, |
1193 | DK_objc_strong_lifetime, |
1194 | DK_objc_weak_lifetime, |
1195 | DK_nontrivial_c_struct |
1196 | }; |
1197 | |
1198 | /// Returns a nonzero value if objects of this type require |
1199 | /// non-trivial work to clean up after. Non-zero because it's |
1200 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1201 | /// something require destruction. |
1202 | DestructionKind isDestructedType() const { |
1203 | return isDestructedTypeImpl(*this); |
1204 | } |
1205 | |
1206 | /// Check if this is or contains a C union that is non-trivial to |
1207 | /// default-initialize, which is a union that has a member that is non-trivial |
1208 | /// to default-initialize. If this returns true, |
1209 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1210 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1211 | |
1212 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1213 | /// which is a union that has a member that is non-trivial to destruct. If |
1214 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1215 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1216 | |
1217 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1218 | /// is a union that has a member that is non-trivial to copy. If this returns |
1219 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1220 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1221 | |
1222 | /// Determine whether expressions of the given type are forbidden |
1223 | /// from being lvalues in C. |
1224 | /// |
1225 | /// The expression types that are forbidden to be lvalues are: |
1226 | /// - 'void', but not qualified void |
1227 | /// - function types |
1228 | /// |
1229 | /// The exact rule here is C99 6.3.2.1: |
1230 | /// An lvalue is an expression with an object type or an incomplete |
1231 | /// type other than void. |
1232 | bool isCForbiddenLValueType() const; |
1233 | |
1234 | /// Substitute type arguments for the Objective-C type parameters used in the |
1235 | /// subject type. |
1236 | /// |
1237 | /// \param ctx ASTContext in which the type exists. |
1238 | /// |
1239 | /// \param typeArgs The type arguments that will be substituted for the |
1240 | /// Objective-C type parameters in the subject type, which are generally |
1241 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1242 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1243 | /// for the context. |
1244 | /// |
1245 | /// \param context The context in which the subject type was written. |
1246 | /// |
1247 | /// \returns the resulting type. |
1248 | QualType substObjCTypeArgs(ASTContext &ctx, |
1249 | ArrayRef<QualType> typeArgs, |
1250 | ObjCSubstitutionContext context) const; |
1251 | |
1252 | /// Substitute type arguments from an object type for the Objective-C type |
1253 | /// parameters used in the subject type. |
1254 | /// |
1255 | /// This operation combines the computation of type arguments for |
1256 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1257 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1258 | /// callers that need to perform a single substitution in isolation. |
1259 | /// |
1260 | /// \param objectType The type of the object whose member type we're |
1261 | /// substituting into. For example, this might be the receiver of a message |
1262 | /// or the base of a property access. |
1263 | /// |
1264 | /// \param dc The declaration context from which the subject type was |
1265 | /// retrieved, which indicates (for example) which type parameters should |
1266 | /// be substituted. |
1267 | /// |
1268 | /// \param context The context in which the subject type was written. |
1269 | /// |
1270 | /// \returns the subject type after replacing all of the Objective-C type |
1271 | /// parameters with their corresponding arguments. |
1272 | QualType substObjCMemberType(QualType objectType, |
1273 | const DeclContext *dc, |
1274 | ObjCSubstitutionContext context) const; |
1275 | |
1276 | /// Strip Objective-C "__kindof" types from the given type. |
1277 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1278 | |
1279 | /// Remove all qualifiers including _Atomic. |
1280 | QualType getAtomicUnqualifiedType() const; |
1281 | |
1282 | private: |
1283 | // These methods are implemented in a separate translation unit; |
1284 | // "static"-ize them to avoid creating temporary QualTypes in the |
1285 | // caller. |
1286 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1287 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1288 | static SplitQualType getSplitDesugaredType(QualType T); |
1289 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1290 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1291 | const ASTContext &C); |
1292 | static QualType IgnoreParens(QualType T); |
1293 | static DestructionKind isDestructedTypeImpl(QualType type); |
1294 | |
1295 | /// Check if \param RD is or contains a non-trivial C union. |
1296 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1297 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1298 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1299 | }; |
1300 | |
1301 | } // namespace clang |
1302 | |
1303 | namespace llvm { |
1304 | |
1305 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1306 | /// to a specific Type class. |
1307 | template<> struct simplify_type< ::clang::QualType> { |
1308 | using SimpleType = const ::clang::Type *; |
1309 | |
1310 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1311 | return Val.getTypePtr(); |
1312 | } |
1313 | }; |
1314 | |
1315 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1316 | template<> |
1317 | struct PointerLikeTypeTraits<clang::QualType> { |
1318 | static inline void *getAsVoidPointer(clang::QualType P) { |
1319 | return P.getAsOpaquePtr(); |
1320 | } |
1321 | |
1322 | static inline clang::QualType getFromVoidPointer(void *P) { |
1323 | return clang::QualType::getFromOpaquePtr(P); |
1324 | } |
1325 | |
1326 | // Various qualifiers go in low bits. |
1327 | static constexpr int NumLowBitsAvailable = 0; |
1328 | }; |
1329 | |
1330 | } // namespace llvm |
1331 | |
1332 | namespace clang { |
1333 | |
1334 | /// Base class that is common to both the \c ExtQuals and \c Type |
1335 | /// classes, which allows \c QualType to access the common fields between the |
1336 | /// two. |
1337 | class ExtQualsTypeCommonBase { |
1338 | friend class ExtQuals; |
1339 | friend class QualType; |
1340 | friend class Type; |
1341 | |
1342 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1343 | /// a self-referential pointer (for \c Type). |
1344 | /// |
1345 | /// This pointer allows an efficient mapping from a QualType to its |
1346 | /// underlying type pointer. |
1347 | const Type *const BaseType; |
1348 | |
1349 | /// The canonical type of this type. A QualType. |
1350 | QualType CanonicalType; |
1351 | |
1352 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1353 | : BaseType(baseType), CanonicalType(canon) {} |
1354 | }; |
1355 | |
1356 | /// We can encode up to four bits in the low bits of a |
1357 | /// type pointer, but there are many more type qualifiers that we want |
1358 | /// to be able to apply to an arbitrary type. Therefore we have this |
1359 | /// struct, intended to be heap-allocated and used by QualType to |
1360 | /// store qualifiers. |
1361 | /// |
1362 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1363 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1364 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1365 | /// Objective-C GC attributes) are much more rare. |
1366 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1367 | // NOTE: changing the fast qualifiers should be straightforward as |
1368 | // long as you don't make 'const' non-fast. |
1369 | // 1. Qualifiers: |
1370 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1371 | // Fast qualifiers must occupy the low-order bits. |
1372 | // b) Update Qualifiers::FastWidth and FastMask. |
1373 | // 2. QualType: |
1374 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1375 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1376 | // this header. |
1377 | // 3. ASTContext: |
1378 | // a) Update get{Volatile,Restrict}Type. |
1379 | |
1380 | /// The immutable set of qualifiers applied by this node. Always contains |
1381 | /// extended qualifiers. |
1382 | Qualifiers Quals; |
1383 | |
1384 | ExtQuals *this_() { return this; } |
1385 | |
1386 | public: |
1387 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1388 | : ExtQualsTypeCommonBase(baseType, |
1389 | canon.isNull() ? QualType(this_(), 0) : canon), |
1390 | Quals(quals) { |
1391 | assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 1392, __PRETTY_FUNCTION__)) |
1392 | && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 1392, __PRETTY_FUNCTION__)); |
1393 | assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 1394, __PRETTY_FUNCTION__)) |
1394 | && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 1394, __PRETTY_FUNCTION__)); |
1395 | } |
1396 | |
1397 | Qualifiers getQualifiers() const { return Quals; } |
1398 | |
1399 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1400 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1401 | |
1402 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1403 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1404 | return Quals.getObjCLifetime(); |
1405 | } |
1406 | |
1407 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1408 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1409 | |
1410 | const Type *getBaseType() const { return BaseType; } |
1411 | |
1412 | public: |
1413 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1414 | Profile(ID, getBaseType(), Quals); |
1415 | } |
1416 | |
1417 | static void Profile(llvm::FoldingSetNodeID &ID, |
1418 | const Type *BaseType, |
1419 | Qualifiers Quals) { |
1420 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 1420, __PRETTY_FUNCTION__)); |
1421 | ID.AddPointer(BaseType); |
1422 | Quals.Profile(ID); |
1423 | } |
1424 | }; |
1425 | |
1426 | /// The kind of C++11 ref-qualifier associated with a function type. |
1427 | /// This determines whether a member function's "this" object can be an |
1428 | /// lvalue, rvalue, or neither. |
1429 | enum RefQualifierKind { |
1430 | /// No ref-qualifier was provided. |
1431 | RQ_None = 0, |
1432 | |
1433 | /// An lvalue ref-qualifier was provided (\c &). |
1434 | RQ_LValue, |
1435 | |
1436 | /// An rvalue ref-qualifier was provided (\c &&). |
1437 | RQ_RValue |
1438 | }; |
1439 | |
1440 | /// Which keyword(s) were used to create an AutoType. |
1441 | enum class AutoTypeKeyword { |
1442 | /// auto |
1443 | Auto, |
1444 | |
1445 | /// decltype(auto) |
1446 | DecltypeAuto, |
1447 | |
1448 | /// __auto_type (GNU extension) |
1449 | GNUAutoType |
1450 | }; |
1451 | |
1452 | /// The base class of the type hierarchy. |
1453 | /// |
1454 | /// A central concept with types is that each type always has a canonical |
1455 | /// type. A canonical type is the type with any typedef names stripped out |
1456 | /// of it or the types it references. For example, consider: |
1457 | /// |
1458 | /// typedef int foo; |
1459 | /// typedef foo* bar; |
1460 | /// 'int *' 'foo *' 'bar' |
1461 | /// |
1462 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1463 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1464 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1465 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1466 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1467 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1468 | /// is also 'int*'. |
1469 | /// |
1470 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1471 | /// information about typedefs being used. Canonical types are useful for type |
1472 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1473 | /// about whether something has a particular form (e.g. is a function type), |
1474 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1475 | /// |
1476 | /// Types, once created, are immutable. |
1477 | /// |
1478 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1479 | public: |
1480 | enum TypeClass { |
1481 | #define TYPE(Class, Base) Class, |
1482 | #define LAST_TYPE(Class) TypeLast = Class |
1483 | #define ABSTRACT_TYPE(Class, Base) |
1484 | #include "clang/AST/TypeNodes.inc" |
1485 | }; |
1486 | |
1487 | private: |
1488 | /// Bitfields required by the Type class. |
1489 | class TypeBitfields { |
1490 | friend class Type; |
1491 | template <class T> friend class TypePropertyCache; |
1492 | |
1493 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1494 | unsigned TC : 8; |
1495 | |
1496 | /// Store information on the type dependency. |
1497 | unsigned Dependence : llvm::BitWidth<TypeDependence>; |
1498 | |
1499 | /// True if the cache (i.e. the bitfields here starting with |
1500 | /// 'Cache') is valid. |
1501 | mutable unsigned CacheValid : 1; |
1502 | |
1503 | /// Linkage of this type. |
1504 | mutable unsigned CachedLinkage : 3; |
1505 | |
1506 | /// Whether this type involves and local or unnamed types. |
1507 | mutable unsigned CachedLocalOrUnnamed : 1; |
1508 | |
1509 | /// Whether this type comes from an AST file. |
1510 | mutable unsigned FromAST : 1; |
1511 | |
1512 | bool isCacheValid() const { |
1513 | return CacheValid; |
1514 | } |
1515 | |
1516 | Linkage getLinkage() const { |
1517 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 1517, __PRETTY_FUNCTION__)); |
1518 | return static_cast<Linkage>(CachedLinkage); |
1519 | } |
1520 | |
1521 | bool hasLocalOrUnnamedType() const { |
1522 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 1522, __PRETTY_FUNCTION__)); |
1523 | return CachedLocalOrUnnamed; |
1524 | } |
1525 | }; |
1526 | enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 }; |
1527 | |
1528 | protected: |
1529 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1530 | // into Type. |
1531 | |
1532 | class ArrayTypeBitfields { |
1533 | friend class ArrayType; |
1534 | |
1535 | unsigned : NumTypeBits; |
1536 | |
1537 | /// CVR qualifiers from declarations like |
1538 | /// 'int X[static restrict 4]'. For function parameters only. |
1539 | unsigned IndexTypeQuals : 3; |
1540 | |
1541 | /// Storage class qualifiers from declarations like |
1542 | /// 'int X[static restrict 4]'. For function parameters only. |
1543 | /// Actually an ArrayType::ArraySizeModifier. |
1544 | unsigned SizeModifier : 3; |
1545 | }; |
1546 | |
1547 | class ConstantArrayTypeBitfields { |
1548 | friend class ConstantArrayType; |
1549 | |
1550 | unsigned : NumTypeBits + 3 + 3; |
1551 | |
1552 | /// Whether we have a stored size expression. |
1553 | unsigned HasStoredSizeExpr : 1; |
1554 | }; |
1555 | |
1556 | class BuiltinTypeBitfields { |
1557 | friend class BuiltinType; |
1558 | |
1559 | unsigned : NumTypeBits; |
1560 | |
1561 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1562 | unsigned Kind : 8; |
1563 | }; |
1564 | |
1565 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1566 | /// Only common bits are stored here. Additional uncommon bits are stored |
1567 | /// in a trailing object after FunctionProtoType. |
1568 | class FunctionTypeBitfields { |
1569 | friend class FunctionProtoType; |
1570 | friend class FunctionType; |
1571 | |
1572 | unsigned : NumTypeBits; |
1573 | |
1574 | /// Extra information which affects how the function is called, like |
1575 | /// regparm and the calling convention. |
1576 | unsigned ExtInfo : 13; |
1577 | |
1578 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1579 | /// |
1580 | /// This is a value of type \c RefQualifierKind. |
1581 | unsigned RefQualifier : 2; |
1582 | |
1583 | /// Used only by FunctionProtoType, put here to pack with the |
1584 | /// other bitfields. |
1585 | /// The qualifiers are part of FunctionProtoType because... |
1586 | /// |
1587 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1588 | /// cv-qualifier-seq, [...], are part of the function type. |
1589 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1590 | /// Whether this function has extended Qualifiers. |
1591 | unsigned HasExtQuals : 1; |
1592 | |
1593 | /// The number of parameters this function has, not counting '...'. |
1594 | /// According to [implimits] 8 bits should be enough here but this is |
1595 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1596 | /// keep NumParams as wide as reasonably possible. |
1597 | unsigned NumParams : 16; |
1598 | |
1599 | /// The type of exception specification this function has. |
1600 | unsigned ExceptionSpecType : 4; |
1601 | |
1602 | /// Whether this function has extended parameter information. |
1603 | unsigned HasExtParameterInfos : 1; |
1604 | |
1605 | /// Whether the function is variadic. |
1606 | unsigned Variadic : 1; |
1607 | |
1608 | /// Whether this function has a trailing return type. |
1609 | unsigned HasTrailingReturn : 1; |
1610 | }; |
1611 | |
1612 | class ObjCObjectTypeBitfields { |
1613 | friend class ObjCObjectType; |
1614 | |
1615 | unsigned : NumTypeBits; |
1616 | |
1617 | /// The number of type arguments stored directly on this object type. |
1618 | unsigned NumTypeArgs : 7; |
1619 | |
1620 | /// The number of protocols stored directly on this object type. |
1621 | unsigned NumProtocols : 6; |
1622 | |
1623 | /// Whether this is a "kindof" type. |
1624 | unsigned IsKindOf : 1; |
1625 | }; |
1626 | |
1627 | class ReferenceTypeBitfields { |
1628 | friend class ReferenceType; |
1629 | |
1630 | unsigned : NumTypeBits; |
1631 | |
1632 | /// True if the type was originally spelled with an lvalue sigil. |
1633 | /// This is never true of rvalue references but can also be false |
1634 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1635 | /// as follows: |
1636 | /// |
1637 | /// typedef int &ref; // lvalue, spelled lvalue |
1638 | /// typedef int &&rvref; // rvalue |
1639 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1640 | /// ref &&a; // lvalue, inner ref |
1641 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1642 | /// rvref &&a; // rvalue, inner ref |
1643 | unsigned SpelledAsLValue : 1; |
1644 | |
1645 | /// True if the inner type is a reference type. This only happens |
1646 | /// in non-canonical forms. |
1647 | unsigned InnerRef : 1; |
1648 | }; |
1649 | |
1650 | class TypeWithKeywordBitfields { |
1651 | friend class TypeWithKeyword; |
1652 | |
1653 | unsigned : NumTypeBits; |
1654 | |
1655 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1656 | unsigned Keyword : 8; |
1657 | }; |
1658 | |
1659 | enum { NumTypeWithKeywordBits = 8 }; |
1660 | |
1661 | class ElaboratedTypeBitfields { |
1662 | friend class ElaboratedType; |
1663 | |
1664 | unsigned : NumTypeBits; |
1665 | unsigned : NumTypeWithKeywordBits; |
1666 | |
1667 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1668 | unsigned HasOwnedTagDecl : 1; |
1669 | }; |
1670 | |
1671 | class VectorTypeBitfields { |
1672 | friend class VectorType; |
1673 | friend class DependentVectorType; |
1674 | |
1675 | unsigned : NumTypeBits; |
1676 | |
1677 | /// The kind of vector, either a generic vector type or some |
1678 | /// target-specific vector type such as for AltiVec or Neon. |
1679 | unsigned VecKind : 3; |
1680 | /// The number of elements in the vector. |
1681 | uint32_t NumElements; |
1682 | }; |
1683 | |
1684 | class AttributedTypeBitfields { |
1685 | friend class AttributedType; |
1686 | |
1687 | unsigned : NumTypeBits; |
1688 | |
1689 | /// An AttributedType::Kind |
1690 | unsigned AttrKind : 32 - NumTypeBits; |
1691 | }; |
1692 | |
1693 | class AutoTypeBitfields { |
1694 | friend class AutoType; |
1695 | |
1696 | unsigned : NumTypeBits; |
1697 | |
1698 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1699 | /// or '__auto_type'? AutoTypeKeyword value. |
1700 | unsigned Keyword : 2; |
1701 | |
1702 | /// The number of template arguments in the type-constraints, which is |
1703 | /// expected to be able to hold at least 1024 according to [implimits]. |
1704 | /// However as this limit is somewhat easy to hit with template |
1705 | /// metaprogramming we'd prefer to keep it as large as possible. |
1706 | /// At the moment it has been left as a non-bitfield since this type |
1707 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1708 | /// introduce the performance impact of a bitfield. |
1709 | unsigned NumArgs; |
1710 | }; |
1711 | |
1712 | class SubstTemplateTypeParmPackTypeBitfields { |
1713 | friend class SubstTemplateTypeParmPackType; |
1714 | |
1715 | unsigned : NumTypeBits; |
1716 | |
1717 | /// The number of template arguments in \c Arguments, which is |
1718 | /// expected to be able to hold at least 1024 according to [implimits]. |
1719 | /// However as this limit is somewhat easy to hit with template |
1720 | /// metaprogramming we'd prefer to keep it as large as possible. |
1721 | /// At the moment it has been left as a non-bitfield since this type |
1722 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1723 | /// introduce the performance impact of a bitfield. |
1724 | unsigned NumArgs; |
1725 | }; |
1726 | |
1727 | class TemplateSpecializationTypeBitfields { |
1728 | friend class TemplateSpecializationType; |
1729 | |
1730 | unsigned : NumTypeBits; |
1731 | |
1732 | /// Whether this template specialization type is a substituted type alias. |
1733 | unsigned TypeAlias : 1; |
1734 | |
1735 | /// The number of template arguments named in this class template |
1736 | /// specialization, which is expected to be able to hold at least 1024 |
1737 | /// according to [implimits]. However, as this limit is somewhat easy to |
1738 | /// hit with template metaprogramming we'd prefer to keep it as large |
1739 | /// as possible. At the moment it has been left as a non-bitfield since |
1740 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1741 | /// to introduce the performance impact of a bitfield. |
1742 | unsigned NumArgs; |
1743 | }; |
1744 | |
1745 | class DependentTemplateSpecializationTypeBitfields { |
1746 | friend class DependentTemplateSpecializationType; |
1747 | |
1748 | unsigned : NumTypeBits; |
1749 | unsigned : NumTypeWithKeywordBits; |
1750 | |
1751 | /// The number of template arguments named in this class template |
1752 | /// specialization, which is expected to be able to hold at least 1024 |
1753 | /// according to [implimits]. However, as this limit is somewhat easy to |
1754 | /// hit with template metaprogramming we'd prefer to keep it as large |
1755 | /// as possible. At the moment it has been left as a non-bitfield since |
1756 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1757 | /// to introduce the performance impact of a bitfield. |
1758 | unsigned NumArgs; |
1759 | }; |
1760 | |
1761 | class PackExpansionTypeBitfields { |
1762 | friend class PackExpansionType; |
1763 | |
1764 | unsigned : NumTypeBits; |
1765 | |
1766 | /// The number of expansions that this pack expansion will |
1767 | /// generate when substituted (+1), which is expected to be able to |
1768 | /// hold at least 1024 according to [implimits]. However, as this limit |
1769 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1770 | /// keep it as large as possible. At the moment it has been left as a |
1771 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1772 | /// there is no reason to introduce the performance impact of a bitfield. |
1773 | /// |
1774 | /// This field will only have a non-zero value when some of the parameter |
1775 | /// packs that occur within the pattern have been substituted but others |
1776 | /// have not. |
1777 | unsigned NumExpansions; |
1778 | }; |
1779 | |
1780 | union { |
1781 | TypeBitfields TypeBits; |
1782 | ArrayTypeBitfields ArrayTypeBits; |
1783 | ConstantArrayTypeBitfields ConstantArrayTypeBits; |
1784 | AttributedTypeBitfields AttributedTypeBits; |
1785 | AutoTypeBitfields AutoTypeBits; |
1786 | BuiltinTypeBitfields BuiltinTypeBits; |
1787 | FunctionTypeBitfields FunctionTypeBits; |
1788 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1789 | ReferenceTypeBitfields ReferenceTypeBits; |
1790 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1791 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1792 | VectorTypeBitfields VectorTypeBits; |
1793 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1794 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1795 | DependentTemplateSpecializationTypeBitfields |
1796 | DependentTemplateSpecializationTypeBits; |
1797 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1798 | }; |
1799 | |
1800 | private: |
1801 | template <class T> friend class TypePropertyCache; |
1802 | |
1803 | /// Set whether this type comes from an AST file. |
1804 | void setFromAST(bool V = true) const { |
1805 | TypeBits.FromAST = V; |
1806 | } |
1807 | |
1808 | protected: |
1809 | friend class ASTContext; |
1810 | |
1811 | Type(TypeClass tc, QualType canon, TypeDependence Dependence) |
1812 | : ExtQualsTypeCommonBase(this, |
1813 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1814 | static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase), |
1815 | "changing bitfields changed sizeof(Type)!"); |
1816 | static_assert(alignof(decltype(*this)) % sizeof(void *) == 0, |
1817 | "Insufficient alignment!"); |
1818 | TypeBits.TC = tc; |
1819 | TypeBits.Dependence = static_cast<unsigned>(Dependence); |
1820 | TypeBits.CacheValid = false; |
1821 | TypeBits.CachedLocalOrUnnamed = false; |
1822 | TypeBits.CachedLinkage = NoLinkage; |
1823 | TypeBits.FromAST = false; |
1824 | } |
1825 | |
1826 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1827 | Type *this_() { return this; } |
1828 | |
1829 | void setDependence(TypeDependence D) { |
1830 | TypeBits.Dependence = static_cast<unsigned>(D); |
1831 | } |
1832 | |
1833 | void addDependence(TypeDependence D) { setDependence(getDependence() | D); } |
1834 | |
1835 | public: |
1836 | friend class ASTReader; |
1837 | friend class ASTWriter; |
1838 | template <class T> friend class serialization::AbstractTypeReader; |
1839 | template <class T> friend class serialization::AbstractTypeWriter; |
1840 | |
1841 | Type(const Type &) = delete; |
1842 | Type(Type &&) = delete; |
1843 | Type &operator=(const Type &) = delete; |
1844 | Type &operator=(Type &&) = delete; |
1845 | |
1846 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1847 | |
1848 | /// Whether this type comes from an AST file. |
1849 | bool isFromAST() const { return TypeBits.FromAST; } |
1850 | |
1851 | /// Whether this type is or contains an unexpanded parameter |
1852 | /// pack, used to support C++0x variadic templates. |
1853 | /// |
1854 | /// A type that contains a parameter pack shall be expanded by the |
1855 | /// ellipsis operator at some point. For example, the typedef in the |
1856 | /// following example contains an unexpanded parameter pack 'T': |
1857 | /// |
1858 | /// \code |
1859 | /// template<typename ...T> |
1860 | /// struct X { |
1861 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1862 | /// }; |
1863 | /// \endcode |
1864 | /// |
1865 | /// Note that this routine does not specify which |
1866 | bool containsUnexpandedParameterPack() const { |
1867 | return getDependence() & TypeDependence::UnexpandedPack; |
1868 | } |
1869 | |
1870 | /// Determines if this type would be canonical if it had no further |
1871 | /// qualification. |
1872 | bool isCanonicalUnqualified() const { |
1873 | return CanonicalType == QualType(this, 0); |
1874 | } |
1875 | |
1876 | /// Pull a single level of sugar off of this locally-unqualified type. |
1877 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1878 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1879 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1880 | |
1881 | /// As an extension, we classify types as one of "sized" or "sizeless"; |
1882 | /// every type is one or the other. Standard types are all sized; |
1883 | /// sizeless types are purely an extension. |
1884 | /// |
1885 | /// Sizeless types contain data with no specified size, alignment, |
1886 | /// or layout. |
1887 | bool isSizelessType() const; |
1888 | bool isSizelessBuiltinType() const; |
1889 | |
1890 | /// Determines if this is a sizeless type supported by the |
1891 | /// 'arm_sve_vector_bits' type attribute, which can be applied to a single |
1892 | /// SVE vector or predicate, excluding tuple types such as svint32x4_t. |
1893 | bool isVLSTBuiltinType() const; |
1894 | |
1895 | /// Returns the representative type for the element of an SVE builtin type. |
1896 | /// This is used to represent fixed-length SVE vectors created with the |
1897 | /// 'arm_sve_vector_bits' type attribute as VectorType. |
1898 | QualType getSveEltType(const ASTContext &Ctx) const; |
1899 | |
1900 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1901 | /// object types, function types, and incomplete types. |
1902 | |
1903 | /// Return true if this is an incomplete type. |
1904 | /// A type that can describe objects, but which lacks information needed to |
1905 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1906 | /// routine will need to determine if the size is actually required. |
1907 | /// |
1908 | /// Def If non-null, and the type refers to some kind of declaration |
1909 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1910 | /// class), will be set to the declaration. |
1911 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1912 | |
1913 | /// Return true if this is an incomplete or object |
1914 | /// type, in other words, not a function type. |
1915 | bool isIncompleteOrObjectType() const { |
1916 | return !isFunctionType(); |
1917 | } |
1918 | |
1919 | /// Determine whether this type is an object type. |
1920 | bool isObjectType() const { |
1921 | // C++ [basic.types]p8: |
1922 | // An object type is a (possibly cv-qualified) type that is not a |
1923 | // function type, not a reference type, and not a void type. |
1924 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1925 | } |
1926 | |
1927 | /// Return true if this is a literal type |
1928 | /// (C++11 [basic.types]p10) |
1929 | bool isLiteralType(const ASTContext &Ctx) const; |
1930 | |
1931 | /// Determine if this type is a structural type, per C++20 [temp.param]p7. |
1932 | bool isStructuralType() const; |
1933 | |
1934 | /// Test if this type is a standard-layout type. |
1935 | /// (C++0x [basic.type]p9) |
1936 | bool isStandardLayoutType() const; |
1937 | |
1938 | /// Helper methods to distinguish type categories. All type predicates |
1939 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1940 | |
1941 | /// Returns true if the type is a builtin type. |
1942 | bool isBuiltinType() const; |
1943 | |
1944 | /// Test for a particular builtin type. |
1945 | bool isSpecificBuiltinType(unsigned K) const; |
1946 | |
1947 | /// Test for a type which does not represent an actual type-system type but |
1948 | /// is instead used as a placeholder for various convenient purposes within |
1949 | /// Clang. All such types are BuiltinTypes. |
1950 | bool isPlaceholderType() const; |
1951 | const BuiltinType *getAsPlaceholderType() const; |
1952 | |
1953 | /// Test for a specific placeholder type. |
1954 | bool isSpecificPlaceholderType(unsigned K) const; |
1955 | |
1956 | /// Test for a placeholder type other than Overload; see |
1957 | /// BuiltinType::isNonOverloadPlaceholderType. |
1958 | bool isNonOverloadPlaceholderType() const; |
1959 | |
1960 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1961 | /// isComplexIntegerType() can be used to test for complex integers. |
1962 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1963 | bool isEnumeralType() const; |
1964 | |
1965 | /// Determine whether this type is a scoped enumeration type. |
1966 | bool isScopedEnumeralType() const; |
1967 | bool isBooleanType() const; |
1968 | bool isCharType() const; |
1969 | bool isWideCharType() const; |
1970 | bool isChar8Type() const; |
1971 | bool isChar16Type() const; |
1972 | bool isChar32Type() const; |
1973 | bool isAnyCharacterType() const; |
1974 | bool isIntegralType(const ASTContext &Ctx) const; |
1975 | |
1976 | /// Determine whether this type is an integral or enumeration type. |
1977 | bool isIntegralOrEnumerationType() const; |
1978 | |
1979 | /// Determine whether this type is an integral or unscoped enumeration type. |
1980 | bool isIntegralOrUnscopedEnumerationType() const; |
1981 | bool isUnscopedEnumerationType() const; |
1982 | |
1983 | /// Floating point categories. |
1984 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1985 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1986 | /// isComplexIntegerType() can be used to test for complex integers. |
1987 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1988 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1989 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1990 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1991 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1992 | bool isBFloat16Type() const; |
1993 | bool isFloat128Type() const; |
1994 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1995 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1996 | bool isVoidType() const; // C99 6.2.5p19 |
1997 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1998 | bool isAggregateType() const; |
1999 | bool isFundamentalType() const; |
2000 | bool isCompoundType() const; |
2001 | |
2002 | // Type Predicates: Check to see if this type is structurally the specified |
2003 | // type, ignoring typedefs and qualifiers. |
2004 | bool isFunctionType() const; |
2005 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
2006 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
2007 | bool isPointerType() const; |
2008 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
2009 | bool isBlockPointerType() const; |
2010 | bool isVoidPointerType() const; |
2011 | bool isReferenceType() const; |
2012 | bool isLValueReferenceType() const; |
2013 | bool isRValueReferenceType() const; |
2014 | bool isObjectPointerType() const; |
2015 | bool isFunctionPointerType() const; |
2016 | bool isFunctionReferenceType() const; |
2017 | bool isMemberPointerType() const; |
2018 | bool isMemberFunctionPointerType() const; |
2019 | bool isMemberDataPointerType() const; |
2020 | bool isArrayType() const; |
2021 | bool isConstantArrayType() const; |
2022 | bool isIncompleteArrayType() const; |
2023 | bool isVariableArrayType() const; |
2024 | bool isDependentSizedArrayType() const; |
2025 | bool isRecordType() const; |
2026 | bool isClassType() const; |
2027 | bool isStructureType() const; |
2028 | bool isObjCBoxableRecordType() const; |
2029 | bool isInterfaceType() const; |
2030 | bool isStructureOrClassType() const; |
2031 | bool isUnionType() const; |
2032 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2033 | bool isVectorType() const; // GCC vector type. |
2034 | bool isExtVectorType() const; // Extended vector type. |
2035 | bool isMatrixType() const; // Matrix type. |
2036 | bool isConstantMatrixType() const; // Constant matrix type. |
2037 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2038 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2039 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2040 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2041 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2042 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2043 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2044 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2045 | // for the common case. |
2046 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2047 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2048 | bool isObjCQualifiedIdType() const; // id<foo> |
2049 | bool isObjCQualifiedClassType() const; // Class<foo> |
2050 | bool isObjCObjectOrInterfaceType() const; |
2051 | bool isObjCIdType() const; // id |
2052 | bool isDecltypeType() const; |
2053 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2054 | /// qualifier? |
2055 | /// |
2056 | /// This approximates the answer to the following question: if this |
2057 | /// translation unit were compiled in ARC, would this type be qualified |
2058 | /// with __unsafe_unretained? |
2059 | bool isObjCInertUnsafeUnretainedType() const { |
2060 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2061 | } |
2062 | |
2063 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2064 | /// object type, e.g., __kindof NSView * or __kindof id |
2065 | /// <NSCopying>. |
2066 | /// |
2067 | /// \param bound Will be set to the bound on non-id subtype types, |
2068 | /// which will be (possibly specialized) Objective-C class type, or |
2069 | /// null for 'id. |
2070 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2071 | const ObjCObjectType *&bound) const; |
2072 | |
2073 | bool isObjCClassType() const; // Class |
2074 | |
2075 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2076 | /// Class type, e.g., __kindof Class <NSCopying>. |
2077 | /// |
2078 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2079 | /// here because Objective-C's type system cannot express "a class |
2080 | /// object for a subclass of NSFoo". |
2081 | bool isObjCClassOrClassKindOfType() const; |
2082 | |
2083 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2084 | bool isObjCSelType() const; // Class |
2085 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2086 | bool isObjCARCBridgableType() const; |
2087 | bool isCARCBridgableType() const; |
2088 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2089 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2090 | bool isNothrowT() const; // C++ std::nothrow_t |
2091 | bool isAlignValT() const; // C++17 std::align_val_t |
2092 | bool isStdByteType() const; // C++17 std::byte |
2093 | bool isAtomicType() const; // C11 _Atomic() |
2094 | bool isUndeducedAutoType() const; // C++11 auto or |
2095 | // C++14 decltype(auto) |
2096 | bool isTypedefNameType() const; // typedef or alias template |
2097 | |
2098 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2099 | bool is##Id##Type() const; |
2100 | #include "clang/Basic/OpenCLImageTypes.def" |
2101 | |
2102 | bool isImageType() const; // Any OpenCL image type |
2103 | |
2104 | bool isSamplerT() const; // OpenCL sampler_t |
2105 | bool isEventT() const; // OpenCL event_t |
2106 | bool isClkEventT() const; // OpenCL clk_event_t |
2107 | bool isQueueT() const; // OpenCL queue_t |
2108 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2109 | |
2110 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2111 | bool is##Id##Type() const; |
2112 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2113 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2114 | bool isOCLIntelSubgroupAVCType() const; |
2115 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2116 | |
2117 | bool isPipeType() const; // OpenCL pipe type |
2118 | bool isExtIntType() const; // Extended Int Type |
2119 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2120 | |
2121 | /// Determines if this type, which must satisfy |
2122 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2123 | /// than implicitly __strong. |
2124 | bool isObjCARCImplicitlyUnretainedType() const; |
2125 | |
2126 | /// Check if the type is the CUDA device builtin surface type. |
2127 | bool isCUDADeviceBuiltinSurfaceType() const; |
2128 | /// Check if the type is the CUDA device builtin texture type. |
2129 | bool isCUDADeviceBuiltinTextureType() const; |
2130 | |
2131 | /// Return the implicit lifetime for this type, which must not be dependent. |
2132 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2133 | |
2134 | enum ScalarTypeKind { |
2135 | STK_CPointer, |
2136 | STK_BlockPointer, |
2137 | STK_ObjCObjectPointer, |
2138 | STK_MemberPointer, |
2139 | STK_Bool, |
2140 | STK_Integral, |
2141 | STK_Floating, |
2142 | STK_IntegralComplex, |
2143 | STK_FloatingComplex, |
2144 | STK_FixedPoint |
2145 | }; |
2146 | |
2147 | /// Given that this is a scalar type, classify it. |
2148 | ScalarTypeKind getScalarTypeKind() const; |
2149 | |
2150 | TypeDependence getDependence() const { |
2151 | return static_cast<TypeDependence>(TypeBits.Dependence); |
2152 | } |
2153 | |
2154 | /// Whether this type is an error type. |
2155 | bool containsErrors() const { |
2156 | return getDependence() & TypeDependence::Error; |
2157 | } |
2158 | |
2159 | /// Whether this type is a dependent type, meaning that its definition |
2160 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2161 | bool isDependentType() const { |
2162 | return getDependence() & TypeDependence::Dependent; |
2163 | } |
2164 | |
2165 | /// Determine whether this type is an instantiation-dependent type, |
2166 | /// meaning that the type involves a template parameter (even if the |
2167 | /// definition does not actually depend on the type substituted for that |
2168 | /// template parameter). |
2169 | bool isInstantiationDependentType() const { |
2170 | return getDependence() & TypeDependence::Instantiation; |
2171 | } |
2172 | |
2173 | /// Determine whether this type is an undeduced type, meaning that |
2174 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2175 | /// deduced. |
2176 | bool isUndeducedType() const; |
2177 | |
2178 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2179 | bool isVariablyModifiedType() const { |
2180 | return getDependence() & TypeDependence::VariablyModified; |
2181 | } |
2182 | |
2183 | /// Whether this type involves a variable-length array type |
2184 | /// with a definite size. |
2185 | bool hasSizedVLAType() const; |
2186 | |
2187 | /// Whether this type is or contains a local or unnamed type. |
2188 | bool hasUnnamedOrLocalType() const; |
2189 | |
2190 | bool isOverloadableType() const; |
2191 | |
2192 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2193 | bool isElaboratedTypeSpecifier() const; |
2194 | |
2195 | bool canDecayToPointerType() const; |
2196 | |
2197 | /// Whether this type is represented natively as a pointer. This includes |
2198 | /// pointers, references, block pointers, and Objective-C interface, |
2199 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2200 | bool hasPointerRepresentation() const; |
2201 | |
2202 | /// Whether this type can represent an objective pointer type for the |
2203 | /// purpose of GC'ability |
2204 | bool hasObjCPointerRepresentation() const; |
2205 | |
2206 | /// Determine whether this type has an integer representation |
2207 | /// of some sort, e.g., it is an integer type or a vector. |
2208 | bool hasIntegerRepresentation() const; |
2209 | |
2210 | /// Determine whether this type has an signed integer representation |
2211 | /// of some sort, e.g., it is an signed integer type or a vector. |
2212 | bool hasSignedIntegerRepresentation() const; |
2213 | |
2214 | /// Determine whether this type has an unsigned integer representation |
2215 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2216 | bool hasUnsignedIntegerRepresentation() const; |
2217 | |
2218 | /// Determine whether this type has a floating-point representation |
2219 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2220 | bool hasFloatingRepresentation() const; |
2221 | |
2222 | // Type Checking Functions: Check to see if this type is structurally the |
2223 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2224 | // the best type we can. |
2225 | const RecordType *getAsStructureType() const; |
2226 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2227 | const RecordType *getAsUnionType() const; |
2228 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2229 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2230 | |
2231 | // The following is a convenience method that returns an ObjCObjectPointerType |
2232 | // for object declared using an interface. |
2233 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2234 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2235 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2236 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2237 | |
2238 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2239 | /// because the type is a RecordType or because it is the injected-class-name |
2240 | /// type of a class template or class template partial specialization. |
2241 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2242 | |
2243 | /// Retrieves the RecordDecl this type refers to. |
2244 | RecordDecl *getAsRecordDecl() const; |
2245 | |
2246 | /// Retrieves the TagDecl that this type refers to, either |
2247 | /// because the type is a TagType or because it is the injected-class-name |
2248 | /// type of a class template or class template partial specialization. |
2249 | TagDecl *getAsTagDecl() const; |
2250 | |
2251 | /// If this is a pointer or reference to a RecordType, return the |
2252 | /// CXXRecordDecl that the type refers to. |
2253 | /// |
2254 | /// If this is not a pointer or reference, or the type being pointed to does |
2255 | /// not refer to a CXXRecordDecl, returns NULL. |
2256 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2257 | |
2258 | /// Get the DeducedType whose type will be deduced for a variable with |
2259 | /// an initializer of this type. This looks through declarators like pointer |
2260 | /// types, but not through decltype or typedefs. |
2261 | DeducedType *getContainedDeducedType() const; |
2262 | |
2263 | /// Get the AutoType whose type will be deduced for a variable with |
2264 | /// an initializer of this type. This looks through declarators like pointer |
2265 | /// types, but not through decltype or typedefs. |
2266 | AutoType *getContainedAutoType() const { |
2267 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2268 | } |
2269 | |
2270 | /// Determine whether this type was written with a leading 'auto' |
2271 | /// corresponding to a trailing return type (possibly for a nested |
2272 | /// function type within a pointer to function type or similar). |
2273 | bool hasAutoForTrailingReturnType() const; |
2274 | |
2275 | /// Member-template getAs<specific type>'. Look through sugar for |
2276 | /// an instance of \<specific type>. This scheme will eventually |
2277 | /// replace the specific getAsXXXX methods above. |
2278 | /// |
2279 | /// There are some specializations of this member template listed |
2280 | /// immediately following this class. |
2281 | template <typename T> const T *getAs() const; |
2282 | |
2283 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2284 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2285 | /// This is used when you need to walk over sugar nodes that represent some |
2286 | /// kind of type adjustment from a type that was written as a \<specific type> |
2287 | /// to another type that is still canonically a \<specific type>. |
2288 | template <typename T> const T *getAsAdjusted() const; |
2289 | |
2290 | /// A variant of getAs<> for array types which silently discards |
2291 | /// qualifiers from the outermost type. |
2292 | const ArrayType *getAsArrayTypeUnsafe() const; |
2293 | |
2294 | /// Member-template castAs<specific type>. Look through sugar for |
2295 | /// the underlying instance of \<specific type>. |
2296 | /// |
2297 | /// This method has the same relationship to getAs<T> as cast<T> has |
2298 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2299 | /// have the intended type, and this method will never return null. |
2300 | template <typename T> const T *castAs() const; |
2301 | |
2302 | /// A variant of castAs<> for array type which silently discards |
2303 | /// qualifiers from the outermost type. |
2304 | const ArrayType *castAsArrayTypeUnsafe() const; |
2305 | |
2306 | /// Determine whether this type had the specified attribute applied to it |
2307 | /// (looking through top-level type sugar). |
2308 | bool hasAttr(attr::Kind AK) const; |
2309 | |
2310 | /// Get the base element type of this type, potentially discarding type |
2311 | /// qualifiers. This should never be used when type qualifiers |
2312 | /// are meaningful. |
2313 | const Type *getBaseElementTypeUnsafe() const; |
2314 | |
2315 | /// If this is an array type, return the element type of the array, |
2316 | /// potentially with type qualifiers missing. |
2317 | /// This should never be used when type qualifiers are meaningful. |
2318 | const Type *getArrayElementTypeNoTypeQual() const; |
2319 | |
2320 | /// If this is a pointer type, return the pointee type. |
2321 | /// If this is an array type, return the array element type. |
2322 | /// This should never be used when type qualifiers are meaningful. |
2323 | const Type *getPointeeOrArrayElementType() const; |
2324 | |
2325 | /// If this is a pointer, ObjC object pointer, or block |
2326 | /// pointer, this returns the respective pointee. |
2327 | QualType getPointeeType() const; |
2328 | |
2329 | /// Return the specified type with any "sugar" removed from the type, |
2330 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2331 | const Type *getUnqualifiedDesugaredType() const; |
2332 | |
2333 | /// More type predicates useful for type checking/promotion |
2334 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2335 | |
2336 | /// Return true if this is an integer type that is |
2337 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2338 | /// or an enum decl which has a signed representation. |
2339 | bool isSignedIntegerType() const; |
2340 | |
2341 | /// Return true if this is an integer type that is |
2342 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2343 | /// or an enum decl which has an unsigned representation. |
2344 | bool isUnsignedIntegerType() const; |
2345 | |
2346 | /// Determines whether this is an integer type that is signed or an |
2347 | /// enumeration types whose underlying type is a signed integer type. |
2348 | bool isSignedIntegerOrEnumerationType() const; |
2349 | |
2350 | /// Determines whether this is an integer type that is unsigned or an |
2351 | /// enumeration types whose underlying type is a unsigned integer type. |
2352 | bool isUnsignedIntegerOrEnumerationType() const; |
2353 | |
2354 | /// Return true if this is a fixed point type according to |
2355 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2356 | bool isFixedPointType() const; |
2357 | |
2358 | /// Return true if this is a fixed point or integer type. |
2359 | bool isFixedPointOrIntegerType() const; |
2360 | |
2361 | /// Return true if this is a saturated fixed point type according to |
2362 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2363 | bool isSaturatedFixedPointType() const; |
2364 | |
2365 | /// Return true if this is a saturated fixed point type according to |
2366 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2367 | bool isUnsaturatedFixedPointType() const; |
2368 | |
2369 | /// Return true if this is a fixed point type that is signed according |
2370 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2371 | bool isSignedFixedPointType() const; |
2372 | |
2373 | /// Return true if this is a fixed point type that is unsigned according |
2374 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2375 | bool isUnsignedFixedPointType() const; |
2376 | |
2377 | /// Return true if this is not a variable sized type, |
2378 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2379 | /// incomplete types. |
2380 | bool isConstantSizeType() const; |
2381 | |
2382 | /// Returns true if this type can be represented by some |
2383 | /// set of type specifiers. |
2384 | bool isSpecifierType() const; |
2385 | |
2386 | /// Determine the linkage of this type. |
2387 | Linkage getLinkage() const; |
2388 | |
2389 | /// Determine the visibility of this type. |
2390 | Visibility getVisibility() const { |
2391 | return getLinkageAndVisibility().getVisibility(); |
2392 | } |
2393 | |
2394 | /// Return true if the visibility was explicitly set is the code. |
2395 | bool isVisibilityExplicit() const { |
2396 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2397 | } |
2398 | |
2399 | /// Determine the linkage and visibility of this type. |
2400 | LinkageInfo getLinkageAndVisibility() const; |
2401 | |
2402 | /// True if the computed linkage is valid. Used for consistency |
2403 | /// checking. Should always return true. |
2404 | bool isLinkageValid() const; |
2405 | |
2406 | /// Determine the nullability of the given type. |
2407 | /// |
2408 | /// Note that nullability is only captured as sugar within the type |
2409 | /// system, not as part of the canonical type, so nullability will |
2410 | /// be lost by canonicalization and desugaring. |
2411 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2412 | |
2413 | /// Determine whether the given type can have a nullability |
2414 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2415 | /// |
2416 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2417 | /// this type can have nullability because it is dependent. |
2418 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2419 | |
2420 | /// Retrieve the set of substitutions required when accessing a member |
2421 | /// of the Objective-C receiver type that is declared in the given context. |
2422 | /// |
2423 | /// \c *this is the type of the object we're operating on, e.g., the |
2424 | /// receiver for a message send or the base of a property access, and is |
2425 | /// expected to be of some object or object pointer type. |
2426 | /// |
2427 | /// \param dc The declaration context for which we are building up a |
2428 | /// substitution mapping, which should be an Objective-C class, extension, |
2429 | /// category, or method within. |
2430 | /// |
2431 | /// \returns an array of type arguments that can be substituted for |
2432 | /// the type parameters of the given declaration context in any type described |
2433 | /// within that context, or an empty optional to indicate that no |
2434 | /// substitution is required. |
2435 | Optional<ArrayRef<QualType>> |
2436 | getObjCSubstitutions(const DeclContext *dc) const; |
2437 | |
2438 | /// Determines if this is an ObjC interface type that may accept type |
2439 | /// parameters. |
2440 | bool acceptsObjCTypeParams() const; |
2441 | |
2442 | const char *getTypeClassName() const; |
2443 | |
2444 | QualType getCanonicalTypeInternal() const { |
2445 | return CanonicalType; |
2446 | } |
2447 | |
2448 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2449 | void dump() const; |
2450 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
2451 | }; |
2452 | |
2453 | /// This will check for a TypedefType by removing any existing sugar |
2454 | /// until it reaches a TypedefType or a non-sugared type. |
2455 | template <> const TypedefType *Type::getAs() const; |
2456 | |
2457 | /// This will check for a TemplateSpecializationType by removing any |
2458 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2459 | /// non-sugared type. |
2460 | template <> const TemplateSpecializationType *Type::getAs() const; |
2461 | |
2462 | /// This will check for an AttributedType by removing any existing sugar |
2463 | /// until it reaches an AttributedType or a non-sugared type. |
2464 | template <> const AttributedType *Type::getAs() const; |
2465 | |
2466 | // We can do canonical leaf types faster, because we don't have to |
2467 | // worry about preserving child type decoration. |
2468 | #define TYPE(Class, Base) |
2469 | #define LEAF_TYPE(Class) \ |
2470 | template <> inline const Class##Type *Type::getAs() const { \ |
2471 | return dyn_cast<Class##Type>(CanonicalType); \ |
2472 | } \ |
2473 | template <> inline const Class##Type *Type::castAs() const { \ |
2474 | return cast<Class##Type>(CanonicalType); \ |
2475 | } |
2476 | #include "clang/AST/TypeNodes.inc" |
2477 | |
2478 | /// This class is used for builtin types like 'int'. Builtin |
2479 | /// types are always canonical and have a literal name field. |
2480 | class BuiltinType : public Type { |
2481 | public: |
2482 | enum Kind { |
2483 | // OpenCL image types |
2484 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2485 | #include "clang/Basic/OpenCLImageTypes.def" |
2486 | // OpenCL extension types |
2487 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2488 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2489 | // SVE Types |
2490 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2491 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2492 | // PPC MMA Types |
2493 | #define PPC_VECTOR_TYPE(Name, Id, Size) Id, |
2494 | #include "clang/Basic/PPCTypes.def" |
2495 | // All other builtin types |
2496 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2497 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2498 | #include "clang/AST/BuiltinTypes.def" |
2499 | }; |
2500 | |
2501 | private: |
2502 | friend class ASTContext; // ASTContext creates these. |
2503 | |
2504 | BuiltinType(Kind K) |
2505 | : Type(Builtin, QualType(), |
2506 | K == Dependent ? TypeDependence::DependentInstantiation |
2507 | : TypeDependence::None) { |
2508 | BuiltinTypeBits.Kind = K; |
2509 | } |
2510 | |
2511 | public: |
2512 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2513 | StringRef getName(const PrintingPolicy &Policy) const; |
2514 | |
2515 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2516 | // The StringRef is null-terminated. |
2517 | StringRef str = getName(Policy); |
2518 | assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast <void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 2518, __PRETTY_FUNCTION__)); |
2519 | return str.data(); |
2520 | } |
2521 | |
2522 | bool isSugared() const { return false; } |
2523 | QualType desugar() const { return QualType(this, 0); } |
2524 | |
2525 | bool isInteger() const { |
2526 | return getKind() >= Bool && getKind() <= Int128; |
2527 | } |
2528 | |
2529 | bool isSignedInteger() const { |
2530 | return getKind() >= Char_S && getKind() <= Int128; |
2531 | } |
2532 | |
2533 | bool isUnsignedInteger() const { |
2534 | return getKind() >= Bool && getKind() <= UInt128; |
2535 | } |
2536 | |
2537 | bool isFloatingPoint() const { |
2538 | return getKind() >= Half && getKind() <= Float128; |
2539 | } |
2540 | |
2541 | /// Determines whether the given kind corresponds to a placeholder type. |
2542 | static bool isPlaceholderTypeKind(Kind K) { |
2543 | return K >= Overload; |
2544 | } |
2545 | |
2546 | /// Determines whether this type is a placeholder type, i.e. a type |
2547 | /// which cannot appear in arbitrary positions in a fully-formed |
2548 | /// expression. |
2549 | bool isPlaceholderType() const { |
2550 | return isPlaceholderTypeKind(getKind()); |
2551 | } |
2552 | |
2553 | /// Determines whether this type is a placeholder type other than |
2554 | /// Overload. Most placeholder types require only syntactic |
2555 | /// information about their context in order to be resolved (e.g. |
2556 | /// whether it is a call expression), which means they can (and |
2557 | /// should) be resolved in an earlier "phase" of analysis. |
2558 | /// Overload expressions sometimes pick up further information |
2559 | /// from their context, like whether the context expects a |
2560 | /// specific function-pointer type, and so frequently need |
2561 | /// special treatment. |
2562 | bool isNonOverloadPlaceholderType() const { |
2563 | return getKind() > Overload; |
2564 | } |
2565 | |
2566 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2567 | }; |
2568 | |
2569 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2570 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2571 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2572 | friend class ASTContext; // ASTContext creates these. |
2573 | |
2574 | QualType ElementType; |
2575 | |
2576 | ComplexType(QualType Element, QualType CanonicalPtr) |
2577 | : Type(Complex, CanonicalPtr, Element->getDependence()), |
2578 | ElementType(Element) {} |
2579 | |
2580 | public: |
2581 | QualType getElementType() const { return ElementType; } |
2582 | |
2583 | bool isSugared() const { return false; } |
2584 | QualType desugar() const { return QualType(this, 0); } |
2585 | |
2586 | void Profile(llvm::FoldingSetNodeID &ID) { |
2587 | Profile(ID, getElementType()); |
2588 | } |
2589 | |
2590 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2591 | ID.AddPointer(Element.getAsOpaquePtr()); |
2592 | } |
2593 | |
2594 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2595 | }; |
2596 | |
2597 | /// Sugar for parentheses used when specifying types. |
2598 | class ParenType : public Type, public llvm::FoldingSetNode { |
2599 | friend class ASTContext; // ASTContext creates these. |
2600 | |
2601 | QualType Inner; |
2602 | |
2603 | ParenType(QualType InnerType, QualType CanonType) |
2604 | : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {} |
2605 | |
2606 | public: |
2607 | QualType getInnerType() const { return Inner; } |
2608 | |
2609 | bool isSugared() const { return true; } |
2610 | QualType desugar() const { return getInnerType(); } |
2611 | |
2612 | void Profile(llvm::FoldingSetNodeID &ID) { |
2613 | Profile(ID, getInnerType()); |
2614 | } |
2615 | |
2616 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2617 | Inner.Profile(ID); |
2618 | } |
2619 | |
2620 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2621 | }; |
2622 | |
2623 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2624 | class PointerType : public Type, public llvm::FoldingSetNode { |
2625 | friend class ASTContext; // ASTContext creates these. |
2626 | |
2627 | QualType PointeeType; |
2628 | |
2629 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2630 | : Type(Pointer, CanonicalPtr, Pointee->getDependence()), |
2631 | PointeeType(Pointee) {} |
2632 | |
2633 | public: |
2634 | QualType getPointeeType() const { return PointeeType; } |
2635 | |
2636 | bool isSugared() const { return false; } |
2637 | QualType desugar() const { return QualType(this, 0); } |
2638 | |
2639 | void Profile(llvm::FoldingSetNodeID &ID) { |
2640 | Profile(ID, getPointeeType()); |
2641 | } |
2642 | |
2643 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2644 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2645 | } |
2646 | |
2647 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2648 | }; |
2649 | |
2650 | /// Represents a type which was implicitly adjusted by the semantic |
2651 | /// engine for arbitrary reasons. For example, array and function types can |
2652 | /// decay, and function types can have their calling conventions adjusted. |
2653 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2654 | QualType OriginalTy; |
2655 | QualType AdjustedTy; |
2656 | |
2657 | protected: |
2658 | friend class ASTContext; // ASTContext creates these. |
2659 | |
2660 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2661 | QualType CanonicalPtr) |
2662 | : Type(TC, CanonicalPtr, OriginalTy->getDependence()), |
2663 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2664 | |
2665 | public: |
2666 | QualType getOriginalType() const { return OriginalTy; } |
2667 | QualType getAdjustedType() const { return AdjustedTy; } |
2668 | |
2669 | bool isSugared() const { return true; } |
2670 | QualType desugar() const { return AdjustedTy; } |
2671 | |
2672 | void Profile(llvm::FoldingSetNodeID &ID) { |
2673 | Profile(ID, OriginalTy, AdjustedTy); |
2674 | } |
2675 | |
2676 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2677 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2678 | ID.AddPointer(New.getAsOpaquePtr()); |
2679 | } |
2680 | |
2681 | static bool classof(const Type *T) { |
2682 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2683 | } |
2684 | }; |
2685 | |
2686 | /// Represents a pointer type decayed from an array or function type. |
2687 | class DecayedType : public AdjustedType { |
2688 | friend class ASTContext; // ASTContext creates these. |
2689 | |
2690 | inline |
2691 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2692 | |
2693 | public: |
2694 | QualType getDecayedType() const { return getAdjustedType(); } |
2695 | |
2696 | inline QualType getPointeeType() const; |
2697 | |
2698 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2699 | }; |
2700 | |
2701 | /// Pointer to a block type. |
2702 | /// This type is to represent types syntactically represented as |
2703 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2704 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2705 | friend class ASTContext; // ASTContext creates these. |
2706 | |
2707 | // Block is some kind of pointer type |
2708 | QualType PointeeType; |
2709 | |
2710 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2711 | : Type(BlockPointer, CanonicalCls, Pointee->getDependence()), |
2712 | PointeeType(Pointee) {} |
2713 | |
2714 | public: |
2715 | // Get the pointee type. Pointee is required to always be a function type. |
2716 | QualType getPointeeType() const { return PointeeType; } |
2717 | |
2718 | bool isSugared() const { return false; } |
2719 | QualType desugar() const { return QualType(this, 0); } |
2720 | |
2721 | void Profile(llvm::FoldingSetNodeID &ID) { |
2722 | Profile(ID, getPointeeType()); |
2723 | } |
2724 | |
2725 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2726 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2727 | } |
2728 | |
2729 | static bool classof(const Type *T) { |
2730 | return T->getTypeClass() == BlockPointer; |
2731 | } |
2732 | }; |
2733 | |
2734 | /// Base for LValueReferenceType and RValueReferenceType |
2735 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2736 | QualType PointeeType; |
2737 | |
2738 | protected: |
2739 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2740 | bool SpelledAsLValue) |
2741 | : Type(tc, CanonicalRef, Referencee->getDependence()), |
2742 | PointeeType(Referencee) { |
2743 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2744 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2745 | } |
2746 | |
2747 | public: |
2748 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2749 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2750 | |
2751 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2752 | |
2753 | QualType getPointeeType() const { |
2754 | // FIXME: this might strip inner qualifiers; okay? |
2755 | const ReferenceType *T = this; |
2756 | while (T->isInnerRef()) |
2757 | T = T->PointeeType->castAs<ReferenceType>(); |
2758 | return T->PointeeType; |
2759 | } |
2760 | |
2761 | void Profile(llvm::FoldingSetNodeID &ID) { |
2762 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2763 | } |
2764 | |
2765 | static void Profile(llvm::FoldingSetNodeID &ID, |
2766 | QualType Referencee, |
2767 | bool SpelledAsLValue) { |
2768 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2769 | ID.AddBoolean(SpelledAsLValue); |
2770 | } |
2771 | |
2772 | static bool classof(const Type *T) { |
2773 | return T->getTypeClass() == LValueReference || |
2774 | T->getTypeClass() == RValueReference; |
2775 | } |
2776 | }; |
2777 | |
2778 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2779 | class LValueReferenceType : public ReferenceType { |
2780 | friend class ASTContext; // ASTContext creates these |
2781 | |
2782 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2783 | bool SpelledAsLValue) |
2784 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2785 | SpelledAsLValue) {} |
2786 | |
2787 | public: |
2788 | bool isSugared() const { return false; } |
2789 | QualType desugar() const { return QualType(this, 0); } |
2790 | |
2791 | static bool classof(const Type *T) { |
2792 | return T->getTypeClass() == LValueReference; |
2793 | } |
2794 | }; |
2795 | |
2796 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2797 | class RValueReferenceType : public ReferenceType { |
2798 | friend class ASTContext; // ASTContext creates these |
2799 | |
2800 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2801 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2802 | |
2803 | public: |
2804 | bool isSugared() const { return false; } |
2805 | QualType desugar() const { return QualType(this, 0); } |
2806 | |
2807 | static bool classof(const Type *T) { |
2808 | return T->getTypeClass() == RValueReference; |
2809 | } |
2810 | }; |
2811 | |
2812 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2813 | /// |
2814 | /// This includes both pointers to data members and pointer to member functions. |
2815 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2816 | friend class ASTContext; // ASTContext creates these. |
2817 | |
2818 | QualType PointeeType; |
2819 | |
2820 | /// The class of which the pointee is a member. Must ultimately be a |
2821 | /// RecordType, but could be a typedef or a template parameter too. |
2822 | const Type *Class; |
2823 | |
2824 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2825 | : Type(MemberPointer, CanonicalPtr, |
2826 | (Cls->getDependence() & ~TypeDependence::VariablyModified) | |
2827 | Pointee->getDependence()), |
2828 | PointeeType(Pointee), Class(Cls) {} |
2829 | |
2830 | public: |
2831 | QualType getPointeeType() const { return PointeeType; } |
2832 | |
2833 | /// Returns true if the member type (i.e. the pointee type) is a |
2834 | /// function type rather than a data-member type. |
2835 | bool isMemberFunctionPointer() const { |
2836 | return PointeeType->isFunctionProtoType(); |
2837 | } |
2838 | |
2839 | /// Returns true if the member type (i.e. the pointee type) is a |
2840 | /// data type rather than a function type. |
2841 | bool isMemberDataPointer() const { |
2842 | return !PointeeType->isFunctionProtoType(); |
2843 | } |
2844 | |
2845 | const Type *getClass() const { return Class; } |
2846 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2847 | |
2848 | bool isSugared() const { return false; } |
2849 | QualType desugar() const { return QualType(this, 0); } |
2850 | |
2851 | void Profile(llvm::FoldingSetNodeID &ID) { |
2852 | Profile(ID, getPointeeType(), getClass()); |
2853 | } |
2854 | |
2855 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2856 | const Type *Class) { |
2857 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2858 | ID.AddPointer(Class); |
2859 | } |
2860 | |
2861 | static bool classof(const Type *T) { |
2862 | return T->getTypeClass() == MemberPointer; |
2863 | } |
2864 | }; |
2865 | |
2866 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2867 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2868 | public: |
2869 | /// Capture whether this is a normal array (e.g. int X[4]) |
2870 | /// an array with a static size (e.g. int X[static 4]), or an array |
2871 | /// with a star size (e.g. int X[*]). |
2872 | /// 'static' is only allowed on function parameters. |
2873 | enum ArraySizeModifier { |
2874 | Normal, Static, Star |
2875 | }; |
2876 | |
2877 | private: |
2878 | /// The element type of the array. |
2879 | QualType ElementType; |
2880 | |
2881 | protected: |
2882 | friend class ASTContext; // ASTContext creates these. |
2883 | |
2884 | ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, |
2885 | unsigned tq, const Expr *sz = nullptr); |
2886 | |
2887 | public: |
2888 | QualType getElementType() const { return ElementType; } |
2889 | |
2890 | ArraySizeModifier getSizeModifier() const { |
2891 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2892 | } |
2893 | |
2894 | Qualifiers getIndexTypeQualifiers() const { |
2895 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2896 | } |
2897 | |
2898 | unsigned getIndexTypeCVRQualifiers() const { |
2899 | return ArrayTypeBits.IndexTypeQuals; |
2900 | } |
2901 | |
2902 | static bool classof(const Type *T) { |
2903 | return T->getTypeClass() == ConstantArray || |
2904 | T->getTypeClass() == VariableArray || |
2905 | T->getTypeClass() == IncompleteArray || |
2906 | T->getTypeClass() == DependentSizedArray; |
2907 | } |
2908 | }; |
2909 | |
2910 | /// Represents the canonical version of C arrays with a specified constant size. |
2911 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2912 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2913 | class ConstantArrayType final |
2914 | : public ArrayType, |
2915 | private llvm::TrailingObjects<ConstantArrayType, const Expr *> { |
2916 | friend class ASTContext; // ASTContext creates these. |
2917 | friend TrailingObjects; |
2918 | |
2919 | llvm::APInt Size; // Allows us to unique the type. |
2920 | |
2921 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2922 | const Expr *sz, ArraySizeModifier sm, unsigned tq) |
2923 | : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { |
2924 | ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; |
2925 | if (ConstantArrayTypeBits.HasStoredSizeExpr) { |
2926 | assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size" ) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 2926, __PRETTY_FUNCTION__)); |
2927 | *getTrailingObjects<const Expr*>() = sz; |
2928 | } |
2929 | } |
2930 | |
2931 | unsigned numTrailingObjects(OverloadToken<const Expr*>) const { |
2932 | return ConstantArrayTypeBits.HasStoredSizeExpr; |
2933 | } |
2934 | |
2935 | public: |
2936 | const llvm::APInt &getSize() const { return Size; } |
2937 | const Expr *getSizeExpr() const { |
2938 | return ConstantArrayTypeBits.HasStoredSizeExpr |
2939 | ? *getTrailingObjects<const Expr *>() |
2940 | : nullptr; |
2941 | } |
2942 | bool isSugared() const { return false; } |
2943 | QualType desugar() const { return QualType(this, 0); } |
2944 | |
2945 | /// Determine the number of bits required to address a member of |
2946 | // an array with the given element type and number of elements. |
2947 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2948 | QualType ElementType, |
2949 | const llvm::APInt &NumElements); |
2950 | |
2951 | /// Determine the maximum number of active bits that an array's size |
2952 | /// can require, which limits the maximum size of the array. |
2953 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2954 | |
2955 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
2956 | Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), |
2957 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2958 | } |
2959 | |
2960 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, |
2961 | QualType ET, const llvm::APInt &ArraySize, |
2962 | const Expr *SizeExpr, ArraySizeModifier SizeMod, |
2963 | unsigned TypeQuals); |
2964 | |
2965 | static bool classof(const Type *T) { |
2966 | return T->getTypeClass() == ConstantArray; |
2967 | } |
2968 | }; |
2969 | |
2970 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2971 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2972 | /// unspecified. |
2973 | class IncompleteArrayType : public ArrayType { |
2974 | friend class ASTContext; // ASTContext creates these. |
2975 | |
2976 | IncompleteArrayType(QualType et, QualType can, |
2977 | ArraySizeModifier sm, unsigned tq) |
2978 | : ArrayType(IncompleteArray, et, can, sm, tq) {} |
2979 | |
2980 | public: |
2981 | friend class StmtIteratorBase; |
2982 | |
2983 | bool isSugared() const { return false; } |
2984 | QualType desugar() const { return QualType(this, 0); } |
2985 | |
2986 | static bool classof(const Type *T) { |
2987 | return T->getTypeClass() == IncompleteArray; |
2988 | } |
2989 | |
2990 | void Profile(llvm::FoldingSetNodeID &ID) { |
2991 | Profile(ID, getElementType(), getSizeModifier(), |
2992 | getIndexTypeCVRQualifiers()); |
2993 | } |
2994 | |
2995 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2996 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
2997 | ID.AddPointer(ET.getAsOpaquePtr()); |
2998 | ID.AddInteger(SizeMod); |
2999 | ID.AddInteger(TypeQuals); |
3000 | } |
3001 | }; |
3002 | |
3003 | /// Represents a C array with a specified size that is not an |
3004 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
3005 | /// Since the size expression is an arbitrary expression, we store it as such. |
3006 | /// |
3007 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3008 | /// should not be: two lexically equivalent variable array types could mean |
3009 | /// different things, for example, these variables do not have the same type |
3010 | /// dynamically: |
3011 | /// |
3012 | /// void foo(int x) { |
3013 | /// int Y[x]; |
3014 | /// ++x; |
3015 | /// int Z[x]; |
3016 | /// } |
3017 | class VariableArrayType : public ArrayType { |
3018 | friend class ASTContext; // ASTContext creates these. |
3019 | |
3020 | /// An assignment-expression. VLA's are only permitted within |
3021 | /// a function block. |
3022 | Stmt *SizeExpr; |
3023 | |
3024 | /// The range spanned by the left and right array brackets. |
3025 | SourceRange Brackets; |
3026 | |
3027 | VariableArrayType(QualType et, QualType can, Expr *e, |
3028 | ArraySizeModifier sm, unsigned tq, |
3029 | SourceRange brackets) |
3030 | : ArrayType(VariableArray, et, can, sm, tq, e), |
3031 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3032 | |
3033 | public: |
3034 | friend class StmtIteratorBase; |
3035 | |
3036 | Expr *getSizeExpr() const { |
3037 | // We use C-style casts instead of cast<> here because we do not wish |
3038 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3039 | return (Expr*) SizeExpr; |
3040 | } |
3041 | |
3042 | SourceRange getBracketsRange() const { return Brackets; } |
3043 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3044 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3045 | |
3046 | bool isSugared() const { return false; } |
3047 | QualType desugar() const { return QualType(this, 0); } |
3048 | |
3049 | static bool classof(const Type *T) { |
3050 | return T->getTypeClass() == VariableArray; |
3051 | } |
3052 | |
3053 | void Profile(llvm::FoldingSetNodeID &ID) { |
3054 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 3054); |
3055 | } |
3056 | }; |
3057 | |
3058 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3059 | /// |
3060 | /// For example: |
3061 | /// \code |
3062 | /// template<typename T, int Size> |
3063 | /// class array { |
3064 | /// T data[Size]; |
3065 | /// }; |
3066 | /// \endcode |
3067 | /// |
3068 | /// For these types, we won't actually know what the array bound is |
3069 | /// until template instantiation occurs, at which point this will |
3070 | /// become either a ConstantArrayType or a VariableArrayType. |
3071 | class DependentSizedArrayType : public ArrayType { |
3072 | friend class ASTContext; // ASTContext creates these. |
3073 | |
3074 | const ASTContext &Context; |
3075 | |
3076 | /// An assignment expression that will instantiate to the |
3077 | /// size of the array. |
3078 | /// |
3079 | /// The expression itself might be null, in which case the array |
3080 | /// type will have its size deduced from an initializer. |
3081 | Stmt *SizeExpr; |
3082 | |
3083 | /// The range spanned by the left and right array brackets. |
3084 | SourceRange Brackets; |
3085 | |
3086 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3087 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3088 | SourceRange brackets); |
3089 | |
3090 | public: |
3091 | friend class StmtIteratorBase; |
3092 | |
3093 | Expr *getSizeExpr() const { |
3094 | // We use C-style casts instead of cast<> here because we do not wish |
3095 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3096 | return (Expr*) SizeExpr; |
3097 | } |
3098 | |
3099 | SourceRange getBracketsRange() const { return Brackets; } |
3100 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3101 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3102 | |
3103 | bool isSugared() const { return false; } |
3104 | QualType desugar() const { return QualType(this, 0); } |
3105 | |
3106 | static bool classof(const Type *T) { |
3107 | return T->getTypeClass() == DependentSizedArray; |
3108 | } |
3109 | |
3110 | void Profile(llvm::FoldingSetNodeID &ID) { |
3111 | Profile(ID, Context, getElementType(), |
3112 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3113 | } |
3114 | |
3115 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3116 | QualType ET, ArraySizeModifier SizeMod, |
3117 | unsigned TypeQuals, Expr *E); |
3118 | }; |
3119 | |
3120 | /// Represents an extended address space qualifier where the input address space |
3121 | /// value is dependent. Non-dependent address spaces are not represented with a |
3122 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3123 | /// |
3124 | /// For example: |
3125 | /// \code |
3126 | /// template<typename T, int AddrSpace> |
3127 | /// class AddressSpace { |
3128 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3129 | /// } |
3130 | /// \endcode |
3131 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3132 | friend class ASTContext; |
3133 | |
3134 | const ASTContext &Context; |
3135 | Expr *AddrSpaceExpr; |
3136 | QualType PointeeType; |
3137 | SourceLocation loc; |
3138 | |
3139 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3140 | QualType can, Expr *AddrSpaceExpr, |
3141 | SourceLocation loc); |
3142 | |
3143 | public: |
3144 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3145 | QualType getPointeeType() const { return PointeeType; } |
3146 | SourceLocation getAttributeLoc() const { return loc; } |
3147 | |
3148 | bool isSugared() const { return false; } |
3149 | QualType desugar() const { return QualType(this, 0); } |
3150 | |
3151 | static bool classof(const Type *T) { |
3152 | return T->getTypeClass() == DependentAddressSpace; |
3153 | } |
3154 | |
3155 | void Profile(llvm::FoldingSetNodeID &ID) { |
3156 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3157 | } |
3158 | |
3159 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3160 | QualType PointeeType, Expr *AddrSpaceExpr); |
3161 | }; |
3162 | |
3163 | /// Represents an extended vector type where either the type or size is |
3164 | /// dependent. |
3165 | /// |
3166 | /// For example: |
3167 | /// \code |
3168 | /// template<typename T, int Size> |
3169 | /// class vector { |
3170 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3171 | /// } |
3172 | /// \endcode |
3173 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3174 | friend class ASTContext; |
3175 | |
3176 | const ASTContext &Context; |
3177 | Expr *SizeExpr; |
3178 | |
3179 | /// The element type of the array. |
3180 | QualType ElementType; |
3181 | |
3182 | SourceLocation loc; |
3183 | |
3184 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3185 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3186 | |
3187 | public: |
3188 | Expr *getSizeExpr() const { return SizeExpr; } |
3189 | QualType getElementType() const { return ElementType; } |
3190 | SourceLocation getAttributeLoc() const { return loc; } |
3191 | |
3192 | bool isSugared() const { return false; } |
3193 | QualType desugar() const { return QualType(this, 0); } |
3194 | |
3195 | static bool classof(const Type *T) { |
3196 | return T->getTypeClass() == DependentSizedExtVector; |
3197 | } |
3198 | |
3199 | void Profile(llvm::FoldingSetNodeID &ID) { |
3200 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3201 | } |
3202 | |
3203 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3204 | QualType ElementType, Expr *SizeExpr); |
3205 | }; |
3206 | |
3207 | |
3208 | /// Represents a GCC generic vector type. This type is created using |
3209 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3210 | /// bytes; or from an Altivec __vector or vector declaration. |
3211 | /// Since the constructor takes the number of vector elements, the |
3212 | /// client is responsible for converting the size into the number of elements. |
3213 | class VectorType : public Type, public llvm::FoldingSetNode { |
3214 | public: |
3215 | enum VectorKind { |
3216 | /// not a target-specific vector type |
3217 | GenericVector, |
3218 | |
3219 | /// is AltiVec vector |
3220 | AltiVecVector, |
3221 | |
3222 | /// is AltiVec 'vector Pixel' |
3223 | AltiVecPixel, |
3224 | |
3225 | /// is AltiVec 'vector bool ...' |
3226 | AltiVecBool, |
3227 | |
3228 | /// is ARM Neon vector |
3229 | NeonVector, |
3230 | |
3231 | /// is ARM Neon polynomial vector |
3232 | NeonPolyVector, |
3233 | |
3234 | /// is AArch64 SVE fixed-length data vector |
3235 | SveFixedLengthDataVector, |
3236 | |
3237 | /// is AArch64 SVE fixed-length predicate vector |
3238 | SveFixedLengthPredicateVector |
3239 | }; |
3240 | |
3241 | protected: |
3242 | friend class ASTContext; // ASTContext creates these. |
3243 | |
3244 | /// The element type of the vector. |
3245 | QualType ElementType; |
3246 | |
3247 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3248 | VectorKind vecKind); |
3249 | |
3250 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3251 | QualType canonType, VectorKind vecKind); |
3252 | |
3253 | public: |
3254 | QualType getElementType() const { return ElementType; } |
3255 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3256 | |
3257 | bool isSugared() const { return false; } |
3258 | QualType desugar() const { return QualType(this, 0); } |
3259 | |
3260 | VectorKind getVectorKind() const { |
3261 | return VectorKind(VectorTypeBits.VecKind); |
3262 | } |
3263 | |
3264 | void Profile(llvm::FoldingSetNodeID &ID) { |
3265 | Profile(ID, getElementType(), getNumElements(), |
3266 | getTypeClass(), getVectorKind()); |
3267 | } |
3268 | |
3269 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3270 | unsigned NumElements, TypeClass TypeClass, |
3271 | VectorKind VecKind) { |
3272 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3273 | ID.AddInteger(NumElements); |
3274 | ID.AddInteger(TypeClass); |
3275 | ID.AddInteger(VecKind); |
3276 | } |
3277 | |
3278 | static bool classof(const Type *T) { |
3279 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3280 | } |
3281 | }; |
3282 | |
3283 | /// Represents a vector type where either the type or size is dependent. |
3284 | //// |
3285 | /// For example: |
3286 | /// \code |
3287 | /// template<typename T, int Size> |
3288 | /// class vector { |
3289 | /// typedef T __attribute__((vector_size(Size))) type; |
3290 | /// } |
3291 | /// \endcode |
3292 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3293 | friend class ASTContext; |
3294 | |
3295 | const ASTContext &Context; |
3296 | QualType ElementType; |
3297 | Expr *SizeExpr; |
3298 | SourceLocation Loc; |
3299 | |
3300 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3301 | QualType CanonType, Expr *SizeExpr, |
3302 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3303 | |
3304 | public: |
3305 | Expr *getSizeExpr() const { return SizeExpr; } |
3306 | QualType getElementType() const { return ElementType; } |
3307 | SourceLocation getAttributeLoc() const { return Loc; } |
3308 | VectorType::VectorKind getVectorKind() const { |
3309 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3310 | } |
3311 | |
3312 | bool isSugared() const { return false; } |
3313 | QualType desugar() const { return QualType(this, 0); } |
3314 | |
3315 | static bool classof(const Type *T) { |
3316 | return T->getTypeClass() == DependentVector; |
3317 | } |
3318 | |
3319 | void Profile(llvm::FoldingSetNodeID &ID) { |
3320 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3321 | } |
3322 | |
3323 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3324 | QualType ElementType, const Expr *SizeExpr, |
3325 | VectorType::VectorKind VecKind); |
3326 | }; |
3327 | |
3328 | /// ExtVectorType - Extended vector type. This type is created using |
3329 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3330 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3331 | /// class enables syntactic extensions, like Vector Components for accessing |
3332 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3333 | /// Shading Language). |
3334 | class ExtVectorType : public VectorType { |
3335 | friend class ASTContext; // ASTContext creates these. |
3336 | |
3337 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3338 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3339 | |
3340 | public: |
3341 | static int getPointAccessorIdx(char c) { |
3342 | switch (c) { |
3343 | default: return -1; |
3344 | case 'x': case 'r': return 0; |
3345 | case 'y': case 'g': return 1; |
3346 | case 'z': case 'b': return 2; |
3347 | case 'w': case 'a': return 3; |
3348 | } |
3349 | } |
3350 | |
3351 | static int getNumericAccessorIdx(char c) { |
3352 | switch (c) { |
3353 | default: return -1; |
3354 | case '0': return 0; |
3355 | case '1': return 1; |
3356 | case '2': return 2; |
3357 | case '3': return 3; |
3358 | case '4': return 4; |
3359 | case '5': return 5; |
3360 | case '6': return 6; |
3361 | case '7': return 7; |
3362 | case '8': return 8; |
3363 | case '9': return 9; |
3364 | case 'A': |
3365 | case 'a': return 10; |
3366 | case 'B': |
3367 | case 'b': return 11; |
3368 | case 'C': |
3369 | case 'c': return 12; |
3370 | case 'D': |
3371 | case 'd': return 13; |
3372 | case 'E': |
3373 | case 'e': return 14; |
3374 | case 'F': |
3375 | case 'f': return 15; |
3376 | } |
3377 | } |
3378 | |
3379 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3380 | if (isNumericAccessor) |
3381 | return getNumericAccessorIdx(c); |
3382 | else |
3383 | return getPointAccessorIdx(c); |
3384 | } |
3385 | |
3386 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3387 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3388 | return unsigned(idx-1) < getNumElements(); |
3389 | return false; |
3390 | } |
3391 | |
3392 | bool isSugared() const { return false; } |
3393 | QualType desugar() const { return QualType(this, 0); } |
3394 | |
3395 | static bool classof(const Type *T) { |
3396 | return T->getTypeClass() == ExtVector; |
3397 | } |
3398 | }; |
3399 | |
3400 | /// Represents a matrix type, as defined in the Matrix Types clang extensions. |
3401 | /// __attribute__((matrix_type(rows, columns))), where "rows" specifies |
3402 | /// number of rows and "columns" specifies the number of columns. |
3403 | class MatrixType : public Type, public llvm::FoldingSetNode { |
3404 | protected: |
3405 | friend class ASTContext; |
3406 | |
3407 | /// The element type of the matrix. |
3408 | QualType ElementType; |
3409 | |
3410 | MatrixType(QualType ElementTy, QualType CanonElementTy); |
3411 | |
3412 | MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy, |
3413 | const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr); |
3414 | |
3415 | public: |
3416 | /// Returns type of the elements being stored in the matrix |
3417 | QualType getElementType() const { return ElementType; } |
3418 | |
3419 | /// Valid elements types are the following: |
3420 | /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types |
3421 | /// and _Bool |
3422 | /// * the standard floating types float or double |
3423 | /// * a half-precision floating point type, if one is supported on the target |
3424 | static bool isValidElementType(QualType T) { |
3425 | return T->isDependentType() || |
3426 | (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType()); |
3427 | } |
3428 | |
3429 | bool isSugared() const { return false; } |
3430 | QualType desugar() const { return QualType(this, 0); } |
3431 | |
3432 | static bool classof(const Type *T) { |
3433 | return T->getTypeClass() == ConstantMatrix || |
3434 | T->getTypeClass() == DependentSizedMatrix; |
3435 | } |
3436 | }; |
3437 | |
3438 | /// Represents a concrete matrix type with constant number of rows and columns |
3439 | class ConstantMatrixType final : public MatrixType { |
3440 | protected: |
3441 | friend class ASTContext; |
3442 | |
3443 | /// The element type of the matrix. |
3444 | // FIXME: Appears to be unused? There is also MatrixType::ElementType... |
3445 | QualType ElementType; |
3446 | |
3447 | /// Number of rows and columns. |
3448 | unsigned NumRows; |
3449 | unsigned NumColumns; |
3450 | |
3451 | static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1; |
3452 | |
3453 | ConstantMatrixType(QualType MatrixElementType, unsigned NRows, |
3454 | unsigned NColumns, QualType CanonElementType); |
3455 | |
3456 | ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows, |
3457 | unsigned NColumns, QualType CanonElementType); |
3458 | |
3459 | public: |
3460 | /// Returns the number of rows in the matrix. |
3461 | unsigned getNumRows() const { return NumRows; } |
3462 | |
3463 | /// Returns the number of columns in the matrix. |
3464 | unsigned getNumColumns() const { return NumColumns; } |
3465 | |
3466 | /// Returns the number of elements required to embed the matrix into a vector. |
3467 | unsigned getNumElementsFlattened() const { |
3468 | return getNumRows() * getNumColumns(); |
3469 | } |
3470 | |
3471 | /// Returns true if \p NumElements is a valid matrix dimension. |
3472 | static constexpr bool isDimensionValid(size_t NumElements) { |
3473 | return NumElements > 0 && NumElements <= MaxElementsPerDimension; |
3474 | } |
3475 | |
3476 | /// Returns the maximum number of elements per dimension. |
3477 | static constexpr unsigned getMaxElementsPerDimension() { |
3478 | return MaxElementsPerDimension; |
3479 | } |
3480 | |
3481 | void Profile(llvm::FoldingSetNodeID &ID) { |
3482 | Profile(ID, getElementType(), getNumRows(), getNumColumns(), |
3483 | getTypeClass()); |
3484 | } |
3485 | |
3486 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3487 | unsigned NumRows, unsigned NumColumns, |
3488 | TypeClass TypeClass) { |
3489 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3490 | ID.AddInteger(NumRows); |
3491 | ID.AddInteger(NumColumns); |
3492 | ID.AddInteger(TypeClass); |
3493 | } |
3494 | |
3495 | static bool classof(const Type *T) { |
3496 | return T->getTypeClass() == ConstantMatrix; |
3497 | } |
3498 | }; |
3499 | |
3500 | /// Represents a matrix type where the type and the number of rows and columns |
3501 | /// is dependent on a template. |
3502 | class DependentSizedMatrixType final : public MatrixType { |
3503 | friend class ASTContext; |
3504 | |
3505 | const ASTContext &Context; |
3506 | Expr *RowExpr; |
3507 | Expr *ColumnExpr; |
3508 | |
3509 | SourceLocation loc; |
3510 | |
3511 | DependentSizedMatrixType(const ASTContext &Context, QualType ElementType, |
3512 | QualType CanonicalType, Expr *RowExpr, |
3513 | Expr *ColumnExpr, SourceLocation loc); |
3514 | |
3515 | public: |
3516 | QualType getElementType() const { return ElementType; } |
3517 | Expr *getRowExpr() const { return RowExpr; } |
3518 | Expr *getColumnExpr() const { return ColumnExpr; } |
3519 | SourceLocation getAttributeLoc() const { return loc; } |
3520 | |
3521 | bool isSugared() const { return false; } |
3522 | QualType desugar() const { return QualType(this, 0); } |
3523 | |
3524 | static bool classof(const Type *T) { |
3525 | return T->getTypeClass() == DependentSizedMatrix; |
3526 | } |
3527 | |
3528 | void Profile(llvm::FoldingSetNodeID &ID) { |
3529 | Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr()); |
3530 | } |
3531 | |
3532 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3533 | QualType ElementType, Expr *RowExpr, Expr *ColumnExpr); |
3534 | }; |
3535 | |
3536 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3537 | /// class of FunctionNoProtoType and FunctionProtoType. |
3538 | class FunctionType : public Type { |
3539 | // The type returned by the function. |
3540 | QualType ResultType; |
3541 | |
3542 | public: |
3543 | /// Interesting information about a specific parameter that can't simply |
3544 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3545 | /// but is in FunctionType to make this class available during the |
3546 | /// specification of the bases of FunctionProtoType. |
3547 | /// |
3548 | /// It makes sense to model language features this way when there's some |
3549 | /// sort of parameter-specific override (such as an attribute) that |
3550 | /// affects how the function is called. For example, the ARC ns_consumed |
3551 | /// attribute changes whether a parameter is passed at +0 (the default) |
3552 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3553 | /// but isn't really a change to the parameter type. |
3554 | /// |
3555 | /// One serious disadvantage of modelling language features this way is |
3556 | /// that they generally do not work with language features that attempt |
3557 | /// to destructure types. For example, template argument deduction will |
3558 | /// not be able to match a parameter declared as |
3559 | /// T (*)(U) |
3560 | /// against an argument of type |
3561 | /// void (*)(__attribute__((ns_consumed)) id) |
3562 | /// because the substitution of T=void, U=id into the former will |
3563 | /// not produce the latter. |
3564 | class ExtParameterInfo { |
3565 | enum { |
3566 | ABIMask = 0x0F, |
3567 | IsConsumed = 0x10, |
3568 | HasPassObjSize = 0x20, |
3569 | IsNoEscape = 0x40, |
3570 | }; |
3571 | unsigned char Data = 0; |
3572 | |
3573 | public: |
3574 | ExtParameterInfo() = default; |
3575 | |
3576 | /// Return the ABI treatment of this parameter. |
3577 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3578 | ExtParameterInfo withABI(ParameterABI kind) const { |
3579 | ExtParameterInfo copy = *this; |
3580 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3581 | return copy; |
3582 | } |
3583 | |
3584 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3585 | /// Consumed parameters must have retainable object type. |
3586 | bool isConsumed() const { return (Data & IsConsumed); } |
3587 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3588 | ExtParameterInfo copy = *this; |
3589 | if (consumed) |
3590 | copy.Data |= IsConsumed; |
3591 | else |
3592 | copy.Data &= ~IsConsumed; |
3593 | return copy; |
3594 | } |
3595 | |
3596 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3597 | ExtParameterInfo withHasPassObjectSize() const { |
3598 | ExtParameterInfo Copy = *this; |
3599 | Copy.Data |= HasPassObjSize; |
3600 | return Copy; |
3601 | } |
3602 | |
3603 | bool isNoEscape() const { return Data & IsNoEscape; } |
3604 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3605 | ExtParameterInfo Copy = *this; |
3606 | if (NoEscape) |
3607 | Copy.Data |= IsNoEscape; |
3608 | else |
3609 | Copy.Data &= ~IsNoEscape; |
3610 | return Copy; |
3611 | } |
3612 | |
3613 | unsigned char getOpaqueValue() const { return Data; } |
3614 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3615 | ExtParameterInfo result; |
3616 | result.Data = data; |
3617 | return result; |
3618 | } |
3619 | |
3620 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3621 | return lhs.Data == rhs.Data; |
3622 | } |
3623 | |
3624 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3625 | return lhs.Data != rhs.Data; |
3626 | } |
3627 | }; |
3628 | |
3629 | /// A class which abstracts out some details necessary for |
3630 | /// making a call. |
3631 | /// |
3632 | /// It is not actually used directly for storing this information in |
3633 | /// a FunctionType, although FunctionType does currently use the |
3634 | /// same bit-pattern. |
3635 | /// |
3636 | // If you add a field (say Foo), other than the obvious places (both, |
3637 | // constructors, compile failures), what you need to update is |
3638 | // * Operator== |
3639 | // * getFoo |
3640 | // * withFoo |
3641 | // * functionType. Add Foo, getFoo. |
3642 | // * ASTContext::getFooType |
3643 | // * ASTContext::mergeFunctionTypes |
3644 | // * FunctionNoProtoType::Profile |
3645 | // * FunctionProtoType::Profile |
3646 | // * TypePrinter::PrintFunctionProto |
3647 | // * AST read and write |
3648 | // * Codegen |
3649 | class ExtInfo { |
3650 | friend class FunctionType; |
3651 | |
3652 | // Feel free to rearrange or add bits, but if you go over 16, you'll need to |
3653 | // adjust the Bits field below, and if you add bits, you'll need to adjust |
3654 | // Type::FunctionTypeBitfields::ExtInfo as well. |
3655 | |
3656 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall| |
3657 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 | |
3658 | // |
3659 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3660 | enum { CallConvMask = 0x1F }; |
3661 | enum { NoReturnMask = 0x20 }; |
3662 | enum { ProducesResultMask = 0x40 }; |
3663 | enum { NoCallerSavedRegsMask = 0x80 }; |
3664 | enum { |
3665 | RegParmMask = 0x700, |
3666 | RegParmOffset = 8 |
3667 | }; |
3668 | enum { NoCfCheckMask = 0x800 }; |
3669 | enum { CmseNSCallMask = 0x1000 }; |
3670 | uint16_t Bits = CC_C; |
3671 | |
3672 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3673 | |
3674 | public: |
3675 | // Constructor with no defaults. Use this when you know that you |
3676 | // have all the elements (when reading an AST file for example). |
3677 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3678 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck, |
3679 | bool cmseNSCall) { |
3680 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value" ) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 3680, __PRETTY_FUNCTION__)); |
3681 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3682 | (producesResult ? ProducesResultMask : 0) | |
3683 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3684 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3685 | (NoCfCheck ? NoCfCheckMask : 0) | |
3686 | (cmseNSCall ? CmseNSCallMask : 0); |
3687 | } |
3688 | |
3689 | // Constructor with all defaults. Use when for example creating a |
3690 | // function known to use defaults. |
3691 | ExtInfo() = default; |
3692 | |
3693 | // Constructor with just the calling convention, which is an important part |
3694 | // of the canonical type. |
3695 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3696 | |
3697 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3698 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3699 | bool getCmseNSCall() const { return Bits & CmseNSCallMask; } |
3700 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3701 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3702 | bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; } |
3703 | |
3704 | unsigned getRegParm() const { |
3705 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3706 | if (RegParm > 0) |
3707 | --RegParm; |
3708 | return RegParm; |
3709 | } |
3710 | |
3711 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3712 | |
3713 | bool operator==(ExtInfo Other) const { |
3714 | return Bits == Other.Bits; |
3715 | } |
3716 | bool operator!=(ExtInfo Other) const { |
3717 | return Bits != Other.Bits; |
3718 | } |
3719 | |
3720 | // Note that we don't have setters. That is by design, use |
3721 | // the following with methods instead of mutating these objects. |
3722 | |
3723 | ExtInfo withNoReturn(bool noReturn) const { |
3724 | if (noReturn) |
3725 | return ExtInfo(Bits | NoReturnMask); |
3726 | else |
3727 | return ExtInfo(Bits & ~NoReturnMask); |
3728 | } |
3729 | |
3730 | ExtInfo withProducesResult(bool producesResult) const { |
3731 | if (producesResult) |
3732 | return ExtInfo(Bits | ProducesResultMask); |
3733 | else |
3734 | return ExtInfo(Bits & ~ProducesResultMask); |
3735 | } |
3736 | |
3737 | ExtInfo withCmseNSCall(bool cmseNSCall) const { |
3738 | if (cmseNSCall) |
3739 | return ExtInfo(Bits | CmseNSCallMask); |
3740 | else |
3741 | return ExtInfo(Bits & ~CmseNSCallMask); |
3742 | } |
3743 | |
3744 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3745 | if (noCallerSavedRegs) |
3746 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3747 | else |
3748 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3749 | } |
3750 | |
3751 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3752 | if (noCfCheck) |
3753 | return ExtInfo(Bits | NoCfCheckMask); |
3754 | else |
3755 | return ExtInfo(Bits & ~NoCfCheckMask); |
3756 | } |
3757 | |
3758 | ExtInfo withRegParm(unsigned RegParm) const { |
3759 | assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast <void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 3759, __PRETTY_FUNCTION__)); |
3760 | return ExtInfo((Bits & ~RegParmMask) | |
3761 | ((RegParm + 1) << RegParmOffset)); |
3762 | } |
3763 | |
3764 | ExtInfo withCallingConv(CallingConv cc) const { |
3765 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3766 | } |
3767 | |
3768 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3769 | ID.AddInteger(Bits); |
3770 | } |
3771 | }; |
3772 | |
3773 | /// A simple holder for a QualType representing a type in an |
3774 | /// exception specification. Unfortunately needed by FunctionProtoType |
3775 | /// because TrailingObjects cannot handle repeated types. |
3776 | struct ExceptionType { QualType Type; }; |
3777 | |
3778 | /// A simple holder for various uncommon bits which do not fit in |
3779 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3780 | /// alignment of subsequent objects in TrailingObjects. You must update |
3781 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3782 | struct alignas(void *) FunctionTypeExtraBitfields { |
3783 | /// The number of types in the exception specification. |
3784 | /// A whole unsigned is not needed here and according to |
3785 | /// [implimits] 8 bits would be enough here. |
3786 | unsigned NumExceptionType; |
3787 | }; |
3788 | |
3789 | protected: |
3790 | FunctionType(TypeClass tc, QualType res, QualType Canonical, |
3791 | TypeDependence Dependence, ExtInfo Info) |
3792 | : Type(tc, Canonical, Dependence), ResultType(res) { |
3793 | FunctionTypeBits.ExtInfo = Info.Bits; |
3794 | } |
3795 | |
3796 | Qualifiers getFastTypeQuals() const { |
3797 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3798 | } |
3799 | |
3800 | public: |
3801 | QualType getReturnType() const { return ResultType; } |
3802 | |
3803 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3804 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3805 | |
3806 | /// Determine whether this function type includes the GNU noreturn |
3807 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3808 | /// type. |
3809 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3810 | |
3811 | bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); } |
3812 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3813 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3814 | |
3815 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3816 | "Const, volatile and restrict are assumed to be a subset of " |
3817 | "the fast qualifiers."); |
3818 | |
3819 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3820 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3821 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3822 | |
3823 | /// Determine the type of an expression that calls a function of |
3824 | /// this type. |
3825 | QualType getCallResultType(const ASTContext &Context) const { |
3826 | return getReturnType().getNonLValueExprType(Context); |
3827 | } |
3828 | |
3829 | static StringRef getNameForCallConv(CallingConv CC); |
3830 | |
3831 | static bool classof(const Type *T) { |
3832 | return T->getTypeClass() == FunctionNoProto || |
3833 | T->getTypeClass() == FunctionProto; |
3834 | } |
3835 | }; |
3836 | |
3837 | /// Represents a K&R-style 'int foo()' function, which has |
3838 | /// no information available about its arguments. |
3839 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3840 | friend class ASTContext; // ASTContext creates these. |
3841 | |
3842 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3843 | : FunctionType(FunctionNoProto, Result, Canonical, |
3844 | Result->getDependence() & |
3845 | ~(TypeDependence::DependentInstantiation | |
3846 | TypeDependence::UnexpandedPack), |
3847 | Info) {} |
3848 | |
3849 | public: |
3850 | // No additional state past what FunctionType provides. |
3851 | |
3852 | bool isSugared() const { return false; } |
3853 | QualType desugar() const { return QualType(this, 0); } |
3854 | |
3855 | void Profile(llvm::FoldingSetNodeID &ID) { |
3856 | Profile(ID, getReturnType(), getExtInfo()); |
3857 | } |
3858 | |
3859 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3860 | ExtInfo Info) { |
3861 | Info.Profile(ID); |
3862 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3863 | } |
3864 | |
3865 | static bool classof(const Type *T) { |
3866 | return T->getTypeClass() == FunctionNoProto; |
3867 | } |
3868 | }; |
3869 | |
3870 | /// Represents a prototype with parameter type info, e.g. |
3871 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3872 | /// parameters, not as having a single void parameter. Such a type can have |
3873 | /// an exception specification, but this specification is not part of the |
3874 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3875 | /// which optional. For more information about the trailing objects see |
3876 | /// the first comment inside FunctionProtoType. |
3877 | class FunctionProtoType final |
3878 | : public FunctionType, |
3879 | public llvm::FoldingSetNode, |
3880 | private llvm::TrailingObjects< |
3881 | FunctionProtoType, QualType, SourceLocation, |
3882 | FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, |
3883 | Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> { |
3884 | friend class ASTContext; // ASTContext creates these. |
3885 | friend TrailingObjects; |
3886 | |
3887 | // FunctionProtoType is followed by several trailing objects, some of |
3888 | // which optional. They are in order: |
3889 | // |
3890 | // * An array of getNumParams() QualType holding the parameter types. |
3891 | // Always present. Note that for the vast majority of FunctionProtoType, |
3892 | // these will be the only trailing objects. |
3893 | // |
3894 | // * Optionally if the function is variadic, the SourceLocation of the |
3895 | // ellipsis. |
3896 | // |
3897 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3898 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3899 | // a single FunctionTypeExtraBitfields. Present if and only if |
3900 | // hasExtraBitfields() is true. |
3901 | // |
3902 | // * Optionally exactly one of: |
3903 | // * an array of getNumExceptions() ExceptionType, |
3904 | // * a single Expr *, |
3905 | // * a pair of FunctionDecl *, |
3906 | // * a single FunctionDecl * |
3907 | // used to store information about the various types of exception |
3908 | // specification. See getExceptionSpecSize for the details. |
3909 | // |
3910 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3911 | // an ExtParameterInfo for each of the parameters. Present if and |
3912 | // only if hasExtParameterInfos() is true. |
3913 | // |
3914 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3915 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3916 | // if hasExtQualifiers() is true. |
3917 | // |
3918 | // The optional FunctionTypeExtraBitfields has to be before the data |
3919 | // related to the exception specification since it contains the number |
3920 | // of exception types. |
3921 | // |
3922 | // We put the ExtParameterInfos last. If all were equal, it would make |
3923 | // more sense to put these before the exception specification, because |
3924 | // it's much easier to skip past them compared to the elaborate switch |
3925 | // required to skip the exception specification. However, all is not |
3926 | // equal; ExtParameterInfos are used to model very uncommon features, |
3927 | // and it's better not to burden the more common paths. |
3928 | |
3929 | public: |
3930 | /// Holds information about the various types of exception specification. |
3931 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3932 | /// used to group together the various bits of information about the |
3933 | /// exception specification. |
3934 | struct ExceptionSpecInfo { |
3935 | /// The kind of exception specification this is. |
3936 | ExceptionSpecificationType Type = EST_None; |
3937 | |
3938 | /// Explicitly-specified list of exception types. |
3939 | ArrayRef<QualType> Exceptions; |
3940 | |
3941 | /// Noexcept expression, if this is a computed noexcept specification. |
3942 | Expr *NoexceptExpr = nullptr; |
3943 | |
3944 | /// The function whose exception specification this is, for |
3945 | /// EST_Unevaluated and EST_Uninstantiated. |
3946 | FunctionDecl *SourceDecl = nullptr; |
3947 | |
3948 | /// The function template whose exception specification this is instantiated |
3949 | /// from, for EST_Uninstantiated. |
3950 | FunctionDecl *SourceTemplate = nullptr; |
3951 | |
3952 | ExceptionSpecInfo() = default; |
3953 | |
3954 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3955 | }; |
3956 | |
3957 | /// Extra information about a function prototype. ExtProtoInfo is not |
3958 | /// stored as such in FunctionProtoType but is used to group together |
3959 | /// the various bits of extra information about a function prototype. |
3960 | struct ExtProtoInfo { |
3961 | FunctionType::ExtInfo ExtInfo; |
3962 | bool Variadic : 1; |
3963 | bool HasTrailingReturn : 1; |
3964 | Qualifiers TypeQuals; |
3965 | RefQualifierKind RefQualifier = RQ_None; |
3966 | ExceptionSpecInfo ExceptionSpec; |
3967 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3968 | SourceLocation EllipsisLoc; |
3969 | |
3970 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3971 | |
3972 | ExtProtoInfo(CallingConv CC) |
3973 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3974 | |
3975 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3976 | ExtProtoInfo Result(*this); |
3977 | Result.ExceptionSpec = ESI; |
3978 | return Result; |
3979 | } |
3980 | }; |
3981 | |
3982 | private: |
3983 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3984 | return getNumParams(); |
3985 | } |
3986 | |
3987 | unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { |
3988 | return isVariadic(); |
3989 | } |
3990 | |
3991 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
3992 | return hasExtraBitfields(); |
3993 | } |
3994 | |
3995 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
3996 | return getExceptionSpecSize().NumExceptionType; |
3997 | } |
3998 | |
3999 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
4000 | return getExceptionSpecSize().NumExprPtr; |
4001 | } |
4002 | |
4003 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
4004 | return getExceptionSpecSize().NumFunctionDeclPtr; |
4005 | } |
4006 | |
4007 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
4008 | return hasExtParameterInfos() ? getNumParams() : 0; |
4009 | } |
4010 | |
4011 | /// Determine whether there are any argument types that |
4012 | /// contain an unexpanded parameter pack. |
4013 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
4014 | unsigned numArgs) { |
4015 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
4016 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
4017 | return true; |
4018 | |
4019 | return false; |
4020 | } |
4021 | |
4022 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
4023 | QualType canonical, const ExtProtoInfo &epi); |
4024 | |
4025 | /// This struct is returned by getExceptionSpecSize and is used to |
4026 | /// translate an ExceptionSpecificationType to the number and kind |
4027 | /// of trailing objects related to the exception specification. |
4028 | struct ExceptionSpecSizeHolder { |
4029 | unsigned NumExceptionType; |
4030 | unsigned NumExprPtr; |
4031 | unsigned NumFunctionDeclPtr; |
4032 | }; |
4033 | |
4034 | /// Return the number and kind of trailing objects |
4035 | /// related to the exception specification. |
4036 | static ExceptionSpecSizeHolder |
4037 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
4038 | switch (EST) { |
4039 | case EST_None: |
4040 | case EST_DynamicNone: |
4041 | case EST_MSAny: |
4042 | case EST_BasicNoexcept: |
4043 | case EST_Unparsed: |
4044 | case EST_NoThrow: |
4045 | return {0, 0, 0}; |
4046 | |
4047 | case EST_Dynamic: |
4048 | return {NumExceptions, 0, 0}; |
4049 | |
4050 | case EST_DependentNoexcept: |
4051 | case EST_NoexceptFalse: |
4052 | case EST_NoexceptTrue: |
4053 | return {0, 1, 0}; |
4054 | |
4055 | case EST_Uninstantiated: |
4056 | return {0, 0, 2}; |
4057 | |
4058 | case EST_Unevaluated: |
4059 | return {0, 0, 1}; |
4060 | } |
4061 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 4061); |
4062 | } |
4063 | |
4064 | /// Return the number and kind of trailing objects |
4065 | /// related to the exception specification. |
4066 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
4067 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
4068 | } |
4069 | |
4070 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4071 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
4072 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
4073 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
4074 | return EST == EST_Dynamic; |
4075 | } |
4076 | |
4077 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4078 | bool hasExtraBitfields() const { |
4079 | return hasExtraBitfields(getExceptionSpecType()); |
4080 | } |
4081 | |
4082 | bool hasExtQualifiers() const { |
4083 | return FunctionTypeBits.HasExtQuals; |
4084 | } |
4085 | |
4086 | public: |
4087 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
4088 | |
4089 | QualType getParamType(unsigned i) const { |
4090 | assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index") ? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 4090, __PRETTY_FUNCTION__)); |
4091 | return param_type_begin()[i]; |
4092 | } |
4093 | |
4094 | ArrayRef<QualType> getParamTypes() const { |
4095 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
4096 | } |
4097 | |
4098 | ExtProtoInfo getExtProtoInfo() const { |
4099 | ExtProtoInfo EPI; |
4100 | EPI.ExtInfo = getExtInfo(); |
4101 | EPI.Variadic = isVariadic(); |
4102 | EPI.EllipsisLoc = getEllipsisLoc(); |
4103 | EPI.HasTrailingReturn = hasTrailingReturn(); |
4104 | EPI.ExceptionSpec = getExceptionSpecInfo(); |
4105 | EPI.TypeQuals = getMethodQuals(); |
4106 | EPI.RefQualifier = getRefQualifier(); |
4107 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
4108 | return EPI; |
4109 | } |
4110 | |
4111 | /// Get the kind of exception specification on this function. |
4112 | ExceptionSpecificationType getExceptionSpecType() const { |
4113 | return static_cast<ExceptionSpecificationType>( |
4114 | FunctionTypeBits.ExceptionSpecType); |
4115 | } |
4116 | |
4117 | /// Return whether this function has any kind of exception spec. |
4118 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
4119 | |
4120 | /// Return whether this function has a dynamic (throw) exception spec. |
4121 | bool hasDynamicExceptionSpec() const { |
4122 | return isDynamicExceptionSpec(getExceptionSpecType()); |
4123 | } |
4124 | |
4125 | /// Return whether this function has a noexcept exception spec. |
4126 | bool hasNoexceptExceptionSpec() const { |
4127 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
4128 | } |
4129 | |
4130 | /// Return whether this function has a dependent exception spec. |
4131 | bool hasDependentExceptionSpec() const; |
4132 | |
4133 | /// Return whether this function has an instantiation-dependent exception |
4134 | /// spec. |
4135 | bool hasInstantiationDependentExceptionSpec() const; |
4136 | |
4137 | /// Return all the available information about this type's exception spec. |
4138 | ExceptionSpecInfo getExceptionSpecInfo() const { |
4139 | ExceptionSpecInfo Result; |
4140 | Result.Type = getExceptionSpecType(); |
4141 | if (Result.Type == EST_Dynamic) { |
4142 | Result.Exceptions = exceptions(); |
4143 | } else if (isComputedNoexcept(Result.Type)) { |
4144 | Result.NoexceptExpr = getNoexceptExpr(); |
4145 | } else if (Result.Type == EST_Uninstantiated) { |
4146 | Result.SourceDecl = getExceptionSpecDecl(); |
4147 | Result.SourceTemplate = getExceptionSpecTemplate(); |
4148 | } else if (Result.Type == EST_Unevaluated) { |
4149 | Result.SourceDecl = getExceptionSpecDecl(); |
4150 | } |
4151 | return Result; |
4152 | } |
4153 | |
4154 | /// Return the number of types in the exception specification. |
4155 | unsigned getNumExceptions() const { |
4156 | return getExceptionSpecType() == EST_Dynamic |
4157 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
4158 | ->NumExceptionType |
4159 | : 0; |
4160 | } |
4161 | |
4162 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
4163 | QualType getExceptionType(unsigned i) const { |
4164 | assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 4164, __PRETTY_FUNCTION__)); |
4165 | return exception_begin()[i]; |
4166 | } |
4167 | |
4168 | /// Return the expression inside noexcept(expression), or a null pointer |
4169 | /// if there is none (because the exception spec is not of this form). |
4170 | Expr *getNoexceptExpr() const { |
4171 | if (!isComputedNoexcept(getExceptionSpecType())) |
4172 | return nullptr; |
4173 | return *getTrailingObjects<Expr *>(); |
4174 | } |
4175 | |
4176 | /// If this function type has an exception specification which hasn't |
4177 | /// been determined yet (either because it has not been evaluated or because |
4178 | /// it has not been instantiated), this is the function whose exception |
4179 | /// specification is represented by this type. |
4180 | FunctionDecl *getExceptionSpecDecl() const { |
4181 | if (getExceptionSpecType() != EST_Uninstantiated && |
4182 | getExceptionSpecType() != EST_Unevaluated) |
4183 | return nullptr; |
4184 | return getTrailingObjects<FunctionDecl *>()[0]; |
4185 | } |
4186 | |
4187 | /// If this function type has an uninstantiated exception |
4188 | /// specification, this is the function whose exception specification |
4189 | /// should be instantiated to find the exception specification for |
4190 | /// this type. |
4191 | FunctionDecl *getExceptionSpecTemplate() const { |
4192 | if (getExceptionSpecType() != EST_Uninstantiated) |
4193 | return nullptr; |
4194 | return getTrailingObjects<FunctionDecl *>()[1]; |
4195 | } |
4196 | |
4197 | /// Determine whether this function type has a non-throwing exception |
4198 | /// specification. |
4199 | CanThrowResult canThrow() const; |
4200 | |
4201 | /// Determine whether this function type has a non-throwing exception |
4202 | /// specification. If this depends on template arguments, returns |
4203 | /// \c ResultIfDependent. |
4204 | bool isNothrow(bool ResultIfDependent = false) const { |
4205 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4206 | } |
4207 | |
4208 | /// Whether this function prototype is variadic. |
4209 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4210 | |
4211 | SourceLocation getEllipsisLoc() const { |
4212 | return isVariadic() ? *getTrailingObjects<SourceLocation>() |
4213 | : SourceLocation(); |
4214 | } |
4215 | |
4216 | /// Determines whether this function prototype contains a |
4217 | /// parameter pack at the end. |
4218 | /// |
4219 | /// A function template whose last parameter is a parameter pack can be |
4220 | /// called with an arbitrary number of arguments, much like a variadic |
4221 | /// function. |
4222 | bool isTemplateVariadic() const; |
4223 | |
4224 | /// Whether this function prototype has a trailing return type. |
4225 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4226 | |
4227 | Qualifiers getMethodQuals() const { |
4228 | if (hasExtQualifiers()) |
4229 | return *getTrailingObjects<Qualifiers>(); |
4230 | else |
4231 | return getFastTypeQuals(); |
4232 | } |
4233 | |
4234 | /// Retrieve the ref-qualifier associated with this function type. |
4235 | RefQualifierKind getRefQualifier() const { |
4236 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4237 | } |
4238 | |
4239 | using param_type_iterator = const QualType *; |
4240 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4241 | |
4242 | param_type_range param_types() const { |
4243 | return param_type_range(param_type_begin(), param_type_end()); |
4244 | } |
4245 | |
4246 | param_type_iterator param_type_begin() const { |
4247 | return getTrailingObjects<QualType>(); |
4248 | } |
4249 | |
4250 | param_type_iterator param_type_end() const { |
4251 | return param_type_begin() + getNumParams(); |
4252 | } |
4253 | |
4254 | using exception_iterator = const QualType *; |
4255 | |
4256 | ArrayRef<QualType> exceptions() const { |
4257 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4258 | } |
4259 | |
4260 | exception_iterator exception_begin() const { |
4261 | return reinterpret_cast<exception_iterator>( |
4262 | getTrailingObjects<ExceptionType>()); |
4263 | } |
4264 | |
4265 | exception_iterator exception_end() const { |
4266 | return exception_begin() + getNumExceptions(); |
4267 | } |
4268 | |
4269 | /// Is there any interesting extra information for any of the parameters |
4270 | /// of this function type? |
4271 | bool hasExtParameterInfos() const { |
4272 | return FunctionTypeBits.HasExtParameterInfos; |
4273 | } |
4274 | |
4275 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4276 | assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 4276, __PRETTY_FUNCTION__)); |
4277 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4278 | getNumParams()); |
4279 | } |
4280 | |
4281 | /// Return a pointer to the beginning of the array of extra parameter |
4282 | /// information, if present, or else null if none of the parameters |
4283 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4284 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4285 | if (!hasExtParameterInfos()) |
4286 | return nullptr; |
4287 | return getTrailingObjects<ExtParameterInfo>(); |
4288 | } |
4289 | |
4290 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4291 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 4291, __PRETTY_FUNCTION__)); |
4292 | if (hasExtParameterInfos()) |
4293 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4294 | return ExtParameterInfo(); |
4295 | } |
4296 | |
4297 | ParameterABI getParameterABI(unsigned I) const { |
4298 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 4298, __PRETTY_FUNCTION__)); |
4299 | if (hasExtParameterInfos()) |
4300 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4301 | return ParameterABI::Ordinary; |
4302 | } |
4303 | |
4304 | bool isParamConsumed(unsigned I) const { |
4305 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include/clang/AST/Type.h" , 4305, __PRETTY_FUNCTION__)); |
4306 | if (hasExtParameterInfos()) |
4307 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4308 | return false; |
4309 | } |
4310 | |
4311 | bool isSugared() const { return false; } |
4312 | QualType desugar() const { return QualType(this, 0); } |
4313 | |
4314 | void printExceptionSpecification(raw_ostream &OS, |
4315 | const PrintingPolicy &Policy) const; |