File: | clang/lib/AST/ExprConstant.cpp |
Warning: | line 3265, column 10 Access to field 'Callee' results in a dereference of a null pointer (loaded from field 'CurrentCall') |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// | ||||
2 | // | ||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
6 | // | ||||
7 | //===----------------------------------------------------------------------===// | ||||
8 | // | ||||
9 | // This file implements the Expr constant evaluator. | ||||
10 | // | ||||
11 | // Constant expression evaluation produces four main results: | ||||
12 | // | ||||
13 | // * A success/failure flag indicating whether constant folding was successful. | ||||
14 | // This is the 'bool' return value used by most of the code in this file. A | ||||
15 | // 'false' return value indicates that constant folding has failed, and any | ||||
16 | // appropriate diagnostic has already been produced. | ||||
17 | // | ||||
18 | // * An evaluated result, valid only if constant folding has not failed. | ||||
19 | // | ||||
20 | // * A flag indicating if evaluation encountered (unevaluated) side-effects. | ||||
21 | // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), | ||||
22 | // where it is possible to determine the evaluated result regardless. | ||||
23 | // | ||||
24 | // * A set of notes indicating why the evaluation was not a constant expression | ||||
25 | // (under the C++11 / C++1y rules only, at the moment), or, if folding failed | ||||
26 | // too, why the expression could not be folded. | ||||
27 | // | ||||
28 | // If we are checking for a potential constant expression, failure to constant | ||||
29 | // fold a potential constant sub-expression will be indicated by a 'false' | ||||
30 | // return value (the expression could not be folded) and no diagnostic (the | ||||
31 | // expression is not necessarily non-constant). | ||||
32 | // | ||||
33 | //===----------------------------------------------------------------------===// | ||||
34 | |||||
35 | #include "Interp/Context.h" | ||||
36 | #include "Interp/Frame.h" | ||||
37 | #include "Interp/State.h" | ||||
38 | #include "clang/AST/APValue.h" | ||||
39 | #include "clang/AST/ASTContext.h" | ||||
40 | #include "clang/AST/ASTDiagnostic.h" | ||||
41 | #include "clang/AST/ASTLambda.h" | ||||
42 | #include "clang/AST/Attr.h" | ||||
43 | #include "clang/AST/CXXInheritance.h" | ||||
44 | #include "clang/AST/CharUnits.h" | ||||
45 | #include "clang/AST/CurrentSourceLocExprScope.h" | ||||
46 | #include "clang/AST/Expr.h" | ||||
47 | #include "clang/AST/OSLog.h" | ||||
48 | #include "clang/AST/OptionalDiagnostic.h" | ||||
49 | #include "clang/AST/RecordLayout.h" | ||||
50 | #include "clang/AST/StmtVisitor.h" | ||||
51 | #include "clang/AST/TypeLoc.h" | ||||
52 | #include "clang/Basic/Builtins.h" | ||||
53 | #include "clang/Basic/TargetInfo.h" | ||||
54 | #include "llvm/ADT/APFixedPoint.h" | ||||
55 | #include "llvm/ADT/Optional.h" | ||||
56 | #include "llvm/ADT/SmallBitVector.h" | ||||
57 | #include "llvm/Support/Debug.h" | ||||
58 | #include "llvm/Support/SaveAndRestore.h" | ||||
59 | #include "llvm/Support/raw_ostream.h" | ||||
60 | #include <cstring> | ||||
61 | #include <functional> | ||||
62 | |||||
63 | #define DEBUG_TYPE"exprconstant" "exprconstant" | ||||
64 | |||||
65 | using namespace clang; | ||||
66 | using llvm::APFixedPoint; | ||||
67 | using llvm::APInt; | ||||
68 | using llvm::APSInt; | ||||
69 | using llvm::APFloat; | ||||
70 | using llvm::FixedPointSemantics; | ||||
71 | using llvm::Optional; | ||||
72 | |||||
73 | namespace { | ||||
74 | struct LValue; | ||||
75 | class CallStackFrame; | ||||
76 | class EvalInfo; | ||||
77 | |||||
78 | using SourceLocExprScopeGuard = | ||||
79 | CurrentSourceLocExprScope::SourceLocExprScopeGuard; | ||||
80 | |||||
81 | static QualType getType(APValue::LValueBase B) { | ||||
82 | return B.getType(); | ||||
83 | } | ||||
84 | |||||
85 | /// Get an LValue path entry, which is known to not be an array index, as a | ||||
86 | /// field declaration. | ||||
87 | static const FieldDecl *getAsField(APValue::LValuePathEntry E) { | ||||
88 | return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); | ||||
89 | } | ||||
90 | /// Get an LValue path entry, which is known to not be an array index, as a | ||||
91 | /// base class declaration. | ||||
92 | static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { | ||||
93 | return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); | ||||
94 | } | ||||
95 | /// Determine whether this LValue path entry for a base class names a virtual | ||||
96 | /// base class. | ||||
97 | static bool isVirtualBaseClass(APValue::LValuePathEntry E) { | ||||
98 | return E.getAsBaseOrMember().getInt(); | ||||
99 | } | ||||
100 | |||||
101 | /// Given an expression, determine the type used to store the result of | ||||
102 | /// evaluating that expression. | ||||
103 | static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { | ||||
104 | if (E->isPRValue()) | ||||
105 | return E->getType(); | ||||
106 | return Ctx.getLValueReferenceType(E->getType()); | ||||
107 | } | ||||
108 | |||||
109 | /// Given a CallExpr, try to get the alloc_size attribute. May return null. | ||||
110 | static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { | ||||
111 | if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) | ||||
112 | return DirectCallee->getAttr<AllocSizeAttr>(); | ||||
113 | if (const Decl *IndirectCallee = CE->getCalleeDecl()) | ||||
114 | return IndirectCallee->getAttr<AllocSizeAttr>(); | ||||
115 | return nullptr; | ||||
116 | } | ||||
117 | |||||
118 | /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. | ||||
119 | /// This will look through a single cast. | ||||
120 | /// | ||||
121 | /// Returns null if we couldn't unwrap a function with alloc_size. | ||||
122 | static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { | ||||
123 | if (!E->getType()->isPointerType()) | ||||
124 | return nullptr; | ||||
125 | |||||
126 | E = E->IgnoreParens(); | ||||
127 | // If we're doing a variable assignment from e.g. malloc(N), there will | ||||
128 | // probably be a cast of some kind. In exotic cases, we might also see a | ||||
129 | // top-level ExprWithCleanups. Ignore them either way. | ||||
130 | if (const auto *FE = dyn_cast<FullExpr>(E)) | ||||
131 | E = FE->getSubExpr()->IgnoreParens(); | ||||
132 | |||||
133 | if (const auto *Cast = dyn_cast<CastExpr>(E)) | ||||
134 | E = Cast->getSubExpr()->IgnoreParens(); | ||||
135 | |||||
136 | if (const auto *CE = dyn_cast<CallExpr>(E)) | ||||
137 | return getAllocSizeAttr(CE) ? CE : nullptr; | ||||
138 | return nullptr; | ||||
139 | } | ||||
140 | |||||
141 | /// Determines whether or not the given Base contains a call to a function | ||||
142 | /// with the alloc_size attribute. | ||||
143 | static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { | ||||
144 | const auto *E = Base.dyn_cast<const Expr *>(); | ||||
145 | return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); | ||||
146 | } | ||||
147 | |||||
148 | /// Determines whether the given kind of constant expression is only ever | ||||
149 | /// used for name mangling. If so, it's permitted to reference things that we | ||||
150 | /// can't generate code for (in particular, dllimported functions). | ||||
151 | static bool isForManglingOnly(ConstantExprKind Kind) { | ||||
152 | switch (Kind) { | ||||
153 | case ConstantExprKind::Normal: | ||||
154 | case ConstantExprKind::ClassTemplateArgument: | ||||
155 | case ConstantExprKind::ImmediateInvocation: | ||||
156 | // Note that non-type template arguments of class type are emitted as | ||||
157 | // template parameter objects. | ||||
158 | return false; | ||||
159 | |||||
160 | case ConstantExprKind::NonClassTemplateArgument: | ||||
161 | return true; | ||||
162 | } | ||||
163 | llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 163); | ||||
164 | } | ||||
165 | |||||
166 | static bool isTemplateArgument(ConstantExprKind Kind) { | ||||
167 | switch (Kind) { | ||||
168 | case ConstantExprKind::Normal: | ||||
169 | case ConstantExprKind::ImmediateInvocation: | ||||
170 | return false; | ||||
171 | |||||
172 | case ConstantExprKind::ClassTemplateArgument: | ||||
173 | case ConstantExprKind::NonClassTemplateArgument: | ||||
174 | return true; | ||||
175 | } | ||||
176 | llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 176); | ||||
177 | } | ||||
178 | |||||
179 | /// The bound to claim that an array of unknown bound has. | ||||
180 | /// The value in MostDerivedArraySize is undefined in this case. So, set it | ||||
181 | /// to an arbitrary value that's likely to loudly break things if it's used. | ||||
182 | static const uint64_t AssumedSizeForUnsizedArray = | ||||
183 | std::numeric_limits<uint64_t>::max() / 2; | ||||
184 | |||||
185 | /// Determines if an LValue with the given LValueBase will have an unsized | ||||
186 | /// array in its designator. | ||||
187 | /// Find the path length and type of the most-derived subobject in the given | ||||
188 | /// path, and find the size of the containing array, if any. | ||||
189 | static unsigned | ||||
190 | findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, | ||||
191 | ArrayRef<APValue::LValuePathEntry> Path, | ||||
192 | uint64_t &ArraySize, QualType &Type, bool &IsArray, | ||||
193 | bool &FirstEntryIsUnsizedArray) { | ||||
194 | // This only accepts LValueBases from APValues, and APValues don't support | ||||
195 | // arrays that lack size info. | ||||
196 | assert(!isBaseAnAllocSizeCall(Base) &&(static_cast <bool> (!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here") ? void (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 197, __extension__ __PRETTY_FUNCTION__)) | ||||
197 | "Unsized arrays shouldn't appear here")(static_cast <bool> (!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here") ? void (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 197, __extension__ __PRETTY_FUNCTION__)); | ||||
198 | unsigned MostDerivedLength = 0; | ||||
199 | Type = getType(Base); | ||||
200 | |||||
201 | for (unsigned I = 0, N = Path.size(); I != N; ++I) { | ||||
202 | if (Type->isArrayType()) { | ||||
203 | const ArrayType *AT = Ctx.getAsArrayType(Type); | ||||
204 | Type = AT->getElementType(); | ||||
205 | MostDerivedLength = I + 1; | ||||
206 | IsArray = true; | ||||
207 | |||||
208 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { | ||||
209 | ArraySize = CAT->getSize().getZExtValue(); | ||||
210 | } else { | ||||
211 | assert(I == 0 && "unexpected unsized array designator")(static_cast <bool> (I == 0 && "unexpected unsized array designator" ) ? void (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 211, __extension__ __PRETTY_FUNCTION__)); | ||||
212 | FirstEntryIsUnsizedArray = true; | ||||
213 | ArraySize = AssumedSizeForUnsizedArray; | ||||
214 | } | ||||
215 | } else if (Type->isAnyComplexType()) { | ||||
216 | const ComplexType *CT = Type->castAs<ComplexType>(); | ||||
217 | Type = CT->getElementType(); | ||||
218 | ArraySize = 2; | ||||
219 | MostDerivedLength = I + 1; | ||||
220 | IsArray = true; | ||||
221 | } else if (const FieldDecl *FD = getAsField(Path[I])) { | ||||
222 | Type = FD->getType(); | ||||
223 | ArraySize = 0; | ||||
224 | MostDerivedLength = I + 1; | ||||
225 | IsArray = false; | ||||
226 | } else { | ||||
227 | // Path[I] describes a base class. | ||||
228 | ArraySize = 0; | ||||
229 | IsArray = false; | ||||
230 | } | ||||
231 | } | ||||
232 | return MostDerivedLength; | ||||
233 | } | ||||
234 | |||||
235 | /// A path from a glvalue to a subobject of that glvalue. | ||||
236 | struct SubobjectDesignator { | ||||
237 | /// True if the subobject was named in a manner not supported by C++11. Such | ||||
238 | /// lvalues can still be folded, but they are not core constant expressions | ||||
239 | /// and we cannot perform lvalue-to-rvalue conversions on them. | ||||
240 | unsigned Invalid : 1; | ||||
241 | |||||
242 | /// Is this a pointer one past the end of an object? | ||||
243 | unsigned IsOnePastTheEnd : 1; | ||||
244 | |||||
245 | /// Indicator of whether the first entry is an unsized array. | ||||
246 | unsigned FirstEntryIsAnUnsizedArray : 1; | ||||
247 | |||||
248 | /// Indicator of whether the most-derived object is an array element. | ||||
249 | unsigned MostDerivedIsArrayElement : 1; | ||||
250 | |||||
251 | /// The length of the path to the most-derived object of which this is a | ||||
252 | /// subobject. | ||||
253 | unsigned MostDerivedPathLength : 28; | ||||
254 | |||||
255 | /// The size of the array of which the most-derived object is an element. | ||||
256 | /// This will always be 0 if the most-derived object is not an array | ||||
257 | /// element. 0 is not an indicator of whether or not the most-derived object | ||||
258 | /// is an array, however, because 0-length arrays are allowed. | ||||
259 | /// | ||||
260 | /// If the current array is an unsized array, the value of this is | ||||
261 | /// undefined. | ||||
262 | uint64_t MostDerivedArraySize; | ||||
263 | |||||
264 | /// The type of the most derived object referred to by this address. | ||||
265 | QualType MostDerivedType; | ||||
266 | |||||
267 | typedef APValue::LValuePathEntry PathEntry; | ||||
268 | |||||
269 | /// The entries on the path from the glvalue to the designated subobject. | ||||
270 | SmallVector<PathEntry, 8> Entries; | ||||
271 | |||||
272 | SubobjectDesignator() : Invalid(true) {} | ||||
273 | |||||
274 | explicit SubobjectDesignator(QualType T) | ||||
275 | : Invalid(false), IsOnePastTheEnd(false), | ||||
276 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), | ||||
277 | MostDerivedPathLength(0), MostDerivedArraySize(0), | ||||
278 | MostDerivedType(T) {} | ||||
279 | |||||
280 | SubobjectDesignator(ASTContext &Ctx, const APValue &V) | ||||
281 | : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), | ||||
282 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), | ||||
283 | MostDerivedPathLength(0), MostDerivedArraySize(0) { | ||||
284 | assert(V.isLValue() && "Non-LValue used to make an LValue designator?")(static_cast <bool> (V.isLValue() && "Non-LValue used to make an LValue designator?" ) ? void (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 284, __extension__ __PRETTY_FUNCTION__)); | ||||
285 | if (!Invalid) { | ||||
286 | IsOnePastTheEnd = V.isLValueOnePastTheEnd(); | ||||
287 | ArrayRef<PathEntry> VEntries = V.getLValuePath(); | ||||
288 | Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); | ||||
289 | if (V.getLValueBase()) { | ||||
290 | bool IsArray = false; | ||||
291 | bool FirstIsUnsizedArray = false; | ||||
292 | MostDerivedPathLength = findMostDerivedSubobject( | ||||
293 | Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, | ||||
294 | MostDerivedType, IsArray, FirstIsUnsizedArray); | ||||
295 | MostDerivedIsArrayElement = IsArray; | ||||
296 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; | ||||
297 | } | ||||
298 | } | ||||
299 | } | ||||
300 | |||||
301 | void truncate(ASTContext &Ctx, APValue::LValueBase Base, | ||||
302 | unsigned NewLength) { | ||||
303 | if (Invalid) | ||||
304 | return; | ||||
305 | |||||
306 | assert(Base && "cannot truncate path for null pointer")(static_cast <bool> (Base && "cannot truncate path for null pointer" ) ? void (0) : __assert_fail ("Base && \"cannot truncate path for null pointer\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 306, __extension__ __PRETTY_FUNCTION__)); | ||||
307 | assert(NewLength <= Entries.size() && "not a truncation")(static_cast <bool> (NewLength <= Entries.size() && "not a truncation") ? void (0) : __assert_fail ("NewLength <= Entries.size() && \"not a truncation\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 307, __extension__ __PRETTY_FUNCTION__)); | ||||
308 | |||||
309 | if (NewLength == Entries.size()) | ||||
310 | return; | ||||
311 | Entries.resize(NewLength); | ||||
312 | |||||
313 | bool IsArray = false; | ||||
314 | bool FirstIsUnsizedArray = false; | ||||
315 | MostDerivedPathLength = findMostDerivedSubobject( | ||||
316 | Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, | ||||
317 | FirstIsUnsizedArray); | ||||
318 | MostDerivedIsArrayElement = IsArray; | ||||
319 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; | ||||
320 | } | ||||
321 | |||||
322 | void setInvalid() { | ||||
323 | Invalid = true; | ||||
324 | Entries.clear(); | ||||
325 | } | ||||
326 | |||||
327 | /// Determine whether the most derived subobject is an array without a | ||||
328 | /// known bound. | ||||
329 | bool isMostDerivedAnUnsizedArray() const { | ||||
330 | assert(!Invalid && "Calling this makes no sense on invalid designators")(static_cast <bool> (!Invalid && "Calling this makes no sense on invalid designators" ) ? void (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 330, __extension__ __PRETTY_FUNCTION__)); | ||||
331 | return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; | ||||
332 | } | ||||
333 | |||||
334 | /// Determine what the most derived array's size is. Results in an assertion | ||||
335 | /// failure if the most derived array lacks a size. | ||||
336 | uint64_t getMostDerivedArraySize() const { | ||||
337 | assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")(static_cast <bool> (!isMostDerivedAnUnsizedArray() && "Unsized array has no size") ? void (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 337, __extension__ __PRETTY_FUNCTION__)); | ||||
338 | return MostDerivedArraySize; | ||||
339 | } | ||||
340 | |||||
341 | /// Determine whether this is a one-past-the-end pointer. | ||||
342 | bool isOnePastTheEnd() const { | ||||
343 | assert(!Invalid)(static_cast <bool> (!Invalid) ? void (0) : __assert_fail ("!Invalid", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 343, __extension__ __PRETTY_FUNCTION__)); | ||||
344 | if (IsOnePastTheEnd) | ||||
345 | return true; | ||||
346 | if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && | ||||
347 | Entries[MostDerivedPathLength - 1].getAsArrayIndex() == | ||||
348 | MostDerivedArraySize) | ||||
349 | return true; | ||||
350 | return false; | ||||
351 | } | ||||
352 | |||||
353 | /// Get the range of valid index adjustments in the form | ||||
354 | /// {maximum value that can be subtracted from this pointer, | ||||
355 | /// maximum value that can be added to this pointer} | ||||
356 | std::pair<uint64_t, uint64_t> validIndexAdjustments() { | ||||
357 | if (Invalid || isMostDerivedAnUnsizedArray()) | ||||
358 | return {0, 0}; | ||||
359 | |||||
360 | // [expr.add]p4: For the purposes of these operators, a pointer to a | ||||
361 | // nonarray object behaves the same as a pointer to the first element of | ||||
362 | // an array of length one with the type of the object as its element type. | ||||
363 | bool IsArray = MostDerivedPathLength == Entries.size() && | ||||
364 | MostDerivedIsArrayElement; | ||||
365 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() | ||||
366 | : (uint64_t)IsOnePastTheEnd; | ||||
367 | uint64_t ArraySize = | ||||
368 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; | ||||
369 | return {ArrayIndex, ArraySize - ArrayIndex}; | ||||
370 | } | ||||
371 | |||||
372 | /// Check that this refers to a valid subobject. | ||||
373 | bool isValidSubobject() const { | ||||
374 | if (Invalid) | ||||
375 | return false; | ||||
376 | return !isOnePastTheEnd(); | ||||
377 | } | ||||
378 | /// Check that this refers to a valid subobject, and if not, produce a | ||||
379 | /// relevant diagnostic and set the designator as invalid. | ||||
380 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); | ||||
381 | |||||
382 | /// Get the type of the designated object. | ||||
383 | QualType getType(ASTContext &Ctx) const { | ||||
384 | assert(!Invalid && "invalid designator has no subobject type")(static_cast <bool> (!Invalid && "invalid designator has no subobject type" ) ? void (0) : __assert_fail ("!Invalid && \"invalid designator has no subobject type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 384, __extension__ __PRETTY_FUNCTION__)); | ||||
385 | return MostDerivedPathLength == Entries.size() | ||||
386 | ? MostDerivedType | ||||
387 | : Ctx.getRecordType(getAsBaseClass(Entries.back())); | ||||
388 | } | ||||
389 | |||||
390 | /// Update this designator to refer to the first element within this array. | ||||
391 | void addArrayUnchecked(const ConstantArrayType *CAT) { | ||||
392 | Entries.push_back(PathEntry::ArrayIndex(0)); | ||||
393 | |||||
394 | // This is a most-derived object. | ||||
395 | MostDerivedType = CAT->getElementType(); | ||||
396 | MostDerivedIsArrayElement = true; | ||||
397 | MostDerivedArraySize = CAT->getSize().getZExtValue(); | ||||
398 | MostDerivedPathLength = Entries.size(); | ||||
399 | } | ||||
400 | /// Update this designator to refer to the first element within the array of | ||||
401 | /// elements of type T. This is an array of unknown size. | ||||
402 | void addUnsizedArrayUnchecked(QualType ElemTy) { | ||||
403 | Entries.push_back(PathEntry::ArrayIndex(0)); | ||||
404 | |||||
405 | MostDerivedType = ElemTy; | ||||
406 | MostDerivedIsArrayElement = true; | ||||
407 | // The value in MostDerivedArraySize is undefined in this case. So, set it | ||||
408 | // to an arbitrary value that's likely to loudly break things if it's | ||||
409 | // used. | ||||
410 | MostDerivedArraySize = AssumedSizeForUnsizedArray; | ||||
411 | MostDerivedPathLength = Entries.size(); | ||||
412 | } | ||||
413 | /// Update this designator to refer to the given base or member of this | ||||
414 | /// object. | ||||
415 | void addDeclUnchecked(const Decl *D, bool Virtual = false) { | ||||
416 | Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); | ||||
417 | |||||
418 | // If this isn't a base class, it's a new most-derived object. | ||||
419 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { | ||||
420 | MostDerivedType = FD->getType(); | ||||
421 | MostDerivedIsArrayElement = false; | ||||
422 | MostDerivedArraySize = 0; | ||||
423 | MostDerivedPathLength = Entries.size(); | ||||
424 | } | ||||
425 | } | ||||
426 | /// Update this designator to refer to the given complex component. | ||||
427 | void addComplexUnchecked(QualType EltTy, bool Imag) { | ||||
428 | Entries.push_back(PathEntry::ArrayIndex(Imag)); | ||||
429 | |||||
430 | // This is technically a most-derived object, though in practice this | ||||
431 | // is unlikely to matter. | ||||
432 | MostDerivedType = EltTy; | ||||
433 | MostDerivedIsArrayElement = true; | ||||
434 | MostDerivedArraySize = 2; | ||||
435 | MostDerivedPathLength = Entries.size(); | ||||
436 | } | ||||
437 | void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); | ||||
438 | void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, | ||||
439 | const APSInt &N); | ||||
440 | /// Add N to the address of this subobject. | ||||
441 | void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { | ||||
442 | if (Invalid || !N) return; | ||||
443 | uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); | ||||
444 | if (isMostDerivedAnUnsizedArray()) { | ||||
445 | diagnoseUnsizedArrayPointerArithmetic(Info, E); | ||||
446 | // Can't verify -- trust that the user is doing the right thing (or if | ||||
447 | // not, trust that the caller will catch the bad behavior). | ||||
448 | // FIXME: Should we reject if this overflows, at least? | ||||
449 | Entries.back() = PathEntry::ArrayIndex( | ||||
450 | Entries.back().getAsArrayIndex() + TruncatedN); | ||||
451 | return; | ||||
452 | } | ||||
453 | |||||
454 | // [expr.add]p4: For the purposes of these operators, a pointer to a | ||||
455 | // nonarray object behaves the same as a pointer to the first element of | ||||
456 | // an array of length one with the type of the object as its element type. | ||||
457 | bool IsArray = MostDerivedPathLength == Entries.size() && | ||||
458 | MostDerivedIsArrayElement; | ||||
459 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() | ||||
460 | : (uint64_t)IsOnePastTheEnd; | ||||
461 | uint64_t ArraySize = | ||||
462 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; | ||||
463 | |||||
464 | if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { | ||||
465 | // Calculate the actual index in a wide enough type, so we can include | ||||
466 | // it in the note. | ||||
467 | N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); | ||||
468 | (llvm::APInt&)N += ArrayIndex; | ||||
469 | assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")(static_cast <bool> (N.ugt(ArraySize) && "bounds check failed for in-bounds index" ) ? void (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 469, __extension__ __PRETTY_FUNCTION__)); | ||||
470 | diagnosePointerArithmetic(Info, E, N); | ||||
471 | setInvalid(); | ||||
472 | return; | ||||
473 | } | ||||
474 | |||||
475 | ArrayIndex += TruncatedN; | ||||
476 | assert(ArrayIndex <= ArraySize &&(static_cast <bool> (ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index") ? void (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 477, __extension__ __PRETTY_FUNCTION__)) | ||||
477 | "bounds check succeeded for out-of-bounds index")(static_cast <bool> (ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index") ? void (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 477, __extension__ __PRETTY_FUNCTION__)); | ||||
478 | |||||
479 | if (IsArray) | ||||
480 | Entries.back() = PathEntry::ArrayIndex(ArrayIndex); | ||||
481 | else | ||||
482 | IsOnePastTheEnd = (ArrayIndex != 0); | ||||
483 | } | ||||
484 | }; | ||||
485 | |||||
486 | /// A scope at the end of which an object can need to be destroyed. | ||||
487 | enum class ScopeKind { | ||||
488 | Block, | ||||
489 | FullExpression, | ||||
490 | Call | ||||
491 | }; | ||||
492 | |||||
493 | /// A reference to a particular call and its arguments. | ||||
494 | struct CallRef { | ||||
495 | CallRef() : OrigCallee(), CallIndex(0), Version() {} | ||||
496 | CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) | ||||
497 | : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} | ||||
498 | |||||
499 | explicit operator bool() const { return OrigCallee; } | ||||
500 | |||||
501 | /// Get the parameter that the caller initialized, corresponding to the | ||||
502 | /// given parameter in the callee. | ||||
503 | const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { | ||||
504 | return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) | ||||
505 | : PVD; | ||||
506 | } | ||||
507 | |||||
508 | /// The callee at the point where the arguments were evaluated. This might | ||||
509 | /// be different from the actual callee (a different redeclaration, or a | ||||
510 | /// virtual override), but this function's parameters are the ones that | ||||
511 | /// appear in the parameter map. | ||||
512 | const FunctionDecl *OrigCallee; | ||||
513 | /// The call index of the frame that holds the argument values. | ||||
514 | unsigned CallIndex; | ||||
515 | /// The version of the parameters corresponding to this call. | ||||
516 | unsigned Version; | ||||
517 | }; | ||||
518 | |||||
519 | /// A stack frame in the constexpr call stack. | ||||
520 | class CallStackFrame : public interp::Frame { | ||||
521 | public: | ||||
522 | EvalInfo &Info; | ||||
523 | |||||
524 | /// Parent - The caller of this stack frame. | ||||
525 | CallStackFrame *Caller; | ||||
526 | |||||
527 | /// Callee - The function which was called. | ||||
528 | const FunctionDecl *Callee; | ||||
529 | |||||
530 | /// This - The binding for the this pointer in this call, if any. | ||||
531 | const LValue *This; | ||||
532 | |||||
533 | /// Information on how to find the arguments to this call. Our arguments | ||||
534 | /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a | ||||
535 | /// key and this value as the version. | ||||
536 | CallRef Arguments; | ||||
537 | |||||
538 | /// Source location information about the default argument or default | ||||
539 | /// initializer expression we're evaluating, if any. | ||||
540 | CurrentSourceLocExprScope CurSourceLocExprScope; | ||||
541 | |||||
542 | // Note that we intentionally use std::map here so that references to | ||||
543 | // values are stable. | ||||
544 | typedef std::pair<const void *, unsigned> MapKeyTy; | ||||
545 | typedef std::map<MapKeyTy, APValue> MapTy; | ||||
546 | /// Temporaries - Temporary lvalues materialized within this stack frame. | ||||
547 | MapTy Temporaries; | ||||
548 | |||||
549 | /// CallLoc - The location of the call expression for this call. | ||||
550 | SourceLocation CallLoc; | ||||
551 | |||||
552 | /// Index - The call index of this call. | ||||
553 | unsigned Index; | ||||
554 | |||||
555 | /// The stack of integers for tracking version numbers for temporaries. | ||||
556 | SmallVector<unsigned, 2> TempVersionStack = {1}; | ||||
557 | unsigned CurTempVersion = TempVersionStack.back(); | ||||
558 | |||||
559 | unsigned getTempVersion() const { return TempVersionStack.back(); } | ||||
560 | |||||
561 | void pushTempVersion() { | ||||
562 | TempVersionStack.push_back(++CurTempVersion); | ||||
563 | } | ||||
564 | |||||
565 | void popTempVersion() { | ||||
566 | TempVersionStack.pop_back(); | ||||
567 | } | ||||
568 | |||||
569 | CallRef createCall(const FunctionDecl *Callee) { | ||||
570 | return {Callee, Index, ++CurTempVersion}; | ||||
571 | } | ||||
572 | |||||
573 | // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact | ||||
574 | // on the overall stack usage of deeply-recursing constexpr evaluations. | ||||
575 | // (We should cache this map rather than recomputing it repeatedly.) | ||||
576 | // But let's try this and see how it goes; we can look into caching the map | ||||
577 | // as a later change. | ||||
578 | |||||
579 | /// LambdaCaptureFields - Mapping from captured variables/this to | ||||
580 | /// corresponding data members in the closure class. | ||||
581 | llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; | ||||
582 | FieldDecl *LambdaThisCaptureField; | ||||
583 | |||||
584 | CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, | ||||
585 | const FunctionDecl *Callee, const LValue *This, | ||||
586 | CallRef Arguments); | ||||
587 | ~CallStackFrame(); | ||||
588 | |||||
589 | // Return the temporary for Key whose version number is Version. | ||||
590 | APValue *getTemporary(const void *Key, unsigned Version) { | ||||
591 | MapKeyTy KV(Key, Version); | ||||
592 | auto LB = Temporaries.lower_bound(KV); | ||||
593 | if (LB != Temporaries.end() && LB->first == KV) | ||||
594 | return &LB->second; | ||||
595 | // Pair (Key,Version) wasn't found in the map. Check that no elements | ||||
596 | // in the map have 'Key' as their key. | ||||
597 | assert((LB == Temporaries.end() || LB->first.first != Key) &&(static_cast <bool> ((LB == Temporaries.end() || LB-> first.first != Key) && (LB == Temporaries.begin() || std ::prev(LB)->first.first != Key) && "Element with key 'Key' found in map" ) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 599, __extension__ __PRETTY_FUNCTION__)) | ||||
598 | (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&(static_cast <bool> ((LB == Temporaries.end() || LB-> first.first != Key) && (LB == Temporaries.begin() || std ::prev(LB)->first.first != Key) && "Element with key 'Key' found in map" ) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 599, __extension__ __PRETTY_FUNCTION__)) | ||||
599 | "Element with key 'Key' found in map")(static_cast <bool> ((LB == Temporaries.end() || LB-> first.first != Key) && (LB == Temporaries.begin() || std ::prev(LB)->first.first != Key) && "Element with key 'Key' found in map" ) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 599, __extension__ __PRETTY_FUNCTION__)); | ||||
600 | return nullptr; | ||||
601 | } | ||||
602 | |||||
603 | // Return the current temporary for Key in the map. | ||||
604 | APValue *getCurrentTemporary(const void *Key) { | ||||
605 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); | ||||
606 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) | ||||
607 | return &std::prev(UB)->second; | ||||
608 | return nullptr; | ||||
609 | } | ||||
610 | |||||
611 | // Return the version number of the current temporary for Key. | ||||
612 | unsigned getCurrentTemporaryVersion(const void *Key) const { | ||||
613 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); | ||||
614 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) | ||||
615 | return std::prev(UB)->first.second; | ||||
616 | return 0; | ||||
617 | } | ||||
618 | |||||
619 | /// Allocate storage for an object of type T in this stack frame. | ||||
620 | /// Populates LV with a handle to the created object. Key identifies | ||||
621 | /// the temporary within the stack frame, and must not be reused without | ||||
622 | /// bumping the temporary version number. | ||||
623 | template<typename KeyT> | ||||
624 | APValue &createTemporary(const KeyT *Key, QualType T, | ||||
625 | ScopeKind Scope, LValue &LV); | ||||
626 | |||||
627 | /// Allocate storage for a parameter of a function call made in this frame. | ||||
628 | APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); | ||||
629 | |||||
630 | void describe(llvm::raw_ostream &OS) override; | ||||
631 | |||||
632 | Frame *getCaller() const override { return Caller; } | ||||
633 | SourceLocation getCallLocation() const override { return CallLoc; } | ||||
634 | const FunctionDecl *getCallee() const override { return Callee; } | ||||
635 | |||||
636 | bool isStdFunction() const { | ||||
637 | for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) | ||||
638 | if (DC->isStdNamespace()) | ||||
639 | return true; | ||||
640 | return false; | ||||
641 | } | ||||
642 | |||||
643 | private: | ||||
644 | APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, | ||||
645 | ScopeKind Scope); | ||||
646 | }; | ||||
647 | |||||
648 | /// Temporarily override 'this'. | ||||
649 | class ThisOverrideRAII { | ||||
650 | public: | ||||
651 | ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) | ||||
652 | : Frame(Frame), OldThis(Frame.This) { | ||||
653 | if (Enable) | ||||
654 | Frame.This = NewThis; | ||||
655 | } | ||||
656 | ~ThisOverrideRAII() { | ||||
657 | Frame.This = OldThis; | ||||
658 | } | ||||
659 | private: | ||||
660 | CallStackFrame &Frame; | ||||
661 | const LValue *OldThis; | ||||
662 | }; | ||||
663 | } | ||||
664 | |||||
665 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, | ||||
666 | const LValue &This, QualType ThisType); | ||||
667 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, | ||||
668 | APValue::LValueBase LVBase, APValue &Value, | ||||
669 | QualType T); | ||||
670 | |||||
671 | namespace { | ||||
672 | /// A cleanup, and a flag indicating whether it is lifetime-extended. | ||||
673 | class Cleanup { | ||||
674 | llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; | ||||
675 | APValue::LValueBase Base; | ||||
676 | QualType T; | ||||
677 | |||||
678 | public: | ||||
679 | Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, | ||||
680 | ScopeKind Scope) | ||||
681 | : Value(Val, Scope), Base(Base), T(T) {} | ||||
682 | |||||
683 | /// Determine whether this cleanup should be performed at the end of the | ||||
684 | /// given kind of scope. | ||||
685 | bool isDestroyedAtEndOf(ScopeKind K) const { | ||||
686 | return (int)Value.getInt() >= (int)K; | ||||
687 | } | ||||
688 | bool endLifetime(EvalInfo &Info, bool RunDestructors) { | ||||
689 | if (RunDestructors) { | ||||
690 | SourceLocation Loc; | ||||
691 | if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) | ||||
692 | Loc = VD->getLocation(); | ||||
693 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) | ||||
694 | Loc = E->getExprLoc(); | ||||
695 | return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); | ||||
696 | } | ||||
697 | *Value.getPointer() = APValue(); | ||||
698 | return true; | ||||
699 | } | ||||
700 | |||||
701 | bool hasSideEffect() { | ||||
702 | return T.isDestructedType(); | ||||
703 | } | ||||
704 | }; | ||||
705 | |||||
706 | /// A reference to an object whose construction we are currently evaluating. | ||||
707 | struct ObjectUnderConstruction { | ||||
708 | APValue::LValueBase Base; | ||||
709 | ArrayRef<APValue::LValuePathEntry> Path; | ||||
710 | friend bool operator==(const ObjectUnderConstruction &LHS, | ||||
711 | const ObjectUnderConstruction &RHS) { | ||||
712 | return LHS.Base == RHS.Base && LHS.Path == RHS.Path; | ||||
713 | } | ||||
714 | friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { | ||||
715 | return llvm::hash_combine(Obj.Base, Obj.Path); | ||||
716 | } | ||||
717 | }; | ||||
718 | enum class ConstructionPhase { | ||||
719 | None, | ||||
720 | Bases, | ||||
721 | AfterBases, | ||||
722 | AfterFields, | ||||
723 | Destroying, | ||||
724 | DestroyingBases | ||||
725 | }; | ||||
726 | } | ||||
727 | |||||
728 | namespace llvm { | ||||
729 | template<> struct DenseMapInfo<ObjectUnderConstruction> { | ||||
730 | using Base = DenseMapInfo<APValue::LValueBase>; | ||||
731 | static ObjectUnderConstruction getEmptyKey() { | ||||
732 | return {Base::getEmptyKey(), {}}; } | ||||
733 | static ObjectUnderConstruction getTombstoneKey() { | ||||
734 | return {Base::getTombstoneKey(), {}}; | ||||
735 | } | ||||
736 | static unsigned getHashValue(const ObjectUnderConstruction &Object) { | ||||
737 | return hash_value(Object); | ||||
738 | } | ||||
739 | static bool isEqual(const ObjectUnderConstruction &LHS, | ||||
740 | const ObjectUnderConstruction &RHS) { | ||||
741 | return LHS == RHS; | ||||
742 | } | ||||
743 | }; | ||||
744 | } | ||||
745 | |||||
746 | namespace { | ||||
747 | /// A dynamically-allocated heap object. | ||||
748 | struct DynAlloc { | ||||
749 | /// The value of this heap-allocated object. | ||||
750 | APValue Value; | ||||
751 | /// The allocating expression; used for diagnostics. Either a CXXNewExpr | ||||
752 | /// or a CallExpr (the latter is for direct calls to operator new inside | ||||
753 | /// std::allocator<T>::allocate). | ||||
754 | const Expr *AllocExpr = nullptr; | ||||
755 | |||||
756 | enum Kind { | ||||
757 | New, | ||||
758 | ArrayNew, | ||||
759 | StdAllocator | ||||
760 | }; | ||||
761 | |||||
762 | /// Get the kind of the allocation. This must match between allocation | ||||
763 | /// and deallocation. | ||||
764 | Kind getKind() const { | ||||
765 | if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) | ||||
766 | return NE->isArray() ? ArrayNew : New; | ||||
767 | assert(isa<CallExpr>(AllocExpr))(static_cast <bool> (isa<CallExpr>(AllocExpr)) ? void (0) : __assert_fail ("isa<CallExpr>(AllocExpr)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 767, __extension__ __PRETTY_FUNCTION__)); | ||||
768 | return StdAllocator; | ||||
769 | } | ||||
770 | }; | ||||
771 | |||||
772 | struct DynAllocOrder { | ||||
773 | bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { | ||||
774 | return L.getIndex() < R.getIndex(); | ||||
775 | } | ||||
776 | }; | ||||
777 | |||||
778 | /// EvalInfo - This is a private struct used by the evaluator to capture | ||||
779 | /// information about a subexpression as it is folded. It retains information | ||||
780 | /// about the AST context, but also maintains information about the folded | ||||
781 | /// expression. | ||||
782 | /// | ||||
783 | /// If an expression could be evaluated, it is still possible it is not a C | ||||
784 | /// "integer constant expression" or constant expression. If not, this struct | ||||
785 | /// captures information about how and why not. | ||||
786 | /// | ||||
787 | /// One bit of information passed *into* the request for constant folding | ||||
788 | /// indicates whether the subexpression is "evaluated" or not according to C | ||||
789 | /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can | ||||
790 | /// evaluate the expression regardless of what the RHS is, but C only allows | ||||
791 | /// certain things in certain situations. | ||||
792 | class EvalInfo : public interp::State { | ||||
793 | public: | ||||
794 | ASTContext &Ctx; | ||||
795 | |||||
796 | /// EvalStatus - Contains information about the evaluation. | ||||
797 | Expr::EvalStatus &EvalStatus; | ||||
798 | |||||
799 | /// CurrentCall - The top of the constexpr call stack. | ||||
800 | CallStackFrame *CurrentCall; | ||||
801 | |||||
802 | /// CallStackDepth - The number of calls in the call stack right now. | ||||
803 | unsigned CallStackDepth; | ||||
804 | |||||
805 | /// NextCallIndex - The next call index to assign. | ||||
806 | unsigned NextCallIndex; | ||||
807 | |||||
808 | /// StepsLeft - The remaining number of evaluation steps we're permitted | ||||
809 | /// to perform. This is essentially a limit for the number of statements | ||||
810 | /// we will evaluate. | ||||
811 | unsigned StepsLeft; | ||||
812 | |||||
813 | /// Enable the experimental new constant interpreter. If an expression is | ||||
814 | /// not supported by the interpreter, an error is triggered. | ||||
815 | bool EnableNewConstInterp; | ||||
816 | |||||
817 | /// BottomFrame - The frame in which evaluation started. This must be | ||||
818 | /// initialized after CurrentCall and CallStackDepth. | ||||
819 | CallStackFrame BottomFrame; | ||||
820 | |||||
821 | /// A stack of values whose lifetimes end at the end of some surrounding | ||||
822 | /// evaluation frame. | ||||
823 | llvm::SmallVector<Cleanup, 16> CleanupStack; | ||||
824 | |||||
825 | /// EvaluatingDecl - This is the declaration whose initializer is being | ||||
826 | /// evaluated, if any. | ||||
827 | APValue::LValueBase EvaluatingDecl; | ||||
828 | |||||
829 | enum class EvaluatingDeclKind { | ||||
830 | None, | ||||
831 | /// We're evaluating the construction of EvaluatingDecl. | ||||
832 | Ctor, | ||||
833 | /// We're evaluating the destruction of EvaluatingDecl. | ||||
834 | Dtor, | ||||
835 | }; | ||||
836 | EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; | ||||
837 | |||||
838 | /// EvaluatingDeclValue - This is the value being constructed for the | ||||
839 | /// declaration whose initializer is being evaluated, if any. | ||||
840 | APValue *EvaluatingDeclValue; | ||||
841 | |||||
842 | /// Set of objects that are currently being constructed. | ||||
843 | llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> | ||||
844 | ObjectsUnderConstruction; | ||||
845 | |||||
846 | /// Current heap allocations, along with the location where each was | ||||
847 | /// allocated. We use std::map here because we need stable addresses | ||||
848 | /// for the stored APValues. | ||||
849 | std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; | ||||
850 | |||||
851 | /// The number of heap allocations performed so far in this evaluation. | ||||
852 | unsigned NumHeapAllocs = 0; | ||||
853 | |||||
854 | struct EvaluatingConstructorRAII { | ||||
855 | EvalInfo &EI; | ||||
856 | ObjectUnderConstruction Object; | ||||
857 | bool DidInsert; | ||||
858 | EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, | ||||
859 | bool HasBases) | ||||
860 | : EI(EI), Object(Object) { | ||||
861 | DidInsert = | ||||
862 | EI.ObjectsUnderConstruction | ||||
863 | .insert({Object, HasBases ? ConstructionPhase::Bases | ||||
864 | : ConstructionPhase::AfterBases}) | ||||
865 | .second; | ||||
866 | } | ||||
867 | void finishedConstructingBases() { | ||||
868 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; | ||||
869 | } | ||||
870 | void finishedConstructingFields() { | ||||
871 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; | ||||
872 | } | ||||
873 | ~EvaluatingConstructorRAII() { | ||||
874 | if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); | ||||
875 | } | ||||
876 | }; | ||||
877 | |||||
878 | struct EvaluatingDestructorRAII { | ||||
879 | EvalInfo &EI; | ||||
880 | ObjectUnderConstruction Object; | ||||
881 | bool DidInsert; | ||||
882 | EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) | ||||
883 | : EI(EI), Object(Object) { | ||||
884 | DidInsert = EI.ObjectsUnderConstruction | ||||
885 | .insert({Object, ConstructionPhase::Destroying}) | ||||
886 | .second; | ||||
887 | } | ||||
888 | void startedDestroyingBases() { | ||||
889 | EI.ObjectsUnderConstruction[Object] = | ||||
890 | ConstructionPhase::DestroyingBases; | ||||
891 | } | ||||
892 | ~EvaluatingDestructorRAII() { | ||||
893 | if (DidInsert) | ||||
894 | EI.ObjectsUnderConstruction.erase(Object); | ||||
895 | } | ||||
896 | }; | ||||
897 | |||||
898 | ConstructionPhase | ||||
899 | isEvaluatingCtorDtor(APValue::LValueBase Base, | ||||
900 | ArrayRef<APValue::LValuePathEntry> Path) { | ||||
901 | return ObjectsUnderConstruction.lookup({Base, Path}); | ||||
902 | } | ||||
903 | |||||
904 | /// If we're currently speculatively evaluating, the outermost call stack | ||||
905 | /// depth at which we can mutate state, otherwise 0. | ||||
906 | unsigned SpeculativeEvaluationDepth = 0; | ||||
907 | |||||
908 | /// The current array initialization index, if we're performing array | ||||
909 | /// initialization. | ||||
910 | uint64_t ArrayInitIndex = -1; | ||||
911 | |||||
912 | /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further | ||||
913 | /// notes attached to it will also be stored, otherwise they will not be. | ||||
914 | bool HasActiveDiagnostic; | ||||
915 | |||||
916 | /// Have we emitted a diagnostic explaining why we couldn't constant | ||||
917 | /// fold (not just why it's not strictly a constant expression)? | ||||
918 | bool HasFoldFailureDiagnostic; | ||||
919 | |||||
920 | /// Whether or not we're in a context where the front end requires a | ||||
921 | /// constant value. | ||||
922 | bool InConstantContext; | ||||
923 | |||||
924 | /// Whether we're checking that an expression is a potential constant | ||||
925 | /// expression. If so, do not fail on constructs that could become constant | ||||
926 | /// later on (such as a use of an undefined global). | ||||
927 | bool CheckingPotentialConstantExpression = false; | ||||
928 | |||||
929 | /// Whether we're checking for an expression that has undefined behavior. | ||||
930 | /// If so, we will produce warnings if we encounter an operation that is | ||||
931 | /// always undefined. | ||||
932 | /// | ||||
933 | /// Note that we still need to evaluate the expression normally when this | ||||
934 | /// is set; this is used when evaluating ICEs in C. | ||||
935 | bool CheckingForUndefinedBehavior = false; | ||||
936 | |||||
937 | enum EvaluationMode { | ||||
938 | /// Evaluate as a constant expression. Stop if we find that the expression | ||||
939 | /// is not a constant expression. | ||||
940 | EM_ConstantExpression, | ||||
941 | |||||
942 | /// Evaluate as a constant expression. Stop if we find that the expression | ||||
943 | /// is not a constant expression. Some expressions can be retried in the | ||||
944 | /// optimizer if we don't constant fold them here, but in an unevaluated | ||||
945 | /// context we try to fold them immediately since the optimizer never | ||||
946 | /// gets a chance to look at it. | ||||
947 | EM_ConstantExpressionUnevaluated, | ||||
948 | |||||
949 | /// Fold the expression to a constant. Stop if we hit a side-effect that | ||||
950 | /// we can't model. | ||||
951 | EM_ConstantFold, | ||||
952 | |||||
953 | /// Evaluate in any way we know how. Don't worry about side-effects that | ||||
954 | /// can't be modeled. | ||||
955 | EM_IgnoreSideEffects, | ||||
956 | } EvalMode; | ||||
957 | |||||
958 | /// Are we checking whether the expression is a potential constant | ||||
959 | /// expression? | ||||
960 | bool checkingPotentialConstantExpression() const override { | ||||
961 | return CheckingPotentialConstantExpression; | ||||
962 | } | ||||
963 | |||||
964 | /// Are we checking an expression for overflow? | ||||
965 | // FIXME: We should check for any kind of undefined or suspicious behavior | ||||
966 | // in such constructs, not just overflow. | ||||
967 | bool checkingForUndefinedBehavior() const override { | ||||
968 | return CheckingForUndefinedBehavior; | ||||
969 | } | ||||
970 | |||||
971 | EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) | ||||
972 | : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), | ||||
973 | CallStackDepth(0), NextCallIndex(1), | ||||
974 | StepsLeft(C.getLangOpts().ConstexprStepLimit), | ||||
975 | EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), | ||||
976 | BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), | ||||
977 | EvaluatingDecl((const ValueDecl *)nullptr), | ||||
978 | EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), | ||||
979 | HasFoldFailureDiagnostic(false), InConstantContext(false), | ||||
980 | EvalMode(Mode) {} | ||||
981 | |||||
982 | ~EvalInfo() { | ||||
983 | discardCleanups(); | ||||
984 | } | ||||
985 | |||||
986 | void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, | ||||
987 | EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { | ||||
988 | EvaluatingDecl = Base; | ||||
989 | IsEvaluatingDecl = EDK; | ||||
990 | EvaluatingDeclValue = &Value; | ||||
991 | } | ||||
992 | |||||
993 | bool CheckCallLimit(SourceLocation Loc) { | ||||
994 | // Don't perform any constexpr calls (other than the call we're checking) | ||||
995 | // when checking a potential constant expression. | ||||
996 | if (checkingPotentialConstantExpression() && CallStackDepth > 1) | ||||
997 | return false; | ||||
998 | if (NextCallIndex == 0) { | ||||
999 | // NextCallIndex has wrapped around. | ||||
1000 | FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); | ||||
1001 | return false; | ||||
1002 | } | ||||
1003 | if (CallStackDepth <= getLangOpts().ConstexprCallDepth) | ||||
1004 | return true; | ||||
1005 | FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) | ||||
1006 | << getLangOpts().ConstexprCallDepth; | ||||
1007 | return false; | ||||
1008 | } | ||||
1009 | |||||
1010 | std::pair<CallStackFrame *, unsigned> | ||||
1011 | getCallFrameAndDepth(unsigned CallIndex) { | ||||
1012 | assert(CallIndex && "no call index in getCallFrameAndDepth")(static_cast <bool> (CallIndex && "no call index in getCallFrameAndDepth" ) ? void (0) : __assert_fail ("CallIndex && \"no call index in getCallFrameAndDepth\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1012, __extension__ __PRETTY_FUNCTION__)); | ||||
1013 | // We will eventually hit BottomFrame, which has Index 1, so Frame can't | ||||
1014 | // be null in this loop. | ||||
1015 | unsigned Depth = CallStackDepth; | ||||
1016 | CallStackFrame *Frame = CurrentCall; | ||||
1017 | while (Frame->Index > CallIndex) { | ||||
1018 | Frame = Frame->Caller; | ||||
1019 | --Depth; | ||||
1020 | } | ||||
1021 | if (Frame->Index == CallIndex) | ||||
1022 | return {Frame, Depth}; | ||||
1023 | return {nullptr, 0}; | ||||
1024 | } | ||||
1025 | |||||
1026 | bool nextStep(const Stmt *S) { | ||||
1027 | if (!StepsLeft) { | ||||
1028 | FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); | ||||
1029 | return false; | ||||
1030 | } | ||||
1031 | --StepsLeft; | ||||
1032 | return true; | ||||
1033 | } | ||||
1034 | |||||
1035 | APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); | ||||
1036 | |||||
1037 | Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { | ||||
1038 | Optional<DynAlloc*> Result; | ||||
1039 | auto It = HeapAllocs.find(DA); | ||||
1040 | if (It != HeapAllocs.end()) | ||||
1041 | Result = &It->second; | ||||
1042 | return Result; | ||||
1043 | } | ||||
1044 | |||||
1045 | /// Get the allocated storage for the given parameter of the given call. | ||||
1046 | APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { | ||||
1047 | CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; | ||||
1048 | return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) | ||||
1049 | : nullptr; | ||||
1050 | } | ||||
1051 | |||||
1052 | /// Information about a stack frame for std::allocator<T>::[de]allocate. | ||||
1053 | struct StdAllocatorCaller { | ||||
1054 | unsigned FrameIndex; | ||||
1055 | QualType ElemType; | ||||
1056 | explicit operator bool() const { return FrameIndex != 0; }; | ||||
1057 | }; | ||||
1058 | |||||
1059 | StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { | ||||
1060 | for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; | ||||
1061 | Call = Call->Caller) { | ||||
1062 | const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); | ||||
1063 | if (!MD) | ||||
1064 | continue; | ||||
1065 | const IdentifierInfo *FnII = MD->getIdentifier(); | ||||
1066 | if (!FnII || !FnII->isStr(FnName)) | ||||
1067 | continue; | ||||
1068 | |||||
1069 | const auto *CTSD = | ||||
1070 | dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); | ||||
1071 | if (!CTSD) | ||||
1072 | continue; | ||||
1073 | |||||
1074 | const IdentifierInfo *ClassII = CTSD->getIdentifier(); | ||||
1075 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); | ||||
1076 | if (CTSD->isInStdNamespace() && ClassII && | ||||
1077 | ClassII->isStr("allocator") && TAL.size() >= 1 && | ||||
1078 | TAL[0].getKind() == TemplateArgument::Type) | ||||
1079 | return {Call->Index, TAL[0].getAsType()}; | ||||
1080 | } | ||||
1081 | |||||
1082 | return {}; | ||||
1083 | } | ||||
1084 | |||||
1085 | void performLifetimeExtension() { | ||||
1086 | // Disable the cleanups for lifetime-extended temporaries. | ||||
1087 | CleanupStack.erase(std::remove_if(CleanupStack.begin(), | ||||
1088 | CleanupStack.end(), | ||||
1089 | [](Cleanup &C) { | ||||
1090 | return !C.isDestroyedAtEndOf( | ||||
1091 | ScopeKind::FullExpression); | ||||
1092 | }), | ||||
1093 | CleanupStack.end()); | ||||
1094 | } | ||||
1095 | |||||
1096 | /// Throw away any remaining cleanups at the end of evaluation. If any | ||||
1097 | /// cleanups would have had a side-effect, note that as an unmodeled | ||||
1098 | /// side-effect and return false. Otherwise, return true. | ||||
1099 | bool discardCleanups() { | ||||
1100 | for (Cleanup &C : CleanupStack) { | ||||
1101 | if (C.hasSideEffect() && !noteSideEffect()) { | ||||
1102 | CleanupStack.clear(); | ||||
1103 | return false; | ||||
1104 | } | ||||
1105 | } | ||||
1106 | CleanupStack.clear(); | ||||
1107 | return true; | ||||
1108 | } | ||||
1109 | |||||
1110 | private: | ||||
1111 | interp::Frame *getCurrentFrame() override { return CurrentCall; } | ||||
1112 | const interp::Frame *getBottomFrame() const override { return &BottomFrame; } | ||||
1113 | |||||
1114 | bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } | ||||
1115 | void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } | ||||
1116 | |||||
1117 | void setFoldFailureDiagnostic(bool Flag) override { | ||||
1118 | HasFoldFailureDiagnostic = Flag; | ||||
1119 | } | ||||
1120 | |||||
1121 | Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } | ||||
1122 | |||||
1123 | ASTContext &getCtx() const override { return Ctx; } | ||||
1124 | |||||
1125 | // If we have a prior diagnostic, it will be noting that the expression | ||||
1126 | // isn't a constant expression. This diagnostic is more important, | ||||
1127 | // unless we require this evaluation to produce a constant expression. | ||||
1128 | // | ||||
1129 | // FIXME: We might want to show both diagnostics to the user in | ||||
1130 | // EM_ConstantFold mode. | ||||
1131 | bool hasPriorDiagnostic() override { | ||||
1132 | if (!EvalStatus.Diag->empty()) { | ||||
1133 | switch (EvalMode) { | ||||
1134 | case EM_ConstantFold: | ||||
1135 | case EM_IgnoreSideEffects: | ||||
1136 | if (!HasFoldFailureDiagnostic) | ||||
1137 | break; | ||||
1138 | // We've already failed to fold something. Keep that diagnostic. | ||||
1139 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
1140 | case EM_ConstantExpression: | ||||
1141 | case EM_ConstantExpressionUnevaluated: | ||||
1142 | setActiveDiagnostic(false); | ||||
1143 | return true; | ||||
1144 | } | ||||
1145 | } | ||||
1146 | return false; | ||||
1147 | } | ||||
1148 | |||||
1149 | unsigned getCallStackDepth() override { return CallStackDepth; } | ||||
1150 | |||||
1151 | public: | ||||
1152 | /// Should we continue evaluation after encountering a side-effect that we | ||||
1153 | /// couldn't model? | ||||
1154 | bool keepEvaluatingAfterSideEffect() { | ||||
1155 | switch (EvalMode) { | ||||
1156 | case EM_IgnoreSideEffects: | ||||
1157 | return true; | ||||
1158 | |||||
1159 | case EM_ConstantExpression: | ||||
1160 | case EM_ConstantExpressionUnevaluated: | ||||
1161 | case EM_ConstantFold: | ||||
1162 | // By default, assume any side effect might be valid in some other | ||||
1163 | // evaluation of this expression from a different context. | ||||
1164 | return checkingPotentialConstantExpression() || | ||||
1165 | checkingForUndefinedBehavior(); | ||||
1166 | } | ||||
1167 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1167); | ||||
1168 | } | ||||
1169 | |||||
1170 | /// Note that we have had a side-effect, and determine whether we should | ||||
1171 | /// keep evaluating. | ||||
1172 | bool noteSideEffect() { | ||||
1173 | EvalStatus.HasSideEffects = true; | ||||
1174 | return keepEvaluatingAfterSideEffect(); | ||||
1175 | } | ||||
1176 | |||||
1177 | /// Should we continue evaluation after encountering undefined behavior? | ||||
1178 | bool keepEvaluatingAfterUndefinedBehavior() { | ||||
1179 | switch (EvalMode) { | ||||
1180 | case EM_IgnoreSideEffects: | ||||
1181 | case EM_ConstantFold: | ||||
1182 | return true; | ||||
1183 | |||||
1184 | case EM_ConstantExpression: | ||||
1185 | case EM_ConstantExpressionUnevaluated: | ||||
1186 | return checkingForUndefinedBehavior(); | ||||
1187 | } | ||||
1188 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1188); | ||||
1189 | } | ||||
1190 | |||||
1191 | /// Note that we hit something that was technically undefined behavior, but | ||||
1192 | /// that we can evaluate past it (such as signed overflow or floating-point | ||||
1193 | /// division by zero.) | ||||
1194 | bool noteUndefinedBehavior() override { | ||||
1195 | EvalStatus.HasUndefinedBehavior = true; | ||||
1196 | return keepEvaluatingAfterUndefinedBehavior(); | ||||
1197 | } | ||||
1198 | |||||
1199 | /// Should we continue evaluation as much as possible after encountering a | ||||
1200 | /// construct which can't be reduced to a value? | ||||
1201 | bool keepEvaluatingAfterFailure() const override { | ||||
1202 | if (!StepsLeft) | ||||
1203 | return false; | ||||
1204 | |||||
1205 | switch (EvalMode) { | ||||
1206 | case EM_ConstantExpression: | ||||
1207 | case EM_ConstantExpressionUnevaluated: | ||||
1208 | case EM_ConstantFold: | ||||
1209 | case EM_IgnoreSideEffects: | ||||
1210 | return checkingPotentialConstantExpression() || | ||||
1211 | checkingForUndefinedBehavior(); | ||||
1212 | } | ||||
1213 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1213); | ||||
1214 | } | ||||
1215 | |||||
1216 | /// Notes that we failed to evaluate an expression that other expressions | ||||
1217 | /// directly depend on, and determine if we should keep evaluating. This | ||||
1218 | /// should only be called if we actually intend to keep evaluating. | ||||
1219 | /// | ||||
1220 | /// Call noteSideEffect() instead if we may be able to ignore the value that | ||||
1221 | /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: | ||||
1222 | /// | ||||
1223 | /// (Foo(), 1) // use noteSideEffect | ||||
1224 | /// (Foo() || true) // use noteSideEffect | ||||
1225 | /// Foo() + 1 // use noteFailure | ||||
1226 | LLVM_NODISCARD[[clang::warn_unused_result]] bool noteFailure() { | ||||
1227 | // Failure when evaluating some expression often means there is some | ||||
1228 | // subexpression whose evaluation was skipped. Therefore, (because we | ||||
1229 | // don't track whether we skipped an expression when unwinding after an | ||||
1230 | // evaluation failure) every evaluation failure that bubbles up from a | ||||
1231 | // subexpression implies that a side-effect has potentially happened. We | ||||
1232 | // skip setting the HasSideEffects flag to true until we decide to | ||||
1233 | // continue evaluating after that point, which happens here. | ||||
1234 | bool KeepGoing = keepEvaluatingAfterFailure(); | ||||
1235 | EvalStatus.HasSideEffects |= KeepGoing; | ||||
1236 | return KeepGoing; | ||||
1237 | } | ||||
1238 | |||||
1239 | class ArrayInitLoopIndex { | ||||
1240 | EvalInfo &Info; | ||||
1241 | uint64_t OuterIndex; | ||||
1242 | |||||
1243 | public: | ||||
1244 | ArrayInitLoopIndex(EvalInfo &Info) | ||||
1245 | : Info(Info), OuterIndex(Info.ArrayInitIndex) { | ||||
1246 | Info.ArrayInitIndex = 0; | ||||
1247 | } | ||||
1248 | ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } | ||||
1249 | |||||
1250 | operator uint64_t&() { return Info.ArrayInitIndex; } | ||||
1251 | }; | ||||
1252 | }; | ||||
1253 | |||||
1254 | /// Object used to treat all foldable expressions as constant expressions. | ||||
1255 | struct FoldConstant { | ||||
1256 | EvalInfo &Info; | ||||
1257 | bool Enabled; | ||||
1258 | bool HadNoPriorDiags; | ||||
1259 | EvalInfo::EvaluationMode OldMode; | ||||
1260 | |||||
1261 | explicit FoldConstant(EvalInfo &Info, bool Enabled) | ||||
1262 | : Info(Info), | ||||
1263 | Enabled(Enabled), | ||||
1264 | HadNoPriorDiags(Info.EvalStatus.Diag && | ||||
1265 | Info.EvalStatus.Diag->empty() && | ||||
1266 | !Info.EvalStatus.HasSideEffects), | ||||
1267 | OldMode(Info.EvalMode) { | ||||
1268 | if (Enabled) | ||||
1269 | Info.EvalMode = EvalInfo::EM_ConstantFold; | ||||
1270 | } | ||||
1271 | void keepDiagnostics() { Enabled = false; } | ||||
1272 | ~FoldConstant() { | ||||
1273 | if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && | ||||
1274 | !Info.EvalStatus.HasSideEffects) | ||||
1275 | Info.EvalStatus.Diag->clear(); | ||||
1276 | Info.EvalMode = OldMode; | ||||
1277 | } | ||||
1278 | }; | ||||
1279 | |||||
1280 | /// RAII object used to set the current evaluation mode to ignore | ||||
1281 | /// side-effects. | ||||
1282 | struct IgnoreSideEffectsRAII { | ||||
1283 | EvalInfo &Info; | ||||
1284 | EvalInfo::EvaluationMode OldMode; | ||||
1285 | explicit IgnoreSideEffectsRAII(EvalInfo &Info) | ||||
1286 | : Info(Info), OldMode(Info.EvalMode) { | ||||
1287 | Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; | ||||
1288 | } | ||||
1289 | |||||
1290 | ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } | ||||
1291 | }; | ||||
1292 | |||||
1293 | /// RAII object used to optionally suppress diagnostics and side-effects from | ||||
1294 | /// a speculative evaluation. | ||||
1295 | class SpeculativeEvaluationRAII { | ||||
1296 | EvalInfo *Info = nullptr; | ||||
1297 | Expr::EvalStatus OldStatus; | ||||
1298 | unsigned OldSpeculativeEvaluationDepth; | ||||
1299 | |||||
1300 | void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { | ||||
1301 | Info = Other.Info; | ||||
1302 | OldStatus = Other.OldStatus; | ||||
1303 | OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; | ||||
1304 | Other.Info = nullptr; | ||||
1305 | } | ||||
1306 | |||||
1307 | void maybeRestoreState() { | ||||
1308 | if (!Info) | ||||
1309 | return; | ||||
1310 | |||||
1311 | Info->EvalStatus = OldStatus; | ||||
1312 | Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; | ||||
1313 | } | ||||
1314 | |||||
1315 | public: | ||||
1316 | SpeculativeEvaluationRAII() = default; | ||||
1317 | |||||
1318 | SpeculativeEvaluationRAII( | ||||
1319 | EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) | ||||
1320 | : Info(&Info), OldStatus(Info.EvalStatus), | ||||
1321 | OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { | ||||
1322 | Info.EvalStatus.Diag = NewDiag; | ||||
1323 | Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; | ||||
1324 | } | ||||
1325 | |||||
1326 | SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; | ||||
1327 | SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { | ||||
1328 | moveFromAndCancel(std::move(Other)); | ||||
1329 | } | ||||
1330 | |||||
1331 | SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { | ||||
1332 | maybeRestoreState(); | ||||
1333 | moveFromAndCancel(std::move(Other)); | ||||
1334 | return *this; | ||||
1335 | } | ||||
1336 | |||||
1337 | ~SpeculativeEvaluationRAII() { maybeRestoreState(); } | ||||
1338 | }; | ||||
1339 | |||||
1340 | /// RAII object wrapping a full-expression or block scope, and handling | ||||
1341 | /// the ending of the lifetime of temporaries created within it. | ||||
1342 | template<ScopeKind Kind> | ||||
1343 | class ScopeRAII { | ||||
1344 | EvalInfo &Info; | ||||
1345 | unsigned OldStackSize; | ||||
1346 | public: | ||||
1347 | ScopeRAII(EvalInfo &Info) | ||||
1348 | : Info(Info), OldStackSize(Info.CleanupStack.size()) { | ||||
1349 | // Push a new temporary version. This is needed to distinguish between | ||||
1350 | // temporaries created in different iterations of a loop. | ||||
1351 | Info.CurrentCall->pushTempVersion(); | ||||
1352 | } | ||||
1353 | bool destroy(bool RunDestructors = true) { | ||||
1354 | bool OK = cleanup(Info, RunDestructors, OldStackSize); | ||||
1355 | OldStackSize = -1U; | ||||
1356 | return OK; | ||||
1357 | } | ||||
1358 | ~ScopeRAII() { | ||||
1359 | if (OldStackSize != -1U) | ||||
1360 | destroy(false); | ||||
1361 | // Body moved to a static method to encourage the compiler to inline away | ||||
1362 | // instances of this class. | ||||
1363 | Info.CurrentCall->popTempVersion(); | ||||
1364 | } | ||||
1365 | private: | ||||
1366 | static bool cleanup(EvalInfo &Info, bool RunDestructors, | ||||
1367 | unsigned OldStackSize) { | ||||
1368 | assert(OldStackSize <= Info.CleanupStack.size() &&(static_cast <bool> (OldStackSize <= Info.CleanupStack .size() && "running cleanups out of order?") ? void ( 0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1369, __extension__ __PRETTY_FUNCTION__)) | ||||
1369 | "running cleanups out of order?")(static_cast <bool> (OldStackSize <= Info.CleanupStack .size() && "running cleanups out of order?") ? void ( 0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1369, __extension__ __PRETTY_FUNCTION__)); | ||||
1370 | |||||
1371 | // Run all cleanups for a block scope, and non-lifetime-extended cleanups | ||||
1372 | // for a full-expression scope. | ||||
1373 | bool Success = true; | ||||
1374 | for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { | ||||
1375 | if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { | ||||
1376 | if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { | ||||
1377 | Success = false; | ||||
1378 | break; | ||||
1379 | } | ||||
1380 | } | ||||
1381 | } | ||||
1382 | |||||
1383 | // Compact any retained cleanups. | ||||
1384 | auto NewEnd = Info.CleanupStack.begin() + OldStackSize; | ||||
1385 | if (Kind != ScopeKind::Block) | ||||
1386 | NewEnd = | ||||
1387 | std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { | ||||
1388 | return C.isDestroyedAtEndOf(Kind); | ||||
1389 | }); | ||||
1390 | Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); | ||||
1391 | return Success; | ||||
1392 | } | ||||
1393 | }; | ||||
1394 | typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; | ||||
1395 | typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; | ||||
1396 | typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; | ||||
1397 | } | ||||
1398 | |||||
1399 | bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, | ||||
1400 | CheckSubobjectKind CSK) { | ||||
1401 | if (Invalid) | ||||
1402 | return false; | ||||
1403 | if (isOnePastTheEnd()) { | ||||
1404 | Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) | ||||
1405 | << CSK; | ||||
1406 | setInvalid(); | ||||
1407 | return false; | ||||
1408 | } | ||||
1409 | // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there | ||||
1410 | // must actually be at least one array element; even a VLA cannot have a | ||||
1411 | // bound of zero. And if our index is nonzero, we already had a CCEDiag. | ||||
1412 | return true; | ||||
1413 | } | ||||
1414 | |||||
1415 | void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, | ||||
1416 | const Expr *E) { | ||||
1417 | Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); | ||||
1418 | // Do not set the designator as invalid: we can represent this situation, | ||||
1419 | // and correct handling of __builtin_object_size requires us to do so. | ||||
1420 | } | ||||
1421 | |||||
1422 | void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, | ||||
1423 | const Expr *E, | ||||
1424 | const APSInt &N) { | ||||
1425 | // If we're complaining, we must be able to statically determine the size of | ||||
1426 | // the most derived array. | ||||
1427 | if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) | ||||
1428 | Info.CCEDiag(E, diag::note_constexpr_array_index) | ||||
1429 | << N << /*array*/ 0 | ||||
1430 | << static_cast<unsigned>(getMostDerivedArraySize()); | ||||
1431 | else | ||||
1432 | Info.CCEDiag(E, diag::note_constexpr_array_index) | ||||
1433 | << N << /*non-array*/ 1; | ||||
1434 | setInvalid(); | ||||
1435 | } | ||||
1436 | |||||
1437 | CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, | ||||
1438 | const FunctionDecl *Callee, const LValue *This, | ||||
1439 | CallRef Call) | ||||
1440 | : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), | ||||
1441 | Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { | ||||
1442 | Info.CurrentCall = this; | ||||
1443 | ++Info.CallStackDepth; | ||||
1444 | } | ||||
1445 | |||||
1446 | CallStackFrame::~CallStackFrame() { | ||||
1447 | assert(Info.CurrentCall == this && "calls retired out of order")(static_cast <bool> (Info.CurrentCall == this && "calls retired out of order") ? void (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1447, __extension__ __PRETTY_FUNCTION__)); | ||||
1448 | --Info.CallStackDepth; | ||||
1449 | Info.CurrentCall = Caller; | ||||
1450 | } | ||||
1451 | |||||
1452 | static bool isRead(AccessKinds AK) { | ||||
1453 | return AK == AK_Read || AK == AK_ReadObjectRepresentation; | ||||
1454 | } | ||||
1455 | |||||
1456 | static bool isModification(AccessKinds AK) { | ||||
1457 | switch (AK) { | ||||
1458 | case AK_Read: | ||||
1459 | case AK_ReadObjectRepresentation: | ||||
1460 | case AK_MemberCall: | ||||
1461 | case AK_DynamicCast: | ||||
1462 | case AK_TypeId: | ||||
1463 | return false; | ||||
1464 | case AK_Assign: | ||||
1465 | case AK_Increment: | ||||
1466 | case AK_Decrement: | ||||
1467 | case AK_Construct: | ||||
1468 | case AK_Destroy: | ||||
1469 | return true; | ||||
1470 | } | ||||
1471 | llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1471); | ||||
1472 | } | ||||
1473 | |||||
1474 | static bool isAnyAccess(AccessKinds AK) { | ||||
1475 | return isRead(AK) || isModification(AK); | ||||
1476 | } | ||||
1477 | |||||
1478 | /// Is this an access per the C++ definition? | ||||
1479 | static bool isFormalAccess(AccessKinds AK) { | ||||
1480 | return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; | ||||
1481 | } | ||||
1482 | |||||
1483 | /// Is this kind of axcess valid on an indeterminate object value? | ||||
1484 | static bool isValidIndeterminateAccess(AccessKinds AK) { | ||||
1485 | switch (AK) { | ||||
1486 | case AK_Read: | ||||
1487 | case AK_Increment: | ||||
1488 | case AK_Decrement: | ||||
1489 | // These need the object's value. | ||||
1490 | return false; | ||||
1491 | |||||
1492 | case AK_ReadObjectRepresentation: | ||||
1493 | case AK_Assign: | ||||
1494 | case AK_Construct: | ||||
1495 | case AK_Destroy: | ||||
1496 | // Construction and destruction don't need the value. | ||||
1497 | return true; | ||||
1498 | |||||
1499 | case AK_MemberCall: | ||||
1500 | case AK_DynamicCast: | ||||
1501 | case AK_TypeId: | ||||
1502 | // These aren't really meaningful on scalars. | ||||
1503 | return true; | ||||
1504 | } | ||||
1505 | llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1505); | ||||
1506 | } | ||||
1507 | |||||
1508 | namespace { | ||||
1509 | struct ComplexValue { | ||||
1510 | private: | ||||
1511 | bool IsInt; | ||||
1512 | |||||
1513 | public: | ||||
1514 | APSInt IntReal, IntImag; | ||||
1515 | APFloat FloatReal, FloatImag; | ||||
1516 | |||||
1517 | ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} | ||||
1518 | |||||
1519 | void makeComplexFloat() { IsInt = false; } | ||||
1520 | bool isComplexFloat() const { return !IsInt; } | ||||
1521 | APFloat &getComplexFloatReal() { return FloatReal; } | ||||
1522 | APFloat &getComplexFloatImag() { return FloatImag; } | ||||
1523 | |||||
1524 | void makeComplexInt() { IsInt = true; } | ||||
1525 | bool isComplexInt() const { return IsInt; } | ||||
1526 | APSInt &getComplexIntReal() { return IntReal; } | ||||
1527 | APSInt &getComplexIntImag() { return IntImag; } | ||||
1528 | |||||
1529 | void moveInto(APValue &v) const { | ||||
1530 | if (isComplexFloat()) | ||||
1531 | v = APValue(FloatReal, FloatImag); | ||||
1532 | else | ||||
1533 | v = APValue(IntReal, IntImag); | ||||
1534 | } | ||||
1535 | void setFrom(const APValue &v) { | ||||
1536 | assert(v.isComplexFloat() || v.isComplexInt())(static_cast <bool> (v.isComplexFloat() || v.isComplexInt ()) ? void (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1536, __extension__ __PRETTY_FUNCTION__)); | ||||
1537 | if (v.isComplexFloat()) { | ||||
1538 | makeComplexFloat(); | ||||
1539 | FloatReal = v.getComplexFloatReal(); | ||||
1540 | FloatImag = v.getComplexFloatImag(); | ||||
1541 | } else { | ||||
1542 | makeComplexInt(); | ||||
1543 | IntReal = v.getComplexIntReal(); | ||||
1544 | IntImag = v.getComplexIntImag(); | ||||
1545 | } | ||||
1546 | } | ||||
1547 | }; | ||||
1548 | |||||
1549 | struct LValue { | ||||
1550 | APValue::LValueBase Base; | ||||
1551 | CharUnits Offset; | ||||
1552 | SubobjectDesignator Designator; | ||||
1553 | bool IsNullPtr : 1; | ||||
1554 | bool InvalidBase : 1; | ||||
1555 | |||||
1556 | const APValue::LValueBase getLValueBase() const { return Base; } | ||||
1557 | CharUnits &getLValueOffset() { return Offset; } | ||||
1558 | const CharUnits &getLValueOffset() const { return Offset; } | ||||
1559 | SubobjectDesignator &getLValueDesignator() { return Designator; } | ||||
1560 | const SubobjectDesignator &getLValueDesignator() const { return Designator;} | ||||
1561 | bool isNullPointer() const { return IsNullPtr;} | ||||
1562 | |||||
1563 | unsigned getLValueCallIndex() const { return Base.getCallIndex(); } | ||||
1564 | unsigned getLValueVersion() const { return Base.getVersion(); } | ||||
1565 | |||||
1566 | void moveInto(APValue &V) const { | ||||
1567 | if (Designator.Invalid) | ||||
1568 | V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); | ||||
1569 | else { | ||||
1570 | assert(!InvalidBase && "APValues can't handle invalid LValue bases")(static_cast <bool> (!InvalidBase && "APValues can't handle invalid LValue bases" ) ? void (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1570, __extension__ __PRETTY_FUNCTION__)); | ||||
1571 | V = APValue(Base, Offset, Designator.Entries, | ||||
1572 | Designator.IsOnePastTheEnd, IsNullPtr); | ||||
1573 | } | ||||
1574 | } | ||||
1575 | void setFrom(ASTContext &Ctx, const APValue &V) { | ||||
1576 | assert(V.isLValue() && "Setting LValue from a non-LValue?")(static_cast <bool> (V.isLValue() && "Setting LValue from a non-LValue?" ) ? void (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1576, __extension__ __PRETTY_FUNCTION__)); | ||||
1577 | Base = V.getLValueBase(); | ||||
1578 | Offset = V.getLValueOffset(); | ||||
1579 | InvalidBase = false; | ||||
1580 | Designator = SubobjectDesignator(Ctx, V); | ||||
1581 | IsNullPtr = V.isNullPointer(); | ||||
1582 | } | ||||
1583 | |||||
1584 | void set(APValue::LValueBase B, bool BInvalid = false) { | ||||
1585 | #ifndef NDEBUG | ||||
1586 | // We only allow a few types of invalid bases. Enforce that here. | ||||
1587 | if (BInvalid) { | ||||
1588 | const auto *E = B.get<const Expr *>(); | ||||
1589 | assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall (E)) && "Unexpected type of invalid base") ? void (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1590, __extension__ __PRETTY_FUNCTION__)) | ||||
1590 | "Unexpected type of invalid base")(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall (E)) && "Unexpected type of invalid base") ? void (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1590, __extension__ __PRETTY_FUNCTION__)); | ||||
1591 | } | ||||
1592 | #endif | ||||
1593 | |||||
1594 | Base = B; | ||||
1595 | Offset = CharUnits::fromQuantity(0); | ||||
1596 | InvalidBase = BInvalid; | ||||
1597 | Designator = SubobjectDesignator(getType(B)); | ||||
1598 | IsNullPtr = false; | ||||
1599 | } | ||||
1600 | |||||
1601 | void setNull(ASTContext &Ctx, QualType PointerTy) { | ||||
1602 | Base = (const ValueDecl *)nullptr; | ||||
1603 | Offset = | ||||
1604 | CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); | ||||
1605 | InvalidBase = false; | ||||
1606 | Designator = SubobjectDesignator(PointerTy->getPointeeType()); | ||||
1607 | IsNullPtr = true; | ||||
1608 | } | ||||
1609 | |||||
1610 | void setInvalid(APValue::LValueBase B, unsigned I = 0) { | ||||
1611 | set(B, true); | ||||
1612 | } | ||||
1613 | |||||
1614 | std::string toString(ASTContext &Ctx, QualType T) const { | ||||
1615 | APValue Printable; | ||||
1616 | moveInto(Printable); | ||||
1617 | return Printable.getAsString(Ctx, T); | ||||
1618 | } | ||||
1619 | |||||
1620 | private: | ||||
1621 | // Check that this LValue is not based on a null pointer. If it is, produce | ||||
1622 | // a diagnostic and mark the designator as invalid. | ||||
1623 | template <typename GenDiagType> | ||||
1624 | bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { | ||||
1625 | if (Designator.Invalid) | ||||
1626 | return false; | ||||
1627 | if (IsNullPtr) { | ||||
1628 | GenDiag(); | ||||
1629 | Designator.setInvalid(); | ||||
1630 | return false; | ||||
1631 | } | ||||
1632 | return true; | ||||
1633 | } | ||||
1634 | |||||
1635 | public: | ||||
1636 | bool checkNullPointer(EvalInfo &Info, const Expr *E, | ||||
1637 | CheckSubobjectKind CSK) { | ||||
1638 | return checkNullPointerDiagnosingWith([&Info, E, CSK] { | ||||
1639 | Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; | ||||
1640 | }); | ||||
1641 | } | ||||
1642 | |||||
1643 | bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, | ||||
1644 | AccessKinds AK) { | ||||
1645 | return checkNullPointerDiagnosingWith([&Info, E, AK] { | ||||
1646 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; | ||||
1647 | }); | ||||
1648 | } | ||||
1649 | |||||
1650 | // Check this LValue refers to an object. If not, set the designator to be | ||||
1651 | // invalid and emit a diagnostic. | ||||
1652 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { | ||||
1653 | return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && | ||||
1654 | Designator.checkSubobject(Info, E, CSK); | ||||
1655 | } | ||||
1656 | |||||
1657 | void addDecl(EvalInfo &Info, const Expr *E, | ||||
1658 | const Decl *D, bool Virtual = false) { | ||||
1659 | if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) | ||||
1660 | Designator.addDeclUnchecked(D, Virtual); | ||||
1661 | } | ||||
1662 | void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { | ||||
1663 | if (!Designator.Entries.empty()) { | ||||
1664 | Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); | ||||
1665 | Designator.setInvalid(); | ||||
1666 | return; | ||||
1667 | } | ||||
1668 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) { | ||||
1669 | assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())(static_cast <bool> (getType(Base)->isPointerType() || getType(Base)->isArrayType()) ? void (0) : __assert_fail ( "getType(Base)->isPointerType() || getType(Base)->isArrayType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1669, __extension__ __PRETTY_FUNCTION__)); | ||||
1670 | Designator.FirstEntryIsAnUnsizedArray = true; | ||||
1671 | Designator.addUnsizedArrayUnchecked(ElemTy); | ||||
1672 | } | ||||
1673 | } | ||||
1674 | void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { | ||||
1675 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) | ||||
1676 | Designator.addArrayUnchecked(CAT); | ||||
1677 | } | ||||
1678 | void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { | ||||
1679 | if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) | ||||
1680 | Designator.addComplexUnchecked(EltTy, Imag); | ||||
1681 | } | ||||
1682 | void clearIsNullPointer() { | ||||
1683 | IsNullPtr = false; | ||||
1684 | } | ||||
1685 | void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, | ||||
1686 | const APSInt &Index, CharUnits ElementSize) { | ||||
1687 | // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, | ||||
1688 | // but we're not required to diagnose it and it's valid in C++.) | ||||
1689 | if (!Index) | ||||
1690 | return; | ||||
1691 | |||||
1692 | // Compute the new offset in the appropriate width, wrapping at 64 bits. | ||||
1693 | // FIXME: When compiling for a 32-bit target, we should use 32-bit | ||||
1694 | // offsets. | ||||
1695 | uint64_t Offset64 = Offset.getQuantity(); | ||||
1696 | uint64_t ElemSize64 = ElementSize.getQuantity(); | ||||
1697 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); | ||||
1698 | Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); | ||||
1699 | |||||
1700 | if (checkNullPointer(Info, E, CSK_ArrayIndex)) | ||||
1701 | Designator.adjustIndex(Info, E, Index); | ||||
1702 | clearIsNullPointer(); | ||||
1703 | } | ||||
1704 | void adjustOffset(CharUnits N) { | ||||
1705 | Offset += N; | ||||
1706 | if (N.getQuantity()) | ||||
1707 | clearIsNullPointer(); | ||||
1708 | } | ||||
1709 | }; | ||||
1710 | |||||
1711 | struct MemberPtr { | ||||
1712 | MemberPtr() {} | ||||
1713 | explicit MemberPtr(const ValueDecl *Decl) : | ||||
1714 | DeclAndIsDerivedMember(Decl, false), Path() {} | ||||
1715 | |||||
1716 | /// The member or (direct or indirect) field referred to by this member | ||||
1717 | /// pointer, or 0 if this is a null member pointer. | ||||
1718 | const ValueDecl *getDecl() const { | ||||
1719 | return DeclAndIsDerivedMember.getPointer(); | ||||
1720 | } | ||||
1721 | /// Is this actually a member of some type derived from the relevant class? | ||||
1722 | bool isDerivedMember() const { | ||||
1723 | return DeclAndIsDerivedMember.getInt(); | ||||
1724 | } | ||||
1725 | /// Get the class which the declaration actually lives in. | ||||
1726 | const CXXRecordDecl *getContainingRecord() const { | ||||
1727 | return cast<CXXRecordDecl>( | ||||
1728 | DeclAndIsDerivedMember.getPointer()->getDeclContext()); | ||||
1729 | } | ||||
1730 | |||||
1731 | void moveInto(APValue &V) const { | ||||
1732 | V = APValue(getDecl(), isDerivedMember(), Path); | ||||
1733 | } | ||||
1734 | void setFrom(const APValue &V) { | ||||
1735 | assert(V.isMemberPointer())(static_cast <bool> (V.isMemberPointer()) ? void (0) : __assert_fail ("V.isMemberPointer()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1735, __extension__ __PRETTY_FUNCTION__)); | ||||
1736 | DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); | ||||
1737 | DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); | ||||
1738 | Path.clear(); | ||||
1739 | ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); | ||||
1740 | Path.insert(Path.end(), P.begin(), P.end()); | ||||
1741 | } | ||||
1742 | |||||
1743 | /// DeclAndIsDerivedMember - The member declaration, and a flag indicating | ||||
1744 | /// whether the member is a member of some class derived from the class type | ||||
1745 | /// of the member pointer. | ||||
1746 | llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; | ||||
1747 | /// Path - The path of base/derived classes from the member declaration's | ||||
1748 | /// class (exclusive) to the class type of the member pointer (inclusive). | ||||
1749 | SmallVector<const CXXRecordDecl*, 4> Path; | ||||
1750 | |||||
1751 | /// Perform a cast towards the class of the Decl (either up or down the | ||||
1752 | /// hierarchy). | ||||
1753 | bool castBack(const CXXRecordDecl *Class) { | ||||
1754 | assert(!Path.empty())(static_cast <bool> (!Path.empty()) ? void (0) : __assert_fail ("!Path.empty()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1754, __extension__ __PRETTY_FUNCTION__)); | ||||
1755 | const CXXRecordDecl *Expected; | ||||
1756 | if (Path.size() >= 2) | ||||
1757 | Expected = Path[Path.size() - 2]; | ||||
1758 | else | ||||
1759 | Expected = getContainingRecord(); | ||||
1760 | if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { | ||||
1761 | // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), | ||||
1762 | // if B does not contain the original member and is not a base or | ||||
1763 | // derived class of the class containing the original member, the result | ||||
1764 | // of the cast is undefined. | ||||
1765 | // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to | ||||
1766 | // (D::*). We consider that to be a language defect. | ||||
1767 | return false; | ||||
1768 | } | ||||
1769 | Path.pop_back(); | ||||
1770 | return true; | ||||
1771 | } | ||||
1772 | /// Perform a base-to-derived member pointer cast. | ||||
1773 | bool castToDerived(const CXXRecordDecl *Derived) { | ||||
1774 | if (!getDecl()) | ||||
1775 | return true; | ||||
1776 | if (!isDerivedMember()) { | ||||
1777 | Path.push_back(Derived); | ||||
1778 | return true; | ||||
1779 | } | ||||
1780 | if (!castBack(Derived)) | ||||
1781 | return false; | ||||
1782 | if (Path.empty()) | ||||
1783 | DeclAndIsDerivedMember.setInt(false); | ||||
1784 | return true; | ||||
1785 | } | ||||
1786 | /// Perform a derived-to-base member pointer cast. | ||||
1787 | bool castToBase(const CXXRecordDecl *Base) { | ||||
1788 | if (!getDecl()) | ||||
1789 | return true; | ||||
1790 | if (Path.empty()) | ||||
1791 | DeclAndIsDerivedMember.setInt(true); | ||||
1792 | if (isDerivedMember()) { | ||||
1793 | Path.push_back(Base); | ||||
1794 | return true; | ||||
1795 | } | ||||
1796 | return castBack(Base); | ||||
1797 | } | ||||
1798 | }; | ||||
1799 | |||||
1800 | /// Compare two member pointers, which are assumed to be of the same type. | ||||
1801 | static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { | ||||
1802 | if (!LHS.getDecl() || !RHS.getDecl()) | ||||
1803 | return !LHS.getDecl() && !RHS.getDecl(); | ||||
1804 | if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) | ||||
1805 | return false; | ||||
1806 | return LHS.Path == RHS.Path; | ||||
1807 | } | ||||
1808 | } | ||||
1809 | |||||
1810 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); | ||||
1811 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, | ||||
1812 | const LValue &This, const Expr *E, | ||||
1813 | bool AllowNonLiteralTypes = false); | ||||
1814 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, | ||||
1815 | bool InvalidBaseOK = false); | ||||
1816 | static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, | ||||
1817 | bool InvalidBaseOK = false); | ||||
1818 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, | ||||
1819 | EvalInfo &Info); | ||||
1820 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); | ||||
1821 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); | ||||
1822 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, | ||||
1823 | EvalInfo &Info); | ||||
1824 | static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); | ||||
1825 | static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); | ||||
1826 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, | ||||
1827 | EvalInfo &Info); | ||||
1828 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); | ||||
1829 | static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, | ||||
1830 | EvalInfo &Info); | ||||
1831 | |||||
1832 | /// Evaluate an integer or fixed point expression into an APResult. | ||||
1833 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, | ||||
1834 | EvalInfo &Info); | ||||
1835 | |||||
1836 | /// Evaluate only a fixed point expression into an APResult. | ||||
1837 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, | ||||
1838 | EvalInfo &Info); | ||||
1839 | |||||
1840 | //===----------------------------------------------------------------------===// | ||||
1841 | // Misc utilities | ||||
1842 | //===----------------------------------------------------------------------===// | ||||
1843 | |||||
1844 | /// Negate an APSInt in place, converting it to a signed form if necessary, and | ||||
1845 | /// preserving its value (by extending by up to one bit as needed). | ||||
1846 | static void negateAsSigned(APSInt &Int) { | ||||
1847 | if (Int.isUnsigned() || Int.isMinSignedValue()) { | ||||
1848 | Int = Int.extend(Int.getBitWidth() + 1); | ||||
1849 | Int.setIsSigned(true); | ||||
1850 | } | ||||
1851 | Int = -Int; | ||||
1852 | } | ||||
1853 | |||||
1854 | template<typename KeyT> | ||||
1855 | APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, | ||||
1856 | ScopeKind Scope, LValue &LV) { | ||||
1857 | unsigned Version = getTempVersion(); | ||||
1858 | APValue::LValueBase Base(Key, Index, Version); | ||||
1859 | LV.set(Base); | ||||
1860 | return createLocal(Base, Key, T, Scope); | ||||
1861 | } | ||||
1862 | |||||
1863 | /// Allocate storage for a parameter of a function call made in this frame. | ||||
1864 | APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, | ||||
1865 | LValue &LV) { | ||||
1866 | assert(Args.CallIndex == Index && "creating parameter in wrong frame")(static_cast <bool> (Args.CallIndex == Index && "creating parameter in wrong frame") ? void (0) : __assert_fail ("Args.CallIndex == Index && \"creating parameter in wrong frame\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1866, __extension__ __PRETTY_FUNCTION__)); | ||||
1867 | APValue::LValueBase Base(PVD, Index, Args.Version); | ||||
1868 | LV.set(Base); | ||||
1869 | // We always destroy parameters at the end of the call, even if we'd allow | ||||
1870 | // them to live to the end of the full-expression at runtime, in order to | ||||
1871 | // give portable results and match other compilers. | ||||
1872 | return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); | ||||
1873 | } | ||||
1874 | |||||
1875 | APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, | ||||
1876 | QualType T, ScopeKind Scope) { | ||||
1877 | assert(Base.getCallIndex() == Index && "lvalue for wrong frame")(static_cast <bool> (Base.getCallIndex() == Index && "lvalue for wrong frame") ? void (0) : __assert_fail ("Base.getCallIndex() == Index && \"lvalue for wrong frame\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1877, __extension__ __PRETTY_FUNCTION__)); | ||||
1878 | unsigned Version = Base.getVersion(); | ||||
1879 | APValue &Result = Temporaries[MapKeyTy(Key, Version)]; | ||||
1880 | assert(Result.isAbsent() && "local created multiple times")(static_cast <bool> (Result.isAbsent() && "local created multiple times" ) ? void (0) : __assert_fail ("Result.isAbsent() && \"local created multiple times\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1880, __extension__ __PRETTY_FUNCTION__)); | ||||
1881 | |||||
1882 | // If we're creating a local immediately in the operand of a speculative | ||||
1883 | // evaluation, don't register a cleanup to be run outside the speculative | ||||
1884 | // evaluation context, since we won't actually be able to initialize this | ||||
1885 | // object. | ||||
1886 | if (Index <= Info.SpeculativeEvaluationDepth) { | ||||
1887 | if (T.isDestructedType()) | ||||
1888 | Info.noteSideEffect(); | ||||
1889 | } else { | ||||
1890 | Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); | ||||
1891 | } | ||||
1892 | return Result; | ||||
1893 | } | ||||
1894 | |||||
1895 | APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { | ||||
1896 | if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { | ||||
1897 | FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); | ||||
1898 | return nullptr; | ||||
1899 | } | ||||
1900 | |||||
1901 | DynamicAllocLValue DA(NumHeapAllocs++); | ||||
1902 | LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); | ||||
1903 | auto Result = HeapAllocs.emplace(std::piecewise_construct, | ||||
1904 | std::forward_as_tuple(DA), std::tuple<>()); | ||||
1905 | assert(Result.second && "reused a heap alloc index?")(static_cast <bool> (Result.second && "reused a heap alloc index?" ) ? void (0) : __assert_fail ("Result.second && \"reused a heap alloc index?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1905, __extension__ __PRETTY_FUNCTION__)); | ||||
1906 | Result.first->second.AllocExpr = E; | ||||
1907 | return &Result.first->second.Value; | ||||
1908 | } | ||||
1909 | |||||
1910 | /// Produce a string describing the given constexpr call. | ||||
1911 | void CallStackFrame::describe(raw_ostream &Out) { | ||||
1912 | unsigned ArgIndex = 0; | ||||
1913 | bool IsMemberCall = isa<CXXMethodDecl>(Callee) && | ||||
1914 | !isa<CXXConstructorDecl>(Callee) && | ||||
1915 | cast<CXXMethodDecl>(Callee)->isInstance(); | ||||
1916 | |||||
1917 | if (!IsMemberCall) | ||||
1918 | Out << *Callee << '('; | ||||
1919 | |||||
1920 | if (This && IsMemberCall) { | ||||
1921 | APValue Val; | ||||
1922 | This->moveInto(Val); | ||||
1923 | Val.printPretty(Out, Info.Ctx, | ||||
1924 | This->Designator.MostDerivedType); | ||||
1925 | // FIXME: Add parens around Val if needed. | ||||
1926 | Out << "->" << *Callee << '('; | ||||
1927 | IsMemberCall = false; | ||||
1928 | } | ||||
1929 | |||||
1930 | for (FunctionDecl::param_const_iterator I = Callee->param_begin(), | ||||
1931 | E = Callee->param_end(); I != E; ++I, ++ArgIndex) { | ||||
1932 | if (ArgIndex > (unsigned)IsMemberCall) | ||||
1933 | Out << ", "; | ||||
1934 | |||||
1935 | const ParmVarDecl *Param = *I; | ||||
1936 | APValue *V = Info.getParamSlot(Arguments, Param); | ||||
1937 | if (V) | ||||
1938 | V->printPretty(Out, Info.Ctx, Param->getType()); | ||||
1939 | else | ||||
1940 | Out << "<...>"; | ||||
1941 | |||||
1942 | if (ArgIndex == 0 && IsMemberCall) | ||||
1943 | Out << "->" << *Callee << '('; | ||||
1944 | } | ||||
1945 | |||||
1946 | Out << ')'; | ||||
1947 | } | ||||
1948 | |||||
1949 | /// Evaluate an expression to see if it had side-effects, and discard its | ||||
1950 | /// result. | ||||
1951 | /// \return \c true if the caller should keep evaluating. | ||||
1952 | static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { | ||||
1953 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 1953, __extension__ __PRETTY_FUNCTION__)); | ||||
1954 | APValue Scratch; | ||||
1955 | if (!Evaluate(Scratch, Info, E)) | ||||
1956 | // We don't need the value, but we might have skipped a side effect here. | ||||
1957 | return Info.noteSideEffect(); | ||||
1958 | return true; | ||||
1959 | } | ||||
1960 | |||||
1961 | /// Should this call expression be treated as a string literal? | ||||
1962 | static bool IsStringLiteralCall(const CallExpr *E) { | ||||
1963 | unsigned Builtin = E->getBuiltinCallee(); | ||||
1964 | return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || | ||||
1965 | Builtin == Builtin::BI__builtin___NSStringMakeConstantString); | ||||
1966 | } | ||||
1967 | |||||
1968 | static bool IsGlobalLValue(APValue::LValueBase B) { | ||||
1969 | // C++11 [expr.const]p3 An address constant expression is a prvalue core | ||||
1970 | // constant expression of pointer type that evaluates to... | ||||
1971 | |||||
1972 | // ... a null pointer value, or a prvalue core constant expression of type | ||||
1973 | // std::nullptr_t. | ||||
1974 | if (!B) return true; | ||||
1975 | |||||
1976 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | ||||
1977 | // ... the address of an object with static storage duration, | ||||
1978 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
1979 | return VD->hasGlobalStorage(); | ||||
1980 | if (isa<TemplateParamObjectDecl>(D)) | ||||
1981 | return true; | ||||
1982 | // ... the address of a function, | ||||
1983 | // ... the address of a GUID [MS extension], | ||||
1984 | return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); | ||||
1985 | } | ||||
1986 | |||||
1987 | if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) | ||||
1988 | return true; | ||||
1989 | |||||
1990 | const Expr *E = B.get<const Expr*>(); | ||||
1991 | switch (E->getStmtClass()) { | ||||
1992 | default: | ||||
1993 | return false; | ||||
1994 | case Expr::CompoundLiteralExprClass: { | ||||
1995 | const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); | ||||
1996 | return CLE->isFileScope() && CLE->isLValue(); | ||||
1997 | } | ||||
1998 | case Expr::MaterializeTemporaryExprClass: | ||||
1999 | // A materialized temporary might have been lifetime-extended to static | ||||
2000 | // storage duration. | ||||
2001 | return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; | ||||
2002 | // A string literal has static storage duration. | ||||
2003 | case Expr::StringLiteralClass: | ||||
2004 | case Expr::PredefinedExprClass: | ||||
2005 | case Expr::ObjCStringLiteralClass: | ||||
2006 | case Expr::ObjCEncodeExprClass: | ||||
2007 | return true; | ||||
2008 | case Expr::ObjCBoxedExprClass: | ||||
2009 | return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); | ||||
2010 | case Expr::CallExprClass: | ||||
2011 | return IsStringLiteralCall(cast<CallExpr>(E)); | ||||
2012 | // For GCC compatibility, &&label has static storage duration. | ||||
2013 | case Expr::AddrLabelExprClass: | ||||
2014 | return true; | ||||
2015 | // A Block literal expression may be used as the initialization value for | ||||
2016 | // Block variables at global or local static scope. | ||||
2017 | case Expr::BlockExprClass: | ||||
2018 | return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); | ||||
2019 | case Expr::ImplicitValueInitExprClass: | ||||
2020 | // FIXME: | ||||
2021 | // We can never form an lvalue with an implicit value initialization as its | ||||
2022 | // base through expression evaluation, so these only appear in one case: the | ||||
2023 | // implicit variable declaration we invent when checking whether a constexpr | ||||
2024 | // constructor can produce a constant expression. We must assume that such | ||||
2025 | // an expression might be a global lvalue. | ||||
2026 | return true; | ||||
2027 | } | ||||
2028 | } | ||||
2029 | |||||
2030 | static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { | ||||
2031 | return LVal.Base.dyn_cast<const ValueDecl*>(); | ||||
2032 | } | ||||
2033 | |||||
2034 | static bool IsLiteralLValue(const LValue &Value) { | ||||
2035 | if (Value.getLValueCallIndex()) | ||||
2036 | return false; | ||||
2037 | const Expr *E = Value.Base.dyn_cast<const Expr*>(); | ||||
2038 | return E && !isa<MaterializeTemporaryExpr>(E); | ||||
2039 | } | ||||
2040 | |||||
2041 | static bool IsWeakLValue(const LValue &Value) { | ||||
2042 | const ValueDecl *Decl = GetLValueBaseDecl(Value); | ||||
2043 | return Decl && Decl->isWeak(); | ||||
2044 | } | ||||
2045 | |||||
2046 | static bool isZeroSized(const LValue &Value) { | ||||
2047 | const ValueDecl *Decl = GetLValueBaseDecl(Value); | ||||
2048 | if (Decl && isa<VarDecl>(Decl)) { | ||||
2049 | QualType Ty = Decl->getType(); | ||||
2050 | if (Ty->isArrayType()) | ||||
2051 | return Ty->isIncompleteType() || | ||||
2052 | Decl->getASTContext().getTypeSize(Ty) == 0; | ||||
2053 | } | ||||
2054 | return false; | ||||
2055 | } | ||||
2056 | |||||
2057 | static bool HasSameBase(const LValue &A, const LValue &B) { | ||||
2058 | if (!A.getLValueBase()) | ||||
2059 | return !B.getLValueBase(); | ||||
2060 | if (!B.getLValueBase()) | ||||
2061 | return false; | ||||
2062 | |||||
2063 | if (A.getLValueBase().getOpaqueValue() != | ||||
2064 | B.getLValueBase().getOpaqueValue()) | ||||
2065 | return false; | ||||
2066 | |||||
2067 | return A.getLValueCallIndex() == B.getLValueCallIndex() && | ||||
2068 | A.getLValueVersion() == B.getLValueVersion(); | ||||
2069 | } | ||||
2070 | |||||
2071 | static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { | ||||
2072 | assert(Base && "no location for a null lvalue")(static_cast <bool> (Base && "no location for a null lvalue" ) ? void (0) : __assert_fail ("Base && \"no location for a null lvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2072, __extension__ __PRETTY_FUNCTION__)); | ||||
2073 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | ||||
2074 | |||||
2075 | // For a parameter, find the corresponding call stack frame (if it still | ||||
2076 | // exists), and point at the parameter of the function definition we actually | ||||
2077 | // invoked. | ||||
2078 | if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { | ||||
2079 | unsigned Idx = PVD->getFunctionScopeIndex(); | ||||
2080 | for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { | ||||
2081 | if (F->Arguments.CallIndex == Base.getCallIndex() && | ||||
2082 | F->Arguments.Version == Base.getVersion() && F->Callee && | ||||
2083 | Idx < F->Callee->getNumParams()) { | ||||
2084 | VD = F->Callee->getParamDecl(Idx); | ||||
2085 | break; | ||||
2086 | } | ||||
2087 | } | ||||
2088 | } | ||||
2089 | |||||
2090 | if (VD) | ||||
2091 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
2092 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) | ||||
2093 | Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); | ||||
2094 | else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { | ||||
2095 | // FIXME: Produce a note for dangling pointers too. | ||||
2096 | if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) | ||||
2097 | Info.Note((*Alloc)->AllocExpr->getExprLoc(), | ||||
2098 | diag::note_constexpr_dynamic_alloc_here); | ||||
2099 | } | ||||
2100 | // We have no information to show for a typeid(T) object. | ||||
2101 | } | ||||
2102 | |||||
2103 | enum class CheckEvaluationResultKind { | ||||
2104 | ConstantExpression, | ||||
2105 | FullyInitialized, | ||||
2106 | }; | ||||
2107 | |||||
2108 | /// Materialized temporaries that we've already checked to determine if they're | ||||
2109 | /// initializsed by a constant expression. | ||||
2110 | using CheckedTemporaries = | ||||
2111 | llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; | ||||
2112 | |||||
2113 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, | ||||
2114 | EvalInfo &Info, SourceLocation DiagLoc, | ||||
2115 | QualType Type, const APValue &Value, | ||||
2116 | ConstantExprKind Kind, | ||||
2117 | SourceLocation SubobjectLoc, | ||||
2118 | CheckedTemporaries &CheckedTemps); | ||||
2119 | |||||
2120 | /// Check that this reference or pointer core constant expression is a valid | ||||
2121 | /// value for an address or reference constant expression. Return true if we | ||||
2122 | /// can fold this expression, whether or not it's a constant expression. | ||||
2123 | static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, | ||||
2124 | QualType Type, const LValue &LVal, | ||||
2125 | ConstantExprKind Kind, | ||||
2126 | CheckedTemporaries &CheckedTemps) { | ||||
2127 | bool IsReferenceType = Type->isReferenceType(); | ||||
2128 | |||||
2129 | APValue::LValueBase Base = LVal.getLValueBase(); | ||||
2130 | const SubobjectDesignator &Designator = LVal.getLValueDesignator(); | ||||
2131 | |||||
2132 | const Expr *BaseE = Base.dyn_cast<const Expr *>(); | ||||
2133 | const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); | ||||
2134 | |||||
2135 | // Additional restrictions apply in a template argument. We only enforce the | ||||
2136 | // C++20 restrictions here; additional syntactic and semantic restrictions | ||||
2137 | // are applied elsewhere. | ||||
2138 | if (isTemplateArgument(Kind)) { | ||||
2139 | int InvalidBaseKind = -1; | ||||
2140 | StringRef Ident; | ||||
2141 | if (Base.is<TypeInfoLValue>()) | ||||
2142 | InvalidBaseKind = 0; | ||||
2143 | else if (isa_and_nonnull<StringLiteral>(BaseE)) | ||||
2144 | InvalidBaseKind = 1; | ||||
2145 | else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || | ||||
2146 | isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) | ||||
2147 | InvalidBaseKind = 2; | ||||
2148 | else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { | ||||
2149 | InvalidBaseKind = 3; | ||||
2150 | Ident = PE->getIdentKindName(); | ||||
2151 | } | ||||
2152 | |||||
2153 | if (InvalidBaseKind != -1) { | ||||
2154 | Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) | ||||
2155 | << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind | ||||
2156 | << Ident; | ||||
2157 | return false; | ||||
2158 | } | ||||
2159 | } | ||||
2160 | |||||
2161 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { | ||||
2162 | if (FD->isConsteval()) { | ||||
2163 | Info.FFDiag(Loc, diag::note_consteval_address_accessible) | ||||
2164 | << !Type->isAnyPointerType(); | ||||
2165 | Info.Note(FD->getLocation(), diag::note_declared_at); | ||||
2166 | return false; | ||||
2167 | } | ||||
2168 | } | ||||
2169 | |||||
2170 | // Check that the object is a global. Note that the fake 'this' object we | ||||
2171 | // manufacture when checking potential constant expressions is conservatively | ||||
2172 | // assumed to be global here. | ||||
2173 | if (!IsGlobalLValue(Base)) { | ||||
2174 | if (Info.getLangOpts().CPlusPlus11) { | ||||
2175 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | ||||
2176 | Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) | ||||
2177 | << IsReferenceType << !Designator.Entries.empty() | ||||
2178 | << !!VD << VD; | ||||
2179 | |||||
2180 | auto *VarD = dyn_cast_or_null<VarDecl>(VD); | ||||
2181 | if (VarD && VarD->isConstexpr()) { | ||||
2182 | // Non-static local constexpr variables have unintuitive semantics: | ||||
2183 | // constexpr int a = 1; | ||||
2184 | // constexpr const int *p = &a; | ||||
2185 | // ... is invalid because the address of 'a' is not constant. Suggest | ||||
2186 | // adding a 'static' in this case. | ||||
2187 | Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) | ||||
2188 | << VarD | ||||
2189 | << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); | ||||
2190 | } else { | ||||
2191 | NoteLValueLocation(Info, Base); | ||||
2192 | } | ||||
2193 | } else { | ||||
2194 | Info.FFDiag(Loc); | ||||
2195 | } | ||||
2196 | // Don't allow references to temporaries to escape. | ||||
2197 | return false; | ||||
2198 | } | ||||
2199 | assert((Info.checkingPotentialConstantExpression() ||(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2201, __extension__ __PRETTY_FUNCTION__)) | ||||
2200 | LVal.getLValueCallIndex() == 0) &&(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2201, __extension__ __PRETTY_FUNCTION__)) | ||||
2201 | "have call index for global lvalue")(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2201, __extension__ __PRETTY_FUNCTION__)); | ||||
2202 | |||||
2203 | if (Base.is<DynamicAllocLValue>()) { | ||||
2204 | Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) | ||||
2205 | << IsReferenceType << !Designator.Entries.empty(); | ||||
2206 | NoteLValueLocation(Info, Base); | ||||
2207 | return false; | ||||
2208 | } | ||||
2209 | |||||
2210 | if (BaseVD) { | ||||
2211 | if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { | ||||
2212 | // Check if this is a thread-local variable. | ||||
2213 | if (Var->getTLSKind()) | ||||
2214 | // FIXME: Diagnostic! | ||||
2215 | return false; | ||||
2216 | |||||
2217 | // A dllimport variable never acts like a constant, unless we're | ||||
2218 | // evaluating a value for use only in name mangling. | ||||
2219 | if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) | ||||
2220 | // FIXME: Diagnostic! | ||||
2221 | return false; | ||||
2222 | } | ||||
2223 | if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { | ||||
2224 | // __declspec(dllimport) must be handled very carefully: | ||||
2225 | // We must never initialize an expression with the thunk in C++. | ||||
2226 | // Doing otherwise would allow the same id-expression to yield | ||||
2227 | // different addresses for the same function in different translation | ||||
2228 | // units. However, this means that we must dynamically initialize the | ||||
2229 | // expression with the contents of the import address table at runtime. | ||||
2230 | // | ||||
2231 | // The C language has no notion of ODR; furthermore, it has no notion of | ||||
2232 | // dynamic initialization. This means that we are permitted to | ||||
2233 | // perform initialization with the address of the thunk. | ||||
2234 | if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && | ||||
2235 | FD->hasAttr<DLLImportAttr>()) | ||||
2236 | // FIXME: Diagnostic! | ||||
2237 | return false; | ||||
2238 | } | ||||
2239 | } else if (const auto *MTE = | ||||
2240 | dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { | ||||
2241 | if (CheckedTemps.insert(MTE).second) { | ||||
2242 | QualType TempType = getType(Base); | ||||
2243 | if (TempType.isDestructedType()) { | ||||
2244 | Info.FFDiag(MTE->getExprLoc(), | ||||
2245 | diag::note_constexpr_unsupported_temporary_nontrivial_dtor) | ||||
2246 | << TempType; | ||||
2247 | return false; | ||||
2248 | } | ||||
2249 | |||||
2250 | APValue *V = MTE->getOrCreateValue(false); | ||||
2251 | assert(V && "evasluation result refers to uninitialised temporary")(static_cast <bool> (V && "evasluation result refers to uninitialised temporary" ) ? void (0) : __assert_fail ("V && \"evasluation result refers to uninitialised temporary\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2251, __extension__ __PRETTY_FUNCTION__)); | ||||
2252 | if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, | ||||
2253 | Info, MTE->getExprLoc(), TempType, *V, | ||||
2254 | Kind, SourceLocation(), CheckedTemps)) | ||||
2255 | return false; | ||||
2256 | } | ||||
2257 | } | ||||
2258 | |||||
2259 | // Allow address constant expressions to be past-the-end pointers. This is | ||||
2260 | // an extension: the standard requires them to point to an object. | ||||
2261 | if (!IsReferenceType) | ||||
2262 | return true; | ||||
2263 | |||||
2264 | // A reference constant expression must refer to an object. | ||||
2265 | if (!Base) { | ||||
2266 | // FIXME: diagnostic | ||||
2267 | Info.CCEDiag(Loc); | ||||
2268 | return true; | ||||
2269 | } | ||||
2270 | |||||
2271 | // Does this refer one past the end of some object? | ||||
2272 | if (!Designator.Invalid && Designator.isOnePastTheEnd()) { | ||||
2273 | Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) | ||||
2274 | << !Designator.Entries.empty() << !!BaseVD << BaseVD; | ||||
2275 | NoteLValueLocation(Info, Base); | ||||
2276 | } | ||||
2277 | |||||
2278 | return true; | ||||
2279 | } | ||||
2280 | |||||
2281 | /// Member pointers are constant expressions unless they point to a | ||||
2282 | /// non-virtual dllimport member function. | ||||
2283 | static bool CheckMemberPointerConstantExpression(EvalInfo &Info, | ||||
2284 | SourceLocation Loc, | ||||
2285 | QualType Type, | ||||
2286 | const APValue &Value, | ||||
2287 | ConstantExprKind Kind) { | ||||
2288 | const ValueDecl *Member = Value.getMemberPointerDecl(); | ||||
2289 | const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); | ||||
2290 | if (!FD) | ||||
2291 | return true; | ||||
2292 | if (FD->isConsteval()) { | ||||
2293 | Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; | ||||
2294 | Info.Note(FD->getLocation(), diag::note_declared_at); | ||||
2295 | return false; | ||||
2296 | } | ||||
2297 | return isForManglingOnly(Kind) || FD->isVirtual() || | ||||
2298 | !FD->hasAttr<DLLImportAttr>(); | ||||
2299 | } | ||||
2300 | |||||
2301 | /// Check that this core constant expression is of literal type, and if not, | ||||
2302 | /// produce an appropriate diagnostic. | ||||
2303 | static bool CheckLiteralType(EvalInfo &Info, const Expr *E, | ||||
2304 | const LValue *This = nullptr) { | ||||
2305 | if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) | ||||
2306 | return true; | ||||
2307 | |||||
2308 | // C++1y: A constant initializer for an object o [...] may also invoke | ||||
2309 | // constexpr constructors for o and its subobjects even if those objects | ||||
2310 | // are of non-literal class types. | ||||
2311 | // | ||||
2312 | // C++11 missed this detail for aggregates, so classes like this: | ||||
2313 | // struct foo_t { union { int i; volatile int j; } u; }; | ||||
2314 | // are not (obviously) initializable like so: | ||||
2315 | // __attribute__((__require_constant_initialization__)) | ||||
2316 | // static const foo_t x = {{0}}; | ||||
2317 | // because "i" is a subobject with non-literal initialization (due to the | ||||
2318 | // volatile member of the union). See: | ||||
2319 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 | ||||
2320 | // Therefore, we use the C++1y behavior. | ||||
2321 | if (This && Info.EvaluatingDecl == This->getLValueBase()) | ||||
2322 | return true; | ||||
2323 | |||||
2324 | // Prvalue constant expressions must be of literal types. | ||||
2325 | if (Info.getLangOpts().CPlusPlus11) | ||||
2326 | Info.FFDiag(E, diag::note_constexpr_nonliteral) | ||||
2327 | << E->getType(); | ||||
2328 | else | ||||
2329 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2330 | return false; | ||||
2331 | } | ||||
2332 | |||||
2333 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, | ||||
2334 | EvalInfo &Info, SourceLocation DiagLoc, | ||||
2335 | QualType Type, const APValue &Value, | ||||
2336 | ConstantExprKind Kind, | ||||
2337 | SourceLocation SubobjectLoc, | ||||
2338 | CheckedTemporaries &CheckedTemps) { | ||||
2339 | if (!Value.hasValue()) { | ||||
2340 | Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) | ||||
2341 | << true << Type; | ||||
2342 | if (SubobjectLoc.isValid()) | ||||
2343 | Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); | ||||
2344 | return false; | ||||
2345 | } | ||||
2346 | |||||
2347 | // We allow _Atomic(T) to be initialized from anything that T can be | ||||
2348 | // initialized from. | ||||
2349 | if (const AtomicType *AT = Type->getAs<AtomicType>()) | ||||
2350 | Type = AT->getValueType(); | ||||
2351 | |||||
2352 | // Core issue 1454: For a literal constant expression of array or class type, | ||||
2353 | // each subobject of its value shall have been initialized by a constant | ||||
2354 | // expression. | ||||
2355 | if (Value.isArray()) { | ||||
2356 | QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); | ||||
2357 | for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { | ||||
2358 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, | ||||
2359 | Value.getArrayInitializedElt(I), Kind, | ||||
2360 | SubobjectLoc, CheckedTemps)) | ||||
2361 | return false; | ||||
2362 | } | ||||
2363 | if (!Value.hasArrayFiller()) | ||||
2364 | return true; | ||||
2365 | return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, | ||||
2366 | Value.getArrayFiller(), Kind, SubobjectLoc, | ||||
2367 | CheckedTemps); | ||||
2368 | } | ||||
2369 | if (Value.isUnion() && Value.getUnionField()) { | ||||
2370 | return CheckEvaluationResult( | ||||
2371 | CERK, Info, DiagLoc, Value.getUnionField()->getType(), | ||||
2372 | Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), | ||||
2373 | CheckedTemps); | ||||
2374 | } | ||||
2375 | if (Value.isStruct()) { | ||||
2376 | RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); | ||||
2377 | if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
2378 | unsigned BaseIndex = 0; | ||||
2379 | for (const CXXBaseSpecifier &BS : CD->bases()) { | ||||
2380 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), | ||||
2381 | Value.getStructBase(BaseIndex), Kind, | ||||
2382 | BS.getBeginLoc(), CheckedTemps)) | ||||
2383 | return false; | ||||
2384 | ++BaseIndex; | ||||
2385 | } | ||||
2386 | } | ||||
2387 | for (const auto *I : RD->fields()) { | ||||
2388 | if (I->isUnnamedBitfield()) | ||||
2389 | continue; | ||||
2390 | |||||
2391 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), | ||||
2392 | Value.getStructField(I->getFieldIndex()), | ||||
2393 | Kind, I->getLocation(), CheckedTemps)) | ||||
2394 | return false; | ||||
2395 | } | ||||
2396 | } | ||||
2397 | |||||
2398 | if (Value.isLValue() && | ||||
2399 | CERK == CheckEvaluationResultKind::ConstantExpression) { | ||||
2400 | LValue LVal; | ||||
2401 | LVal.setFrom(Info.Ctx, Value); | ||||
2402 | return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, | ||||
2403 | CheckedTemps); | ||||
2404 | } | ||||
2405 | |||||
2406 | if (Value.isMemberPointer() && | ||||
2407 | CERK == CheckEvaluationResultKind::ConstantExpression) | ||||
2408 | return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); | ||||
2409 | |||||
2410 | // Everything else is fine. | ||||
2411 | return true; | ||||
2412 | } | ||||
2413 | |||||
2414 | /// Check that this core constant expression value is a valid value for a | ||||
2415 | /// constant expression. If not, report an appropriate diagnostic. Does not | ||||
2416 | /// check that the expression is of literal type. | ||||
2417 | static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, | ||||
2418 | QualType Type, const APValue &Value, | ||||
2419 | ConstantExprKind Kind) { | ||||
2420 | // Nothing to check for a constant expression of type 'cv void'. | ||||
2421 | if (Type->isVoidType()) | ||||
2422 | return true; | ||||
2423 | |||||
2424 | CheckedTemporaries CheckedTemps; | ||||
2425 | return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, | ||||
2426 | Info, DiagLoc, Type, Value, Kind, | ||||
2427 | SourceLocation(), CheckedTemps); | ||||
2428 | } | ||||
2429 | |||||
2430 | /// Check that this evaluated value is fully-initialized and can be loaded by | ||||
2431 | /// an lvalue-to-rvalue conversion. | ||||
2432 | static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, | ||||
2433 | QualType Type, const APValue &Value) { | ||||
2434 | CheckedTemporaries CheckedTemps; | ||||
2435 | return CheckEvaluationResult( | ||||
2436 | CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, | ||||
2437 | ConstantExprKind::Normal, SourceLocation(), CheckedTemps); | ||||
2438 | } | ||||
2439 | |||||
2440 | /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless | ||||
2441 | /// "the allocated storage is deallocated within the evaluation". | ||||
2442 | static bool CheckMemoryLeaks(EvalInfo &Info) { | ||||
2443 | if (!Info.HeapAllocs.empty()) { | ||||
2444 | // We can still fold to a constant despite a compile-time memory leak, | ||||
2445 | // so long as the heap allocation isn't referenced in the result (we check | ||||
2446 | // that in CheckConstantExpression). | ||||
2447 | Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, | ||||
2448 | diag::note_constexpr_memory_leak) | ||||
2449 | << unsigned(Info.HeapAllocs.size() - 1); | ||||
2450 | } | ||||
2451 | return true; | ||||
2452 | } | ||||
2453 | |||||
2454 | static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { | ||||
2455 | // A null base expression indicates a null pointer. These are always | ||||
2456 | // evaluatable, and they are false unless the offset is zero. | ||||
2457 | if (!Value.getLValueBase()) { | ||||
2458 | Result = !Value.getLValueOffset().isZero(); | ||||
2459 | return true; | ||||
2460 | } | ||||
2461 | |||||
2462 | // We have a non-null base. These are generally known to be true, but if it's | ||||
2463 | // a weak declaration it can be null at runtime. | ||||
2464 | Result = true; | ||||
2465 | const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); | ||||
2466 | return !Decl || !Decl->isWeak(); | ||||
2467 | } | ||||
2468 | |||||
2469 | static bool HandleConversionToBool(const APValue &Val, bool &Result) { | ||||
2470 | switch (Val.getKind()) { | ||||
2471 | case APValue::None: | ||||
2472 | case APValue::Indeterminate: | ||||
2473 | return false; | ||||
2474 | case APValue::Int: | ||||
2475 | Result = Val.getInt().getBoolValue(); | ||||
2476 | return true; | ||||
2477 | case APValue::FixedPoint: | ||||
2478 | Result = Val.getFixedPoint().getBoolValue(); | ||||
2479 | return true; | ||||
2480 | case APValue::Float: | ||||
2481 | Result = !Val.getFloat().isZero(); | ||||
2482 | return true; | ||||
2483 | case APValue::ComplexInt: | ||||
2484 | Result = Val.getComplexIntReal().getBoolValue() || | ||||
2485 | Val.getComplexIntImag().getBoolValue(); | ||||
2486 | return true; | ||||
2487 | case APValue::ComplexFloat: | ||||
2488 | Result = !Val.getComplexFloatReal().isZero() || | ||||
2489 | !Val.getComplexFloatImag().isZero(); | ||||
2490 | return true; | ||||
2491 | case APValue::LValue: | ||||
2492 | return EvalPointerValueAsBool(Val, Result); | ||||
2493 | case APValue::MemberPointer: | ||||
2494 | Result = Val.getMemberPointerDecl(); | ||||
2495 | return true; | ||||
2496 | case APValue::Vector: | ||||
2497 | case APValue::Array: | ||||
2498 | case APValue::Struct: | ||||
2499 | case APValue::Union: | ||||
2500 | case APValue::AddrLabelDiff: | ||||
2501 | return false; | ||||
2502 | } | ||||
2503 | |||||
2504 | llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2504); | ||||
2505 | } | ||||
2506 | |||||
2507 | static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, | ||||
2508 | EvalInfo &Info) { | ||||
2509 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2509, __extension__ __PRETTY_FUNCTION__)); | ||||
2510 | assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition")(static_cast <bool> (E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition" ) ? void (0) : __assert_fail ("E->isPRValue() && \"missing lvalue-to-rvalue conv in bool condition\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2510, __extension__ __PRETTY_FUNCTION__)); | ||||
2511 | APValue Val; | ||||
2512 | if (!Evaluate(Val, Info, E)) | ||||
2513 | return false; | ||||
2514 | return HandleConversionToBool(Val, Result); | ||||
2515 | } | ||||
2516 | |||||
2517 | template<typename T> | ||||
2518 | static bool HandleOverflow(EvalInfo &Info, const Expr *E, | ||||
2519 | const T &SrcValue, QualType DestType) { | ||||
2520 | Info.CCEDiag(E, diag::note_constexpr_overflow) | ||||
2521 | << SrcValue << DestType; | ||||
2522 | return Info.noteUndefinedBehavior(); | ||||
2523 | } | ||||
2524 | |||||
2525 | static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, | ||||
2526 | QualType SrcType, const APFloat &Value, | ||||
2527 | QualType DestType, APSInt &Result) { | ||||
2528 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); | ||||
2529 | // Determine whether we are converting to unsigned or signed. | ||||
2530 | bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); | ||||
2531 | |||||
2532 | Result = APSInt(DestWidth, !DestSigned); | ||||
2533 | bool ignored; | ||||
2534 | if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) | ||||
2535 | & APFloat::opInvalidOp) | ||||
2536 | return HandleOverflow(Info, E, Value, DestType); | ||||
2537 | return true; | ||||
2538 | } | ||||
2539 | |||||
2540 | /// Get rounding mode used for evaluation of the specified expression. | ||||
2541 | /// \param[out] DynamicRM Is set to true is the requested rounding mode is | ||||
2542 | /// dynamic. | ||||
2543 | /// If rounding mode is unknown at compile time, still try to evaluate the | ||||
2544 | /// expression. If the result is exact, it does not depend on rounding mode. | ||||
2545 | /// So return "tonearest" mode instead of "dynamic". | ||||
2546 | static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, | ||||
2547 | bool &DynamicRM) { | ||||
2548 | llvm::RoundingMode RM = | ||||
2549 | E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); | ||||
2550 | DynamicRM = (RM == llvm::RoundingMode::Dynamic); | ||||
2551 | if (DynamicRM) | ||||
2552 | RM = llvm::RoundingMode::NearestTiesToEven; | ||||
2553 | return RM; | ||||
2554 | } | ||||
2555 | |||||
2556 | /// Check if the given evaluation result is allowed for constant evaluation. | ||||
2557 | static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, | ||||
2558 | APFloat::opStatus St) { | ||||
2559 | // In a constant context, assume that any dynamic rounding mode or FP | ||||
2560 | // exception state matches the default floating-point environment. | ||||
2561 | if (Info.InConstantContext) | ||||
2562 | return true; | ||||
2563 | |||||
2564 | FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); | ||||
2565 | if ((St & APFloat::opInexact) && | ||||
2566 | FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { | ||||
2567 | // Inexact result means that it depends on rounding mode. If the requested | ||||
2568 | // mode is dynamic, the evaluation cannot be made in compile time. | ||||
2569 | Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); | ||||
2570 | return false; | ||||
2571 | } | ||||
2572 | |||||
2573 | if ((St != APFloat::opOK) && | ||||
2574 | (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || | ||||
2575 | FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || | ||||
2576 | FPO.getAllowFEnvAccess())) { | ||||
2577 | Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); | ||||
2578 | return false; | ||||
2579 | } | ||||
2580 | |||||
2581 | if ((St & APFloat::opStatus::opInvalidOp) && | ||||
2582 | FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { | ||||
2583 | // There is no usefully definable result. | ||||
2584 | Info.FFDiag(E); | ||||
2585 | return false; | ||||
2586 | } | ||||
2587 | |||||
2588 | // FIXME: if: | ||||
2589 | // - evaluation triggered other FP exception, and | ||||
2590 | // - exception mode is not "ignore", and | ||||
2591 | // - the expression being evaluated is not a part of global variable | ||||
2592 | // initializer, | ||||
2593 | // the evaluation probably need to be rejected. | ||||
2594 | return true; | ||||
2595 | } | ||||
2596 | |||||
2597 | static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, | ||||
2598 | QualType SrcType, QualType DestType, | ||||
2599 | APFloat &Result) { | ||||
2600 | assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E))(static_cast <bool> (isa<CastExpr>(E) || isa<CompoundAssignOperator >(E)) ? void (0) : __assert_fail ("isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2600, __extension__ __PRETTY_FUNCTION__)); | ||||
2601 | bool DynamicRM; | ||||
2602 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); | ||||
2603 | APFloat::opStatus St; | ||||
2604 | APFloat Value = Result; | ||||
2605 | bool ignored; | ||||
2606 | St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); | ||||
2607 | return checkFloatingPointResult(Info, E, St); | ||||
2608 | } | ||||
2609 | |||||
2610 | static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, | ||||
2611 | QualType DestType, QualType SrcType, | ||||
2612 | const APSInt &Value) { | ||||
2613 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); | ||||
2614 | // Figure out if this is a truncate, extend or noop cast. | ||||
2615 | // If the input is signed, do a sign extend, noop, or truncate. | ||||
2616 | APSInt Result = Value.extOrTrunc(DestWidth); | ||||
2617 | Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); | ||||
2618 | if (DestType->isBooleanType()) | ||||
2619 | Result = Value.getBoolValue(); | ||||
2620 | return Result; | ||||
2621 | } | ||||
2622 | |||||
2623 | static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, | ||||
2624 | const FPOptions FPO, | ||||
2625 | QualType SrcType, const APSInt &Value, | ||||
2626 | QualType DestType, APFloat &Result) { | ||||
2627 | Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); | ||||
2628 | APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), | ||||
2629 | APFloat::rmNearestTiesToEven); | ||||
2630 | if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && | ||||
2631 | FPO.isFPConstrained()) { | ||||
2632 | Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); | ||||
2633 | return false; | ||||
2634 | } | ||||
2635 | return true; | ||||
2636 | } | ||||
2637 | |||||
2638 | static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, | ||||
2639 | APValue &Value, const FieldDecl *FD) { | ||||
2640 | assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")(static_cast <bool> (FD->isBitField() && "truncateBitfieldValue on non-bitfield" ) ? void (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2640, __extension__ __PRETTY_FUNCTION__)); | ||||
2641 | |||||
2642 | if (!Value.isInt()) { | ||||
2643 | // Trying to store a pointer-cast-to-integer into a bitfield. | ||||
2644 | // FIXME: In this case, we should provide the diagnostic for casting | ||||
2645 | // a pointer to an integer. | ||||
2646 | assert(Value.isLValue() && "integral value neither int nor lvalue?")(static_cast <bool> (Value.isLValue() && "integral value neither int nor lvalue?" ) ? void (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2646, __extension__ __PRETTY_FUNCTION__)); | ||||
2647 | Info.FFDiag(E); | ||||
2648 | return false; | ||||
2649 | } | ||||
2650 | |||||
2651 | APSInt &Int = Value.getInt(); | ||||
2652 | unsigned OldBitWidth = Int.getBitWidth(); | ||||
2653 | unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); | ||||
2654 | if (NewBitWidth < OldBitWidth) | ||||
2655 | Int = Int.trunc(NewBitWidth).extend(OldBitWidth); | ||||
2656 | return true; | ||||
2657 | } | ||||
2658 | |||||
2659 | static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, | ||||
2660 | llvm::APInt &Res) { | ||||
2661 | APValue SVal; | ||||
2662 | if (!Evaluate(SVal, Info, E)) | ||||
2663 | return false; | ||||
2664 | if (SVal.isInt()) { | ||||
2665 | Res = SVal.getInt(); | ||||
2666 | return true; | ||||
2667 | } | ||||
2668 | if (SVal.isFloat()) { | ||||
2669 | Res = SVal.getFloat().bitcastToAPInt(); | ||||
2670 | return true; | ||||
2671 | } | ||||
2672 | if (SVal.isVector()) { | ||||
2673 | QualType VecTy = E->getType(); | ||||
2674 | unsigned VecSize = Info.Ctx.getTypeSize(VecTy); | ||||
2675 | QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); | ||||
2676 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); | ||||
2677 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); | ||||
2678 | Res = llvm::APInt::getNullValue(VecSize); | ||||
2679 | for (unsigned i = 0; i < SVal.getVectorLength(); i++) { | ||||
2680 | APValue &Elt = SVal.getVectorElt(i); | ||||
2681 | llvm::APInt EltAsInt; | ||||
2682 | if (Elt.isInt()) { | ||||
2683 | EltAsInt = Elt.getInt(); | ||||
2684 | } else if (Elt.isFloat()) { | ||||
2685 | EltAsInt = Elt.getFloat().bitcastToAPInt(); | ||||
2686 | } else { | ||||
2687 | // Don't try to handle vectors of anything other than int or float | ||||
2688 | // (not sure if it's possible to hit this case). | ||||
2689 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2690 | return false; | ||||
2691 | } | ||||
2692 | unsigned BaseEltSize = EltAsInt.getBitWidth(); | ||||
2693 | if (BigEndian) | ||||
2694 | Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); | ||||
2695 | else | ||||
2696 | Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); | ||||
2697 | } | ||||
2698 | return true; | ||||
2699 | } | ||||
2700 | // Give up if the input isn't an int, float, or vector. For example, we | ||||
2701 | // reject "(v4i16)(intptr_t)&a". | ||||
2702 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2703 | return false; | ||||
2704 | } | ||||
2705 | |||||
2706 | /// Perform the given integer operation, which is known to need at most BitWidth | ||||
2707 | /// bits, and check for overflow in the original type (if that type was not an | ||||
2708 | /// unsigned type). | ||||
2709 | template<typename Operation> | ||||
2710 | static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, | ||||
2711 | const APSInt &LHS, const APSInt &RHS, | ||||
2712 | unsigned BitWidth, Operation Op, | ||||
2713 | APSInt &Result) { | ||||
2714 | if (LHS.isUnsigned()) { | ||||
2715 | Result = Op(LHS, RHS); | ||||
2716 | return true; | ||||
2717 | } | ||||
2718 | |||||
2719 | APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); | ||||
2720 | Result = Value.trunc(LHS.getBitWidth()); | ||||
2721 | if (Result.extend(BitWidth) != Value) { | ||||
2722 | if (Info.checkingForUndefinedBehavior()) | ||||
2723 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | ||||
2724 | diag::warn_integer_constant_overflow) | ||||
2725 | << toString(Result, 10) << E->getType(); | ||||
2726 | return HandleOverflow(Info, E, Value, E->getType()); | ||||
2727 | } | ||||
2728 | return true; | ||||
2729 | } | ||||
2730 | |||||
2731 | /// Perform the given binary integer operation. | ||||
2732 | static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, | ||||
2733 | BinaryOperatorKind Opcode, APSInt RHS, | ||||
2734 | APSInt &Result) { | ||||
2735 | switch (Opcode) { | ||||
2736 | default: | ||||
2737 | Info.FFDiag(E); | ||||
2738 | return false; | ||||
2739 | case BO_Mul: | ||||
2740 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, | ||||
2741 | std::multiplies<APSInt>(), Result); | ||||
2742 | case BO_Add: | ||||
2743 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, | ||||
2744 | std::plus<APSInt>(), Result); | ||||
2745 | case BO_Sub: | ||||
2746 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, | ||||
2747 | std::minus<APSInt>(), Result); | ||||
2748 | case BO_And: Result = LHS & RHS; return true; | ||||
2749 | case BO_Xor: Result = LHS ^ RHS; return true; | ||||
2750 | case BO_Or: Result = LHS | RHS; return true; | ||||
2751 | case BO_Div: | ||||
2752 | case BO_Rem: | ||||
2753 | if (RHS == 0) { | ||||
2754 | Info.FFDiag(E, diag::note_expr_divide_by_zero); | ||||
2755 | return false; | ||||
2756 | } | ||||
2757 | Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); | ||||
2758 | // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports | ||||
2759 | // this operation and gives the two's complement result. | ||||
2760 | if (RHS.isNegative() && RHS.isAllOnesValue() && | ||||
2761 | LHS.isSigned() && LHS.isMinSignedValue()) | ||||
2762 | return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), | ||||
2763 | E->getType()); | ||||
2764 | return true; | ||||
2765 | case BO_Shl: { | ||||
2766 | if (Info.getLangOpts().OpenCL) | ||||
2767 | // OpenCL 6.3j: shift values are effectively % word size of LHS. | ||||
2768 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), | ||||
2769 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), | ||||
2770 | RHS.isUnsigned()); | ||||
2771 | else if (RHS.isSigned() && RHS.isNegative()) { | ||||
2772 | // During constant-folding, a negative shift is an opposite shift. Such | ||||
2773 | // a shift is not a constant expression. | ||||
2774 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; | ||||
2775 | RHS = -RHS; | ||||
2776 | goto shift_right; | ||||
2777 | } | ||||
2778 | shift_left: | ||||
2779 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of | ||||
2780 | // the shifted type. | ||||
2781 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); | ||||
2782 | if (SA != RHS) { | ||||
2783 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | ||||
2784 | << RHS << E->getType() << LHS.getBitWidth(); | ||||
2785 | } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { | ||||
2786 | // C++11 [expr.shift]p2: A signed left shift must have a non-negative | ||||
2787 | // operand, and must not overflow the corresponding unsigned type. | ||||
2788 | // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to | ||||
2789 | // E1 x 2^E2 module 2^N. | ||||
2790 | if (LHS.isNegative()) | ||||
2791 | Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; | ||||
2792 | else if (LHS.countLeadingZeros() < SA) | ||||
2793 | Info.CCEDiag(E, diag::note_constexpr_lshift_discards); | ||||
2794 | } | ||||
2795 | Result = LHS << SA; | ||||
2796 | return true; | ||||
2797 | } | ||||
2798 | case BO_Shr: { | ||||
2799 | if (Info.getLangOpts().OpenCL) | ||||
2800 | // OpenCL 6.3j: shift values are effectively % word size of LHS. | ||||
2801 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), | ||||
2802 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), | ||||
2803 | RHS.isUnsigned()); | ||||
2804 | else if (RHS.isSigned() && RHS.isNegative()) { | ||||
2805 | // During constant-folding, a negative shift is an opposite shift. Such a | ||||
2806 | // shift is not a constant expression. | ||||
2807 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; | ||||
2808 | RHS = -RHS; | ||||
2809 | goto shift_left; | ||||
2810 | } | ||||
2811 | shift_right: | ||||
2812 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of the | ||||
2813 | // shifted type. | ||||
2814 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); | ||||
2815 | if (SA != RHS) | ||||
2816 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | ||||
2817 | << RHS << E->getType() << LHS.getBitWidth(); | ||||
2818 | Result = LHS >> SA; | ||||
2819 | return true; | ||||
2820 | } | ||||
2821 | |||||
2822 | case BO_LT: Result = LHS < RHS; return true; | ||||
2823 | case BO_GT: Result = LHS > RHS; return true; | ||||
2824 | case BO_LE: Result = LHS <= RHS; return true; | ||||
2825 | case BO_GE: Result = LHS >= RHS; return true; | ||||
2826 | case BO_EQ: Result = LHS == RHS; return true; | ||||
2827 | case BO_NE: Result = LHS != RHS; return true; | ||||
2828 | case BO_Cmp: | ||||
2829 | llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2829); | ||||
2830 | } | ||||
2831 | } | ||||
2832 | |||||
2833 | /// Perform the given binary floating-point operation, in-place, on LHS. | ||||
2834 | static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, | ||||
2835 | APFloat &LHS, BinaryOperatorKind Opcode, | ||||
2836 | const APFloat &RHS) { | ||||
2837 | bool DynamicRM; | ||||
2838 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); | ||||
2839 | APFloat::opStatus St; | ||||
2840 | switch (Opcode) { | ||||
2841 | default: | ||||
2842 | Info.FFDiag(E); | ||||
2843 | return false; | ||||
2844 | case BO_Mul: | ||||
2845 | St = LHS.multiply(RHS, RM); | ||||
2846 | break; | ||||
2847 | case BO_Add: | ||||
2848 | St = LHS.add(RHS, RM); | ||||
2849 | break; | ||||
2850 | case BO_Sub: | ||||
2851 | St = LHS.subtract(RHS, RM); | ||||
2852 | break; | ||||
2853 | case BO_Div: | ||||
2854 | // [expr.mul]p4: | ||||
2855 | // If the second operand of / or % is zero the behavior is undefined. | ||||
2856 | if (RHS.isZero()) | ||||
2857 | Info.CCEDiag(E, diag::note_expr_divide_by_zero); | ||||
2858 | St = LHS.divide(RHS, RM); | ||||
2859 | break; | ||||
2860 | } | ||||
2861 | |||||
2862 | // [expr.pre]p4: | ||||
2863 | // If during the evaluation of an expression, the result is not | ||||
2864 | // mathematically defined [...], the behavior is undefined. | ||||
2865 | // FIXME: C++ rules require us to not conform to IEEE 754 here. | ||||
2866 | if (LHS.isNaN()) { | ||||
2867 | Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); | ||||
2868 | return Info.noteUndefinedBehavior(); | ||||
2869 | } | ||||
2870 | |||||
2871 | return checkFloatingPointResult(Info, E, St); | ||||
2872 | } | ||||
2873 | |||||
2874 | static bool handleLogicalOpForVector(const APInt &LHSValue, | ||||
2875 | BinaryOperatorKind Opcode, | ||||
2876 | const APInt &RHSValue, APInt &Result) { | ||||
2877 | bool LHS = (LHSValue != 0); | ||||
2878 | bool RHS = (RHSValue != 0); | ||||
2879 | |||||
2880 | if (Opcode == BO_LAnd) | ||||
2881 | Result = LHS && RHS; | ||||
2882 | else | ||||
2883 | Result = LHS || RHS; | ||||
2884 | return true; | ||||
2885 | } | ||||
2886 | static bool handleLogicalOpForVector(const APFloat &LHSValue, | ||||
2887 | BinaryOperatorKind Opcode, | ||||
2888 | const APFloat &RHSValue, APInt &Result) { | ||||
2889 | bool LHS = !LHSValue.isZero(); | ||||
2890 | bool RHS = !RHSValue.isZero(); | ||||
2891 | |||||
2892 | if (Opcode == BO_LAnd) | ||||
2893 | Result = LHS && RHS; | ||||
2894 | else | ||||
2895 | Result = LHS || RHS; | ||||
2896 | return true; | ||||
2897 | } | ||||
2898 | |||||
2899 | static bool handleLogicalOpForVector(const APValue &LHSValue, | ||||
2900 | BinaryOperatorKind Opcode, | ||||
2901 | const APValue &RHSValue, APInt &Result) { | ||||
2902 | // The result is always an int type, however operands match the first. | ||||
2903 | if (LHSValue.getKind() == APValue::Int) | ||||
2904 | return handleLogicalOpForVector(LHSValue.getInt(), Opcode, | ||||
2905 | RHSValue.getInt(), Result); | ||||
2906 | assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float && "Should be no other options") ? void (0) : __assert_fail ("LHSValue.getKind() == APValue::Float && \"Should be no other options\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2906, __extension__ __PRETTY_FUNCTION__)); | ||||
2907 | return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, | ||||
2908 | RHSValue.getFloat(), Result); | ||||
2909 | } | ||||
2910 | |||||
2911 | template <typename APTy> | ||||
2912 | static bool | ||||
2913 | handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, | ||||
2914 | const APTy &RHSValue, APInt &Result) { | ||||
2915 | switch (Opcode) { | ||||
2916 | default: | ||||
2917 | llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2917); | ||||
2918 | case BO_EQ: | ||||
2919 | Result = (LHSValue == RHSValue); | ||||
2920 | break; | ||||
2921 | case BO_NE: | ||||
2922 | Result = (LHSValue != RHSValue); | ||||
2923 | break; | ||||
2924 | case BO_LT: | ||||
2925 | Result = (LHSValue < RHSValue); | ||||
2926 | break; | ||||
2927 | case BO_GT: | ||||
2928 | Result = (LHSValue > RHSValue); | ||||
2929 | break; | ||||
2930 | case BO_LE: | ||||
2931 | Result = (LHSValue <= RHSValue); | ||||
2932 | break; | ||||
2933 | case BO_GE: | ||||
2934 | Result = (LHSValue >= RHSValue); | ||||
2935 | break; | ||||
2936 | } | ||||
2937 | |||||
2938 | return true; | ||||
2939 | } | ||||
2940 | |||||
2941 | static bool handleCompareOpForVector(const APValue &LHSValue, | ||||
2942 | BinaryOperatorKind Opcode, | ||||
2943 | const APValue &RHSValue, APInt &Result) { | ||||
2944 | // The result is always an int type, however operands match the first. | ||||
2945 | if (LHSValue.getKind() == APValue::Int) | ||||
2946 | return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, | ||||
2947 | RHSValue.getInt(), Result); | ||||
2948 | assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float && "Should be no other options") ? void (0) : __assert_fail ("LHSValue.getKind() == APValue::Float && \"Should be no other options\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2948, __extension__ __PRETTY_FUNCTION__)); | ||||
2949 | return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, | ||||
2950 | RHSValue.getFloat(), Result); | ||||
2951 | } | ||||
2952 | |||||
2953 | // Perform binary operations for vector types, in place on the LHS. | ||||
2954 | static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, | ||||
2955 | BinaryOperatorKind Opcode, | ||||
2956 | APValue &LHSValue, | ||||
2957 | const APValue &RHSValue) { | ||||
2958 | assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&(static_cast <bool> (Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2959, __extension__ __PRETTY_FUNCTION__)) | ||||
2959 | "Operation not supported on vector types")(static_cast <bool> (Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2959, __extension__ __PRETTY_FUNCTION__)); | ||||
2960 | |||||
2961 | const auto *VT = E->getType()->castAs<VectorType>(); | ||||
2962 | unsigned NumElements = VT->getNumElements(); | ||||
2963 | QualType EltTy = VT->getElementType(); | ||||
2964 | |||||
2965 | // In the cases (typically C as I've observed) where we aren't evaluating | ||||
2966 | // constexpr but are checking for cases where the LHS isn't yet evaluatable, | ||||
2967 | // just give up. | ||||
2968 | if (!LHSValue.isVector()) { | ||||
2969 | assert(LHSValue.isLValue() &&(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue" ) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2970, __extension__ __PRETTY_FUNCTION__)) | ||||
2970 | "A vector result that isn't a vector OR uncalculated LValue")(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue" ) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2970, __extension__ __PRETTY_FUNCTION__)); | ||||
2971 | Info.FFDiag(E); | ||||
2972 | return false; | ||||
2973 | } | ||||
2974 | |||||
2975 | assert(LHSValue.getVectorLength() == NumElements &&(static_cast <bool> (LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && "Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2976, __extension__ __PRETTY_FUNCTION__)) | ||||
2976 | RHSValue.getVectorLength() == NumElements && "Different vector sizes")(static_cast <bool> (LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && "Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 2976, __extension__ __PRETTY_FUNCTION__)); | ||||
2977 | |||||
2978 | SmallVector<APValue, 4> ResultElements; | ||||
2979 | |||||
2980 | for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { | ||||
2981 | APValue LHSElt = LHSValue.getVectorElt(EltNum); | ||||
2982 | APValue RHSElt = RHSValue.getVectorElt(EltNum); | ||||
2983 | |||||
2984 | if (EltTy->isIntegerType()) { | ||||
2985 | APSInt EltResult{Info.Ctx.getIntWidth(EltTy), | ||||
2986 | EltTy->isUnsignedIntegerType()}; | ||||
2987 | bool Success = true; | ||||
2988 | |||||
2989 | if (BinaryOperator::isLogicalOp(Opcode)) | ||||
2990 | Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); | ||||
2991 | else if (BinaryOperator::isComparisonOp(Opcode)) | ||||
2992 | Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); | ||||
2993 | else | ||||
2994 | Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, | ||||
2995 | RHSElt.getInt(), EltResult); | ||||
2996 | |||||
2997 | if (!Success) { | ||||
2998 | Info.FFDiag(E); | ||||
2999 | return false; | ||||
3000 | } | ||||
3001 | ResultElements.emplace_back(EltResult); | ||||
3002 | |||||
3003 | } else if (EltTy->isFloatingType()) { | ||||
3004 | assert(LHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3006, __extension__ __PRETTY_FUNCTION__)) | ||||
3005 | RHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3006, __extension__ __PRETTY_FUNCTION__)) | ||||
3006 | "Mismatched LHS/RHS/Result Type")(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3006, __extension__ __PRETTY_FUNCTION__)); | ||||
3007 | APFloat LHSFloat = LHSElt.getFloat(); | ||||
3008 | |||||
3009 | if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, | ||||
3010 | RHSElt.getFloat())) { | ||||
3011 | Info.FFDiag(E); | ||||
3012 | return false; | ||||
3013 | } | ||||
3014 | |||||
3015 | ResultElements.emplace_back(LHSFloat); | ||||
3016 | } | ||||
3017 | } | ||||
3018 | |||||
3019 | LHSValue = APValue(ResultElements.data(), ResultElements.size()); | ||||
3020 | return true; | ||||
3021 | } | ||||
3022 | |||||
3023 | /// Cast an lvalue referring to a base subobject to a derived class, by | ||||
3024 | /// truncating the lvalue's path to the given length. | ||||
3025 | static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, | ||||
3026 | const RecordDecl *TruncatedType, | ||||
3027 | unsigned TruncatedElements) { | ||||
3028 | SubobjectDesignator &D = Result.Designator; | ||||
3029 | |||||
3030 | // Check we actually point to a derived class object. | ||||
3031 | if (TruncatedElements == D.Entries.size()) | ||||
3032 | return true; | ||||
3033 | assert(TruncatedElements >= D.MostDerivedPathLength &&(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class") ? void (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3034, __extension__ __PRETTY_FUNCTION__)) | ||||
3034 | "not casting to a derived class")(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class") ? void (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3034, __extension__ __PRETTY_FUNCTION__)); | ||||
3035 | if (!Result.checkSubobject(Info, E, CSK_Derived)) | ||||
3036 | return false; | ||||
3037 | |||||
3038 | // Truncate the path to the subobject, and remove any derived-to-base offsets. | ||||
3039 | const RecordDecl *RD = TruncatedType; | ||||
3040 | for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { | ||||
3041 | if (RD->isInvalidDecl()) return false; | ||||
3042 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
3043 | const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); | ||||
3044 | if (isVirtualBaseClass(D.Entries[I])) | ||||
3045 | Result.Offset -= Layout.getVBaseClassOffset(Base); | ||||
3046 | else | ||||
3047 | Result.Offset -= Layout.getBaseClassOffset(Base); | ||||
3048 | RD = Base; | ||||
3049 | } | ||||
3050 | D.Entries.resize(TruncatedElements); | ||||
3051 | return true; | ||||
3052 | } | ||||
3053 | |||||
3054 | static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, | ||||
3055 | const CXXRecordDecl *Derived, | ||||
3056 | const CXXRecordDecl *Base, | ||||
3057 | const ASTRecordLayout *RL = nullptr) { | ||||
3058 | if (!RL) { | ||||
3059 | if (Derived->isInvalidDecl()) return false; | ||||
3060 | RL = &Info.Ctx.getASTRecordLayout(Derived); | ||||
3061 | } | ||||
3062 | |||||
3063 | Obj.getLValueOffset() += RL->getBaseClassOffset(Base); | ||||
3064 | Obj.addDecl(Info, E, Base, /*Virtual*/ false); | ||||
3065 | return true; | ||||
3066 | } | ||||
3067 | |||||
3068 | static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, | ||||
3069 | const CXXRecordDecl *DerivedDecl, | ||||
3070 | const CXXBaseSpecifier *Base) { | ||||
3071 | const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); | ||||
3072 | |||||
3073 | if (!Base->isVirtual()) | ||||
3074 | return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); | ||||
3075 | |||||
3076 | SubobjectDesignator &D = Obj.Designator; | ||||
3077 | if (D.Invalid) | ||||
3078 | return false; | ||||
3079 | |||||
3080 | // Extract most-derived object and corresponding type. | ||||
3081 | DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); | ||||
3082 | if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) | ||||
3083 | return false; | ||||
3084 | |||||
3085 | // Find the virtual base class. | ||||
3086 | if (DerivedDecl->isInvalidDecl()) return false; | ||||
3087 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); | ||||
3088 | Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); | ||||
3089 | Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); | ||||
3090 | return true; | ||||
3091 | } | ||||
3092 | |||||
3093 | static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, | ||||
3094 | QualType Type, LValue &Result) { | ||||
3095 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||
3096 | PathE = E->path_end(); | ||||
3097 | PathI != PathE; ++PathI) { | ||||
3098 | if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), | ||||
3099 | *PathI)) | ||||
3100 | return false; | ||||
3101 | Type = (*PathI)->getType(); | ||||
3102 | } | ||||
3103 | return true; | ||||
3104 | } | ||||
3105 | |||||
3106 | /// Cast an lvalue referring to a derived class to a known base subobject. | ||||
3107 | static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, | ||||
3108 | const CXXRecordDecl *DerivedRD, | ||||
3109 | const CXXRecordDecl *BaseRD) { | ||||
3110 | CXXBasePaths Paths(/*FindAmbiguities=*/false, | ||||
3111 | /*RecordPaths=*/true, /*DetectVirtual=*/false); | ||||
3112 | if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) | ||||
3113 | llvm_unreachable("Class must be derived from the passed in base class!")::llvm::llvm_unreachable_internal("Class must be derived from the passed in base class!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3113); | ||||
3114 | |||||
3115 | for (CXXBasePathElement &Elem : Paths.front()) | ||||
3116 | if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) | ||||
3117 | return false; | ||||
3118 | return true; | ||||
3119 | } | ||||
3120 | |||||
3121 | /// Update LVal to refer to the given field, which must be a member of the type | ||||
3122 | /// currently described by LVal. | ||||
3123 | static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, | ||||
3124 | const FieldDecl *FD, | ||||
3125 | const ASTRecordLayout *RL = nullptr) { | ||||
3126 | if (!RL) { | ||||
3127 | if (FD->getParent()->isInvalidDecl()) return false; | ||||
3128 | RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); | ||||
3129 | } | ||||
3130 | |||||
3131 | unsigned I = FD->getFieldIndex(); | ||||
3132 | LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); | ||||
3133 | LVal.addDecl(Info, E, FD); | ||||
3134 | return true; | ||||
3135 | } | ||||
3136 | |||||
3137 | /// Update LVal to refer to the given indirect field. | ||||
3138 | static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, | ||||
3139 | LValue &LVal, | ||||
3140 | const IndirectFieldDecl *IFD) { | ||||
3141 | for (const auto *C : IFD->chain()) | ||||
3142 | if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) | ||||
3143 | return false; | ||||
3144 | return true; | ||||
3145 | } | ||||
3146 | |||||
3147 | /// Get the size of the given type in char units. | ||||
3148 | static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, | ||||
3149 | QualType Type, CharUnits &Size) { | ||||
3150 | // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc | ||||
3151 | // extension. | ||||
3152 | if (Type->isVoidType() || Type->isFunctionType()) { | ||||
3153 | Size = CharUnits::One(); | ||||
3154 | return true; | ||||
3155 | } | ||||
3156 | |||||
3157 | if (Type->isDependentType()) { | ||||
3158 | Info.FFDiag(Loc); | ||||
3159 | return false; | ||||
3160 | } | ||||
3161 | |||||
3162 | if (!Type->isConstantSizeType()) { | ||||
3163 | // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. | ||||
3164 | // FIXME: Better diagnostic. | ||||
3165 | Info.FFDiag(Loc); | ||||
3166 | return false; | ||||
3167 | } | ||||
3168 | |||||
3169 | Size = Info.Ctx.getTypeSizeInChars(Type); | ||||
3170 | return true; | ||||
3171 | } | ||||
3172 | |||||
3173 | /// Update a pointer value to model pointer arithmetic. | ||||
3174 | /// \param Info - Information about the ongoing evaluation. | ||||
3175 | /// \param E - The expression being evaluated, for diagnostic purposes. | ||||
3176 | /// \param LVal - The pointer value to be updated. | ||||
3177 | /// \param EltTy - The pointee type represented by LVal. | ||||
3178 | /// \param Adjustment - The adjustment, in objects of type EltTy, to add. | ||||
3179 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, | ||||
3180 | LValue &LVal, QualType EltTy, | ||||
3181 | APSInt Adjustment) { | ||||
3182 | CharUnits SizeOfPointee; | ||||
3183 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) | ||||
3184 | return false; | ||||
3185 | |||||
3186 | LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); | ||||
3187 | return true; | ||||
3188 | } | ||||
3189 | |||||
3190 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, | ||||
3191 | LValue &LVal, QualType EltTy, | ||||
3192 | int64_t Adjustment) { | ||||
3193 | return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, | ||||
3194 | APSInt::get(Adjustment)); | ||||
3195 | } | ||||
3196 | |||||
3197 | /// Update an lvalue to refer to a component of a complex number. | ||||
3198 | /// \param Info - Information about the ongoing evaluation. | ||||
3199 | /// \param LVal - The lvalue to be updated. | ||||
3200 | /// \param EltTy - The complex number's component type. | ||||
3201 | /// \param Imag - False for the real component, true for the imaginary. | ||||
3202 | static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, | ||||
3203 | LValue &LVal, QualType EltTy, | ||||
3204 | bool Imag) { | ||||
3205 | if (Imag) { | ||||
3206 | CharUnits SizeOfComponent; | ||||
3207 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) | ||||
3208 | return false; | ||||
3209 | LVal.Offset += SizeOfComponent; | ||||
3210 | } | ||||
3211 | LVal.addComplex(Info, E, EltTy, Imag); | ||||
3212 | return true; | ||||
3213 | } | ||||
3214 | |||||
3215 | /// Try to evaluate the initializer for a variable declaration. | ||||
3216 | /// | ||||
3217 | /// \param Info Information about the ongoing evaluation. | ||||
3218 | /// \param E An expression to be used when printing diagnostics. | ||||
3219 | /// \param VD The variable whose initializer should be obtained. | ||||
3220 | /// \param Version The version of the variable within the frame. | ||||
3221 | /// \param Frame The frame in which the variable was created. Must be null | ||||
3222 | /// if this variable is not local to the evaluation. | ||||
3223 | /// \param Result Filled in with a pointer to the value of the variable. | ||||
3224 | static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, | ||||
3225 | const VarDecl *VD, CallStackFrame *Frame, | ||||
3226 | unsigned Version, APValue *&Result) { | ||||
3227 | APValue::LValueBase Base(VD, Frame
| ||||
3228 | |||||
3229 | // If this is a local variable, dig out its value. | ||||
3230 | if (Frame
| ||||
3231 | Result = Frame->getTemporary(VD, Version); | ||||
3232 | if (Result) | ||||
3233 | return true; | ||||
3234 | |||||
3235 | if (!isa<ParmVarDecl>(VD)) { | ||||
3236 | // Assume variables referenced within a lambda's call operator that were | ||||
3237 | // not declared within the call operator are captures and during checking | ||||
3238 | // of a potential constant expression, assume they are unknown constant | ||||
3239 | // expressions. | ||||
3240 | assert(isLambdaCallOperator(Frame->Callee) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3242, __extension__ __PRETTY_FUNCTION__)) | ||||
3241 | (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3242, __extension__ __PRETTY_FUNCTION__)) | ||||
3242 | "missing value for local variable")(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3242, __extension__ __PRETTY_FUNCTION__)); | ||||
3243 | if (Info.checkingPotentialConstantExpression()) | ||||
3244 | return false; | ||||
3245 | // FIXME: This diagnostic is bogus; we do support captures. Is this code | ||||
3246 | // still reachable at all? | ||||
3247 | Info.FFDiag(E->getBeginLoc(), | ||||
3248 | diag::note_unimplemented_constexpr_lambda_feature_ast) | ||||
3249 | << "captures not currently allowed"; | ||||
3250 | return false; | ||||
3251 | } | ||||
3252 | } | ||||
3253 | |||||
3254 | // If we're currently evaluating the initializer of this declaration, use that | ||||
3255 | // in-flight value. | ||||
3256 | if (Info.EvaluatingDecl == Base) { | ||||
3257 | Result = Info.EvaluatingDeclValue; | ||||
3258 | return true; | ||||
3259 | } | ||||
3260 | |||||
3261 | if (isa<ParmVarDecl>(VD)) { | ||||
3262 | // Assume parameters of a potential constant expression are usable in | ||||
3263 | // constant expressions. | ||||
3264 | if (!Info.checkingPotentialConstantExpression() || | ||||
3265 | !Info.CurrentCall->Callee || | ||||
| |||||
3266 | !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { | ||||
3267 | if (Info.getLangOpts().CPlusPlus11) { | ||||
3268 | Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) | ||||
3269 | << VD; | ||||
3270 | NoteLValueLocation(Info, Base); | ||||
3271 | } else { | ||||
3272 | Info.FFDiag(E); | ||||
3273 | } | ||||
3274 | } | ||||
3275 | return false; | ||||
3276 | } | ||||
3277 | |||||
3278 | // Dig out the initializer, and use the declaration which it's attached to. | ||||
3279 | // FIXME: We should eventually check whether the variable has a reachable | ||||
3280 | // initializing declaration. | ||||
3281 | const Expr *Init = VD->getAnyInitializer(VD); | ||||
3282 | if (!Init) { | ||||
3283 | // Don't diagnose during potential constant expression checking; an | ||||
3284 | // initializer might be added later. | ||||
3285 | if (!Info.checkingPotentialConstantExpression()) { | ||||
3286 | Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) | ||||
3287 | << VD; | ||||
3288 | NoteLValueLocation(Info, Base); | ||||
3289 | } | ||||
3290 | return false; | ||||
3291 | } | ||||
3292 | |||||
3293 | if (Init->isValueDependent()) { | ||||
3294 | // The DeclRefExpr is not value-dependent, but the variable it refers to | ||||
3295 | // has a value-dependent initializer. This should only happen in | ||||
3296 | // constant-folding cases, where the variable is not actually of a suitable | ||||
3297 | // type for use in a constant expression (otherwise the DeclRefExpr would | ||||
3298 | // have been value-dependent too), so diagnose that. | ||||
3299 | assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx))(static_cast <bool> (!VD->mightBeUsableInConstantExpressions (Info.Ctx)) ? void (0) : __assert_fail ("!VD->mightBeUsableInConstantExpressions(Info.Ctx)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3299, __extension__ __PRETTY_FUNCTION__)); | ||||
3300 | if (!Info.checkingPotentialConstantExpression()) { | ||||
3301 | Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 | ||||
3302 | ? diag::note_constexpr_ltor_non_constexpr | ||||
3303 | : diag::note_constexpr_ltor_non_integral, 1) | ||||
3304 | << VD << VD->getType(); | ||||
3305 | NoteLValueLocation(Info, Base); | ||||
3306 | } | ||||
3307 | return false; | ||||
3308 | } | ||||
3309 | |||||
3310 | // Check that we can fold the initializer. In C++, we will have already done | ||||
3311 | // this in the cases where it matters for conformance. | ||||
3312 | if (!VD->evaluateValue()) { | ||||
3313 | Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; | ||||
3314 | NoteLValueLocation(Info, Base); | ||||
3315 | return false; | ||||
3316 | } | ||||
3317 | |||||
3318 | // Check that the variable is actually usable in constant expressions. For a | ||||
3319 | // const integral variable or a reference, we might have a non-constant | ||||
3320 | // initializer that we can nonetheless evaluate the initializer for. Such | ||||
3321 | // variables are not usable in constant expressions. In C++98, the | ||||
3322 | // initializer also syntactically needs to be an ICE. | ||||
3323 | // | ||||
3324 | // FIXME: We don't diagnose cases that aren't potentially usable in constant | ||||
3325 | // expressions here; doing so would regress diagnostics for things like | ||||
3326 | // reading from a volatile constexpr variable. | ||||
3327 | if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && | ||||
3328 | VD->mightBeUsableInConstantExpressions(Info.Ctx)) || | ||||
3329 | ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && | ||||
3330 | !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { | ||||
3331 | Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; | ||||
3332 | NoteLValueLocation(Info, Base); | ||||
3333 | } | ||||
3334 | |||||
3335 | // Never use the initializer of a weak variable, not even for constant | ||||
3336 | // folding. We can't be sure that this is the definition that will be used. | ||||
3337 | if (VD->isWeak()) { | ||||
3338 | Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; | ||||
3339 | NoteLValueLocation(Info, Base); | ||||
3340 | return false; | ||||
3341 | } | ||||
3342 | |||||
3343 | Result = VD->getEvaluatedValue(); | ||||
3344 | return true; | ||||
3345 | } | ||||
3346 | |||||
3347 | /// Get the base index of the given base class within an APValue representing | ||||
3348 | /// the given derived class. | ||||
3349 | static unsigned getBaseIndex(const CXXRecordDecl *Derived, | ||||
3350 | const CXXRecordDecl *Base) { | ||||
3351 | Base = Base->getCanonicalDecl(); | ||||
3352 | unsigned Index = 0; | ||||
3353 | for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), | ||||
3354 | E = Derived->bases_end(); I != E; ++I, ++Index) { | ||||
3355 | if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) | ||||
3356 | return Index; | ||||
3357 | } | ||||
3358 | |||||
3359 | llvm_unreachable("base class missing from derived class's bases list")::llvm::llvm_unreachable_internal("base class missing from derived class's bases list" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3359); | ||||
3360 | } | ||||
3361 | |||||
3362 | /// Extract the value of a character from a string literal. | ||||
3363 | static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, | ||||
3364 | uint64_t Index) { | ||||
3365 | assert(!isa<SourceLocExpr>(Lit) &&(static_cast <bool> (!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3366, __extension__ __PRETTY_FUNCTION__)) | ||||
3366 | "SourceLocExpr should have already been converted to a StringLiteral")(static_cast <bool> (!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3366, __extension__ __PRETTY_FUNCTION__)); | ||||
3367 | |||||
3368 | // FIXME: Support MakeStringConstant | ||||
3369 | if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { | ||||
3370 | std::string Str; | ||||
3371 | Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); | ||||
3372 | assert(Index <= Str.size() && "Index too large")(static_cast <bool> (Index <= Str.size() && "Index too large" ) ? void (0) : __assert_fail ("Index <= Str.size() && \"Index too large\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3372, __extension__ __PRETTY_FUNCTION__)); | ||||
3373 | return APSInt::getUnsigned(Str.c_str()[Index]); | ||||
3374 | } | ||||
3375 | |||||
3376 | if (auto PE = dyn_cast<PredefinedExpr>(Lit)) | ||||
3377 | Lit = PE->getFunctionName(); | ||||
3378 | const StringLiteral *S = cast<StringLiteral>(Lit); | ||||
3379 | const ConstantArrayType *CAT = | ||||
3380 | Info.Ctx.getAsConstantArrayType(S->getType()); | ||||
3381 | assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array" ) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3381, __extension__ __PRETTY_FUNCTION__)); | ||||
3382 | QualType CharType = CAT->getElementType(); | ||||
3383 | assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() && "unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3383, __extension__ __PRETTY_FUNCTION__)); | ||||
3384 | |||||
3385 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), | ||||
3386 | CharType->isUnsignedIntegerType()); | ||||
3387 | if (Index < S->getLength()) | ||||
3388 | Value = S->getCodeUnit(Index); | ||||
3389 | return Value; | ||||
3390 | } | ||||
3391 | |||||
3392 | // Expand a string literal into an array of characters. | ||||
3393 | // | ||||
3394 | // FIXME: This is inefficient; we should probably introduce something similar | ||||
3395 | // to the LLVM ConstantDataArray to make this cheaper. | ||||
3396 | static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, | ||||
3397 | APValue &Result, | ||||
3398 | QualType AllocType = QualType()) { | ||||
3399 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( | ||||
3400 | AllocType.isNull() ? S->getType() : AllocType); | ||||
3401 | assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array" ) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3401, __extension__ __PRETTY_FUNCTION__)); | ||||
3402 | QualType CharType = CAT->getElementType(); | ||||
3403 | assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() && "unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3403, __extension__ __PRETTY_FUNCTION__)); | ||||
3404 | |||||
3405 | unsigned Elts = CAT->getSize().getZExtValue(); | ||||
3406 | Result = APValue(APValue::UninitArray(), | ||||
3407 | std::min(S->getLength(), Elts), Elts); | ||||
3408 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), | ||||
3409 | CharType->isUnsignedIntegerType()); | ||||
3410 | if (Result.hasArrayFiller()) | ||||
3411 | Result.getArrayFiller() = APValue(Value); | ||||
3412 | for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { | ||||
3413 | Value = S->getCodeUnit(I); | ||||
3414 | Result.getArrayInitializedElt(I) = APValue(Value); | ||||
3415 | } | ||||
3416 | } | ||||
3417 | |||||
3418 | // Expand an array so that it has more than Index filled elements. | ||||
3419 | static void expandArray(APValue &Array, unsigned Index) { | ||||
3420 | unsigned Size = Array.getArraySize(); | ||||
3421 | assert(Index < Size)(static_cast <bool> (Index < Size) ? void (0) : __assert_fail ("Index < Size", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3421, __extension__ __PRETTY_FUNCTION__)); | ||||
3422 | |||||
3423 | // Always at least double the number of elements for which we store a value. | ||||
3424 | unsigned OldElts = Array.getArrayInitializedElts(); | ||||
3425 | unsigned NewElts = std::max(Index+1, OldElts * 2); | ||||
3426 | NewElts = std::min(Size, std::max(NewElts, 8u)); | ||||
3427 | |||||
3428 | // Copy the data across. | ||||
3429 | APValue NewValue(APValue::UninitArray(), NewElts, Size); | ||||
3430 | for (unsigned I = 0; I != OldElts; ++I) | ||||
3431 | NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); | ||||
3432 | for (unsigned I = OldElts; I != NewElts; ++I) | ||||
3433 | NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); | ||||
3434 | if (NewValue.hasArrayFiller()) | ||||
3435 | NewValue.getArrayFiller() = Array.getArrayFiller(); | ||||
3436 | Array.swap(NewValue); | ||||
3437 | } | ||||
3438 | |||||
3439 | /// Determine whether a type would actually be read by an lvalue-to-rvalue | ||||
3440 | /// conversion. If it's of class type, we may assume that the copy operation | ||||
3441 | /// is trivial. Note that this is never true for a union type with fields | ||||
3442 | /// (because the copy always "reads" the active member) and always true for | ||||
3443 | /// a non-class type. | ||||
3444 | static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); | ||||
3445 | static bool isReadByLvalueToRvalueConversion(QualType T) { | ||||
3446 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||
3447 | return !RD || isReadByLvalueToRvalueConversion(RD); | ||||
3448 | } | ||||
3449 | static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { | ||||
3450 | // FIXME: A trivial copy of a union copies the object representation, even if | ||||
3451 | // the union is empty. | ||||
3452 | if (RD->isUnion()) | ||||
3453 | return !RD->field_empty(); | ||||
3454 | if (RD->isEmpty()) | ||||
3455 | return false; | ||||
3456 | |||||
3457 | for (auto *Field : RD->fields()) | ||||
3458 | if (!Field->isUnnamedBitfield() && | ||||
3459 | isReadByLvalueToRvalueConversion(Field->getType())) | ||||
3460 | return true; | ||||
3461 | |||||
3462 | for (auto &BaseSpec : RD->bases()) | ||||
3463 | if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) | ||||
3464 | return true; | ||||
3465 | |||||
3466 | return false; | ||||
3467 | } | ||||
3468 | |||||
3469 | /// Diagnose an attempt to read from any unreadable field within the specified | ||||
3470 | /// type, which might be a class type. | ||||
3471 | static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, | ||||
3472 | QualType T) { | ||||
3473 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||
3474 | if (!RD) | ||||
3475 | return false; | ||||
3476 | |||||
3477 | if (!RD->hasMutableFields()) | ||||
3478 | return false; | ||||
3479 | |||||
3480 | for (auto *Field : RD->fields()) { | ||||
3481 | // If we're actually going to read this field in some way, then it can't | ||||
3482 | // be mutable. If we're in a union, then assigning to a mutable field | ||||
3483 | // (even an empty one) can change the active member, so that's not OK. | ||||
3484 | // FIXME: Add core issue number for the union case. | ||||
3485 | if (Field->isMutable() && | ||||
3486 | (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { | ||||
3487 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; | ||||
3488 | Info.Note(Field->getLocation(), diag::note_declared_at); | ||||
3489 | return true; | ||||
3490 | } | ||||
3491 | |||||
3492 | if (diagnoseMutableFields(Info, E, AK, Field->getType())) | ||||
3493 | return true; | ||||
3494 | } | ||||
3495 | |||||
3496 | for (auto &BaseSpec : RD->bases()) | ||||
3497 | if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) | ||||
3498 | return true; | ||||
3499 | |||||
3500 | // All mutable fields were empty, and thus not actually read. | ||||
3501 | return false; | ||||
3502 | } | ||||
3503 | |||||
3504 | static bool lifetimeStartedInEvaluation(EvalInfo &Info, | ||||
3505 | APValue::LValueBase Base, | ||||
3506 | bool MutableSubobject = false) { | ||||
3507 | // A temporary or transient heap allocation we created. | ||||
3508 | if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) | ||||
3509 | return true; | ||||
3510 | |||||
3511 | switch (Info.IsEvaluatingDecl) { | ||||
3512 | case EvalInfo::EvaluatingDeclKind::None: | ||||
3513 | return false; | ||||
3514 | |||||
3515 | case EvalInfo::EvaluatingDeclKind::Ctor: | ||||
3516 | // The variable whose initializer we're evaluating. | ||||
3517 | if (Info.EvaluatingDecl == Base) | ||||
3518 | return true; | ||||
3519 | |||||
3520 | // A temporary lifetime-extended by the variable whose initializer we're | ||||
3521 | // evaluating. | ||||
3522 | if (auto *BaseE = Base.dyn_cast<const Expr *>()) | ||||
3523 | if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) | ||||
3524 | return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); | ||||
3525 | return false; | ||||
3526 | |||||
3527 | case EvalInfo::EvaluatingDeclKind::Dtor: | ||||
3528 | // C++2a [expr.const]p6: | ||||
3529 | // [during constant destruction] the lifetime of a and its non-mutable | ||||
3530 | // subobjects (but not its mutable subobjects) [are] considered to start | ||||
3531 | // within e. | ||||
3532 | if (MutableSubobject || Base != Info.EvaluatingDecl) | ||||
3533 | return false; | ||||
3534 | // FIXME: We can meaningfully extend this to cover non-const objects, but | ||||
3535 | // we will need special handling: we should be able to access only | ||||
3536 | // subobjects of such objects that are themselves declared const. | ||||
3537 | QualType T = getType(Base); | ||||
3538 | return T.isConstQualified() || T->isReferenceType(); | ||||
3539 | } | ||||
3540 | |||||
3541 | llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3541); | ||||
3542 | } | ||||
3543 | |||||
3544 | namespace { | ||||
3545 | /// A handle to a complete object (an object that is not a subobject of | ||||
3546 | /// another object). | ||||
3547 | struct CompleteObject { | ||||
3548 | /// The identity of the object. | ||||
3549 | APValue::LValueBase Base; | ||||
3550 | /// The value of the complete object. | ||||
3551 | APValue *Value; | ||||
3552 | /// The type of the complete object. | ||||
3553 | QualType Type; | ||||
3554 | |||||
3555 | CompleteObject() : Value(nullptr) {} | ||||
3556 | CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) | ||||
3557 | : Base(Base), Value(Value), Type(Type) {} | ||||
3558 | |||||
3559 | bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { | ||||
3560 | // If this isn't a "real" access (eg, if it's just accessing the type | ||||
3561 | // info), allow it. We assume the type doesn't change dynamically for | ||||
3562 | // subobjects of constexpr objects (even though we'd hit UB here if it | ||||
3563 | // did). FIXME: Is this right? | ||||
3564 | if (!isAnyAccess(AK)) | ||||
3565 | return true; | ||||
3566 | |||||
3567 | // In C++14 onwards, it is permitted to read a mutable member whose | ||||
3568 | // lifetime began within the evaluation. | ||||
3569 | // FIXME: Should we also allow this in C++11? | ||||
3570 | if (!Info.getLangOpts().CPlusPlus14) | ||||
3571 | return false; | ||||
3572 | return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); | ||||
3573 | } | ||||
3574 | |||||
3575 | explicit operator bool() const { return !Type.isNull(); } | ||||
3576 | }; | ||||
3577 | } // end anonymous namespace | ||||
3578 | |||||
3579 | static QualType getSubobjectType(QualType ObjType, QualType SubobjType, | ||||
3580 | bool IsMutable = false) { | ||||
3581 | // C++ [basic.type.qualifier]p1: | ||||
3582 | // - A const object is an object of type const T or a non-mutable subobject | ||||
3583 | // of a const object. | ||||
3584 | if (ObjType.isConstQualified() && !IsMutable) | ||||
3585 | SubobjType.addConst(); | ||||
3586 | // - A volatile object is an object of type const T or a subobject of a | ||||
3587 | // volatile object. | ||||
3588 | if (ObjType.isVolatileQualified()) | ||||
3589 | SubobjType.addVolatile(); | ||||
3590 | return SubobjType; | ||||
3591 | } | ||||
3592 | |||||
3593 | /// Find the designated sub-object of an rvalue. | ||||
3594 | template<typename SubobjectHandler> | ||||
3595 | typename SubobjectHandler::result_type | ||||
3596 | findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, | ||||
3597 | const SubobjectDesignator &Sub, SubobjectHandler &handler) { | ||||
3598 | if (Sub.Invalid) | ||||
3599 | // A diagnostic will have already been produced. | ||||
3600 | return handler.failed(); | ||||
3601 | if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { | ||||
3602 | if (Info.getLangOpts().CPlusPlus11) | ||||
3603 | Info.FFDiag(E, Sub.isOnePastTheEnd() | ||||
3604 | ? diag::note_constexpr_access_past_end | ||||
3605 | : diag::note_constexpr_access_unsized_array) | ||||
3606 | << handler.AccessKind; | ||||
3607 | else | ||||
3608 | Info.FFDiag(E); | ||||
3609 | return handler.failed(); | ||||
3610 | } | ||||
3611 | |||||
3612 | APValue *O = Obj.Value; | ||||
3613 | QualType ObjType = Obj.Type; | ||||
3614 | const FieldDecl *LastField = nullptr; | ||||
3615 | const FieldDecl *VolatileField = nullptr; | ||||
3616 | |||||
3617 | // Walk the designator's path to find the subobject. | ||||
3618 | for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { | ||||
3619 | // Reading an indeterminate value is undefined, but assigning over one is OK. | ||||
3620 | if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || | ||||
3621 | (O->isIndeterminate() && | ||||
3622 | !isValidIndeterminateAccess(handler.AccessKind))) { | ||||
3623 | if (!Info.checkingPotentialConstantExpression()) | ||||
3624 | Info.FFDiag(E, diag::note_constexpr_access_uninit) | ||||
3625 | << handler.AccessKind << O->isIndeterminate(); | ||||
3626 | return handler.failed(); | ||||
3627 | } | ||||
3628 | |||||
3629 | // C++ [class.ctor]p5, C++ [class.dtor]p5: | ||||
3630 | // const and volatile semantics are not applied on an object under | ||||
3631 | // {con,de}struction. | ||||
3632 | if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && | ||||
3633 | ObjType->isRecordType() && | ||||
3634 | Info.isEvaluatingCtorDtor( | ||||
3635 | Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), | ||||
3636 | Sub.Entries.begin() + I)) != | ||||
3637 | ConstructionPhase::None) { | ||||
3638 | ObjType = Info.Ctx.getCanonicalType(ObjType); | ||||
3639 | ObjType.removeLocalConst(); | ||||
3640 | ObjType.removeLocalVolatile(); | ||||
3641 | } | ||||
3642 | |||||
3643 | // If this is our last pass, check that the final object type is OK. | ||||
3644 | if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { | ||||
3645 | // Accesses to volatile objects are prohibited. | ||||
3646 | if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { | ||||
3647 | if (Info.getLangOpts().CPlusPlus) { | ||||
3648 | int DiagKind; | ||||
3649 | SourceLocation Loc; | ||||
3650 | const NamedDecl *Decl = nullptr; | ||||
3651 | if (VolatileField) { | ||||
3652 | DiagKind = 2; | ||||
3653 | Loc = VolatileField->getLocation(); | ||||
3654 | Decl = VolatileField; | ||||
3655 | } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { | ||||
3656 | DiagKind = 1; | ||||
3657 | Loc = VD->getLocation(); | ||||
3658 | Decl = VD; | ||||
3659 | } else { | ||||
3660 | DiagKind = 0; | ||||
3661 | if (auto *E = Obj.Base.dyn_cast<const Expr *>()) | ||||
3662 | Loc = E->getExprLoc(); | ||||
3663 | } | ||||
3664 | Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) | ||||
3665 | << handler.AccessKind << DiagKind << Decl; | ||||
3666 | Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; | ||||
3667 | } else { | ||||
3668 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
3669 | } | ||||
3670 | return handler.failed(); | ||||
3671 | } | ||||
3672 | |||||
3673 | // If we are reading an object of class type, there may still be more | ||||
3674 | // things we need to check: if there are any mutable subobjects, we | ||||
3675 | // cannot perform this read. (This only happens when performing a trivial | ||||
3676 | // copy or assignment.) | ||||
3677 | if (ObjType->isRecordType() && | ||||
3678 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && | ||||
3679 | diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) | ||||
3680 | return handler.failed(); | ||||
3681 | } | ||||
3682 | |||||
3683 | if (I == N) { | ||||
3684 | if (!handler.found(*O, ObjType)) | ||||
3685 | return false; | ||||
3686 | |||||
3687 | // If we modified a bit-field, truncate it to the right width. | ||||
3688 | if (isModification(handler.AccessKind) && | ||||
3689 | LastField && LastField->isBitField() && | ||||
3690 | !truncateBitfieldValue(Info, E, *O, LastField)) | ||||
3691 | return false; | ||||
3692 | |||||
3693 | return true; | ||||
3694 | } | ||||
3695 | |||||
3696 | LastField = nullptr; | ||||
3697 | if (ObjType->isArrayType()) { | ||||
3698 | // Next subobject is an array element. | ||||
3699 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); | ||||
3700 | assert(CAT && "vla in literal type?")(static_cast <bool> (CAT && "vla in literal type?" ) ? void (0) : __assert_fail ("CAT && \"vla in literal type?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3700, __extension__ __PRETTY_FUNCTION__)); | ||||
3701 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); | ||||
3702 | if (CAT->getSize().ule(Index)) { | ||||
3703 | // Note, it should not be possible to form a pointer with a valid | ||||
3704 | // designator which points more than one past the end of the array. | ||||
3705 | if (Info.getLangOpts().CPlusPlus11) | ||||
3706 | Info.FFDiag(E, diag::note_constexpr_access_past_end) | ||||
3707 | << handler.AccessKind; | ||||
3708 | else | ||||
3709 | Info.FFDiag(E); | ||||
3710 | return handler.failed(); | ||||
3711 | } | ||||
3712 | |||||
3713 | ObjType = CAT->getElementType(); | ||||
3714 | |||||
3715 | if (O->getArrayInitializedElts() > Index) | ||||
3716 | O = &O->getArrayInitializedElt(Index); | ||||
3717 | else if (!isRead(handler.AccessKind)) { | ||||
3718 | expandArray(*O, Index); | ||||
3719 | O = &O->getArrayInitializedElt(Index); | ||||
3720 | } else | ||||
3721 | O = &O->getArrayFiller(); | ||||
3722 | } else if (ObjType->isAnyComplexType()) { | ||||
3723 | // Next subobject is a complex number. | ||||
3724 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); | ||||
3725 | if (Index > 1) { | ||||
3726 | if (Info.getLangOpts().CPlusPlus11) | ||||
3727 | Info.FFDiag(E, diag::note_constexpr_access_past_end) | ||||
3728 | << handler.AccessKind; | ||||
3729 | else | ||||
3730 | Info.FFDiag(E); | ||||
3731 | return handler.failed(); | ||||
3732 | } | ||||
3733 | |||||
3734 | ObjType = getSubobjectType( | ||||
3735 | ObjType, ObjType->castAs<ComplexType>()->getElementType()); | ||||
3736 | |||||
3737 | assert(I == N - 1 && "extracting subobject of scalar?")(static_cast <bool> (I == N - 1 && "extracting subobject of scalar?" ) ? void (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3737, __extension__ __PRETTY_FUNCTION__)); | ||||
3738 | if (O->isComplexInt()) { | ||||
3739 | return handler.found(Index ? O->getComplexIntImag() | ||||
3740 | : O->getComplexIntReal(), ObjType); | ||||
3741 | } else { | ||||
3742 | assert(O->isComplexFloat())(static_cast <bool> (O->isComplexFloat()) ? void (0) : __assert_fail ("O->isComplexFloat()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3742, __extension__ __PRETTY_FUNCTION__)); | ||||
3743 | return handler.found(Index ? O->getComplexFloatImag() | ||||
3744 | : O->getComplexFloatReal(), ObjType); | ||||
3745 | } | ||||
3746 | } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { | ||||
3747 | if (Field->isMutable() && | ||||
3748 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { | ||||
3749 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) | ||||
3750 | << handler.AccessKind << Field; | ||||
3751 | Info.Note(Field->getLocation(), diag::note_declared_at); | ||||
3752 | return handler.failed(); | ||||
3753 | } | ||||
3754 | |||||
3755 | // Next subobject is a class, struct or union field. | ||||
3756 | RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); | ||||
3757 | if (RD->isUnion()) { | ||||
3758 | const FieldDecl *UnionField = O->getUnionField(); | ||||
3759 | if (!UnionField || | ||||
3760 | UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { | ||||
3761 | if (I == N - 1 && handler.AccessKind == AK_Construct) { | ||||
3762 | // Placement new onto an inactive union member makes it active. | ||||
3763 | O->setUnion(Field, APValue()); | ||||
3764 | } else { | ||||
3765 | // FIXME: If O->getUnionValue() is absent, report that there's no | ||||
3766 | // active union member rather than reporting the prior active union | ||||
3767 | // member. We'll need to fix nullptr_t to not use APValue() as its | ||||
3768 | // representation first. | ||||
3769 | Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) | ||||
3770 | << handler.AccessKind << Field << !UnionField << UnionField; | ||||
3771 | return handler.failed(); | ||||
3772 | } | ||||
3773 | } | ||||
3774 | O = &O->getUnionValue(); | ||||
3775 | } else | ||||
3776 | O = &O->getStructField(Field->getFieldIndex()); | ||||
3777 | |||||
3778 | ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); | ||||
3779 | LastField = Field; | ||||
3780 | if (Field->getType().isVolatileQualified()) | ||||
3781 | VolatileField = Field; | ||||
3782 | } else { | ||||
3783 | // Next subobject is a base class. | ||||
3784 | const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); | ||||
3785 | const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); | ||||
3786 | O = &O->getStructBase(getBaseIndex(Derived, Base)); | ||||
3787 | |||||
3788 | ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); | ||||
3789 | } | ||||
3790 | } | ||||
3791 | } | ||||
3792 | |||||
3793 | namespace { | ||||
3794 | struct ExtractSubobjectHandler { | ||||
3795 | EvalInfo &Info; | ||||
3796 | const Expr *E; | ||||
3797 | APValue &Result; | ||||
3798 | const AccessKinds AccessKind; | ||||
3799 | |||||
3800 | typedef bool result_type; | ||||
3801 | bool failed() { return false; } | ||||
3802 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
3803 | Result = Subobj; | ||||
3804 | if (AccessKind == AK_ReadObjectRepresentation) | ||||
3805 | return true; | ||||
3806 | return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); | ||||
3807 | } | ||||
3808 | bool found(APSInt &Value, QualType SubobjType) { | ||||
3809 | Result = APValue(Value); | ||||
3810 | return true; | ||||
3811 | } | ||||
3812 | bool found(APFloat &Value, QualType SubobjType) { | ||||
3813 | Result = APValue(Value); | ||||
3814 | return true; | ||||
3815 | } | ||||
3816 | }; | ||||
3817 | } // end anonymous namespace | ||||
3818 | |||||
3819 | /// Extract the designated sub-object of an rvalue. | ||||
3820 | static bool extractSubobject(EvalInfo &Info, const Expr *E, | ||||
3821 | const CompleteObject &Obj, | ||||
3822 | const SubobjectDesignator &Sub, APValue &Result, | ||||
3823 | AccessKinds AK = AK_Read) { | ||||
3824 | assert(AK == AK_Read || AK == AK_ReadObjectRepresentation)(static_cast <bool> (AK == AK_Read || AK == AK_ReadObjectRepresentation ) ? void (0) : __assert_fail ("AK == AK_Read || AK == AK_ReadObjectRepresentation" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 3824, __extension__ __PRETTY_FUNCTION__)); | ||||
3825 | ExtractSubobjectHandler Handler = {Info, E, Result, AK}; | ||||
3826 | return findSubobject(Info, E, Obj, Sub, Handler); | ||||
3827 | } | ||||
3828 | |||||
3829 | namespace { | ||||
3830 | struct ModifySubobjectHandler { | ||||
3831 | EvalInfo &Info; | ||||
3832 | APValue &NewVal; | ||||
3833 | const Expr *E; | ||||
3834 | |||||
3835 | typedef bool result_type; | ||||
3836 | static const AccessKinds AccessKind = AK_Assign; | ||||
3837 | |||||
3838 | bool checkConst(QualType QT) { | ||||
3839 | // Assigning to a const object has undefined behavior. | ||||
3840 | if (QT.isConstQualified()) { | ||||
3841 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||
3842 | return false; | ||||
3843 | } | ||||
3844 | return true; | ||||
3845 | } | ||||
3846 | |||||
3847 | bool failed() { return false; } | ||||
3848 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
3849 | if (!checkConst(SubobjType)) | ||||
3850 | return false; | ||||
3851 | // We've been given ownership of NewVal, so just swap it in. | ||||
3852 | Subobj.swap(NewVal); | ||||
3853 | return true; | ||||
3854 | } | ||||
3855 | bool found(APSInt &Value, QualType SubobjType) { | ||||
3856 | if (!checkConst(SubobjType)) | ||||
3857 | return false; | ||||
3858 | if (!NewVal.isInt()) { | ||||
3859 | // Maybe trying to write a cast pointer value into a complex? | ||||
3860 | Info.FFDiag(E); | ||||
3861 | return false; | ||||
3862 | } | ||||
3863 | Value = NewVal.getInt(); | ||||
3864 | return true; | ||||
3865 | } | ||||
3866 | bool found(APFloat &Value, QualType SubobjType) { | ||||
3867 | if (!checkConst(SubobjType)) | ||||
3868 | return false; | ||||
3869 | Value = NewVal.getFloat(); | ||||
3870 | return true; | ||||
3871 | } | ||||
3872 | }; | ||||
3873 | } // end anonymous namespace | ||||
3874 | |||||
3875 | const AccessKinds ModifySubobjectHandler::AccessKind; | ||||
3876 | |||||
3877 | /// Update the designated sub-object of an rvalue to the given value. | ||||
3878 | static bool modifySubobject(EvalInfo &Info, const Expr *E, | ||||
3879 | const CompleteObject &Obj, | ||||
3880 | const SubobjectDesignator &Sub, | ||||
3881 | APValue &NewVal) { | ||||
3882 | ModifySubobjectHandler Handler = { Info, NewVal, E }; | ||||
3883 | return findSubobject(Info, E, Obj, Sub, Handler); | ||||
3884 | } | ||||
3885 | |||||
3886 | /// Find the position where two subobject designators diverge, or equivalently | ||||
3887 | /// the length of the common initial subsequence. | ||||
3888 | static unsigned FindDesignatorMismatch(QualType ObjType, | ||||
3889 | const SubobjectDesignator &A, | ||||
3890 | const SubobjectDesignator &B, | ||||
3891 | bool &WasArrayIndex) { | ||||
3892 | unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); | ||||
3893 | for (/**/; I != N; ++I) { | ||||
3894 | if (!ObjType.isNull() && | ||||
3895 | (ObjType->isArrayType() || ObjType->isAnyComplexType())) { | ||||
3896 | // Next subobject is an array element. | ||||
3897 | if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { | ||||
3898 | WasArrayIndex = true; | ||||
3899 | return I; | ||||
3900 | } | ||||
3901 | if (ObjType->isAnyComplexType()) | ||||
3902 | ObjType = ObjType->castAs<ComplexType>()->getElementType(); | ||||
3903 | else | ||||
3904 | ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); | ||||
3905 | } else { | ||||
3906 | if (A.Entries[I].getAsBaseOrMember() != | ||||
3907 | B.Entries[I].getAsBaseOrMember()) { | ||||
3908 | WasArrayIndex = false; | ||||
3909 | return I; | ||||
3910 | } | ||||
3911 | if (const FieldDecl *FD = getAsField(A.Entries[I])) | ||||
3912 | // Next subobject is a field. | ||||
3913 | ObjType = FD->getType(); | ||||
3914 | else | ||||
3915 | // Next subobject is a base class. | ||||
3916 | ObjType = QualType(); | ||||
3917 | } | ||||
3918 | } | ||||
3919 | WasArrayIndex = false; | ||||
3920 | return I; | ||||
3921 | } | ||||
3922 | |||||
3923 | /// Determine whether the given subobject designators refer to elements of the | ||||
3924 | /// same array object. | ||||
3925 | static bool AreElementsOfSameArray(QualType ObjType, | ||||
3926 | const SubobjectDesignator &A, | ||||
3927 | const SubobjectDesignator &B) { | ||||
3928 | if (A.Entries.size() != B.Entries.size()) | ||||
3929 | return false; | ||||
3930 | |||||
3931 | bool IsArray = A.MostDerivedIsArrayElement; | ||||
3932 | if (IsArray && A.MostDerivedPathLength != A.Entries.size()) | ||||
3933 | // A is a subobject of the array element. | ||||
3934 | return false; | ||||
3935 | |||||
3936 | // If A (and B) designates an array element, the last entry will be the array | ||||
3937 | // index. That doesn't have to match. Otherwise, we're in the 'implicit array | ||||
3938 | // of length 1' case, and the entire path must match. | ||||
3939 | bool WasArrayIndex; | ||||
3940 | unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); | ||||
3941 | return CommonLength >= A.Entries.size() - IsArray; | ||||
3942 | } | ||||
3943 | |||||
3944 | /// Find the complete object to which an LValue refers. | ||||
3945 | static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, | ||||
3946 | AccessKinds AK, const LValue &LVal, | ||||
3947 | QualType LValType) { | ||||
3948 | if (LVal.InvalidBase) { | ||||
3949 | Info.FFDiag(E); | ||||
3950 | return CompleteObject(); | ||||
3951 | } | ||||
3952 | |||||
3953 | if (!LVal.Base) { | ||||
3954 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; | ||||
3955 | return CompleteObject(); | ||||
3956 | } | ||||
3957 | |||||
3958 | CallStackFrame *Frame = nullptr; | ||||
3959 | unsigned Depth = 0; | ||||
3960 | if (LVal.getLValueCallIndex()) { | ||||
3961 | std::tie(Frame, Depth) = | ||||
3962 | Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); | ||||
3963 | if (!Frame) { | ||||
3964 | Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) | ||||
3965 | << AK << LVal.Base.is<const ValueDecl*>(); | ||||
3966 | NoteLValueLocation(Info, LVal.Base); | ||||
3967 | return CompleteObject(); | ||||
3968 | } | ||||
3969 | } | ||||
3970 | |||||
3971 | bool IsAccess = isAnyAccess(AK); | ||||
3972 | |||||
3973 | // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type | ||||
3974 | // is not a constant expression (even if the object is non-volatile). We also | ||||
3975 | // apply this rule to C++98, in order to conform to the expected 'volatile' | ||||
3976 | // semantics. | ||||
3977 | if (isFormalAccess(AK) && LValType.isVolatileQualified()) { | ||||
3978 | if (Info.getLangOpts().CPlusPlus) | ||||
3979 | Info.FFDiag(E, diag::note_constexpr_access_volatile_type) | ||||
3980 | << AK << LValType; | ||||
3981 | else | ||||
3982 | Info.FFDiag(E); | ||||
3983 | return CompleteObject(); | ||||
3984 | } | ||||
3985 | |||||
3986 | // Compute value storage location and type of base object. | ||||
3987 | APValue *BaseVal = nullptr; | ||||
3988 | QualType BaseType = getType(LVal.Base); | ||||
3989 | |||||
3990 | if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && | ||||
3991 | lifetimeStartedInEvaluation(Info, LVal.Base)) { | ||||
3992 | // This is the object whose initializer we're evaluating, so its lifetime | ||||
3993 | // started in the current evaluation. | ||||
3994 | BaseVal = Info.EvaluatingDeclValue; | ||||
3995 | } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { | ||||
3996 | // Allow reading from a GUID declaration. | ||||
3997 | if (auto *GD = dyn_cast<MSGuidDecl>(D)) { | ||||
3998 | if (isModification(AK)) { | ||||
3999 | // All the remaining cases do not permit modification of the object. | ||||
4000 | Info.FFDiag(E, diag::note_constexpr_modify_global); | ||||
4001 | return CompleteObject(); | ||||
4002 | } | ||||
4003 | APValue &V = GD->getAsAPValue(); | ||||
4004 | if (V.isAbsent()) { | ||||
4005 | Info.FFDiag(E, diag::note_constexpr_unsupported_layout) | ||||
4006 | << GD->getType(); | ||||
4007 | return CompleteObject(); | ||||
4008 | } | ||||
4009 | return CompleteObject(LVal.Base, &V, GD->getType()); | ||||
4010 | } | ||||
4011 | |||||
4012 | // Allow reading from template parameter objects. | ||||
4013 | if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { | ||||
4014 | if (isModification(AK)) { | ||||
4015 | Info.FFDiag(E, diag::note_constexpr_modify_global); | ||||
4016 | return CompleteObject(); | ||||
4017 | } | ||||
4018 | return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), | ||||
4019 | TPO->getType()); | ||||
4020 | } | ||||
4021 | |||||
4022 | // In C++98, const, non-volatile integers initialized with ICEs are ICEs. | ||||
4023 | // In C++11, constexpr, non-volatile variables initialized with constant | ||||
4024 | // expressions are constant expressions too. Inside constexpr functions, | ||||
4025 | // parameters are constant expressions even if they're non-const. | ||||
4026 | // In C++1y, objects local to a constant expression (those with a Frame) are | ||||
4027 | // both readable and writable inside constant expressions. | ||||
4028 | // In C, such things can also be folded, although they are not ICEs. | ||||
4029 | const VarDecl *VD = dyn_cast<VarDecl>(D); | ||||
4030 | if (VD) { | ||||
4031 | if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) | ||||
4032 | VD = VDef; | ||||
4033 | } | ||||
4034 | if (!VD || VD->isInvalidDecl()) { | ||||
4035 | Info.FFDiag(E); | ||||
4036 | return CompleteObject(); | ||||
4037 | } | ||||
4038 | |||||
4039 | bool IsConstant = BaseType.isConstant(Info.Ctx); | ||||
4040 | |||||
4041 | // Unless we're looking at a local variable or argument in a constexpr call, | ||||
4042 | // the variable we're reading must be const. | ||||
4043 | if (!Frame) { | ||||
4044 | if (IsAccess && isa<ParmVarDecl>(VD)) { | ||||
4045 | // Access of a parameter that's not associated with a frame isn't going | ||||
4046 | // to work out, but we can leave it to evaluateVarDeclInit to provide a | ||||
4047 | // suitable diagnostic. | ||||
4048 | } else if (Info.getLangOpts().CPlusPlus14 && | ||||
4049 | lifetimeStartedInEvaluation(Info, LVal.Base)) { | ||||
4050 | // OK, we can read and modify an object if we're in the process of | ||||
4051 | // evaluating its initializer, because its lifetime began in this | ||||
4052 | // evaluation. | ||||
4053 | } else if (isModification(AK)) { | ||||
4054 | // All the remaining cases do not permit modification of the object. | ||||
4055 | Info.FFDiag(E, diag::note_constexpr_modify_global); | ||||
4056 | return CompleteObject(); | ||||
4057 | } else if (VD->isConstexpr()) { | ||||
4058 | // OK, we can read this variable. | ||||
4059 | } else if (BaseType->isIntegralOrEnumerationType()) { | ||||
4060 | if (!IsConstant) { | ||||
4061 | if (!IsAccess) | ||||
4062 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||
4063 | if (Info.getLangOpts().CPlusPlus) { | ||||
4064 | Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; | ||||
4065 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
4066 | } else { | ||||
4067 | Info.FFDiag(E); | ||||
4068 | } | ||||
4069 | return CompleteObject(); | ||||
4070 | } | ||||
4071 | } else if (!IsAccess) { | ||||
4072 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||
4073 | } else if (IsConstant && Info.checkingPotentialConstantExpression() && | ||||
4074 | BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { | ||||
4075 | // This variable might end up being constexpr. Don't diagnose it yet. | ||||
4076 | } else if (IsConstant) { | ||||
4077 | // Keep evaluating to see what we can do. In particular, we support | ||||
4078 | // folding of const floating-point types, in order to make static const | ||||
4079 | // data members of such types (supported as an extension) more useful. | ||||
4080 | if (Info.getLangOpts().CPlusPlus) { | ||||
4081 | Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 | ||||
4082 | ? diag::note_constexpr_ltor_non_constexpr | ||||
4083 | : diag::note_constexpr_ltor_non_integral, 1) | ||||
4084 | << VD << BaseType; | ||||
4085 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
4086 | } else { | ||||
4087 | Info.CCEDiag(E); | ||||
4088 | } | ||||
4089 | } else { | ||||
4090 | // Never allow reading a non-const value. | ||||
4091 | if (Info.getLangOpts().CPlusPlus) { | ||||
4092 | Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 | ||||
4093 | ? diag::note_constexpr_ltor_non_constexpr | ||||
4094 | : diag::note_constexpr_ltor_non_integral, 1) | ||||
4095 | << VD << BaseType; | ||||
4096 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
4097 | } else { | ||||
4098 | Info.FFDiag(E); | ||||
4099 | } | ||||
4100 | return CompleteObject(); | ||||
4101 | } | ||||
4102 | } | ||||
4103 | |||||
4104 | if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) | ||||
4105 | return CompleteObject(); | ||||
4106 | } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { | ||||
4107 | Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); | ||||
4108 | if (!Alloc) { | ||||
4109 | Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; | ||||
4110 | return CompleteObject(); | ||||
4111 | } | ||||
4112 | return CompleteObject(LVal.Base, &(*Alloc)->Value, | ||||
4113 | LVal.Base.getDynamicAllocType()); | ||||
4114 | } else { | ||||
4115 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); | ||||
4116 | |||||
4117 | if (!Frame) { | ||||
4118 | if (const MaterializeTemporaryExpr *MTE = | ||||
4119 | dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { | ||||
4120 | assert(MTE->getStorageDuration() == SD_Static &&(static_cast <bool> (MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4121, __extension__ __PRETTY_FUNCTION__)) | ||||
4121 | "should have a frame for a non-global materialized temporary")(static_cast <bool> (MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4121, __extension__ __PRETTY_FUNCTION__)); | ||||
4122 | |||||
4123 | // C++20 [expr.const]p4: [DR2126] | ||||
4124 | // An object or reference is usable in constant expressions if it is | ||||
4125 | // - a temporary object of non-volatile const-qualified literal type | ||||
4126 | // whose lifetime is extended to that of a variable that is usable | ||||
4127 | // in constant expressions | ||||
4128 | // | ||||
4129 | // C++20 [expr.const]p5: | ||||
4130 | // an lvalue-to-rvalue conversion [is not allowed unless it applies to] | ||||
4131 | // - a non-volatile glvalue that refers to an object that is usable | ||||
4132 | // in constant expressions, or | ||||
4133 | // - a non-volatile glvalue of literal type that refers to a | ||||
4134 | // non-volatile object whose lifetime began within the evaluation | ||||
4135 | // of E; | ||||
4136 | // | ||||
4137 | // C++11 misses the 'began within the evaluation of e' check and | ||||
4138 | // instead allows all temporaries, including things like: | ||||
4139 | // int &&r = 1; | ||||
4140 | // int x = ++r; | ||||
4141 | // constexpr int k = r; | ||||
4142 | // Therefore we use the C++14-onwards rules in C++11 too. | ||||
4143 | // | ||||
4144 | // Note that temporaries whose lifetimes began while evaluating a | ||||
4145 | // variable's constructor are not usable while evaluating the | ||||
4146 | // corresponding destructor, not even if they're of const-qualified | ||||
4147 | // types. | ||||
4148 | if (!MTE->isUsableInConstantExpressions(Info.Ctx) && | ||||
4149 | !lifetimeStartedInEvaluation(Info, LVal.Base)) { | ||||
4150 | if (!IsAccess) | ||||
4151 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||
4152 | Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; | ||||
4153 | Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); | ||||
4154 | return CompleteObject(); | ||||
4155 | } | ||||
4156 | |||||
4157 | BaseVal = MTE->getOrCreateValue(false); | ||||
4158 | assert(BaseVal && "got reference to unevaluated temporary")(static_cast <bool> (BaseVal && "got reference to unevaluated temporary" ) ? void (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4158, __extension__ __PRETTY_FUNCTION__)); | ||||
4159 | } else { | ||||
4160 | if (!IsAccess) | ||||
4161 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||
4162 | APValue Val; | ||||
4163 | LVal.moveInto(Val); | ||||
4164 | Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) | ||||
4165 | << AK | ||||
4166 | << Val.getAsString(Info.Ctx, | ||||
4167 | Info.Ctx.getLValueReferenceType(LValType)); | ||||
4168 | NoteLValueLocation(Info, LVal.Base); | ||||
4169 | return CompleteObject(); | ||||
4170 | } | ||||
4171 | } else { | ||||
4172 | BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); | ||||
4173 | assert(BaseVal && "missing value for temporary")(static_cast <bool> (BaseVal && "missing value for temporary" ) ? void (0) : __assert_fail ("BaseVal && \"missing value for temporary\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4173, __extension__ __PRETTY_FUNCTION__)); | ||||
4174 | } | ||||
4175 | } | ||||
4176 | |||||
4177 | // In C++14, we can't safely access any mutable state when we might be | ||||
4178 | // evaluating after an unmodeled side effect. Parameters are modeled as state | ||||
4179 | // in the caller, but aren't visible once the call returns, so they can be | ||||
4180 | // modified in a speculatively-evaluated call. | ||||
4181 | // | ||||
4182 | // FIXME: Not all local state is mutable. Allow local constant subobjects | ||||
4183 | // to be read here (but take care with 'mutable' fields). | ||||
4184 | unsigned VisibleDepth = Depth; | ||||
4185 | if (llvm::isa_and_nonnull<ParmVarDecl>( | ||||
4186 | LVal.Base.dyn_cast<const ValueDecl *>())) | ||||
4187 | ++VisibleDepth; | ||||
4188 | if ((Frame && Info.getLangOpts().CPlusPlus14 && | ||||
4189 | Info.EvalStatus.HasSideEffects) || | ||||
4190 | (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) | ||||
4191 | return CompleteObject(); | ||||
4192 | |||||
4193 | return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); | ||||
4194 | } | ||||
4195 | |||||
4196 | /// Perform an lvalue-to-rvalue conversion on the given glvalue. This | ||||
4197 | /// can also be used for 'lvalue-to-lvalue' conversions for looking up the | ||||
4198 | /// glvalue referred to by an entity of reference type. | ||||
4199 | /// | ||||
4200 | /// \param Info - Information about the ongoing evaluation. | ||||
4201 | /// \param Conv - The expression for which we are performing the conversion. | ||||
4202 | /// Used for diagnostics. | ||||
4203 | /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the | ||||
4204 | /// case of a non-class type). | ||||
4205 | /// \param LVal - The glvalue on which we are attempting to perform this action. | ||||
4206 | /// \param RVal - The produced value will be placed here. | ||||
4207 | /// \param WantObjectRepresentation - If true, we're looking for the object | ||||
4208 | /// representation rather than the value, and in particular, | ||||
4209 | /// there is no requirement that the result be fully initialized. | ||||
4210 | static bool | ||||
4211 | handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, | ||||
4212 | const LValue &LVal, APValue &RVal, | ||||
4213 | bool WantObjectRepresentation = false) { | ||||
4214 | if (LVal.Designator.Invalid) | ||||
4215 | return false; | ||||
4216 | |||||
4217 | // Check for special cases where there is no existing APValue to look at. | ||||
4218 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); | ||||
4219 | |||||
4220 | AccessKinds AK = | ||||
4221 | WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; | ||||
4222 | |||||
4223 | if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { | ||||
4224 | if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { | ||||
4225 | // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the | ||||
4226 | // initializer until now for such expressions. Such an expression can't be | ||||
4227 | // an ICE in C, so this only matters for fold. | ||||
4228 | if (Type.isVolatileQualified()) { | ||||
4229 | Info.FFDiag(Conv); | ||||
4230 | return false; | ||||
4231 | } | ||||
4232 | APValue Lit; | ||||
4233 | if (!Evaluate(Lit, Info, CLE->getInitializer())) | ||||
4234 | return false; | ||||
4235 | CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); | ||||
4236 | return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); | ||||
4237 | } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { | ||||
4238 | // Special-case character extraction so we don't have to construct an | ||||
4239 | // APValue for the whole string. | ||||
4240 | assert(LVal.Designator.Entries.size() <= 1 &&(static_cast <bool> (LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4241, __extension__ __PRETTY_FUNCTION__)) | ||||
4241 | "Can only read characters from string literals")(static_cast <bool> (LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4241, __extension__ __PRETTY_FUNCTION__)); | ||||
4242 | if (LVal.Designator.Entries.empty()) { | ||||
4243 | // Fail for now for LValue to RValue conversion of an array. | ||||
4244 | // (This shouldn't show up in C/C++, but it could be triggered by a | ||||
4245 | // weird EvaluateAsRValue call from a tool.) | ||||
4246 | Info.FFDiag(Conv); | ||||
4247 | return false; | ||||
4248 | } | ||||
4249 | if (LVal.Designator.isOnePastTheEnd()) { | ||||
4250 | if (Info.getLangOpts().CPlusPlus11) | ||||
4251 | Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; | ||||
4252 | else | ||||
4253 | Info.FFDiag(Conv); | ||||
4254 | return false; | ||||
4255 | } | ||||
4256 | uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); | ||||
4257 | RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); | ||||
4258 | return true; | ||||
4259 | } | ||||
4260 | } | ||||
4261 | |||||
4262 | CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); | ||||
4263 | return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); | ||||
4264 | } | ||||
4265 | |||||
4266 | /// Perform an assignment of Val to LVal. Takes ownership of Val. | ||||
4267 | static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, | ||||
4268 | QualType LValType, APValue &Val) { | ||||
4269 | if (LVal.Designator.Invalid) | ||||
4270 | return false; | ||||
4271 | |||||
4272 | if (!Info.getLangOpts().CPlusPlus14) { | ||||
4273 | Info.FFDiag(E); | ||||
4274 | return false; | ||||
4275 | } | ||||
4276 | |||||
4277 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); | ||||
4278 | return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); | ||||
4279 | } | ||||
4280 | |||||
4281 | namespace { | ||||
4282 | struct CompoundAssignSubobjectHandler { | ||||
4283 | EvalInfo &Info; | ||||
4284 | const CompoundAssignOperator *E; | ||||
4285 | QualType PromotedLHSType; | ||||
4286 | BinaryOperatorKind Opcode; | ||||
4287 | const APValue &RHS; | ||||
4288 | |||||
4289 | static const AccessKinds AccessKind = AK_Assign; | ||||
4290 | |||||
4291 | typedef bool result_type; | ||||
4292 | |||||
4293 | bool checkConst(QualType QT) { | ||||
4294 | // Assigning to a const object has undefined behavior. | ||||
4295 | if (QT.isConstQualified()) { | ||||
4296 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||
4297 | return false; | ||||
4298 | } | ||||
4299 | return true; | ||||
4300 | } | ||||
4301 | |||||
4302 | bool failed() { return false; } | ||||
4303 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
4304 | switch (Subobj.getKind()) { | ||||
4305 | case APValue::Int: | ||||
4306 | return found(Subobj.getInt(), SubobjType); | ||||
4307 | case APValue::Float: | ||||
4308 | return found(Subobj.getFloat(), SubobjType); | ||||
4309 | case APValue::ComplexInt: | ||||
4310 | case APValue::ComplexFloat: | ||||
4311 | // FIXME: Implement complex compound assignment. | ||||
4312 | Info.FFDiag(E); | ||||
4313 | return false; | ||||
4314 | case APValue::LValue: | ||||
4315 | return foundPointer(Subobj, SubobjType); | ||||
4316 | case APValue::Vector: | ||||
4317 | return foundVector(Subobj, SubobjType); | ||||
4318 | default: | ||||
4319 | // FIXME: can this happen? | ||||
4320 | Info.FFDiag(E); | ||||
4321 | return false; | ||||
4322 | } | ||||
4323 | } | ||||
4324 | |||||
4325 | bool foundVector(APValue &Value, QualType SubobjType) { | ||||
4326 | if (!checkConst(SubobjType)) | ||||
4327 | return false; | ||||
4328 | |||||
4329 | if (!SubobjType->isVectorType()) { | ||||
4330 | Info.FFDiag(E); | ||||
4331 | return false; | ||||
4332 | } | ||||
4333 | return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); | ||||
4334 | } | ||||
4335 | |||||
4336 | bool found(APSInt &Value, QualType SubobjType) { | ||||
4337 | if (!checkConst(SubobjType)) | ||||
4338 | return false; | ||||
4339 | |||||
4340 | if (!SubobjType->isIntegerType()) { | ||||
4341 | // We don't support compound assignment on integer-cast-to-pointer | ||||
4342 | // values. | ||||
4343 | Info.FFDiag(E); | ||||
4344 | return false; | ||||
4345 | } | ||||
4346 | |||||
4347 | if (RHS.isInt()) { | ||||
4348 | APSInt LHS = | ||||
4349 | HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); | ||||
4350 | if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) | ||||
4351 | return false; | ||||
4352 | Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); | ||||
4353 | return true; | ||||
4354 | } else if (RHS.isFloat()) { | ||||
4355 | const FPOptions FPO = E->getFPFeaturesInEffect( | ||||
4356 | Info.Ctx.getLangOpts()); | ||||
4357 | APFloat FValue(0.0); | ||||
4358 | return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, | ||||
4359 | PromotedLHSType, FValue) && | ||||
4360 | handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && | ||||
4361 | HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, | ||||
4362 | Value); | ||||
4363 | } | ||||
4364 | |||||
4365 | Info.FFDiag(E); | ||||
4366 | return false; | ||||
4367 | } | ||||
4368 | bool found(APFloat &Value, QualType SubobjType) { | ||||
4369 | return checkConst(SubobjType) && | ||||
4370 | HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, | ||||
4371 | Value) && | ||||
4372 | handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && | ||||
4373 | HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); | ||||
4374 | } | ||||
4375 | bool foundPointer(APValue &Subobj, QualType SubobjType) { | ||||
4376 | if (!checkConst(SubobjType)) | ||||
4377 | return false; | ||||
4378 | |||||
4379 | QualType PointeeType; | ||||
4380 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) | ||||
4381 | PointeeType = PT->getPointeeType(); | ||||
4382 | |||||
4383 | if (PointeeType.isNull() || !RHS.isInt() || | ||||
4384 | (Opcode != BO_Add && Opcode != BO_Sub)) { | ||||
4385 | Info.FFDiag(E); | ||||
4386 | return false; | ||||
4387 | } | ||||
4388 | |||||
4389 | APSInt Offset = RHS.getInt(); | ||||
4390 | if (Opcode == BO_Sub) | ||||
4391 | negateAsSigned(Offset); | ||||
4392 | |||||
4393 | LValue LVal; | ||||
4394 | LVal.setFrom(Info.Ctx, Subobj); | ||||
4395 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) | ||||
4396 | return false; | ||||
4397 | LVal.moveInto(Subobj); | ||||
4398 | return true; | ||||
4399 | } | ||||
4400 | }; | ||||
4401 | } // end anonymous namespace | ||||
4402 | |||||
4403 | const AccessKinds CompoundAssignSubobjectHandler::AccessKind; | ||||
4404 | |||||
4405 | /// Perform a compound assignment of LVal <op>= RVal. | ||||
4406 | static bool handleCompoundAssignment(EvalInfo &Info, | ||||
4407 | const CompoundAssignOperator *E, | ||||
4408 | const LValue &LVal, QualType LValType, | ||||
4409 | QualType PromotedLValType, | ||||
4410 | BinaryOperatorKind Opcode, | ||||
4411 | const APValue &RVal) { | ||||
4412 | if (LVal.Designator.Invalid) | ||||
4413 | return false; | ||||
4414 | |||||
4415 | if (!Info.getLangOpts().CPlusPlus14) { | ||||
4416 | Info.FFDiag(E); | ||||
4417 | return false; | ||||
4418 | } | ||||
4419 | |||||
4420 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); | ||||
4421 | CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, | ||||
4422 | RVal }; | ||||
4423 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); | ||||
4424 | } | ||||
4425 | |||||
4426 | namespace { | ||||
4427 | struct IncDecSubobjectHandler { | ||||
4428 | EvalInfo &Info; | ||||
4429 | const UnaryOperator *E; | ||||
4430 | AccessKinds AccessKind; | ||||
4431 | APValue *Old; | ||||
4432 | |||||
4433 | typedef bool result_type; | ||||
4434 | |||||
4435 | bool checkConst(QualType QT) { | ||||
4436 | // Assigning to a const object has undefined behavior. | ||||
4437 | if (QT.isConstQualified()) { | ||||
4438 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||
4439 | return false; | ||||
4440 | } | ||||
4441 | return true; | ||||
4442 | } | ||||
4443 | |||||
4444 | bool failed() { return false; } | ||||
4445 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
4446 | // Stash the old value. Also clear Old, so we don't clobber it later | ||||
4447 | // if we're post-incrementing a complex. | ||||
4448 | if (Old) { | ||||
4449 | *Old = Subobj; | ||||
4450 | Old = nullptr; | ||||
4451 | } | ||||
4452 | |||||
4453 | switch (Subobj.getKind()) { | ||||
4454 | case APValue::Int: | ||||
4455 | return found(Subobj.getInt(), SubobjType); | ||||
4456 | case APValue::Float: | ||||
4457 | return found(Subobj.getFloat(), SubobjType); | ||||
4458 | case APValue::ComplexInt: | ||||
4459 | return found(Subobj.getComplexIntReal(), | ||||
4460 | SubobjType->castAs<ComplexType>()->getElementType() | ||||
4461 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); | ||||
4462 | case APValue::ComplexFloat: | ||||
4463 | return found(Subobj.getComplexFloatReal(), | ||||
4464 | SubobjType->castAs<ComplexType>()->getElementType() | ||||
4465 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); | ||||
4466 | case APValue::LValue: | ||||
4467 | return foundPointer(Subobj, SubobjType); | ||||
4468 | default: | ||||
4469 | // FIXME: can this happen? | ||||
4470 | Info.FFDiag(E); | ||||
4471 | return false; | ||||
4472 | } | ||||
4473 | } | ||||
4474 | bool found(APSInt &Value, QualType SubobjType) { | ||||
4475 | if (!checkConst(SubobjType)) | ||||
4476 | return false; | ||||
4477 | |||||
4478 | if (!SubobjType->isIntegerType()) { | ||||
4479 | // We don't support increment / decrement on integer-cast-to-pointer | ||||
4480 | // values. | ||||
4481 | Info.FFDiag(E); | ||||
4482 | return false; | ||||
4483 | } | ||||
4484 | |||||
4485 | if (Old) *Old = APValue(Value); | ||||
4486 | |||||
4487 | // bool arithmetic promotes to int, and the conversion back to bool | ||||
4488 | // doesn't reduce mod 2^n, so special-case it. | ||||
4489 | if (SubobjType->isBooleanType()) { | ||||
4490 | if (AccessKind == AK_Increment) | ||||
4491 | Value = 1; | ||||
4492 | else | ||||
4493 | Value = !Value; | ||||
4494 | return true; | ||||
4495 | } | ||||
4496 | |||||
4497 | bool WasNegative = Value.isNegative(); | ||||
4498 | if (AccessKind == AK_Increment) { | ||||
4499 | ++Value; | ||||
4500 | |||||
4501 | if (!WasNegative && Value.isNegative() && E->canOverflow()) { | ||||
4502 | APSInt ActualValue(Value, /*IsUnsigned*/true); | ||||
4503 | return HandleOverflow(Info, E, ActualValue, SubobjType); | ||||
4504 | } | ||||
4505 | } else { | ||||
4506 | --Value; | ||||
4507 | |||||
4508 | if (WasNegative && !Value.isNegative() && E->canOverflow()) { | ||||
4509 | unsigned BitWidth = Value.getBitWidth(); | ||||
4510 | APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); | ||||
4511 | ActualValue.setBit(BitWidth); | ||||
4512 | return HandleOverflow(Info, E, ActualValue, SubobjType); | ||||
4513 | } | ||||
4514 | } | ||||
4515 | return true; | ||||
4516 | } | ||||
4517 | bool found(APFloat &Value, QualType SubobjType) { | ||||
4518 | if (!checkConst(SubobjType)) | ||||
4519 | return false; | ||||
4520 | |||||
4521 | if (Old) *Old = APValue(Value); | ||||
4522 | |||||
4523 | APFloat One(Value.getSemantics(), 1); | ||||
4524 | if (AccessKind == AK_Increment) | ||||
4525 | Value.add(One, APFloat::rmNearestTiesToEven); | ||||
4526 | else | ||||
4527 | Value.subtract(One, APFloat::rmNearestTiesToEven); | ||||
4528 | return true; | ||||
4529 | } | ||||
4530 | bool foundPointer(APValue &Subobj, QualType SubobjType) { | ||||
4531 | if (!checkConst(SubobjType)) | ||||
4532 | return false; | ||||
4533 | |||||
4534 | QualType PointeeType; | ||||
4535 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) | ||||
4536 | PointeeType = PT->getPointeeType(); | ||||
4537 | else { | ||||
4538 | Info.FFDiag(E); | ||||
4539 | return false; | ||||
4540 | } | ||||
4541 | |||||
4542 | LValue LVal; | ||||
4543 | LVal.setFrom(Info.Ctx, Subobj); | ||||
4544 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, | ||||
4545 | AccessKind == AK_Increment ? 1 : -1)) | ||||
4546 | return false; | ||||
4547 | LVal.moveInto(Subobj); | ||||
4548 | return true; | ||||
4549 | } | ||||
4550 | }; | ||||
4551 | } // end anonymous namespace | ||||
4552 | |||||
4553 | /// Perform an increment or decrement on LVal. | ||||
4554 | static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, | ||||
4555 | QualType LValType, bool IsIncrement, APValue *Old) { | ||||
4556 | if (LVal.Designator.Invalid) | ||||
4557 | return false; | ||||
4558 | |||||
4559 | if (!Info.getLangOpts().CPlusPlus14) { | ||||
4560 | Info.FFDiag(E); | ||||
4561 | return false; | ||||
4562 | } | ||||
4563 | |||||
4564 | AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; | ||||
4565 | CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); | ||||
4566 | IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; | ||||
4567 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); | ||||
4568 | } | ||||
4569 | |||||
4570 | /// Build an lvalue for the object argument of a member function call. | ||||
4571 | static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, | ||||
4572 | LValue &This) { | ||||
4573 | if (Object->getType()->isPointerType() && Object->isPRValue()) | ||||
4574 | return EvaluatePointer(Object, This, Info); | ||||
4575 | |||||
4576 | if (Object->isGLValue()) | ||||
4577 | return EvaluateLValue(Object, This, Info); | ||||
4578 | |||||
4579 | if (Object->getType()->isLiteralType(Info.Ctx)) | ||||
4580 | return EvaluateTemporary(Object, This, Info); | ||||
4581 | |||||
4582 | Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); | ||||
4583 | return false; | ||||
4584 | } | ||||
4585 | |||||
4586 | /// HandleMemberPointerAccess - Evaluate a member access operation and build an | ||||
4587 | /// lvalue referring to the result. | ||||
4588 | /// | ||||
4589 | /// \param Info - Information about the ongoing evaluation. | ||||
4590 | /// \param LV - An lvalue referring to the base of the member pointer. | ||||
4591 | /// \param RHS - The member pointer expression. | ||||
4592 | /// \param IncludeMember - Specifies whether the member itself is included in | ||||
4593 | /// the resulting LValue subobject designator. This is not possible when | ||||
4594 | /// creating a bound member function. | ||||
4595 | /// \return The field or method declaration to which the member pointer refers, | ||||
4596 | /// or 0 if evaluation fails. | ||||
4597 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, | ||||
4598 | QualType LVType, | ||||
4599 | LValue &LV, | ||||
4600 | const Expr *RHS, | ||||
4601 | bool IncludeMember = true) { | ||||
4602 | MemberPtr MemPtr; | ||||
4603 | if (!EvaluateMemberPointer(RHS, MemPtr, Info)) | ||||
4604 | return nullptr; | ||||
4605 | |||||
4606 | // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to | ||||
4607 | // member value, the behavior is undefined. | ||||
4608 | if (!MemPtr.getDecl()) { | ||||
4609 | // FIXME: Specific diagnostic. | ||||
4610 | Info.FFDiag(RHS); | ||||
4611 | return nullptr; | ||||
4612 | } | ||||
4613 | |||||
4614 | if (MemPtr.isDerivedMember()) { | ||||
4615 | // This is a member of some derived class. Truncate LV appropriately. | ||||
4616 | // The end of the derived-to-base path for the base object must match the | ||||
4617 | // derived-to-base path for the member pointer. | ||||
4618 | if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > | ||||
4619 | LV.Designator.Entries.size()) { | ||||
4620 | Info.FFDiag(RHS); | ||||
4621 | return nullptr; | ||||
4622 | } | ||||
4623 | unsigned PathLengthToMember = | ||||
4624 | LV.Designator.Entries.size() - MemPtr.Path.size(); | ||||
4625 | for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { | ||||
4626 | const CXXRecordDecl *LVDecl = getAsBaseClass( | ||||
4627 | LV.Designator.Entries[PathLengthToMember + I]); | ||||
4628 | const CXXRecordDecl *MPDecl = MemPtr.Path[I]; | ||||
4629 | if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { | ||||
4630 | Info.FFDiag(RHS); | ||||
4631 | return nullptr; | ||||
4632 | } | ||||
4633 | } | ||||
4634 | |||||
4635 | // Truncate the lvalue to the appropriate derived class. | ||||
4636 | if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), | ||||
4637 | PathLengthToMember)) | ||||
4638 | return nullptr; | ||||
4639 | } else if (!MemPtr.Path.empty()) { | ||||
4640 | // Extend the LValue path with the member pointer's path. | ||||
4641 | LV.Designator.Entries.reserve(LV.Designator.Entries.size() + | ||||
4642 | MemPtr.Path.size() + IncludeMember); | ||||
4643 | |||||
4644 | // Walk down to the appropriate base class. | ||||
4645 | if (const PointerType *PT = LVType->getAs<PointerType>()) | ||||
4646 | LVType = PT->getPointeeType(); | ||||
4647 | const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); | ||||
4648 | assert(RD && "member pointer access on non-class-type expression")(static_cast <bool> (RD && "member pointer access on non-class-type expression" ) ? void (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4648, __extension__ __PRETTY_FUNCTION__)); | ||||
4649 | // The first class in the path is that of the lvalue. | ||||
4650 | for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { | ||||
4651 | const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; | ||||
4652 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) | ||||
4653 | return nullptr; | ||||
4654 | RD = Base; | ||||
4655 | } | ||||
4656 | // Finally cast to the class containing the member. | ||||
4657 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, | ||||
4658 | MemPtr.getContainingRecord())) | ||||
4659 | return nullptr; | ||||
4660 | } | ||||
4661 | |||||
4662 | // Add the member. Note that we cannot build bound member functions here. | ||||
4663 | if (IncludeMember) { | ||||
4664 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { | ||||
4665 | if (!HandleLValueMember(Info, RHS, LV, FD)) | ||||
4666 | return nullptr; | ||||
4667 | } else if (const IndirectFieldDecl *IFD = | ||||
4668 | dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { | ||||
4669 | if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) | ||||
4670 | return nullptr; | ||||
4671 | } else { | ||||
4672 | llvm_unreachable("can't construct reference to bound member function")::llvm::llvm_unreachable_internal("can't construct reference to bound member function" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4672); | ||||
4673 | } | ||||
4674 | } | ||||
4675 | |||||
4676 | return MemPtr.getDecl(); | ||||
4677 | } | ||||
4678 | |||||
4679 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, | ||||
4680 | const BinaryOperator *BO, | ||||
4681 | LValue &LV, | ||||
4682 | bool IncludeMember = true) { | ||||
4683 | assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)(static_cast <bool> (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail ("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4683, __extension__ __PRETTY_FUNCTION__)); | ||||
4684 | |||||
4685 | if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { | ||||
4686 | if (Info.noteFailure()) { | ||||
4687 | MemberPtr MemPtr; | ||||
4688 | EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); | ||||
4689 | } | ||||
4690 | return nullptr; | ||||
4691 | } | ||||
4692 | |||||
4693 | return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, | ||||
4694 | BO->getRHS(), IncludeMember); | ||||
4695 | } | ||||
4696 | |||||
4697 | /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on | ||||
4698 | /// the provided lvalue, which currently refers to the base object. | ||||
4699 | static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, | ||||
4700 | LValue &Result) { | ||||
4701 | SubobjectDesignator &D = Result.Designator; | ||||
4702 | if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) | ||||
4703 | return false; | ||||
4704 | |||||
4705 | QualType TargetQT = E->getType(); | ||||
4706 | if (const PointerType *PT = TargetQT->getAs<PointerType>()) | ||||
4707 | TargetQT = PT->getPointeeType(); | ||||
4708 | |||||
4709 | // Check this cast lands within the final derived-to-base subobject path. | ||||
4710 | if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { | ||||
4711 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) | ||||
4712 | << D.MostDerivedType << TargetQT; | ||||
4713 | return false; | ||||
4714 | } | ||||
4715 | |||||
4716 | // Check the type of the final cast. We don't need to check the path, | ||||
4717 | // since a cast can only be formed if the path is unique. | ||||
4718 | unsigned NewEntriesSize = D.Entries.size() - E->path_size(); | ||||
4719 | const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); | ||||
4720 | const CXXRecordDecl *FinalType; | ||||
4721 | if (NewEntriesSize == D.MostDerivedPathLength) | ||||
4722 | FinalType = D.MostDerivedType->getAsCXXRecordDecl(); | ||||
4723 | else | ||||
4724 | FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); | ||||
4725 | if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { | ||||
4726 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) | ||||
4727 | << D.MostDerivedType << TargetQT; | ||||
4728 | return false; | ||||
4729 | } | ||||
4730 | |||||
4731 | // Truncate the lvalue to the appropriate derived class. | ||||
4732 | return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); | ||||
4733 | } | ||||
4734 | |||||
4735 | /// Get the value to use for a default-initialized object of type T. | ||||
4736 | /// Return false if it encounters something invalid. | ||||
4737 | static bool getDefaultInitValue(QualType T, APValue &Result) { | ||||
4738 | bool Success = true; | ||||
4739 | if (auto *RD = T->getAsCXXRecordDecl()) { | ||||
4740 | if (RD->isInvalidDecl()) { | ||||
4741 | Result = APValue(); | ||||
4742 | return false; | ||||
4743 | } | ||||
4744 | if (RD->isUnion()) { | ||||
4745 | Result = APValue((const FieldDecl *)nullptr); | ||||
4746 | return true; | ||||
4747 | } | ||||
4748 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), | ||||
4749 | std::distance(RD->field_begin(), RD->field_end())); | ||||
4750 | |||||
4751 | unsigned Index = 0; | ||||
4752 | for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), | ||||
4753 | End = RD->bases_end(); | ||||
4754 | I != End; ++I, ++Index) | ||||
4755 | Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); | ||||
4756 | |||||
4757 | for (const auto *I : RD->fields()) { | ||||
4758 | if (I->isUnnamedBitfield()) | ||||
4759 | continue; | ||||
4760 | Success &= getDefaultInitValue(I->getType(), | ||||
4761 | Result.getStructField(I->getFieldIndex())); | ||||
4762 | } | ||||
4763 | return Success; | ||||
4764 | } | ||||
4765 | |||||
4766 | if (auto *AT = | ||||
4767 | dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { | ||||
4768 | Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); | ||||
4769 | if (Result.hasArrayFiller()) | ||||
4770 | Success &= | ||||
4771 | getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); | ||||
4772 | |||||
4773 | return Success; | ||||
4774 | } | ||||
4775 | |||||
4776 | Result = APValue::IndeterminateValue(); | ||||
4777 | return true; | ||||
4778 | } | ||||
4779 | |||||
4780 | namespace { | ||||
4781 | enum EvalStmtResult { | ||||
4782 | /// Evaluation failed. | ||||
4783 | ESR_Failed, | ||||
4784 | /// Hit a 'return' statement. | ||||
4785 | ESR_Returned, | ||||
4786 | /// Evaluation succeeded. | ||||
4787 | ESR_Succeeded, | ||||
4788 | /// Hit a 'continue' statement. | ||||
4789 | ESR_Continue, | ||||
4790 | /// Hit a 'break' statement. | ||||
4791 | ESR_Break, | ||||
4792 | /// Still scanning for 'case' or 'default' statement. | ||||
4793 | ESR_CaseNotFound | ||||
4794 | }; | ||||
4795 | } | ||||
4796 | |||||
4797 | static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { | ||||
4798 | // We don't need to evaluate the initializer for a static local. | ||||
4799 | if (!VD->hasLocalStorage()) | ||||
4800 | return true; | ||||
4801 | |||||
4802 | LValue Result; | ||||
4803 | APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), | ||||
4804 | ScopeKind::Block, Result); | ||||
4805 | |||||
4806 | const Expr *InitE = VD->getInit(); | ||||
4807 | if (!InitE) { | ||||
4808 | if (VD->getType()->isDependentType()) | ||||
4809 | return Info.noteSideEffect(); | ||||
4810 | return getDefaultInitValue(VD->getType(), Val); | ||||
4811 | } | ||||
4812 | if (InitE->isValueDependent()) | ||||
4813 | return false; | ||||
4814 | |||||
4815 | if (!EvaluateInPlace(Val, Info, Result, InitE)) { | ||||
4816 | // Wipe out any partially-computed value, to allow tracking that this | ||||
4817 | // evaluation failed. | ||||
4818 | Val = APValue(); | ||||
4819 | return false; | ||||
4820 | } | ||||
4821 | |||||
4822 | return true; | ||||
4823 | } | ||||
4824 | |||||
4825 | static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { | ||||
4826 | bool OK = true; | ||||
4827 | |||||
4828 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
4829 | OK &= EvaluateVarDecl(Info, VD); | ||||
4830 | |||||
4831 | if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) | ||||
4832 | for (auto *BD : DD->bindings()) | ||||
4833 | if (auto *VD = BD->getHoldingVar()) | ||||
4834 | OK &= EvaluateDecl(Info, VD); | ||||
4835 | |||||
4836 | return OK; | ||||
4837 | } | ||||
4838 | |||||
4839 | static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { | ||||
4840 | assert(E->isValueDependent())(static_cast <bool> (E->isValueDependent()) ? void ( 0) : __assert_fail ("E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4840, __extension__ __PRETTY_FUNCTION__)); | ||||
4841 | if (Info.noteSideEffect()) | ||||
4842 | return true; | ||||
4843 | assert(E->containsErrors() && "valid value-dependent expression should never "(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never " "reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4844, __extension__ __PRETTY_FUNCTION__)) | ||||
4844 | "reach invalid code path.")(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never " "reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4844, __extension__ __PRETTY_FUNCTION__)); | ||||
4845 | return false; | ||||
4846 | } | ||||
4847 | |||||
4848 | /// Evaluate a condition (either a variable declaration or an expression). | ||||
4849 | static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, | ||||
4850 | const Expr *Cond, bool &Result) { | ||||
4851 | if (Cond->isValueDependent()) | ||||
4852 | return false; | ||||
4853 | FullExpressionRAII Scope(Info); | ||||
4854 | if (CondDecl && !EvaluateDecl(Info, CondDecl)) | ||||
4855 | return false; | ||||
4856 | if (!EvaluateAsBooleanCondition(Cond, Result, Info)) | ||||
4857 | return false; | ||||
4858 | return Scope.destroy(); | ||||
4859 | } | ||||
4860 | |||||
4861 | namespace { | ||||
4862 | /// A location where the result (returned value) of evaluating a | ||||
4863 | /// statement should be stored. | ||||
4864 | struct StmtResult { | ||||
4865 | /// The APValue that should be filled in with the returned value. | ||||
4866 | APValue &Value; | ||||
4867 | /// The location containing the result, if any (used to support RVO). | ||||
4868 | const LValue *Slot; | ||||
4869 | }; | ||||
4870 | |||||
4871 | struct TempVersionRAII { | ||||
4872 | CallStackFrame &Frame; | ||||
4873 | |||||
4874 | TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { | ||||
4875 | Frame.pushTempVersion(); | ||||
4876 | } | ||||
4877 | |||||
4878 | ~TempVersionRAII() { | ||||
4879 | Frame.popTempVersion(); | ||||
4880 | } | ||||
4881 | }; | ||||
4882 | |||||
4883 | } | ||||
4884 | |||||
4885 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, | ||||
4886 | const Stmt *S, | ||||
4887 | const SwitchCase *SC = nullptr); | ||||
4888 | |||||
4889 | /// Evaluate the body of a loop, and translate the result as appropriate. | ||||
4890 | static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, | ||||
4891 | const Stmt *Body, | ||||
4892 | const SwitchCase *Case = nullptr) { | ||||
4893 | BlockScopeRAII Scope(Info); | ||||
4894 | |||||
4895 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); | ||||
4896 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) | ||||
4897 | ESR = ESR_Failed; | ||||
4898 | |||||
4899 | switch (ESR) { | ||||
4900 | case ESR_Break: | ||||
4901 | return ESR_Succeeded; | ||||
4902 | case ESR_Succeeded: | ||||
4903 | case ESR_Continue: | ||||
4904 | return ESR_Continue; | ||||
4905 | case ESR_Failed: | ||||
4906 | case ESR_Returned: | ||||
4907 | case ESR_CaseNotFound: | ||||
4908 | return ESR; | ||||
4909 | } | ||||
4910 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4910); | ||||
4911 | } | ||||
4912 | |||||
4913 | /// Evaluate a switch statement. | ||||
4914 | static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, | ||||
4915 | const SwitchStmt *SS) { | ||||
4916 | BlockScopeRAII Scope(Info); | ||||
4917 | |||||
4918 | // Evaluate the switch condition. | ||||
4919 | APSInt Value; | ||||
4920 | { | ||||
4921 | if (const Stmt *Init = SS->getInit()) { | ||||
4922 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); | ||||
4923 | if (ESR != ESR_Succeeded) { | ||||
4924 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4925 | ESR = ESR_Failed; | ||||
4926 | return ESR; | ||||
4927 | } | ||||
4928 | } | ||||
4929 | |||||
4930 | FullExpressionRAII CondScope(Info); | ||||
4931 | if (SS->getConditionVariable() && | ||||
4932 | !EvaluateDecl(Info, SS->getConditionVariable())) | ||||
4933 | return ESR_Failed; | ||||
4934 | if (!EvaluateInteger(SS->getCond(), Value, Info)) | ||||
4935 | return ESR_Failed; | ||||
4936 | if (!CondScope.destroy()) | ||||
4937 | return ESR_Failed; | ||||
4938 | } | ||||
4939 | |||||
4940 | // Find the switch case corresponding to the value of the condition. | ||||
4941 | // FIXME: Cache this lookup. | ||||
4942 | const SwitchCase *Found = nullptr; | ||||
4943 | for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; | ||||
4944 | SC = SC->getNextSwitchCase()) { | ||||
4945 | if (isa<DefaultStmt>(SC)) { | ||||
4946 | Found = SC; | ||||
4947 | continue; | ||||
4948 | } | ||||
4949 | |||||
4950 | const CaseStmt *CS = cast<CaseStmt>(SC); | ||||
4951 | APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); | ||||
4952 | APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) | ||||
4953 | : LHS; | ||||
4954 | if (LHS <= Value && Value <= RHS) { | ||||
4955 | Found = SC; | ||||
4956 | break; | ||||
4957 | } | ||||
4958 | } | ||||
4959 | |||||
4960 | if (!Found) | ||||
4961 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
4962 | |||||
4963 | // Search the switch body for the switch case and evaluate it from there. | ||||
4964 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); | ||||
4965 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) | ||||
4966 | return ESR_Failed; | ||||
4967 | |||||
4968 | switch (ESR) { | ||||
4969 | case ESR_Break: | ||||
4970 | return ESR_Succeeded; | ||||
4971 | case ESR_Succeeded: | ||||
4972 | case ESR_Continue: | ||||
4973 | case ESR_Failed: | ||||
4974 | case ESR_Returned: | ||||
4975 | return ESR; | ||||
4976 | case ESR_CaseNotFound: | ||||
4977 | // This can only happen if the switch case is nested within a statement | ||||
4978 | // expression. We have no intention of supporting that. | ||||
4979 | Info.FFDiag(Found->getBeginLoc(), | ||||
4980 | diag::note_constexpr_stmt_expr_unsupported); | ||||
4981 | return ESR_Failed; | ||||
4982 | } | ||||
4983 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 4983); | ||||
4984 | } | ||||
4985 | |||||
4986 | // Evaluate a statement. | ||||
4987 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, | ||||
4988 | const Stmt *S, const SwitchCase *Case) { | ||||
4989 | if (!Info.nextStep(S)) | ||||
4990 | return ESR_Failed; | ||||
4991 | |||||
4992 | // If we're hunting down a 'case' or 'default' label, recurse through | ||||
4993 | // substatements until we hit the label. | ||||
4994 | if (Case) { | ||||
4995 | switch (S->getStmtClass()) { | ||||
4996 | case Stmt::CompoundStmtClass: | ||||
4997 | // FIXME: Precompute which substatement of a compound statement we | ||||
4998 | // would jump to, and go straight there rather than performing a | ||||
4999 | // linear scan each time. | ||||
5000 | case Stmt::LabelStmtClass: | ||||
5001 | case Stmt::AttributedStmtClass: | ||||
5002 | case Stmt::DoStmtClass: | ||||
5003 | break; | ||||
5004 | |||||
5005 | case Stmt::CaseStmtClass: | ||||
5006 | case Stmt::DefaultStmtClass: | ||||
5007 | if (Case == S) | ||||
5008 | Case = nullptr; | ||||
5009 | break; | ||||
5010 | |||||
5011 | case Stmt::IfStmtClass: { | ||||
5012 | // FIXME: Precompute which side of an 'if' we would jump to, and go | ||||
5013 | // straight there rather than scanning both sides. | ||||
5014 | const IfStmt *IS = cast<IfStmt>(S); | ||||
5015 | |||||
5016 | // Wrap the evaluation in a block scope, in case it's a DeclStmt | ||||
5017 | // preceded by our switch label. | ||||
5018 | BlockScopeRAII Scope(Info); | ||||
5019 | |||||
5020 | // Step into the init statement in case it brings an (uninitialized) | ||||
5021 | // variable into scope. | ||||
5022 | if (const Stmt *Init = IS->getInit()) { | ||||
5023 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); | ||||
5024 | if (ESR != ESR_CaseNotFound) { | ||||
5025 | assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) : __assert_fail ("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5025, __extension__ __PRETTY_FUNCTION__)); | ||||
5026 | return ESR; | ||||
5027 | } | ||||
5028 | } | ||||
5029 | |||||
5030 | // Condition variable must be initialized if it exists. | ||||
5031 | // FIXME: We can skip evaluating the body if there's a condition | ||||
5032 | // variable, as there can't be any case labels within it. | ||||
5033 | // (The same is true for 'for' statements.) | ||||
5034 | |||||
5035 | EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); | ||||
5036 | if (ESR == ESR_Failed) | ||||
5037 | return ESR; | ||||
5038 | if (ESR != ESR_CaseNotFound) | ||||
5039 | return Scope.destroy() ? ESR : ESR_Failed; | ||||
5040 | if (!IS->getElse()) | ||||
5041 | return ESR_CaseNotFound; | ||||
5042 | |||||
5043 | ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); | ||||
5044 | if (ESR == ESR_Failed) | ||||
5045 | return ESR; | ||||
5046 | if (ESR != ESR_CaseNotFound) | ||||
5047 | return Scope.destroy() ? ESR : ESR_Failed; | ||||
5048 | return ESR_CaseNotFound; | ||||
5049 | } | ||||
5050 | |||||
5051 | case Stmt::WhileStmtClass: { | ||||
5052 | EvalStmtResult ESR = | ||||
5053 | EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); | ||||
5054 | if (ESR != ESR_Continue) | ||||
5055 | return ESR; | ||||
5056 | break; | ||||
5057 | } | ||||
5058 | |||||
5059 | case Stmt::ForStmtClass: { | ||||
5060 | const ForStmt *FS = cast<ForStmt>(S); | ||||
5061 | BlockScopeRAII Scope(Info); | ||||
5062 | |||||
5063 | // Step into the init statement in case it brings an (uninitialized) | ||||
5064 | // variable into scope. | ||||
5065 | if (const Stmt *Init = FS->getInit()) { | ||||
5066 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); | ||||
5067 | if (ESR != ESR_CaseNotFound) { | ||||
5068 | assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) : __assert_fail ("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5068, __extension__ __PRETTY_FUNCTION__)); | ||||
5069 | return ESR; | ||||
5070 | } | ||||
5071 | } | ||||
5072 | |||||
5073 | EvalStmtResult ESR = | ||||
5074 | EvaluateLoopBody(Result, Info, FS->getBody(), Case); | ||||
5075 | if (ESR != ESR_Continue) | ||||
5076 | return ESR; | ||||
5077 | if (const auto *Inc = FS->getInc()) { | ||||
5078 | if (Inc->isValueDependent()) { | ||||
5079 | if (!EvaluateDependentExpr(Inc, Info)) | ||||
5080 | return ESR_Failed; | ||||
5081 | } else { | ||||
5082 | FullExpressionRAII IncScope(Info); | ||||
5083 | if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) | ||||
5084 | return ESR_Failed; | ||||
5085 | } | ||||
5086 | } | ||||
5087 | break; | ||||
5088 | } | ||||
5089 | |||||
5090 | case Stmt::DeclStmtClass: { | ||||
5091 | // Start the lifetime of any uninitialized variables we encounter. They | ||||
5092 | // might be used by the selected branch of the switch. | ||||
5093 | const DeclStmt *DS = cast<DeclStmt>(S); | ||||
5094 | for (const auto *D : DS->decls()) { | ||||
5095 | if (const auto *VD = dyn_cast<VarDecl>(D)) { | ||||
5096 | if (VD->hasLocalStorage() && !VD->getInit()) | ||||
5097 | if (!EvaluateVarDecl(Info, VD)) | ||||
5098 | return ESR_Failed; | ||||
5099 | // FIXME: If the variable has initialization that can't be jumped | ||||
5100 | // over, bail out of any immediately-surrounding compound-statement | ||||
5101 | // too. There can't be any case labels here. | ||||
5102 | } | ||||
5103 | } | ||||
5104 | return ESR_CaseNotFound; | ||||
5105 | } | ||||
5106 | |||||
5107 | default: | ||||
5108 | return ESR_CaseNotFound; | ||||
5109 | } | ||||
5110 | } | ||||
5111 | |||||
5112 | switch (S->getStmtClass()) { | ||||
5113 | default: | ||||
5114 | if (const Expr *E = dyn_cast<Expr>(S)) { | ||||
5115 | if (E->isValueDependent()) { | ||||
5116 | if (!EvaluateDependentExpr(E, Info)) | ||||
5117 | return ESR_Failed; | ||||
5118 | } else { | ||||
5119 | // Don't bother evaluating beyond an expression-statement which couldn't | ||||
5120 | // be evaluated. | ||||
5121 | // FIXME: Do we need the FullExpressionRAII object here? | ||||
5122 | // VisitExprWithCleanups should create one when necessary. | ||||
5123 | FullExpressionRAII Scope(Info); | ||||
5124 | if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) | ||||
5125 | return ESR_Failed; | ||||
5126 | } | ||||
5127 | return ESR_Succeeded; | ||||
5128 | } | ||||
5129 | |||||
5130 | Info.FFDiag(S->getBeginLoc()); | ||||
5131 | return ESR_Failed; | ||||
5132 | |||||
5133 | case Stmt::NullStmtClass: | ||||
5134 | return ESR_Succeeded; | ||||
5135 | |||||
5136 | case Stmt::DeclStmtClass: { | ||||
5137 | const DeclStmt *DS = cast<DeclStmt>(S); | ||||
5138 | for (const auto *D : DS->decls()) { | ||||
5139 | // Each declaration initialization is its own full-expression. | ||||
5140 | FullExpressionRAII Scope(Info); | ||||
5141 | if (!EvaluateDecl(Info, D) && !Info.noteFailure()) | ||||
5142 | return ESR_Failed; | ||||
5143 | if (!Scope.destroy()) | ||||
5144 | return ESR_Failed; | ||||
5145 | } | ||||
5146 | return ESR_Succeeded; | ||||
5147 | } | ||||
5148 | |||||
5149 | case Stmt::ReturnStmtClass: { | ||||
5150 | const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); | ||||
5151 | FullExpressionRAII Scope(Info); | ||||
5152 | if (RetExpr && RetExpr->isValueDependent()) { | ||||
5153 | EvaluateDependentExpr(RetExpr, Info); | ||||
5154 | // We know we returned, but we don't know what the value is. | ||||
5155 | return ESR_Failed; | ||||
5156 | } | ||||
5157 | if (RetExpr && | ||||
5158 | !(Result.Slot | ||||
5159 | ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) | ||||
5160 | : Evaluate(Result.Value, Info, RetExpr))) | ||||
5161 | return ESR_Failed; | ||||
5162 | return Scope.destroy() ? ESR_Returned : ESR_Failed; | ||||
5163 | } | ||||
5164 | |||||
5165 | case Stmt::CompoundStmtClass: { | ||||
5166 | BlockScopeRAII Scope(Info); | ||||
5167 | |||||
5168 | const CompoundStmt *CS = cast<CompoundStmt>(S); | ||||
5169 | for (const auto *BI : CS->body()) { | ||||
5170 | EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); | ||||
5171 | if (ESR == ESR_Succeeded) | ||||
5172 | Case = nullptr; | ||||
5173 | else if (ESR != ESR_CaseNotFound) { | ||||
5174 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
5175 | return ESR_Failed; | ||||
5176 | return ESR; | ||||
5177 | } | ||||
5178 | } | ||||
5179 | if (Case) | ||||
5180 | return ESR_CaseNotFound; | ||||
5181 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
5182 | } | ||||
5183 | |||||
5184 | case Stmt::IfStmtClass: { | ||||
5185 | const IfStmt *IS = cast<IfStmt>(S); | ||||
5186 | |||||
5187 | // Evaluate the condition, as either a var decl or as an expression. | ||||
5188 | BlockScopeRAII Scope(Info); | ||||
5189 | if (const Stmt *Init = IS->getInit()) { | ||||
5190 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); | ||||
5191 | if (ESR != ESR_Succeeded) { | ||||
5192 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
5193 | return ESR_Failed; | ||||
5194 | return ESR; | ||||
5195 | } | ||||
5196 | } | ||||
5197 | bool Cond; | ||||
5198 | if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) | ||||
5199 | return ESR_Failed; | ||||
5200 | |||||
5201 | if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { | ||||
5202 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); | ||||
5203 | if (ESR != ESR_Succeeded) { | ||||
5204 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
5205 | return ESR_Failed; | ||||
5206 | return ESR; | ||||
5207 | } | ||||
5208 | } | ||||
5209 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
5210 | } | ||||
5211 | |||||
5212 | case Stmt::WhileStmtClass: { | ||||
5213 | const WhileStmt *WS = cast<WhileStmt>(S); | ||||
5214 | while (true) { | ||||
5215 | BlockScopeRAII Scope(Info); | ||||
5216 | bool Continue; | ||||
5217 | if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), | ||||
5218 | Continue)) | ||||
5219 | return ESR_Failed; | ||||
5220 | if (!Continue) | ||||
5221 | break; | ||||
5222 | |||||
5223 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); | ||||
5224 | if (ESR != ESR_Continue) { | ||||
5225 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
5226 | return ESR_Failed; | ||||
5227 | return ESR; | ||||
5228 | } | ||||
5229 | if (!Scope.destroy()) | ||||
5230 | return ESR_Failed; | ||||
5231 | } | ||||
5232 | return ESR_Succeeded; | ||||
5233 | } | ||||
5234 | |||||
5235 | case Stmt::DoStmtClass: { | ||||
5236 | const DoStmt *DS = cast<DoStmt>(S); | ||||
5237 | bool Continue; | ||||
5238 | do { | ||||
5239 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); | ||||
5240 | if (ESR != ESR_Continue) | ||||
5241 | return ESR; | ||||
5242 | Case = nullptr; | ||||
5243 | |||||
5244 | if (DS->getCond()->isValueDependent()) { | ||||
5245 | EvaluateDependentExpr(DS->getCond(), Info); | ||||
5246 | // Bailout as we don't know whether to keep going or terminate the loop. | ||||
5247 | return ESR_Failed; | ||||
5248 | } | ||||
5249 | FullExpressionRAII CondScope(Info); | ||||
5250 | if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || | ||||
5251 | !CondScope.destroy()) | ||||
5252 | return ESR_Failed; | ||||
5253 | } while (Continue); | ||||
5254 | return ESR_Succeeded; | ||||
5255 | } | ||||
5256 | |||||
5257 | case Stmt::ForStmtClass: { | ||||
5258 | const ForStmt *FS = cast<ForStmt>(S); | ||||
5259 | BlockScopeRAII ForScope(Info); | ||||
5260 | if (FS->getInit()) { | ||||
5261 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); | ||||
5262 | if (ESR != ESR_Succeeded) { | ||||
5263 | if (ESR != ESR_Failed && !ForScope.destroy()) | ||||
5264 | return ESR_Failed; | ||||
5265 | return ESR; | ||||
5266 | } | ||||
5267 | } | ||||
5268 | while (true) { | ||||
5269 | BlockScopeRAII IterScope(Info); | ||||
5270 | bool Continue = true; | ||||
5271 | if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), | ||||
5272 | FS->getCond(), Continue)) | ||||
5273 | return ESR_Failed; | ||||
5274 | if (!Continue) | ||||
5275 | break; | ||||
5276 | |||||
5277 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); | ||||
5278 | if (ESR != ESR_Continue) { | ||||
5279 | if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) | ||||
5280 | return ESR_Failed; | ||||
5281 | return ESR; | ||||
5282 | } | ||||
5283 | |||||
5284 | if (const auto *Inc = FS->getInc()) { | ||||
5285 | if (Inc->isValueDependent()) { | ||||
5286 | if (!EvaluateDependentExpr(Inc, Info)) | ||||
5287 | return ESR_Failed; | ||||
5288 | } else { | ||||
5289 | FullExpressionRAII IncScope(Info); | ||||
5290 | if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) | ||||
5291 | return ESR_Failed; | ||||
5292 | } | ||||
5293 | } | ||||
5294 | |||||
5295 | if (!IterScope.destroy()) | ||||
5296 | return ESR_Failed; | ||||
5297 | } | ||||
5298 | return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
5299 | } | ||||
5300 | |||||
5301 | case Stmt::CXXForRangeStmtClass: { | ||||
5302 | const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); | ||||
5303 | BlockScopeRAII Scope(Info); | ||||
5304 | |||||
5305 | // Evaluate the init-statement if present. | ||||
5306 | if (FS->getInit()) { | ||||
5307 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); | ||||
5308 | if (ESR != ESR_Succeeded) { | ||||
5309 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
5310 | return ESR_Failed; | ||||
5311 | return ESR; | ||||
5312 | } | ||||
5313 | } | ||||
5314 | |||||
5315 | // Initialize the __range variable. | ||||
5316 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); | ||||
5317 | if (ESR != ESR_Succeeded) { | ||||
5318 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
5319 | return ESR_Failed; | ||||
5320 | return ESR; | ||||
5321 | } | ||||
5322 | |||||
5323 | // Create the __begin and __end iterators. | ||||
5324 | ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); | ||||
5325 | if (ESR != ESR_Succeeded) { | ||||
5326 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
5327 | return ESR_Failed; | ||||
5328 | return ESR; | ||||
5329 | } | ||||
5330 | ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); | ||||
5331 | if (ESR != ESR_Succeeded) { | ||||
5332 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
5333 | return ESR_Failed; | ||||
5334 | return ESR; | ||||
5335 | } | ||||
5336 | |||||
5337 | while (true) { | ||||
5338 | // Condition: __begin != __end. | ||||
5339 | { | ||||
5340 | if (FS->getCond()->isValueDependent()) { | ||||
5341 | EvaluateDependentExpr(FS->getCond(), Info); | ||||
5342 | // We don't know whether to keep going or terminate the loop. | ||||
5343 | return ESR_Failed; | ||||
5344 | } | ||||
5345 | bool Continue = true; | ||||
5346 | FullExpressionRAII CondExpr(Info); | ||||
5347 | if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) | ||||
5348 | return ESR_Failed; | ||||
5349 | if (!Continue) | ||||
5350 | break; | ||||
5351 | } | ||||
5352 | |||||
5353 | // User's variable declaration, initialized by *__begin. | ||||
5354 | BlockScopeRAII InnerScope(Info); | ||||
5355 | ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); | ||||
5356 | if (ESR != ESR_Succeeded) { | ||||
5357 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) | ||||
5358 | return ESR_Failed; | ||||
5359 | return ESR; | ||||
5360 | } | ||||
5361 | |||||
5362 | // Loop body. | ||||
5363 | ESR = EvaluateLoopBody(Result, Info, FS->getBody()); | ||||
5364 | if (ESR != ESR_Continue) { | ||||
5365 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) | ||||
5366 | return ESR_Failed; | ||||
5367 | return ESR; | ||||
5368 | } | ||||
5369 | if (FS->getInc()->isValueDependent()) { | ||||
5370 | if (!EvaluateDependentExpr(FS->getInc(), Info)) | ||||
5371 | return ESR_Failed; | ||||
5372 | } else { | ||||
5373 | // Increment: ++__begin | ||||
5374 | if (!EvaluateIgnoredValue(Info, FS->getInc())) | ||||
5375 | return ESR_Failed; | ||||
5376 | } | ||||
5377 | |||||
5378 | if (!InnerScope.destroy()) | ||||
5379 | return ESR_Failed; | ||||
5380 | } | ||||
5381 | |||||
5382 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
5383 | } | ||||
5384 | |||||
5385 | case Stmt::SwitchStmtClass: | ||||
5386 | return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); | ||||
5387 | |||||
5388 | case Stmt::ContinueStmtClass: | ||||
5389 | return ESR_Continue; | ||||
5390 | |||||
5391 | case Stmt::BreakStmtClass: | ||||
5392 | return ESR_Break; | ||||
5393 | |||||
5394 | case Stmt::LabelStmtClass: | ||||
5395 | return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); | ||||
5396 | |||||
5397 | case Stmt::AttributedStmtClass: | ||||
5398 | // As a general principle, C++11 attributes can be ignored without | ||||
5399 | // any semantic impact. | ||||
5400 | return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), | ||||
5401 | Case); | ||||
5402 | |||||
5403 | case Stmt::CaseStmtClass: | ||||
5404 | case Stmt::DefaultStmtClass: | ||||
5405 | return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); | ||||
5406 | case Stmt::CXXTryStmtClass: | ||||
5407 | // Evaluate try blocks by evaluating all sub statements. | ||||
5408 | return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); | ||||
5409 | } | ||||
5410 | } | ||||
5411 | |||||
5412 | /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial | ||||
5413 | /// default constructor. If so, we'll fold it whether or not it's marked as | ||||
5414 | /// constexpr. If it is marked as constexpr, we will never implicitly define it, | ||||
5415 | /// so we need special handling. | ||||
5416 | static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, | ||||
5417 | const CXXConstructorDecl *CD, | ||||
5418 | bool IsValueInitialization) { | ||||
5419 | if (!CD->isTrivial() || !CD->isDefaultConstructor()) | ||||
5420 | return false; | ||||
5421 | |||||
5422 | // Value-initialization does not call a trivial default constructor, so such a | ||||
5423 | // call is a core constant expression whether or not the constructor is | ||||
5424 | // constexpr. | ||||
5425 | if (!CD->isConstexpr() && !IsValueInitialization) { | ||||
5426 | if (Info.getLangOpts().CPlusPlus11) { | ||||
5427 | // FIXME: If DiagDecl is an implicitly-declared special member function, | ||||
5428 | // we should be much more explicit about why it's not constexpr. | ||||
5429 | Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) | ||||
5430 | << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; | ||||
5431 | Info.Note(CD->getLocation(), diag::note_declared_at); | ||||
5432 | } else { | ||||
5433 | Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); | ||||
5434 | } | ||||
5435 | } | ||||
5436 | return true; | ||||
5437 | } | ||||
5438 | |||||
5439 | /// CheckConstexprFunction - Check that a function can be called in a constant | ||||
5440 | /// expression. | ||||
5441 | static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, | ||||
5442 | const FunctionDecl *Declaration, | ||||
5443 | const FunctionDecl *Definition, | ||||
5444 | const Stmt *Body) { | ||||
5445 | // Potential constant expressions can contain calls to declared, but not yet | ||||
5446 | // defined, constexpr functions. | ||||
5447 | if (Info.checkingPotentialConstantExpression() && !Definition && | ||||
5448 | Declaration->isConstexpr()) | ||||
5449 | return false; | ||||
5450 | |||||
5451 | // Bail out if the function declaration itself is invalid. We will | ||||
5452 | // have produced a relevant diagnostic while parsing it, so just | ||||
5453 | // note the problematic sub-expression. | ||||
5454 | if (Declaration->isInvalidDecl()) { | ||||
5455 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||
5456 | return false; | ||||
5457 | } | ||||
5458 | |||||
5459 | // DR1872: An instantiated virtual constexpr function can't be called in a | ||||
5460 | // constant expression (prior to C++20). We can still constant-fold such a | ||||
5461 | // call. | ||||
5462 | if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && | ||||
5463 | cast<CXXMethodDecl>(Declaration)->isVirtual()) | ||||
5464 | Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); | ||||
5465 | |||||
5466 | if (Definition && Definition->isInvalidDecl()) { | ||||
5467 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||
5468 | return false; | ||||
5469 | } | ||||
5470 | |||||
5471 | // Can we evaluate this function call? | ||||
5472 | if (Definition && Definition->isConstexpr() && Body) | ||||
5473 | return true; | ||||
5474 | |||||
5475 | if (Info.getLangOpts().CPlusPlus11) { | ||||
5476 | const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; | ||||
5477 | |||||
5478 | // If this function is not constexpr because it is an inherited | ||||
5479 | // non-constexpr constructor, diagnose that directly. | ||||
5480 | auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); | ||||
5481 | if (CD && CD->isInheritingConstructor()) { | ||||
5482 | auto *Inherited = CD->getInheritedConstructor().getConstructor(); | ||||
5483 | if (!Inherited->isConstexpr()) | ||||
5484 | DiagDecl = CD = Inherited; | ||||
5485 | } | ||||
5486 | |||||
5487 | // FIXME: If DiagDecl is an implicitly-declared special member function | ||||
5488 | // or an inheriting constructor, we should be much more explicit about why | ||||
5489 | // it's not constexpr. | ||||
5490 | if (CD && CD->isInheritingConstructor()) | ||||
5491 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) | ||||
5492 | << CD->getInheritedConstructor().getConstructor()->getParent(); | ||||
5493 | else | ||||
5494 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) | ||||
5495 | << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; | ||||
5496 | Info.Note(DiagDecl->getLocation(), diag::note_declared_at); | ||||
5497 | } else { | ||||
5498 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||
5499 | } | ||||
5500 | return false; | ||||
5501 | } | ||||
5502 | |||||
5503 | namespace { | ||||
5504 | struct CheckDynamicTypeHandler { | ||||
5505 | AccessKinds AccessKind; | ||||
5506 | typedef bool result_type; | ||||
5507 | bool failed() { return false; } | ||||
5508 | bool found(APValue &Subobj, QualType SubobjType) { return true; } | ||||
5509 | bool found(APSInt &Value, QualType SubobjType) { return true; } | ||||
5510 | bool found(APFloat &Value, QualType SubobjType) { return true; } | ||||
5511 | }; | ||||
5512 | } // end anonymous namespace | ||||
5513 | |||||
5514 | /// Check that we can access the notional vptr of an object / determine its | ||||
5515 | /// dynamic type. | ||||
5516 | static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, | ||||
5517 | AccessKinds AK, bool Polymorphic) { | ||||
5518 | if (This.Designator.Invalid) | ||||
5519 | return false; | ||||
5520 | |||||
5521 | CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); | ||||
5522 | |||||
5523 | if (!Obj) | ||||
5524 | return false; | ||||
5525 | |||||
5526 | if (!Obj.Value) { | ||||
5527 | // The object is not usable in constant expressions, so we can't inspect | ||||
5528 | // its value to see if it's in-lifetime or what the active union members | ||||
5529 | // are. We can still check for a one-past-the-end lvalue. | ||||
5530 | if (This.Designator.isOnePastTheEnd() || | ||||
5531 | This.Designator.isMostDerivedAnUnsizedArray()) { | ||||
5532 | Info.FFDiag(E, This.Designator.isOnePastTheEnd() | ||||
5533 | ? diag::note_constexpr_access_past_end | ||||
5534 | : diag::note_constexpr_access_unsized_array) | ||||
5535 | << AK; | ||||
5536 | return false; | ||||
5537 | } else if (Polymorphic) { | ||||
5538 | // Conservatively refuse to perform a polymorphic operation if we would | ||||
5539 | // not be able to read a notional 'vptr' value. | ||||
5540 | APValue Val; | ||||
5541 | This.moveInto(Val); | ||||
5542 | QualType StarThisType = | ||||
5543 | Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); | ||||
5544 | Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) | ||||
5545 | << AK << Val.getAsString(Info.Ctx, StarThisType); | ||||
5546 | return false; | ||||
5547 | } | ||||
5548 | return true; | ||||
5549 | } | ||||
5550 | |||||
5551 | CheckDynamicTypeHandler Handler{AK}; | ||||
5552 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); | ||||
5553 | } | ||||
5554 | |||||
5555 | /// Check that the pointee of the 'this' pointer in a member function call is | ||||
5556 | /// either within its lifetime or in its period of construction or destruction. | ||||
5557 | static bool | ||||
5558 | checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, | ||||
5559 | const LValue &This, | ||||
5560 | const CXXMethodDecl *NamedMember) { | ||||
5561 | return checkDynamicType( | ||||
5562 | Info, E, This, | ||||
5563 | isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); | ||||
5564 | } | ||||
5565 | |||||
5566 | struct DynamicType { | ||||
5567 | /// The dynamic class type of the object. | ||||
5568 | const CXXRecordDecl *Type; | ||||
5569 | /// The corresponding path length in the lvalue. | ||||
5570 | unsigned PathLength; | ||||
5571 | }; | ||||
5572 | |||||
5573 | static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, | ||||
5574 | unsigned PathLength) { | ||||
5575 | assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5576, __extension__ __PRETTY_FUNCTION__)) | ||||
5576 | Designator.Entries.size() && "invalid path length")(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5576, __extension__ __PRETTY_FUNCTION__)); | ||||
5577 | return (PathLength == Designator.MostDerivedPathLength) | ||||
5578 | ? Designator.MostDerivedType->getAsCXXRecordDecl() | ||||
5579 | : getAsBaseClass(Designator.Entries[PathLength - 1]); | ||||
5580 | } | ||||
5581 | |||||
5582 | /// Determine the dynamic type of an object. | ||||
5583 | static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, | ||||
5584 | LValue &This, AccessKinds AK) { | ||||
5585 | // If we don't have an lvalue denoting an object of class type, there is no | ||||
5586 | // meaningful dynamic type. (We consider objects of non-class type to have no | ||||
5587 | // dynamic type.) | ||||
5588 | if (!checkDynamicType(Info, E, This, AK, true)) | ||||
5589 | return None; | ||||
5590 | |||||
5591 | // Refuse to compute a dynamic type in the presence of virtual bases. This | ||||
5592 | // shouldn't happen other than in constant-folding situations, since literal | ||||
5593 | // types can't have virtual bases. | ||||
5594 | // | ||||
5595 | // Note that consumers of DynamicType assume that the type has no virtual | ||||
5596 | // bases, and will need modifications if this restriction is relaxed. | ||||
5597 | const CXXRecordDecl *Class = | ||||
5598 | This.Designator.MostDerivedType->getAsCXXRecordDecl(); | ||||
5599 | if (!Class || Class->getNumVBases()) { | ||||
5600 | Info.FFDiag(E); | ||||
5601 | return None; | ||||
5602 | } | ||||
5603 | |||||
5604 | // FIXME: For very deep class hierarchies, it might be beneficial to use a | ||||
5605 | // binary search here instead. But the overwhelmingly common case is that | ||||
5606 | // we're not in the middle of a constructor, so it probably doesn't matter | ||||
5607 | // in practice. | ||||
5608 | ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; | ||||
5609 | for (unsigned PathLength = This.Designator.MostDerivedPathLength; | ||||
5610 | PathLength <= Path.size(); ++PathLength) { | ||||
5611 | switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), | ||||
5612 | Path.slice(0, PathLength))) { | ||||
5613 | case ConstructionPhase::Bases: | ||||
5614 | case ConstructionPhase::DestroyingBases: | ||||
5615 | // We're constructing or destroying a base class. This is not the dynamic | ||||
5616 | // type. | ||||
5617 | break; | ||||
5618 | |||||
5619 | case ConstructionPhase::None: | ||||
5620 | case ConstructionPhase::AfterBases: | ||||
5621 | case ConstructionPhase::AfterFields: | ||||
5622 | case ConstructionPhase::Destroying: | ||||
5623 | // We've finished constructing the base classes and not yet started | ||||
5624 | // destroying them again, so this is the dynamic type. | ||||
5625 | return DynamicType{getBaseClassType(This.Designator, PathLength), | ||||
5626 | PathLength}; | ||||
5627 | } | ||||
5628 | } | ||||
5629 | |||||
5630 | // CWG issue 1517: we're constructing a base class of the object described by | ||||
5631 | // 'This', so that object has not yet begun its period of construction and | ||||
5632 | // any polymorphic operation on it results in undefined behavior. | ||||
5633 | Info.FFDiag(E); | ||||
5634 | return None; | ||||
5635 | } | ||||
5636 | |||||
5637 | /// Perform virtual dispatch. | ||||
5638 | static const CXXMethodDecl *HandleVirtualDispatch( | ||||
5639 | EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, | ||||
5640 | llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { | ||||
5641 | Optional<DynamicType> DynType = ComputeDynamicType( | ||||
5642 | Info, E, This, | ||||
5643 | isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); | ||||
5644 | if (!DynType) | ||||
5645 | return nullptr; | ||||
5646 | |||||
5647 | // Find the final overrider. It must be declared in one of the classes on the | ||||
5648 | // path from the dynamic type to the static type. | ||||
5649 | // FIXME: If we ever allow literal types to have virtual base classes, that | ||||
5650 | // won't be true. | ||||
5651 | const CXXMethodDecl *Callee = Found; | ||||
5652 | unsigned PathLength = DynType->PathLength; | ||||
5653 | for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { | ||||
5654 | const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); | ||||
5655 | const CXXMethodDecl *Overrider = | ||||
5656 | Found->getCorrespondingMethodDeclaredInClass(Class, false); | ||||
5657 | if (Overrider) { | ||||
5658 | Callee = Overrider; | ||||
5659 | break; | ||||
5660 | } | ||||
5661 | } | ||||
5662 | |||||
5663 | // C++2a [class.abstract]p6: | ||||
5664 | // the effect of making a virtual call to a pure virtual function [...] is | ||||
5665 | // undefined | ||||
5666 | if (Callee->isPure()) { | ||||
5667 | Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; | ||||
5668 | Info.Note(Callee->getLocation(), diag::note_declared_at); | ||||
5669 | return nullptr; | ||||
5670 | } | ||||
5671 | |||||
5672 | // If necessary, walk the rest of the path to determine the sequence of | ||||
5673 | // covariant adjustment steps to apply. | ||||
5674 | if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), | ||||
5675 | Found->getReturnType())) { | ||||
5676 | CovariantAdjustmentPath.push_back(Callee->getReturnType()); | ||||
5677 | for (unsigned CovariantPathLength = PathLength + 1; | ||||
5678 | CovariantPathLength != This.Designator.Entries.size(); | ||||
5679 | ++CovariantPathLength) { | ||||
5680 | const CXXRecordDecl *NextClass = | ||||
5681 | getBaseClassType(This.Designator, CovariantPathLength); | ||||
5682 | const CXXMethodDecl *Next = | ||||
5683 | Found->getCorrespondingMethodDeclaredInClass(NextClass, false); | ||||
5684 | if (Next && !Info.Ctx.hasSameUnqualifiedType( | ||||
5685 | Next->getReturnType(), CovariantAdjustmentPath.back())) | ||||
5686 | CovariantAdjustmentPath.push_back(Next->getReturnType()); | ||||
5687 | } | ||||
5688 | if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), | ||||
5689 | CovariantAdjustmentPath.back())) | ||||
5690 | CovariantAdjustmentPath.push_back(Found->getReturnType()); | ||||
5691 | } | ||||
5692 | |||||
5693 | // Perform 'this' adjustment. | ||||
5694 | if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) | ||||
5695 | return nullptr; | ||||
5696 | |||||
5697 | return Callee; | ||||
5698 | } | ||||
5699 | |||||
5700 | /// Perform the adjustment from a value returned by a virtual function to | ||||
5701 | /// a value of the statically expected type, which may be a pointer or | ||||
5702 | /// reference to a base class of the returned type. | ||||
5703 | static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, | ||||
5704 | APValue &Result, | ||||
5705 | ArrayRef<QualType> Path) { | ||||
5706 | assert(Result.isLValue() &&(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5707, __extension__ __PRETTY_FUNCTION__)) | ||||
5707 | "unexpected kind of APValue for covariant return")(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5707, __extension__ __PRETTY_FUNCTION__)); | ||||
5708 | if (Result.isNullPointer()) | ||||
5709 | return true; | ||||
5710 | |||||
5711 | LValue LVal; | ||||
5712 | LVal.setFrom(Info.Ctx, Result); | ||||
5713 | |||||
5714 | const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); | ||||
5715 | for (unsigned I = 1; I != Path.size(); ++I) { | ||||
5716 | const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); | ||||
5717 | assert(OldClass && NewClass && "unexpected kind of covariant return")(static_cast <bool> (OldClass && NewClass && "unexpected kind of covariant return") ? void (0) : __assert_fail ("OldClass && NewClass && \"unexpected kind of covariant return\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5717, __extension__ __PRETTY_FUNCTION__)); | ||||
5718 | if (OldClass != NewClass && | ||||
5719 | !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) | ||||
5720 | return false; | ||||
5721 | OldClass = NewClass; | ||||
5722 | } | ||||
5723 | |||||
5724 | LVal.moveInto(Result); | ||||
5725 | return true; | ||||
5726 | } | ||||
5727 | |||||
5728 | /// Determine whether \p Base, which is known to be a direct base class of | ||||
5729 | /// \p Derived, is a public base class. | ||||
5730 | static bool isBaseClassPublic(const CXXRecordDecl *Derived, | ||||
5731 | const CXXRecordDecl *Base) { | ||||
5732 | for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { | ||||
5733 | auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); | ||||
5734 | if (BaseClass && declaresSameEntity(BaseClass, Base)) | ||||
5735 | return BaseSpec.getAccessSpecifier() == AS_public; | ||||
5736 | } | ||||
5737 | llvm_unreachable("Base is not a direct base of Derived")::llvm::llvm_unreachable_internal("Base is not a direct base of Derived" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5737); | ||||
5738 | } | ||||
5739 | |||||
5740 | /// Apply the given dynamic cast operation on the provided lvalue. | ||||
5741 | /// | ||||
5742 | /// This implements the hard case of dynamic_cast, requiring a "runtime check" | ||||
5743 | /// to find a suitable target subobject. | ||||
5744 | static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, | ||||
5745 | LValue &Ptr) { | ||||
5746 | // We can't do anything with a non-symbolic pointer value. | ||||
5747 | SubobjectDesignator &D = Ptr.Designator; | ||||
5748 | if (D.Invalid) | ||||
5749 | return false; | ||||
5750 | |||||
5751 | // C++ [expr.dynamic.cast]p6: | ||||
5752 | // If v is a null pointer value, the result is a null pointer value. | ||||
5753 | if (Ptr.isNullPointer() && !E->isGLValue()) | ||||
5754 | return true; | ||||
5755 | |||||
5756 | // For all the other cases, we need the pointer to point to an object within | ||||
5757 | // its lifetime / period of construction / destruction, and we need to know | ||||
5758 | // its dynamic type. | ||||
5759 | Optional<DynamicType> DynType = | ||||
5760 | ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); | ||||
5761 | if (!DynType) | ||||
5762 | return false; | ||||
5763 | |||||
5764 | // C++ [expr.dynamic.cast]p7: | ||||
5765 | // If T is "pointer to cv void", then the result is a pointer to the most | ||||
5766 | // derived object | ||||
5767 | if (E->getType()->isVoidPointerType()) | ||||
5768 | return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); | ||||
5769 | |||||
5770 | const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); | ||||
5771 | assert(C && "dynamic_cast target is not void pointer nor class")(static_cast <bool> (C && "dynamic_cast target is not void pointer nor class" ) ? void (0) : __assert_fail ("C && \"dynamic_cast target is not void pointer nor class\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5771, __extension__ __PRETTY_FUNCTION__)); | ||||
5772 | CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); | ||||
5773 | |||||
5774 | auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { | ||||
5775 | // C++ [expr.dynamic.cast]p9: | ||||
5776 | if (!E->isGLValue()) { | ||||
5777 | // The value of a failed cast to pointer type is the null pointer value | ||||
5778 | // of the required result type. | ||||
5779 | Ptr.setNull(Info.Ctx, E->getType()); | ||||
5780 | return true; | ||||
5781 | } | ||||
5782 | |||||
5783 | // A failed cast to reference type throws [...] std::bad_cast. | ||||
5784 | unsigned DiagKind; | ||||
5785 | if (!Paths && (declaresSameEntity(DynType->Type, C) || | ||||
5786 | DynType->Type->isDerivedFrom(C))) | ||||
5787 | DiagKind = 0; | ||||
5788 | else if (!Paths || Paths->begin() == Paths->end()) | ||||
5789 | DiagKind = 1; | ||||
5790 | else if (Paths->isAmbiguous(CQT)) | ||||
5791 | DiagKind = 2; | ||||
5792 | else { | ||||
5793 | assert(Paths->front().Access != AS_public && "why did the cast fail?")(static_cast <bool> (Paths->front().Access != AS_public && "why did the cast fail?") ? void (0) : __assert_fail ("Paths->front().Access != AS_public && \"why did the cast fail?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5793, __extension__ __PRETTY_FUNCTION__)); | ||||
5794 | DiagKind = 3; | ||||
5795 | } | ||||
5796 | Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) | ||||
5797 | << DiagKind << Ptr.Designator.getType(Info.Ctx) | ||||
5798 | << Info.Ctx.getRecordType(DynType->Type) | ||||
5799 | << E->getType().getUnqualifiedType(); | ||||
5800 | return false; | ||||
5801 | }; | ||||
5802 | |||||
5803 | // Runtime check, phase 1: | ||||
5804 | // Walk from the base subobject towards the derived object looking for the | ||||
5805 | // target type. | ||||
5806 | for (int PathLength = Ptr.Designator.Entries.size(); | ||||
5807 | PathLength >= (int)DynType->PathLength; --PathLength) { | ||||
5808 | const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); | ||||
5809 | if (declaresSameEntity(Class, C)) | ||||
5810 | return CastToDerivedClass(Info, E, Ptr, Class, PathLength); | ||||
5811 | // We can only walk across public inheritance edges. | ||||
5812 | if (PathLength > (int)DynType->PathLength && | ||||
5813 | !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), | ||||
5814 | Class)) | ||||
5815 | return RuntimeCheckFailed(nullptr); | ||||
5816 | } | ||||
5817 | |||||
5818 | // Runtime check, phase 2: | ||||
5819 | // Search the dynamic type for an unambiguous public base of type C. | ||||
5820 | CXXBasePaths Paths(/*FindAmbiguities=*/true, | ||||
5821 | /*RecordPaths=*/true, /*DetectVirtual=*/false); | ||||
5822 | if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && | ||||
5823 | Paths.front().Access == AS_public) { | ||||
5824 | // Downcast to the dynamic type... | ||||
5825 | if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) | ||||
5826 | return false; | ||||
5827 | // ... then upcast to the chosen base class subobject. | ||||
5828 | for (CXXBasePathElement &Elem : Paths.front()) | ||||
5829 | if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) | ||||
5830 | return false; | ||||
5831 | return true; | ||||
5832 | } | ||||
5833 | |||||
5834 | // Otherwise, the runtime check fails. | ||||
5835 | return RuntimeCheckFailed(&Paths); | ||||
5836 | } | ||||
5837 | |||||
5838 | namespace { | ||||
5839 | struct StartLifetimeOfUnionMemberHandler { | ||||
5840 | EvalInfo &Info; | ||||
5841 | const Expr *LHSExpr; | ||||
5842 | const FieldDecl *Field; | ||||
5843 | bool DuringInit; | ||||
5844 | bool Failed = false; | ||||
5845 | static const AccessKinds AccessKind = AK_Assign; | ||||
5846 | |||||
5847 | typedef bool result_type; | ||||
5848 | bool failed() { return Failed; } | ||||
5849 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
5850 | // We are supposed to perform no initialization but begin the lifetime of | ||||
5851 | // the object. We interpret that as meaning to do what default | ||||
5852 | // initialization of the object would do if all constructors involved were | ||||
5853 | // trivial: | ||||
5854 | // * All base, non-variant member, and array element subobjects' lifetimes | ||||
5855 | // begin | ||||
5856 | // * No variant members' lifetimes begin | ||||
5857 | // * All scalar subobjects whose lifetimes begin have indeterminate values | ||||
5858 | assert(SubobjType->isUnionType())(static_cast <bool> (SubobjType->isUnionType()) ? void (0) : __assert_fail ("SubobjType->isUnionType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5858, __extension__ __PRETTY_FUNCTION__)); | ||||
5859 | if (declaresSameEntity(Subobj.getUnionField(), Field)) { | ||||
5860 | // This union member is already active. If it's also in-lifetime, there's | ||||
5861 | // nothing to do. | ||||
5862 | if (Subobj.getUnionValue().hasValue()) | ||||
5863 | return true; | ||||
5864 | } else if (DuringInit) { | ||||
5865 | // We're currently in the process of initializing a different union | ||||
5866 | // member. If we carried on, that initialization would attempt to | ||||
5867 | // store to an inactive union member, resulting in undefined behavior. | ||||
5868 | Info.FFDiag(LHSExpr, | ||||
5869 | diag::note_constexpr_union_member_change_during_init); | ||||
5870 | return false; | ||||
5871 | } | ||||
5872 | APValue Result; | ||||
5873 | Failed = !getDefaultInitValue(Field->getType(), Result); | ||||
5874 | Subobj.setUnion(Field, Result); | ||||
5875 | return true; | ||||
5876 | } | ||||
5877 | bool found(APSInt &Value, QualType SubobjType) { | ||||
5878 | llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5878); | ||||
5879 | } | ||||
5880 | bool found(APFloat &Value, QualType SubobjType) { | ||||
5881 | llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5881); | ||||
5882 | } | ||||
5883 | }; | ||||
5884 | } // end anonymous namespace | ||||
5885 | |||||
5886 | const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; | ||||
5887 | |||||
5888 | /// Handle a builtin simple-assignment or a call to a trivial assignment | ||||
5889 | /// operator whose left-hand side might involve a union member access. If it | ||||
5890 | /// does, implicitly start the lifetime of any accessed union elements per | ||||
5891 | /// C++20 [class.union]5. | ||||
5892 | static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, | ||||
5893 | const LValue &LHS) { | ||||
5894 | if (LHS.InvalidBase || LHS.Designator.Invalid) | ||||
5895 | return false; | ||||
5896 | |||||
5897 | llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; | ||||
5898 | // C++ [class.union]p5: | ||||
5899 | // define the set S(E) of subexpressions of E as follows: | ||||
5900 | unsigned PathLength = LHS.Designator.Entries.size(); | ||||
5901 | for (const Expr *E = LHSExpr; E != nullptr;) { | ||||
5902 | // -- If E is of the form A.B, S(E) contains the elements of S(A)... | ||||
5903 | if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||
5904 | auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | ||||
5905 | // Note that we can't implicitly start the lifetime of a reference, | ||||
5906 | // so we don't need to proceed any further if we reach one. | ||||
5907 | if (!FD || FD->getType()->isReferenceType()) | ||||
5908 | break; | ||||
5909 | |||||
5910 | // ... and also contains A.B if B names a union member ... | ||||
5911 | if (FD->getParent()->isUnion()) { | ||||
5912 | // ... of a non-class, non-array type, or of a class type with a | ||||
5913 | // trivial default constructor that is not deleted, or an array of | ||||
5914 | // such types. | ||||
5915 | auto *RD = | ||||
5916 | FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||
5917 | if (!RD || RD->hasTrivialDefaultConstructor()) | ||||
5918 | UnionPathLengths.push_back({PathLength - 1, FD}); | ||||
5919 | } | ||||
5920 | |||||
5921 | E = ME->getBase(); | ||||
5922 | --PathLength; | ||||
5923 | assert(declaresSameEntity(FD,(static_cast <bool> (declaresSameEntity(FD, LHS.Designator .Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5925, __extension__ __PRETTY_FUNCTION__)) | ||||
5924 | LHS.Designator.Entries[PathLength](static_cast <bool> (declaresSameEntity(FD, LHS.Designator .Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5925, __extension__ __PRETTY_FUNCTION__)) | ||||
5925 | .getAsBaseOrMember().getPointer()))(static_cast <bool> (declaresSameEntity(FD, LHS.Designator .Entries[PathLength] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5925, __extension__ __PRETTY_FUNCTION__)); | ||||
5926 | |||||
5927 | // -- If E is of the form A[B] and is interpreted as a built-in array | ||||
5928 | // subscripting operator, S(E) is [S(the array operand, if any)]. | ||||
5929 | } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { | ||||
5930 | // Step over an ArrayToPointerDecay implicit cast. | ||||
5931 | auto *Base = ASE->getBase()->IgnoreImplicit(); | ||||
5932 | if (!Base->getType()->isArrayType()) | ||||
5933 | break; | ||||
5934 | |||||
5935 | E = Base; | ||||
5936 | --PathLength; | ||||
5937 | |||||
5938 | } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { | ||||
5939 | // Step over a derived-to-base conversion. | ||||
5940 | E = ICE->getSubExpr(); | ||||
5941 | if (ICE->getCastKind() == CK_NoOp) | ||||
5942 | continue; | ||||
5943 | if (ICE->getCastKind() != CK_DerivedToBase && | ||||
5944 | ICE->getCastKind() != CK_UncheckedDerivedToBase) | ||||
5945 | break; | ||||
5946 | // Walk path backwards as we walk up from the base to the derived class. | ||||
5947 | for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { | ||||
5948 | --PathLength; | ||||
5949 | (void)Elt; | ||||
5950 | assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),(static_cast <bool> (declaresSameEntity(Elt->getType ()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength ] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5952, __extension__ __PRETTY_FUNCTION__)) | ||||
5951 | LHS.Designator.Entries[PathLength](static_cast <bool> (declaresSameEntity(Elt->getType ()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength ] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5952, __extension__ __PRETTY_FUNCTION__)) | ||||
5952 | .getAsBaseOrMember().getPointer()))(static_cast <bool> (declaresSameEntity(Elt->getType ()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength ] .getAsBaseOrMember().getPointer())) ? void (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 5952, __extension__ __PRETTY_FUNCTION__)); | ||||
5953 | } | ||||
5954 | |||||
5955 | // -- Otherwise, S(E) is empty. | ||||
5956 | } else { | ||||
5957 | break; | ||||
5958 | } | ||||
5959 | } | ||||
5960 | |||||
5961 | // Common case: no unions' lifetimes are started. | ||||
5962 | if (UnionPathLengths.empty()) | ||||
5963 | return true; | ||||
5964 | |||||
5965 | // if modification of X [would access an inactive union member], an object | ||||
5966 | // of the type of X is implicitly created | ||||
5967 | CompleteObject Obj = | ||||
5968 | findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); | ||||
5969 | if (!Obj) | ||||
5970 | return false; | ||||
5971 | for (std::pair<unsigned, const FieldDecl *> LengthAndField : | ||||
5972 | llvm::reverse(UnionPathLengths)) { | ||||
5973 | // Form a designator for the union object. | ||||
5974 | SubobjectDesignator D = LHS.Designator; | ||||
5975 | D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); | ||||
5976 | |||||
5977 | bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == | ||||
5978 | ConstructionPhase::AfterBases; | ||||
5979 | StartLifetimeOfUnionMemberHandler StartLifetime{ | ||||
5980 | Info, LHSExpr, LengthAndField.second, DuringInit}; | ||||
5981 | if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) | ||||
5982 | return false; | ||||
5983 | } | ||||
5984 | |||||
5985 | return true; | ||||
5986 | } | ||||
5987 | |||||
5988 | static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, | ||||
5989 | CallRef Call, EvalInfo &Info, | ||||
5990 | bool NonNull = false) { | ||||
5991 | LValue LV; | ||||
5992 | // Create the parameter slot and register its destruction. For a vararg | ||||
5993 | // argument, create a temporary. | ||||
5994 | // FIXME: For calling conventions that destroy parameters in the callee, | ||||
5995 | // should we consider performing destruction when the function returns | ||||
5996 | // instead? | ||||
5997 | APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) | ||||
5998 | : Info.CurrentCall->createTemporary(Arg, Arg->getType(), | ||||
5999 | ScopeKind::Call, LV); | ||||
6000 | if (!EvaluateInPlace(V, Info, LV, Arg)) | ||||
6001 | return false; | ||||
6002 | |||||
6003 | // Passing a null pointer to an __attribute__((nonnull)) parameter results in | ||||
6004 | // undefined behavior, so is non-constant. | ||||
6005 | if (NonNull && V.isLValue() && V.isNullPointer()) { | ||||
6006 | Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); | ||||
6007 | return false; | ||||
6008 | } | ||||
6009 | |||||
6010 | return true; | ||||
6011 | } | ||||
6012 | |||||
6013 | /// Evaluate the arguments to a function call. | ||||
6014 | static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, | ||||
6015 | EvalInfo &Info, const FunctionDecl *Callee, | ||||
6016 | bool RightToLeft = false) { | ||||
6017 | bool Success = true; | ||||
6018 | llvm::SmallBitVector ForbiddenNullArgs; | ||||
6019 | if (Callee->hasAttr<NonNullAttr>()) { | ||||
6020 | ForbiddenNullArgs.resize(Args.size()); | ||||
6021 | for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { | ||||
6022 | if (!Attr->args_size()) { | ||||
6023 | ForbiddenNullArgs.set(); | ||||
6024 | break; | ||||
6025 | } else | ||||
6026 | for (auto Idx : Attr->args()) { | ||||
6027 | unsigned ASTIdx = Idx.getASTIndex(); | ||||
6028 | if (ASTIdx >= Args.size()) | ||||
6029 | continue; | ||||
6030 | ForbiddenNullArgs[ASTIdx] = 1; | ||||
6031 | } | ||||
6032 | } | ||||
6033 | } | ||||
6034 | for (unsigned I = 0; I < Args.size(); I++) { | ||||
6035 | unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; | ||||
6036 | const ParmVarDecl *PVD = | ||||
6037 | Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; | ||||
6038 | bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; | ||||
6039 | if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { | ||||
6040 | // If we're checking for a potential constant expression, evaluate all | ||||
6041 | // initializers even if some of them fail. | ||||
6042 | if (!Info.noteFailure()) | ||||
6043 | return false; | ||||
6044 | Success = false; | ||||
6045 | } | ||||
6046 | } | ||||
6047 | return Success; | ||||
6048 | } | ||||
6049 | |||||
6050 | /// Perform a trivial copy from Param, which is the parameter of a copy or move | ||||
6051 | /// constructor or assignment operator. | ||||
6052 | static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, | ||||
6053 | const Expr *E, APValue &Result, | ||||
6054 | bool CopyObjectRepresentation) { | ||||
6055 | // Find the reference argument. | ||||
6056 | CallStackFrame *Frame = Info.CurrentCall; | ||||
6057 | APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); | ||||
6058 | if (!RefValue) { | ||||
6059 | Info.FFDiag(E); | ||||
6060 | return false; | ||||
6061 | } | ||||
6062 | |||||
6063 | // Copy out the contents of the RHS object. | ||||
6064 | LValue RefLValue; | ||||
6065 | RefLValue.setFrom(Info.Ctx, *RefValue); | ||||
6066 | return handleLValueToRValueConversion( | ||||
6067 | Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, | ||||
6068 | CopyObjectRepresentation); | ||||
6069 | } | ||||
6070 | |||||
6071 | /// Evaluate a function call. | ||||
6072 | static bool HandleFunctionCall(SourceLocation CallLoc, | ||||
6073 | const FunctionDecl *Callee, const LValue *This, | ||||
6074 | ArrayRef<const Expr *> Args, CallRef Call, | ||||
6075 | const Stmt *Body, EvalInfo &Info, | ||||
6076 | APValue &Result, const LValue *ResultSlot) { | ||||
6077 | if (!Info.CheckCallLimit(CallLoc)) | ||||
6078 | return false; | ||||
6079 | |||||
6080 | CallStackFrame Frame(Info, CallLoc, Callee, This, Call); | ||||
6081 | |||||
6082 | // For a trivial copy or move assignment, perform an APValue copy. This is | ||||
6083 | // essential for unions, where the operations performed by the assignment | ||||
6084 | // operator cannot be represented as statements. | ||||
6085 | // | ||||
6086 | // Skip this for non-union classes with no fields; in that case, the defaulted | ||||
6087 | // copy/move does not actually read the object. | ||||
6088 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); | ||||
6089 | if (MD && MD->isDefaulted() && | ||||
6090 | (MD->getParent()->isUnion() || | ||||
6091 | (MD->isTrivial() && | ||||
6092 | isReadByLvalueToRvalueConversion(MD->getParent())))) { | ||||
6093 | assert(This &&(static_cast <bool> (This && (MD->isCopyAssignmentOperator () || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail ("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6094, __extension__ __PRETTY_FUNCTION__)) | ||||
6094 | (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))(static_cast <bool> (This && (MD->isCopyAssignmentOperator () || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail ("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6094, __extension__ __PRETTY_FUNCTION__)); | ||||
6095 | APValue RHSValue; | ||||
6096 | if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, | ||||
6097 | MD->getParent()->isUnion())) | ||||
6098 | return false; | ||||
6099 | if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && | ||||
6100 | !HandleUnionActiveMemberChange(Info, Args[0], *This)) | ||||
6101 | return false; | ||||
6102 | if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), | ||||
6103 | RHSValue)) | ||||
6104 | return false; | ||||
6105 | This->moveInto(Result); | ||||
6106 | return true; | ||||
6107 | } else if (MD && isLambdaCallOperator(MD)) { | ||||
6108 | // We're in a lambda; determine the lambda capture field maps unless we're | ||||
6109 | // just constexpr checking a lambda's call operator. constexpr checking is | ||||
6110 | // done before the captures have been added to the closure object (unless | ||||
6111 | // we're inferring constexpr-ness), so we don't have access to them in this | ||||
6112 | // case. But since we don't need the captures to constexpr check, we can | ||||
6113 | // just ignore them. | ||||
6114 | if (!Info.checkingPotentialConstantExpression()) | ||||
6115 | MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, | ||||
6116 | Frame.LambdaThisCaptureField); | ||||
6117 | } | ||||
6118 | |||||
6119 | StmtResult Ret = {Result, ResultSlot}; | ||||
6120 | EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); | ||||
6121 | if (ESR == ESR_Succeeded) { | ||||
6122 | if (Callee->getReturnType()->isVoidType()) | ||||
6123 | return true; | ||||
6124 | Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); | ||||
6125 | } | ||||
6126 | return ESR == ESR_Returned; | ||||
6127 | } | ||||
6128 | |||||
6129 | /// Evaluate a constructor call. | ||||
6130 | static bool HandleConstructorCall(const Expr *E, const LValue &This, | ||||
6131 | CallRef Call, | ||||
6132 | const CXXConstructorDecl *Definition, | ||||
6133 | EvalInfo &Info, APValue &Result) { | ||||
6134 | SourceLocation CallLoc = E->getExprLoc(); | ||||
6135 | if (!Info.CheckCallLimit(CallLoc)) | ||||
6136 | return false; | ||||
6137 | |||||
6138 | const CXXRecordDecl *RD = Definition->getParent(); | ||||
6139 | if (RD->getNumVBases()) { | ||||
6140 | Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; | ||||
6141 | return false; | ||||
6142 | } | ||||
6143 | |||||
6144 | EvalInfo::EvaluatingConstructorRAII EvalObj( | ||||
6145 | Info, | ||||
6146 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, | ||||
6147 | RD->getNumBases()); | ||||
6148 | CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); | ||||
6149 | |||||
6150 | // FIXME: Creating an APValue just to hold a nonexistent return value is | ||||
6151 | // wasteful. | ||||
6152 | APValue RetVal; | ||||
6153 | StmtResult Ret = {RetVal, nullptr}; | ||||
6154 | |||||
6155 | // If it's a delegating constructor, delegate. | ||||
6156 | if (Definition->isDelegatingConstructor()) { | ||||
6157 | CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); | ||||
6158 | if ((*I)->getInit()->isValueDependent()) { | ||||
6159 | if (!EvaluateDependentExpr((*I)->getInit(), Info)) | ||||
6160 | return false; | ||||
6161 | } else { | ||||
6162 | FullExpressionRAII InitScope(Info); | ||||
6163 | if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || | ||||
6164 | !InitScope.destroy()) | ||||
6165 | return false; | ||||
6166 | } | ||||
6167 | return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; | ||||
6168 | } | ||||
6169 | |||||
6170 | // For a trivial copy or move constructor, perform an APValue copy. This is | ||||
6171 | // essential for unions (or classes with anonymous union members), where the | ||||
6172 | // operations performed by the constructor cannot be represented by | ||||
6173 | // ctor-initializers. | ||||
6174 | // | ||||
6175 | // Skip this for empty non-union classes; we should not perform an | ||||
6176 | // lvalue-to-rvalue conversion on them because their copy constructor does not | ||||
6177 | // actually read them. | ||||
6178 | if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && | ||||
6179 | (Definition->getParent()->isUnion() || | ||||
6180 | (Definition->isTrivial() && | ||||
6181 | isReadByLvalueToRvalueConversion(Definition->getParent())))) { | ||||
6182 | return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, | ||||
6183 | Definition->getParent()->isUnion()); | ||||
6184 | } | ||||
6185 | |||||
6186 | // Reserve space for the struct members. | ||||
6187 | if (!Result.hasValue()) { | ||||
6188 | if (!RD->isUnion()) | ||||
6189 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), | ||||
6190 | std::distance(RD->field_begin(), RD->field_end())); | ||||
6191 | else | ||||
6192 | // A union starts with no active member. | ||||
6193 | Result = APValue((const FieldDecl*)nullptr); | ||||
6194 | } | ||||
6195 | |||||
6196 | if (RD->isInvalidDecl()) return false; | ||||
6197 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
6198 | |||||
6199 | // A scope for temporaries lifetime-extended by reference members. | ||||
6200 | BlockScopeRAII LifetimeExtendedScope(Info); | ||||
6201 | |||||
6202 | bool Success = true; | ||||
6203 | unsigned BasesSeen = 0; | ||||
6204 | #ifndef NDEBUG | ||||
6205 | CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); | ||||
6206 | #endif | ||||
6207 | CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); | ||||
6208 | auto SkipToField = [&](FieldDecl *FD, bool Indirect) { | ||||
6209 | // We might be initializing the same field again if this is an indirect | ||||
6210 | // field initialization. | ||||
6211 | if (FieldIt == RD->field_end() || | ||||
6212 | FieldIt->getFieldIndex() > FD->getFieldIndex()) { | ||||
6213 | assert(Indirect && "fields out of order?")(static_cast <bool> (Indirect && "fields out of order?" ) ? void (0) : __assert_fail ("Indirect && \"fields out of order?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6213, __extension__ __PRETTY_FUNCTION__)); | ||||
6214 | return; | ||||
6215 | } | ||||
6216 | |||||
6217 | // Default-initialize any fields with no explicit initializer. | ||||
6218 | for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { | ||||
6219 | assert(FieldIt != RD->field_end() && "missing field?")(static_cast <bool> (FieldIt != RD->field_end() && "missing field?") ? void (0) : __assert_fail ("FieldIt != RD->field_end() && \"missing field?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6219, __extension__ __PRETTY_FUNCTION__)); | ||||
6220 | if (!FieldIt->isUnnamedBitfield()) | ||||
6221 | Success &= getDefaultInitValue( | ||||
6222 | FieldIt->getType(), | ||||
6223 | Result.getStructField(FieldIt->getFieldIndex())); | ||||
6224 | } | ||||
6225 | ++FieldIt; | ||||
6226 | }; | ||||
6227 | for (const auto *I : Definition->inits()) { | ||||
6228 | LValue Subobject = This; | ||||
6229 | LValue SubobjectParent = This; | ||||
6230 | APValue *Value = &Result; | ||||
6231 | |||||
6232 | // Determine the subobject to initialize. | ||||
6233 | FieldDecl *FD = nullptr; | ||||
6234 | if (I->isBaseInitializer()) { | ||||
6235 | QualType BaseType(I->getBaseClass(), 0); | ||||
6236 | #ifndef NDEBUG | ||||
6237 | // Non-virtual base classes are initialized in the order in the class | ||||
6238 | // definition. We have already checked for virtual base classes. | ||||
6239 | assert(!BaseIt->isVirtual() && "virtual base for literal type")(static_cast <bool> (!BaseIt->isVirtual() && "virtual base for literal type") ? void (0) : __assert_fail ( "!BaseIt->isVirtual() && \"virtual base for literal type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6239, __extension__ __PRETTY_FUNCTION__)); | ||||
6240 | assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&(static_cast <bool> (Info.Ctx.hasSameType(BaseIt->getType (), BaseType) && "base class initializers not in expected order" ) ? void (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6241, __extension__ __PRETTY_FUNCTION__)) | ||||
6241 | "base class initializers not in expected order")(static_cast <bool> (Info.Ctx.hasSameType(BaseIt->getType (), BaseType) && "base class initializers not in expected order" ) ? void (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6241, __extension__ __PRETTY_FUNCTION__)); | ||||
6242 | ++BaseIt; | ||||
6243 | #endif | ||||
6244 | if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, | ||||
6245 | BaseType->getAsCXXRecordDecl(), &Layout)) | ||||
6246 | return false; | ||||
6247 | Value = &Result.getStructBase(BasesSeen++); | ||||
6248 | } else if ((FD = I->getMember())) { | ||||
6249 | if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) | ||||
6250 | return false; | ||||
6251 | if (RD->isUnion()) { | ||||
6252 | Result = APValue(FD); | ||||
6253 | Value = &Result.getUnionValue(); | ||||
6254 | } else { | ||||
6255 | SkipToField(FD, false); | ||||
6256 | Value = &Result.getStructField(FD->getFieldIndex()); | ||||
6257 | } | ||||
6258 | } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { | ||||
6259 | // Walk the indirect field decl's chain to find the object to initialize, | ||||
6260 | // and make sure we've initialized every step along it. | ||||
6261 | auto IndirectFieldChain = IFD->chain(); | ||||
6262 | for (auto *C : IndirectFieldChain) { | ||||
6263 | FD = cast<FieldDecl>(C); | ||||
6264 | CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); | ||||
6265 | // Switch the union field if it differs. This happens if we had | ||||
6266 | // preceding zero-initialization, and we're now initializing a union | ||||
6267 | // subobject other than the first. | ||||
6268 | // FIXME: In this case, the values of the other subobjects are | ||||
6269 | // specified, since zero-initialization sets all padding bits to zero. | ||||
6270 | if (!Value->hasValue() || | ||||
6271 | (Value->isUnion() && Value->getUnionField() != FD)) { | ||||
6272 | if (CD->isUnion()) | ||||
6273 | *Value = APValue(FD); | ||||
6274 | else | ||||
6275 | // FIXME: This immediately starts the lifetime of all members of | ||||
6276 | // an anonymous struct. It would be preferable to strictly start | ||||
6277 | // member lifetime in initialization order. | ||||
6278 | Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); | ||||
6279 | } | ||||
6280 | // Store Subobject as its parent before updating it for the last element | ||||
6281 | // in the chain. | ||||
6282 | if (C == IndirectFieldChain.back()) | ||||
6283 | SubobjectParent = Subobject; | ||||
6284 | if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) | ||||
6285 | return false; | ||||
6286 | if (CD->isUnion()) | ||||
6287 | Value = &Value->getUnionValue(); | ||||
6288 | else { | ||||
6289 | if (C == IndirectFieldChain.front() && !RD->isUnion()) | ||||
6290 | SkipToField(FD, true); | ||||
6291 | Value = &Value->getStructField(FD->getFieldIndex()); | ||||
6292 | } | ||||
6293 | } | ||||
6294 | } else { | ||||
6295 | llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6295); | ||||
6296 | } | ||||
6297 | |||||
6298 | // Need to override This for implicit field initializers as in this case | ||||
6299 | // This refers to innermost anonymous struct/union containing initializer, | ||||
6300 | // not to currently constructed class. | ||||
6301 | const Expr *Init = I->getInit(); | ||||
6302 | if (Init->isValueDependent()) { | ||||
6303 | if (!EvaluateDependentExpr(Init, Info)) | ||||
6304 | return false; | ||||
6305 | } else { | ||||
6306 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, | ||||
6307 | isa<CXXDefaultInitExpr>(Init)); | ||||
6308 | FullExpressionRAII InitScope(Info); | ||||
6309 | if (!EvaluateInPlace(*Value, Info, Subobject, Init) || | ||||
6310 | (FD && FD->isBitField() && | ||||
6311 | !truncateBitfieldValue(Info, Init, *Value, FD))) { | ||||
6312 | // If we're checking for a potential constant expression, evaluate all | ||||
6313 | // initializers even if some of them fail. | ||||
6314 | if (!Info.noteFailure()) | ||||
6315 | return false; | ||||
6316 | Success = false; | ||||
6317 | } | ||||
6318 | } | ||||
6319 | |||||
6320 | // This is the point at which the dynamic type of the object becomes this | ||||
6321 | // class type. | ||||
6322 | if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) | ||||
6323 | EvalObj.finishedConstructingBases(); | ||||
6324 | } | ||||
6325 | |||||
6326 | // Default-initialize any remaining fields. | ||||
6327 | if (!RD->isUnion()) { | ||||
6328 | for (; FieldIt != RD->field_end(); ++FieldIt) { | ||||
6329 | if (!FieldIt->isUnnamedBitfield()) | ||||
6330 | Success &= getDefaultInitValue( | ||||
6331 | FieldIt->getType(), | ||||
6332 | Result.getStructField(FieldIt->getFieldIndex())); | ||||
6333 | } | ||||
6334 | } | ||||
6335 | |||||
6336 | EvalObj.finishedConstructingFields(); | ||||
6337 | |||||
6338 | return Success && | ||||
6339 | EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && | ||||
6340 | LifetimeExtendedScope.destroy(); | ||||
6341 | } | ||||
6342 | |||||
6343 | static bool HandleConstructorCall(const Expr *E, const LValue &This, | ||||
6344 | ArrayRef<const Expr*> Args, | ||||
6345 | const CXXConstructorDecl *Definition, | ||||
6346 | EvalInfo &Info, APValue &Result) { | ||||
6347 | CallScopeRAII CallScope(Info); | ||||
6348 | CallRef Call = Info.CurrentCall->createCall(Definition); | ||||
6349 | if (!EvaluateArgs(Args, Call, Info, Definition)) | ||||
6350 | return false; | ||||
6351 | |||||
6352 | return HandleConstructorCall(E, This, Call, Definition, Info, Result) && | ||||
6353 | CallScope.destroy(); | ||||
6354 | } | ||||
6355 | |||||
6356 | static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, | ||||
6357 | const LValue &This, APValue &Value, | ||||
6358 | QualType T) { | ||||
6359 | // Objects can only be destroyed while they're within their lifetimes. | ||||
6360 | // FIXME: We have no representation for whether an object of type nullptr_t | ||||
6361 | // is in its lifetime; it usually doesn't matter. Perhaps we should model it | ||||
6362 | // as indeterminate instead? | ||||
6363 | if (Value.isAbsent() && !T->isNullPtrType()) { | ||||
6364 | APValue Printable; | ||||
6365 | This.moveInto(Printable); | ||||
6366 | Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) | ||||
6367 | << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); | ||||
6368 | return false; | ||||
6369 | } | ||||
6370 | |||||
6371 | // Invent an expression for location purposes. | ||||
6372 | // FIXME: We shouldn't need to do this. | ||||
6373 | OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); | ||||
6374 | |||||
6375 | // For arrays, destroy elements right-to-left. | ||||
6376 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { | ||||
6377 | uint64_t Size = CAT->getSize().getZExtValue(); | ||||
6378 | QualType ElemT = CAT->getElementType(); | ||||
6379 | |||||
6380 | LValue ElemLV = This; | ||||
6381 | ElemLV.addArray(Info, &LocE, CAT); | ||||
6382 | if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) | ||||
6383 | return false; | ||||
6384 | |||||
6385 | // Ensure that we have actual array elements available to destroy; the | ||||
6386 | // destructors might mutate the value, so we can't run them on the array | ||||
6387 | // filler. | ||||
6388 | if (Size && Size > Value.getArrayInitializedElts()) | ||||
6389 | expandArray(Value, Value.getArraySize() - 1); | ||||
6390 | |||||
6391 | for (; Size != 0; --Size) { | ||||
6392 | APValue &Elem = Value.getArrayInitializedElt(Size - 1); | ||||
6393 | if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || | ||||
6394 | !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) | ||||
6395 | return false; | ||||
6396 | } | ||||
6397 | |||||
6398 | // End the lifetime of this array now. | ||||
6399 | Value = APValue(); | ||||
6400 | return true; | ||||
6401 | } | ||||
6402 | |||||
6403 | const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); | ||||
6404 | if (!RD) { | ||||
6405 | if (T.isDestructedType()) { | ||||
6406 | Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; | ||||
6407 | return false; | ||||
6408 | } | ||||
6409 | |||||
6410 | Value = APValue(); | ||||
6411 | return true; | ||||
6412 | } | ||||
6413 | |||||
6414 | if (RD->getNumVBases()) { | ||||
6415 | Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; | ||||
6416 | return false; | ||||
6417 | } | ||||
6418 | |||||
6419 | const CXXDestructorDecl *DD = RD->getDestructor(); | ||||
6420 | if (!DD && !RD->hasTrivialDestructor()) { | ||||
6421 | Info.FFDiag(CallLoc); | ||||
6422 | return false; | ||||
6423 | } | ||||
6424 | |||||
6425 | if (!DD || DD->isTrivial() || | ||||
6426 | (RD->isAnonymousStructOrUnion() && RD->isUnion())) { | ||||
6427 | // A trivial destructor just ends the lifetime of the object. Check for | ||||
6428 | // this case before checking for a body, because we might not bother | ||||
6429 | // building a body for a trivial destructor. Note that it doesn't matter | ||||
6430 | // whether the destructor is constexpr in this case; all trivial | ||||
6431 | // destructors are constexpr. | ||||
6432 | // | ||||
6433 | // If an anonymous union would be destroyed, some enclosing destructor must | ||||
6434 | // have been explicitly defined, and the anonymous union destruction should | ||||
6435 | // have no effect. | ||||
6436 | Value = APValue(); | ||||
6437 | return true; | ||||
6438 | } | ||||
6439 | |||||
6440 | if (!Info.CheckCallLimit(CallLoc)) | ||||
6441 | return false; | ||||
6442 | |||||
6443 | const FunctionDecl *Definition = nullptr; | ||||
6444 | const Stmt *Body = DD->getBody(Definition); | ||||
6445 | |||||
6446 | if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) | ||||
6447 | return false; | ||||
6448 | |||||
6449 | CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); | ||||
6450 | |||||
6451 | // We're now in the period of destruction of this object. | ||||
6452 | unsigned BasesLeft = RD->getNumBases(); | ||||
6453 | EvalInfo::EvaluatingDestructorRAII EvalObj( | ||||
6454 | Info, | ||||
6455 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); | ||||
6456 | if (!EvalObj.DidInsert) { | ||||
6457 | // C++2a [class.dtor]p19: | ||||
6458 | // the behavior is undefined if the destructor is invoked for an object | ||||
6459 | // whose lifetime has ended | ||||
6460 | // (Note that formally the lifetime ends when the period of destruction | ||||
6461 | // begins, even though certain uses of the object remain valid until the | ||||
6462 | // period of destruction ends.) | ||||
6463 | Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); | ||||
6464 | return false; | ||||
6465 | } | ||||
6466 | |||||
6467 | // FIXME: Creating an APValue just to hold a nonexistent return value is | ||||
6468 | // wasteful. | ||||
6469 | APValue RetVal; | ||||
6470 | StmtResult Ret = {RetVal, nullptr}; | ||||
6471 | if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) | ||||
6472 | return false; | ||||
6473 | |||||
6474 | // A union destructor does not implicitly destroy its members. | ||||
6475 | if (RD->isUnion()) | ||||
6476 | return true; | ||||
6477 | |||||
6478 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
6479 | |||||
6480 | // We don't have a good way to iterate fields in reverse, so collect all the | ||||
6481 | // fields first and then walk them backwards. | ||||
6482 | SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); | ||||
6483 | for (const FieldDecl *FD : llvm::reverse(Fields)) { | ||||
6484 | if (FD->isUnnamedBitfield()) | ||||
6485 | continue; | ||||
6486 | |||||
6487 | LValue Subobject = This; | ||||
6488 | if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) | ||||
6489 | return false; | ||||
6490 | |||||
6491 | APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); | ||||
6492 | if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, | ||||
6493 | FD->getType())) | ||||
6494 | return false; | ||||
6495 | } | ||||
6496 | |||||
6497 | if (BasesLeft != 0) | ||||
6498 | EvalObj.startedDestroyingBases(); | ||||
6499 | |||||
6500 | // Destroy base classes in reverse order. | ||||
6501 | for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { | ||||
6502 | --BasesLeft; | ||||
6503 | |||||
6504 | QualType BaseType = Base.getType(); | ||||
6505 | LValue Subobject = This; | ||||
6506 | if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, | ||||
6507 | BaseType->getAsCXXRecordDecl(), &Layout)) | ||||
6508 | return false; | ||||
6509 | |||||
6510 | APValue *SubobjectValue = &Value.getStructBase(BasesLeft); | ||||
6511 | if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, | ||||
6512 | BaseType)) | ||||
6513 | return false; | ||||
6514 | } | ||||
6515 | assert(BasesLeft == 0 && "NumBases was wrong?")(static_cast <bool> (BasesLeft == 0 && "NumBases was wrong?" ) ? void (0) : __assert_fail ("BasesLeft == 0 && \"NumBases was wrong?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6515, __extension__ __PRETTY_FUNCTION__)); | ||||
6516 | |||||
6517 | // The period of destruction ends now. The object is gone. | ||||
6518 | Value = APValue(); | ||||
6519 | return true; | ||||
6520 | } | ||||
6521 | |||||
6522 | namespace { | ||||
6523 | struct DestroyObjectHandler { | ||||
6524 | EvalInfo &Info; | ||||
6525 | const Expr *E; | ||||
6526 | const LValue &This; | ||||
6527 | const AccessKinds AccessKind; | ||||
6528 | |||||
6529 | typedef bool result_type; | ||||
6530 | bool failed() { return false; } | ||||
6531 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
6532 | return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, | ||||
6533 | SubobjType); | ||||
6534 | } | ||||
6535 | bool found(APSInt &Value, QualType SubobjType) { | ||||
6536 | Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); | ||||
6537 | return false; | ||||
6538 | } | ||||
6539 | bool found(APFloat &Value, QualType SubobjType) { | ||||
6540 | Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); | ||||
6541 | return false; | ||||
6542 | } | ||||
6543 | }; | ||||
6544 | } | ||||
6545 | |||||
6546 | /// Perform a destructor or pseudo-destructor call on the given object, which | ||||
6547 | /// might in general not be a complete object. | ||||
6548 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, | ||||
6549 | const LValue &This, QualType ThisType) { | ||||
6550 | CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); | ||||
6551 | DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; | ||||
6552 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); | ||||
6553 | } | ||||
6554 | |||||
6555 | /// Destroy and end the lifetime of the given complete object. | ||||
6556 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, | ||||
6557 | APValue::LValueBase LVBase, APValue &Value, | ||||
6558 | QualType T) { | ||||
6559 | // If we've had an unmodeled side-effect, we can't rely on mutable state | ||||
6560 | // (such as the object we're about to destroy) being correct. | ||||
6561 | if (Info.EvalStatus.HasSideEffects) | ||||
6562 | return false; | ||||
6563 | |||||
6564 | LValue LV; | ||||
6565 | LV.set({LVBase}); | ||||
6566 | return HandleDestructionImpl(Info, Loc, LV, Value, T); | ||||
6567 | } | ||||
6568 | |||||
6569 | /// Perform a call to 'perator new' or to `__builtin_operator_new'. | ||||
6570 | static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, | ||||
6571 | LValue &Result) { | ||||
6572 | if (Info.checkingPotentialConstantExpression() || | ||||
6573 | Info.SpeculativeEvaluationDepth) | ||||
6574 | return false; | ||||
6575 | |||||
6576 | // This is permitted only within a call to std::allocator<T>::allocate. | ||||
6577 | auto Caller = Info.getStdAllocatorCaller("allocate"); | ||||
6578 | if (!Caller) { | ||||
6579 | Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 | ||||
6580 | ? diag::note_constexpr_new_untyped | ||||
6581 | : diag::note_constexpr_new); | ||||
6582 | return false; | ||||
6583 | } | ||||
6584 | |||||
6585 | QualType ElemType = Caller.ElemType; | ||||
6586 | if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { | ||||
6587 | Info.FFDiag(E->getExprLoc(), | ||||
6588 | diag::note_constexpr_new_not_complete_object_type) | ||||
6589 | << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; | ||||
6590 | return false; | ||||
6591 | } | ||||
6592 | |||||
6593 | APSInt ByteSize; | ||||
6594 | if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) | ||||
6595 | return false; | ||||
6596 | bool IsNothrow = false; | ||||
6597 | for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { | ||||
6598 | EvaluateIgnoredValue(Info, E->getArg(I)); | ||||
6599 | IsNothrow |= E->getType()->isNothrowT(); | ||||
6600 | } | ||||
6601 | |||||
6602 | CharUnits ElemSize; | ||||
6603 | if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) | ||||
6604 | return false; | ||||
6605 | APInt Size, Remainder; | ||||
6606 | APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); | ||||
6607 | APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); | ||||
6608 | if (Remainder != 0) { | ||||
6609 | // This likely indicates a bug in the implementation of 'std::allocator'. | ||||
6610 | Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) | ||||
6611 | << ByteSize << APSInt(ElemSizeAP, true) << ElemType; | ||||
6612 | return false; | ||||
6613 | } | ||||
6614 | |||||
6615 | if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { | ||||
6616 | if (IsNothrow) { | ||||
6617 | Result.setNull(Info.Ctx, E->getType()); | ||||
6618 | return true; | ||||
6619 | } | ||||
6620 | |||||
6621 | Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); | ||||
6622 | return false; | ||||
6623 | } | ||||
6624 | |||||
6625 | QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, | ||||
6626 | ArrayType::Normal, 0); | ||||
6627 | APValue *Val = Info.createHeapAlloc(E, AllocType, Result); | ||||
6628 | *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); | ||||
6629 | Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); | ||||
6630 | return true; | ||||
6631 | } | ||||
6632 | |||||
6633 | static bool hasVirtualDestructor(QualType T) { | ||||
6634 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | ||||
6635 | if (CXXDestructorDecl *DD = RD->getDestructor()) | ||||
6636 | return DD->isVirtual(); | ||||
6637 | return false; | ||||
6638 | } | ||||
6639 | |||||
6640 | static const FunctionDecl *getVirtualOperatorDelete(QualType T) { | ||||
6641 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | ||||
6642 | if (CXXDestructorDecl *DD = RD->getDestructor()) | ||||
6643 | return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; | ||||
6644 | return nullptr; | ||||
6645 | } | ||||
6646 | |||||
6647 | /// Check that the given object is a suitable pointer to a heap allocation that | ||||
6648 | /// still exists and is of the right kind for the purpose of a deletion. | ||||
6649 | /// | ||||
6650 | /// On success, returns the heap allocation to deallocate. On failure, produces | ||||
6651 | /// a diagnostic and returns None. | ||||
6652 | static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, | ||||
6653 | const LValue &Pointer, | ||||
6654 | DynAlloc::Kind DeallocKind) { | ||||
6655 | auto PointerAsString = [&] { | ||||
6656 | return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); | ||||
6657 | }; | ||||
6658 | |||||
6659 | DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); | ||||
6660 | if (!DA) { | ||||
6661 | Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) | ||||
6662 | << PointerAsString(); | ||||
6663 | if (Pointer.Base) | ||||
6664 | NoteLValueLocation(Info, Pointer.Base); | ||||
6665 | return None; | ||||
6666 | } | ||||
6667 | |||||
6668 | Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); | ||||
6669 | if (!Alloc) { | ||||
6670 | Info.FFDiag(E, diag::note_constexpr_double_delete); | ||||
6671 | return None; | ||||
6672 | } | ||||
6673 | |||||
6674 | QualType AllocType = Pointer.Base.getDynamicAllocType(); | ||||
6675 | if (DeallocKind != (*Alloc)->getKind()) { | ||||
6676 | Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) | ||||
6677 | << DeallocKind << (*Alloc)->getKind() << AllocType; | ||||
6678 | NoteLValueLocation(Info, Pointer.Base); | ||||
6679 | return None; | ||||
6680 | } | ||||
6681 | |||||
6682 | bool Subobject = false; | ||||
6683 | if (DeallocKind == DynAlloc::New) { | ||||
6684 | Subobject = Pointer.Designator.MostDerivedPathLength != 0 || | ||||
6685 | Pointer.Designator.isOnePastTheEnd(); | ||||
6686 | } else { | ||||
6687 | Subobject = Pointer.Designator.Entries.size() != 1 || | ||||
6688 | Pointer.Designator.Entries[0].getAsArrayIndex() != 0; | ||||
6689 | } | ||||
6690 | if (Subobject) { | ||||
6691 | Info.FFDiag(E, diag::note_constexpr_delete_subobject) | ||||
6692 | << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); | ||||
6693 | return None; | ||||
6694 | } | ||||
6695 | |||||
6696 | return Alloc; | ||||
6697 | } | ||||
6698 | |||||
6699 | // Perform a call to 'operator delete' or '__builtin_operator_delete'. | ||||
6700 | bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { | ||||
6701 | if (Info.checkingPotentialConstantExpression() || | ||||
6702 | Info.SpeculativeEvaluationDepth) | ||||
6703 | return false; | ||||
6704 | |||||
6705 | // This is permitted only within a call to std::allocator<T>::deallocate. | ||||
6706 | if (!Info.getStdAllocatorCaller("deallocate")) { | ||||
6707 | Info.FFDiag(E->getExprLoc()); | ||||
6708 | return true; | ||||
6709 | } | ||||
6710 | |||||
6711 | LValue Pointer; | ||||
6712 | if (!EvaluatePointer(E->getArg(0), Pointer, Info)) | ||||
6713 | return false; | ||||
6714 | for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) | ||||
6715 | EvaluateIgnoredValue(Info, E->getArg(I)); | ||||
6716 | |||||
6717 | if (Pointer.Designator.Invalid) | ||||
6718 | return false; | ||||
6719 | |||||
6720 | // Deleting a null pointer would have no effect, but it's not permitted by | ||||
6721 | // std::allocator<T>::deallocate's contract. | ||||
6722 | if (Pointer.isNullPointer()) { | ||||
6723 | Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); | ||||
6724 | return true; | ||||
6725 | } | ||||
6726 | |||||
6727 | if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) | ||||
6728 | return false; | ||||
6729 | |||||
6730 | Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); | ||||
6731 | return true; | ||||
6732 | } | ||||
6733 | |||||
6734 | //===----------------------------------------------------------------------===// | ||||
6735 | // Generic Evaluation | ||||
6736 | //===----------------------------------------------------------------------===// | ||||
6737 | namespace { | ||||
6738 | |||||
6739 | class BitCastBuffer { | ||||
6740 | // FIXME: We're going to need bit-level granularity when we support | ||||
6741 | // bit-fields. | ||||
6742 | // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but | ||||
6743 | // we don't support a host or target where that is the case. Still, we should | ||||
6744 | // use a more generic type in case we ever do. | ||||
6745 | SmallVector<Optional<unsigned char>, 32> Bytes; | ||||
6746 | |||||
6747 | static_assert(std::numeric_limits<unsigned char>::digits >= 8, | ||||
6748 | "Need at least 8 bit unsigned char"); | ||||
6749 | |||||
6750 | bool TargetIsLittleEndian; | ||||
6751 | |||||
6752 | public: | ||||
6753 | BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) | ||||
6754 | : Bytes(Width.getQuantity()), | ||||
6755 | TargetIsLittleEndian(TargetIsLittleEndian) {} | ||||
6756 | |||||
6757 | LLVM_NODISCARD[[clang::warn_unused_result]] | ||||
6758 | bool readObject(CharUnits Offset, CharUnits Width, | ||||
6759 | SmallVectorImpl<unsigned char> &Output) const { | ||||
6760 | for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { | ||||
6761 | // If a byte of an integer is uninitialized, then the whole integer is | ||||
6762 | // uninitalized. | ||||
6763 | if (!Bytes[I.getQuantity()]) | ||||
6764 | return false; | ||||
6765 | Output.push_back(*Bytes[I.getQuantity()]); | ||||
6766 | } | ||||
6767 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) | ||||
6768 | std::reverse(Output.begin(), Output.end()); | ||||
6769 | return true; | ||||
6770 | } | ||||
6771 | |||||
6772 | void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { | ||||
6773 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) | ||||
6774 | std::reverse(Input.begin(), Input.end()); | ||||
6775 | |||||
6776 | size_t Index = 0; | ||||
6777 | for (unsigned char Byte : Input) { | ||||
6778 | assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?")(static_cast <bool> (!Bytes[Offset.getQuantity() + Index ] && "overwriting a byte?") ? void (0) : __assert_fail ("!Bytes[Offset.getQuantity() + Index] && \"overwriting a byte?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6778, __extension__ __PRETTY_FUNCTION__)); | ||||
6779 | Bytes[Offset.getQuantity() + Index] = Byte; | ||||
6780 | ++Index; | ||||
6781 | } | ||||
6782 | } | ||||
6783 | |||||
6784 | size_t size() { return Bytes.size(); } | ||||
6785 | }; | ||||
6786 | |||||
6787 | /// Traverse an APValue to produce an BitCastBuffer, emulating how the current | ||||
6788 | /// target would represent the value at runtime. | ||||
6789 | class APValueToBufferConverter { | ||||
6790 | EvalInfo &Info; | ||||
6791 | BitCastBuffer Buffer; | ||||
6792 | const CastExpr *BCE; | ||||
6793 | |||||
6794 | APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, | ||||
6795 | const CastExpr *BCE) | ||||
6796 | : Info(Info), | ||||
6797 | Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), | ||||
6798 | BCE(BCE) {} | ||||
6799 | |||||
6800 | bool visit(const APValue &Val, QualType Ty) { | ||||
6801 | return visit(Val, Ty, CharUnits::fromQuantity(0)); | ||||
6802 | } | ||||
6803 | |||||
6804 | // Write out Val with type Ty into Buffer starting at Offset. | ||||
6805 | bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||
6806 | assert((size_t)Offset.getQuantity() <= Buffer.size())(static_cast <bool> ((size_t)Offset.getQuantity() <= Buffer.size()) ? void (0) : __assert_fail ("(size_t)Offset.getQuantity() <= Buffer.size()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6806, __extension__ __PRETTY_FUNCTION__)); | ||||
6807 | |||||
6808 | // As a special case, nullptr_t has an indeterminate value. | ||||
6809 | if (Ty->isNullPtrType()) | ||||
6810 | return true; | ||||
6811 | |||||
6812 | // Dig through Src to find the byte at SrcOffset. | ||||
6813 | switch (Val.getKind()) { | ||||
6814 | case APValue::Indeterminate: | ||||
6815 | case APValue::None: | ||||
6816 | return true; | ||||
6817 | |||||
6818 | case APValue::Int: | ||||
6819 | return visitInt(Val.getInt(), Ty, Offset); | ||||
6820 | case APValue::Float: | ||||
6821 | return visitFloat(Val.getFloat(), Ty, Offset); | ||||
6822 | case APValue::Array: | ||||
6823 | return visitArray(Val, Ty, Offset); | ||||
6824 | case APValue::Struct: | ||||
6825 | return visitRecord(Val, Ty, Offset); | ||||
6826 | |||||
6827 | case APValue::ComplexInt: | ||||
6828 | case APValue::ComplexFloat: | ||||
6829 | case APValue::Vector: | ||||
6830 | case APValue::FixedPoint: | ||||
6831 | // FIXME: We should support these. | ||||
6832 | |||||
6833 | case APValue::Union: | ||||
6834 | case APValue::MemberPointer: | ||||
6835 | case APValue::AddrLabelDiff: { | ||||
6836 | Info.FFDiag(BCE->getBeginLoc(), | ||||
6837 | diag::note_constexpr_bit_cast_unsupported_type) | ||||
6838 | << Ty; | ||||
6839 | return false; | ||||
6840 | } | ||||
6841 | |||||
6842 | case APValue::LValue: | ||||
6843 | llvm_unreachable("LValue subobject in bit_cast?")::llvm::llvm_unreachable_internal("LValue subobject in bit_cast?" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6843); | ||||
6844 | } | ||||
6845 | llvm_unreachable("Unhandled APValue::ValueKind")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6845); | ||||
6846 | } | ||||
6847 | |||||
6848 | bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||
6849 | const RecordDecl *RD = Ty->getAsRecordDecl(); | ||||
6850 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
6851 | |||||
6852 | // Visit the base classes. | ||||
6853 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
6854 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { | ||||
6855 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; | ||||
6856 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | ||||
6857 | |||||
6858 | if (!visitRecord(Val.getStructBase(I), BS.getType(), | ||||
6859 | Layout.getBaseClassOffset(BaseDecl) + Offset)) | ||||
6860 | return false; | ||||
6861 | } | ||||
6862 | } | ||||
6863 | |||||
6864 | // Visit the fields. | ||||
6865 | unsigned FieldIdx = 0; | ||||
6866 | for (FieldDecl *FD : RD->fields()) { | ||||
6867 | if (FD->isBitField()) { | ||||
6868 | Info.FFDiag(BCE->getBeginLoc(), | ||||
6869 | diag::note_constexpr_bit_cast_unsupported_bitfield); | ||||
6870 | return false; | ||||
6871 | } | ||||
6872 | |||||
6873 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); | ||||
6874 | |||||
6875 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth () == 0 && "only bit-fields can have sub-char alignment" ) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6876, __extension__ __PRETTY_FUNCTION__)) | ||||
6876 | "only bit-fields can have sub-char alignment")(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth () == 0 && "only bit-fields can have sub-char alignment" ) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6876, __extension__ __PRETTY_FUNCTION__)); | ||||
6877 | CharUnits FieldOffset = | ||||
6878 | Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; | ||||
6879 | QualType FieldTy = FD->getType(); | ||||
6880 | if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) | ||||
6881 | return false; | ||||
6882 | ++FieldIdx; | ||||
6883 | } | ||||
6884 | |||||
6885 | return true; | ||||
6886 | } | ||||
6887 | |||||
6888 | bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||
6889 | const auto *CAT = | ||||
6890 | dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); | ||||
6891 | if (!CAT) | ||||
6892 | return false; | ||||
6893 | |||||
6894 | CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); | ||||
6895 | unsigned NumInitializedElts = Val.getArrayInitializedElts(); | ||||
6896 | unsigned ArraySize = Val.getArraySize(); | ||||
6897 | // First, initialize the initialized elements. | ||||
6898 | for (unsigned I = 0; I != NumInitializedElts; ++I) { | ||||
6899 | const APValue &SubObj = Val.getArrayInitializedElt(I); | ||||
6900 | if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) | ||||
6901 | return false; | ||||
6902 | } | ||||
6903 | |||||
6904 | // Next, initialize the rest of the array using the filler. | ||||
6905 | if (Val.hasArrayFiller()) { | ||||
6906 | const APValue &Filler = Val.getArrayFiller(); | ||||
6907 | for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { | ||||
6908 | if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) | ||||
6909 | return false; | ||||
6910 | } | ||||
6911 | } | ||||
6912 | |||||
6913 | return true; | ||||
6914 | } | ||||
6915 | |||||
6916 | bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { | ||||
6917 | APSInt AdjustedVal = Val; | ||||
6918 | unsigned Width = AdjustedVal.getBitWidth(); | ||||
6919 | if (Ty->isBooleanType()) { | ||||
6920 | Width = Info.Ctx.getTypeSize(Ty); | ||||
6921 | AdjustedVal = AdjustedVal.extend(Width); | ||||
6922 | } | ||||
6923 | |||||
6924 | SmallVector<unsigned char, 8> Bytes(Width / 8); | ||||
6925 | llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); | ||||
6926 | Buffer.writeObject(Offset, Bytes); | ||||
6927 | return true; | ||||
6928 | } | ||||
6929 | |||||
6930 | bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { | ||||
6931 | APSInt AsInt(Val.bitcastToAPInt()); | ||||
6932 | return visitInt(AsInt, Ty, Offset); | ||||
6933 | } | ||||
6934 | |||||
6935 | public: | ||||
6936 | static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, | ||||
6937 | const CastExpr *BCE) { | ||||
6938 | CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); | ||||
6939 | APValueToBufferConverter Converter(Info, DstSize, BCE); | ||||
6940 | if (!Converter.visit(Src, BCE->getSubExpr()->getType())) | ||||
6941 | return None; | ||||
6942 | return Converter.Buffer; | ||||
6943 | } | ||||
6944 | }; | ||||
6945 | |||||
6946 | /// Write an BitCastBuffer into an APValue. | ||||
6947 | class BufferToAPValueConverter { | ||||
6948 | EvalInfo &Info; | ||||
6949 | const BitCastBuffer &Buffer; | ||||
6950 | const CastExpr *BCE; | ||||
6951 | |||||
6952 | BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, | ||||
6953 | const CastExpr *BCE) | ||||
6954 | : Info(Info), Buffer(Buffer), BCE(BCE) {} | ||||
6955 | |||||
6956 | // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast | ||||
6957 | // with an invalid type, so anything left is a deficiency on our part (FIXME). | ||||
6958 | // Ideally this will be unreachable. | ||||
6959 | llvm::NoneType unsupportedType(QualType Ty) { | ||||
6960 | Info.FFDiag(BCE->getBeginLoc(), | ||||
6961 | diag::note_constexpr_bit_cast_unsupported_type) | ||||
6962 | << Ty; | ||||
6963 | return None; | ||||
6964 | } | ||||
6965 | |||||
6966 | llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { | ||||
6967 | Info.FFDiag(BCE->getBeginLoc(), | ||||
6968 | diag::note_constexpr_bit_cast_unrepresentable_value) | ||||
6969 | << Ty << toString(Val, /*Radix=*/10); | ||||
6970 | return None; | ||||
6971 | } | ||||
6972 | |||||
6973 | Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, | ||||
6974 | const EnumType *EnumSugar = nullptr) { | ||||
6975 | if (T->isNullPtrType()) { | ||||
6976 | uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); | ||||
6977 | return APValue((Expr *)nullptr, | ||||
6978 | /*Offset=*/CharUnits::fromQuantity(NullValue), | ||||
6979 | APValue::NoLValuePath{}, /*IsNullPtr=*/true); | ||||
6980 | } | ||||
6981 | |||||
6982 | CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); | ||||
6983 | |||||
6984 | // Work around floating point types that contain unused padding bytes. This | ||||
6985 | // is really just `long double` on x86, which is the only fundamental type | ||||
6986 | // with padding bytes. | ||||
6987 | if (T->isRealFloatingType()) { | ||||
6988 | const llvm::fltSemantics &Semantics = | ||||
6989 | Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); | ||||
6990 | unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); | ||||
6991 | assert(NumBits % 8 == 0)(static_cast <bool> (NumBits % 8 == 0) ? void (0) : __assert_fail ("NumBits % 8 == 0", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 6991, __extension__ __PRETTY_FUNCTION__)); | ||||
6992 | CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); | ||||
6993 | if (NumBytes != SizeOf) | ||||
6994 | SizeOf = NumBytes; | ||||
6995 | } | ||||
6996 | |||||
6997 | SmallVector<uint8_t, 8> Bytes; | ||||
6998 | if (!Buffer.readObject(Offset, SizeOf, Bytes)) { | ||||
6999 | // If this is std::byte or unsigned char, then its okay to store an | ||||
7000 | // indeterminate value. | ||||
7001 | bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); | ||||
7002 | bool IsUChar = | ||||
7003 | !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || | ||||
7004 | T->isSpecificBuiltinType(BuiltinType::Char_U)); | ||||
7005 | if (!IsStdByte && !IsUChar) { | ||||
7006 | QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); | ||||
7007 | Info.FFDiag(BCE->getExprLoc(), | ||||
7008 | diag::note_constexpr_bit_cast_indet_dest) | ||||
7009 | << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; | ||||
7010 | return None; | ||||
7011 | } | ||||
7012 | |||||
7013 | return APValue::IndeterminateValue(); | ||||
7014 | } | ||||
7015 | |||||
7016 | APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); | ||||
7017 | llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); | ||||
7018 | |||||
7019 | if (T->isIntegralOrEnumerationType()) { | ||||
7020 | Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); | ||||
7021 | |||||
7022 | unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); | ||||
7023 | if (IntWidth != Val.getBitWidth()) { | ||||
7024 | APSInt Truncated = Val.trunc(IntWidth); | ||||
7025 | if (Truncated.extend(Val.getBitWidth()) != Val) | ||||
7026 | return unrepresentableValue(QualType(T, 0), Val); | ||||
7027 | Val = Truncated; | ||||
7028 | } | ||||
7029 | |||||
7030 | return APValue(Val); | ||||
7031 | } | ||||
7032 | |||||
7033 | if (T->isRealFloatingType()) { | ||||
7034 | const llvm::fltSemantics &Semantics = | ||||
7035 | Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); | ||||
7036 | return APValue(APFloat(Semantics, Val)); | ||||
7037 | } | ||||
7038 | |||||
7039 | return unsupportedType(QualType(T, 0)); | ||||
7040 | } | ||||
7041 | |||||
7042 | Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { | ||||
7043 | const RecordDecl *RD = RTy->getAsRecordDecl(); | ||||
7044 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
7045 | |||||
7046 | unsigned NumBases = 0; | ||||
7047 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) | ||||
7048 | NumBases = CXXRD->getNumBases(); | ||||
7049 | |||||
7050 | APValue ResultVal(APValue::UninitStruct(), NumBases, | ||||
7051 | std::distance(RD->field_begin(), RD->field_end())); | ||||
7052 | |||||
7053 | // Visit the base classes. | ||||
7054 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
7055 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { | ||||
7056 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; | ||||
7057 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | ||||
7058 | if (BaseDecl->isEmpty() || | ||||
7059 | Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) | ||||
7060 | continue; | ||||
7061 | |||||
7062 | Optional<APValue> SubObj = visitType( | ||||
7063 | BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); | ||||
7064 | if (!SubObj) | ||||
7065 | return None; | ||||
7066 | ResultVal.getStructBase(I) = *SubObj; | ||||
7067 | } | ||||
7068 | } | ||||
7069 | |||||
7070 | // Visit the fields. | ||||
7071 | unsigned FieldIdx = 0; | ||||
7072 | for (FieldDecl *FD : RD->fields()) { | ||||
7073 | // FIXME: We don't currently support bit-fields. A lot of the logic for | ||||
7074 | // this is in CodeGen, so we need to factor it around. | ||||
7075 | if (FD->isBitField()) { | ||||
7076 | Info.FFDiag(BCE->getBeginLoc(), | ||||
7077 | diag::note_constexpr_bit_cast_unsupported_bitfield); | ||||
7078 | return None; | ||||
7079 | } | ||||
7080 | |||||
7081 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); | ||||
7082 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0)(static_cast <bool> (FieldOffsetBits % Info.Ctx.getCharWidth () == 0) ? void (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7082, __extension__ __PRETTY_FUNCTION__)); | ||||
7083 | |||||
7084 | CharUnits FieldOffset = | ||||
7085 | CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + | ||||
7086 | Offset; | ||||
7087 | QualType FieldTy = FD->getType(); | ||||
7088 | Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); | ||||
7089 | if (!SubObj) | ||||
7090 | return None; | ||||
7091 | ResultVal.getStructField(FieldIdx) = *SubObj; | ||||
7092 | ++FieldIdx; | ||||
7093 | } | ||||
7094 | |||||
7095 | return ResultVal; | ||||
7096 | } | ||||
7097 | |||||
7098 | Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { | ||||
7099 | QualType RepresentationType = Ty->getDecl()->getIntegerType(); | ||||
7100 | assert(!RepresentationType.isNull() &&(static_cast <bool> (!RepresentationType.isNull() && "enum forward decl should be caught by Sema") ? void (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7101, __extension__ __PRETTY_FUNCTION__)) | ||||
7101 | "enum forward decl should be caught by Sema")(static_cast <bool> (!RepresentationType.isNull() && "enum forward decl should be caught by Sema") ? void (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7101, __extension__ __PRETTY_FUNCTION__)); | ||||
7102 | const auto *AsBuiltin = | ||||
7103 | RepresentationType.getCanonicalType()->castAs<BuiltinType>(); | ||||
7104 | // Recurse into the underlying type. Treat std::byte transparently as | ||||
7105 | // unsigned char. | ||||
7106 | return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); | ||||
7107 | } | ||||
7108 | |||||
7109 | Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { | ||||
7110 | size_t Size = Ty->getSize().getLimitedValue(); | ||||
7111 | CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); | ||||
7112 | |||||
7113 | APValue ArrayValue(APValue::UninitArray(), Size, Size); | ||||
7114 | for (size_t I = 0; I != Size; ++I) { | ||||
7115 | Optional<APValue> ElementValue = | ||||
7116 | visitType(Ty->getElementType(), Offset + I * ElementWidth); | ||||
7117 | if (!ElementValue) | ||||
7118 | return None; | ||||
7119 | ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); | ||||
7120 | } | ||||
7121 | |||||
7122 | return ArrayValue; | ||||
7123 | } | ||||
7124 | |||||
7125 | Optional<APValue> visit(const Type *Ty, CharUnits Offset) { | ||||
7126 | return unsupportedType(QualType(Ty, 0)); | ||||
7127 | } | ||||
7128 | |||||
7129 | Optional<APValue> visitType(QualType Ty, CharUnits Offset) { | ||||
7130 | QualType Can = Ty.getCanonicalType(); | ||||
7131 | |||||
7132 | switch (Can->getTypeClass()) { | ||||
7133 | #define TYPE(Class, Base) \ | ||||
7134 | case Type::Class: \ | ||||
7135 | return visit(cast<Class##Type>(Can.getTypePtr()), Offset); | ||||
7136 | #define ABSTRACT_TYPE(Class, Base) | ||||
7137 | #define NON_CANONICAL_TYPE(Class, Base) \ | ||||
7138 | case Type::Class: \ | ||||
7139 | llvm_unreachable("non-canonical type should be impossible!")::llvm::llvm_unreachable_internal("non-canonical type should be impossible!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7139); | ||||
7140 | #define DEPENDENT_TYPE(Class, Base) \ | ||||
7141 | case Type::Class: \ | ||||
7142 | llvm_unreachable( \::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7143) | ||||
7143 | "dependent types aren't supported in the constant evaluator!")::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7143); | ||||
7144 | #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)case Type::Class: ::llvm::llvm_unreachable_internal("either dependent or not canonical!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7144); \ | ||||
7145 | case Type::Class: \ | ||||
7146 | llvm_unreachable("either dependent or not canonical!")::llvm::llvm_unreachable_internal("either dependent or not canonical!" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7146); | ||||
7147 | #include "clang/AST/TypeNodes.inc" | ||||
7148 | } | ||||
7149 | llvm_unreachable("Unhandled Type::TypeClass")::llvm::llvm_unreachable_internal("Unhandled Type::TypeClass" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7149); | ||||
7150 | } | ||||
7151 | |||||
7152 | public: | ||||
7153 | // Pull out a full value of type DstType. | ||||
7154 | static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, | ||||
7155 | const CastExpr *BCE) { | ||||
7156 | BufferToAPValueConverter Converter(Info, Buffer, BCE); | ||||
7157 | return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); | ||||
7158 | } | ||||
7159 | }; | ||||
7160 | |||||
7161 | static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, | ||||
7162 | QualType Ty, EvalInfo *Info, | ||||
7163 | const ASTContext &Ctx, | ||||
7164 | bool CheckingDest) { | ||||
7165 | Ty = Ty.getCanonicalType(); | ||||
7166 | |||||
7167 | auto diag = [&](int Reason) { | ||||
7168 | if (Info) | ||||
7169 | Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) | ||||
7170 | << CheckingDest << (Reason == 4) << Reason; | ||||
7171 | return false; | ||||
7172 | }; | ||||
7173 | auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { | ||||
7174 | if (Info) | ||||
7175 | Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) | ||||
7176 | << NoteTy << Construct << Ty; | ||||
7177 | return false; | ||||
7178 | }; | ||||
7179 | |||||
7180 | if (Ty->isUnionType()) | ||||
7181 | return diag(0); | ||||
7182 | if (Ty->isPointerType()) | ||||
7183 | return diag(1); | ||||
7184 | if (Ty->isMemberPointerType()) | ||||
7185 | return diag(2); | ||||
7186 | if (Ty.isVolatileQualified()) | ||||
7187 | return diag(3); | ||||
7188 | |||||
7189 | if (RecordDecl *Record = Ty->getAsRecordDecl()) { | ||||
7190 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { | ||||
7191 | for (CXXBaseSpecifier &BS : CXXRD->bases()) | ||||
7192 | if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, | ||||
7193 | CheckingDest)) | ||||
7194 | return note(1, BS.getType(), BS.getBeginLoc()); | ||||
7195 | } | ||||
7196 | for (FieldDecl *FD : Record->fields()) { | ||||
7197 | if (FD->getType()->isReferenceType()) | ||||
7198 | return diag(4); | ||||
7199 | if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, | ||||
7200 | CheckingDest)) | ||||
7201 | return note(0, FD->getType(), FD->getBeginLoc()); | ||||
7202 | } | ||||
7203 | } | ||||
7204 | |||||
7205 | if (Ty->isArrayType() && | ||||
7206 | !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), | ||||
7207 | Info, Ctx, CheckingDest)) | ||||
7208 | return false; | ||||
7209 | |||||
7210 | return true; | ||||
7211 | } | ||||
7212 | |||||
7213 | static bool checkBitCastConstexprEligibility(EvalInfo *Info, | ||||
7214 | const ASTContext &Ctx, | ||||
7215 | const CastExpr *BCE) { | ||||
7216 | bool DestOK = checkBitCastConstexprEligibilityType( | ||||
7217 | BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); | ||||
7218 | bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( | ||||
7219 | BCE->getBeginLoc(), | ||||
7220 | BCE->getSubExpr()->getType(), Info, Ctx, false); | ||||
7221 | return SourceOK; | ||||
7222 | } | ||||
7223 | |||||
7224 | static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, | ||||
7225 | APValue &SourceValue, | ||||
7226 | const CastExpr *BCE) { | ||||
7227 | assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&(static_cast <bool> (8 == 8 && Info.Ctx.getTargetInfo ().getCharWidth() == 8 && "no host or target supports non 8-bit chars" ) ? void (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7228, __extension__ __PRETTY_FUNCTION__)) | ||||
7228 | "no host or target supports non 8-bit chars")(static_cast <bool> (8 == 8 && Info.Ctx.getTargetInfo ().getCharWidth() == 8 && "no host or target supports non 8-bit chars" ) ? void (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7228, __extension__ __PRETTY_FUNCTION__)); | ||||
7229 | assert(SourceValue.isLValue() &&(static_cast <bool> (SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!" ) ? void (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7230, __extension__ __PRETTY_FUNCTION__)) | ||||
7230 | "LValueToRValueBitcast requires an lvalue operand!")(static_cast <bool> (SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!" ) ? void (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7230, __extension__ __PRETTY_FUNCTION__)); | ||||
7231 | |||||
7232 | if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) | ||||
7233 | return false; | ||||
7234 | |||||
7235 | LValue SourceLValue; | ||||
7236 | APValue SourceRValue; | ||||
7237 | SourceLValue.setFrom(Info.Ctx, SourceValue); | ||||
7238 | if (!handleLValueToRValueConversion( | ||||
7239 | Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, | ||||
7240 | SourceRValue, /*WantObjectRepresentation=*/true)) | ||||
7241 | return false; | ||||
7242 | |||||
7243 | // Read out SourceValue into a char buffer. | ||||
7244 | Optional<BitCastBuffer> Buffer = | ||||
7245 | APValueToBufferConverter::convert(Info, SourceRValue, BCE); | ||||
7246 | if (!Buffer) | ||||
7247 | return false; | ||||
7248 | |||||
7249 | // Write out the buffer into a new APValue. | ||||
7250 | Optional<APValue> MaybeDestValue = | ||||
7251 | BufferToAPValueConverter::convert(Info, *Buffer, BCE); | ||||
7252 | if (!MaybeDestValue) | ||||
7253 | return false; | ||||
7254 | |||||
7255 | DestValue = std::move(*MaybeDestValue); | ||||
7256 | return true; | ||||
7257 | } | ||||
7258 | |||||
7259 | template <class Derived> | ||||
7260 | class ExprEvaluatorBase | ||||
7261 | : public ConstStmtVisitor<Derived, bool> { | ||||
7262 | private: | ||||
7263 | Derived &getDerived() { return static_cast<Derived&>(*this); } | ||||
7264 | bool DerivedSuccess(const APValue &V, const Expr *E) { | ||||
7265 | return getDerived().Success(V, E); | ||||
7266 | } | ||||
7267 | bool DerivedZeroInitialization(const Expr *E) { | ||||
7268 | return getDerived().ZeroInitialization(E); | ||||
7269 | } | ||||
7270 | |||||
7271 | // Check whether a conditional operator with a non-constant condition is a | ||||
7272 | // potential constant expression. If neither arm is a potential constant | ||||
7273 | // expression, then the conditional operator is not either. | ||||
7274 | template<typename ConditionalOperator> | ||||
7275 | void CheckPotentialConstantConditional(const ConditionalOperator *E) { | ||||
7276 | assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression ()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7276, __extension__ __PRETTY_FUNCTION__)); | ||||
7277 | |||||
7278 | // Speculatively evaluate both arms. | ||||
7279 | SmallVector<PartialDiagnosticAt, 8> Diag; | ||||
7280 | { | ||||
7281 | SpeculativeEvaluationRAII Speculate(Info, &Diag); | ||||
7282 | StmtVisitorTy::Visit(E->getFalseExpr()); | ||||
7283 | if (Diag.empty()) | ||||
7284 | return; | ||||
7285 | } | ||||
7286 | |||||
7287 | { | ||||
7288 | SpeculativeEvaluationRAII Speculate(Info, &Diag); | ||||
7289 | Diag.clear(); | ||||
7290 | StmtVisitorTy::Visit(E->getTrueExpr()); | ||||
7291 | if (Diag.empty()) | ||||
7292 | return; | ||||
7293 | } | ||||
7294 | |||||
7295 | Error(E, diag::note_constexpr_conditional_never_const); | ||||
7296 | } | ||||
7297 | |||||
7298 | |||||
7299 | template<typename ConditionalOperator> | ||||
7300 | bool HandleConditionalOperator(const ConditionalOperator *E) { | ||||
7301 | bool BoolResult; | ||||
7302 | if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { | ||||
7303 | if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { | ||||
7304 | CheckPotentialConstantConditional(E); | ||||
7305 | return false; | ||||
7306 | } | ||||
7307 | if (Info.noteFailure()) { | ||||
7308 | StmtVisitorTy::Visit(E->getTrueExpr()); | ||||
7309 | StmtVisitorTy::Visit(E->getFalseExpr()); | ||||
7310 | } | ||||
7311 | return false; | ||||
7312 | } | ||||
7313 | |||||
7314 | Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); | ||||
7315 | return StmtVisitorTy::Visit(EvalExpr); | ||||
7316 | } | ||||
7317 | |||||
7318 | protected: | ||||
7319 | EvalInfo &Info; | ||||
7320 | typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; | ||||
7321 | typedef ExprEvaluatorBase ExprEvaluatorBaseTy; | ||||
7322 | |||||
7323 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { | ||||
7324 | return Info.CCEDiag(E, D); | ||||
7325 | } | ||||
7326 | |||||
7327 | bool ZeroInitialization(const Expr *E) { return Error(E); } | ||||
7328 | |||||
7329 | public: | ||||
7330 | ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} | ||||
7331 | |||||
7332 | EvalInfo &getEvalInfo() { return Info; } | ||||
7333 | |||||
7334 | /// Report an evaluation error. This should only be called when an error is | ||||
7335 | /// first discovered. When propagating an error, just return false. | ||||
7336 | bool Error(const Expr *E, diag::kind D) { | ||||
7337 | Info.FFDiag(E, D); | ||||
7338 | return false; | ||||
7339 | } | ||||
7340 | bool Error(const Expr *E) { | ||||
7341 | return Error(E, diag::note_invalid_subexpr_in_const_expr); | ||||
7342 | } | ||||
7343 | |||||
7344 | bool VisitStmt(const Stmt *) { | ||||
7345 | llvm_unreachable("Expression evaluator should not be called on stmts")::llvm::llvm_unreachable_internal("Expression evaluator should not be called on stmts" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7345); | ||||
7346 | } | ||||
7347 | bool VisitExpr(const Expr *E) { | ||||
7348 | return Error(E); | ||||
7349 | } | ||||
7350 | |||||
7351 | bool VisitConstantExpr(const ConstantExpr *E) { | ||||
7352 | if (E->hasAPValueResult()) | ||||
7353 | return DerivedSuccess(E->getAPValueResult(), E); | ||||
7354 | |||||
7355 | return StmtVisitorTy::Visit(E->getSubExpr()); | ||||
7356 | } | ||||
7357 | |||||
7358 | bool VisitParenExpr(const ParenExpr *E) | ||||
7359 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||
7360 | bool VisitUnaryExtension(const UnaryOperator *E) | ||||
7361 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||
7362 | bool VisitUnaryPlus(const UnaryOperator *E) | ||||
7363 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||
7364 | bool VisitChooseExpr(const ChooseExpr *E) | ||||
7365 | { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } | ||||
7366 | bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) | ||||
7367 | { return StmtVisitorTy::Visit(E->getResultExpr()); } | ||||
7368 | bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) | ||||
7369 | { return StmtVisitorTy::Visit(E->getReplacement()); } | ||||
7370 | bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { | ||||
7371 | TempVersionRAII RAII(*Info.CurrentCall); | ||||
7372 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); | ||||
7373 | return StmtVisitorTy::Visit(E->getExpr()); | ||||
7374 | } | ||||
7375 | bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { | ||||
7376 | TempVersionRAII RAII(*Info.CurrentCall); | ||||
7377 | // The initializer may not have been parsed yet, or might be erroneous. | ||||
7378 | if (!E->getExpr()) | ||||
7379 | return Error(E); | ||||
7380 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); | ||||
7381 | return StmtVisitorTy::Visit(E->getExpr()); | ||||
7382 | } | ||||
7383 | |||||
7384 | bool VisitExprWithCleanups(const ExprWithCleanups *E) { | ||||
7385 | FullExpressionRAII Scope(Info); | ||||
7386 | return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); | ||||
7387 | } | ||||
7388 | |||||
7389 | // Temporaries are registered when created, so we don't care about | ||||
7390 | // CXXBindTemporaryExpr. | ||||
7391 | bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { | ||||
7392 | return StmtVisitorTy::Visit(E->getSubExpr()); | ||||
7393 | } | ||||
7394 | |||||
7395 | bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { | ||||
7396 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; | ||||
7397 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||
7398 | } | ||||
7399 | bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { | ||||
7400 | if (!Info.Ctx.getLangOpts().CPlusPlus20) | ||||
7401 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; | ||||
7402 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||
7403 | } | ||||
7404 | bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { | ||||
7405 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||
7406 | } | ||||
7407 | |||||
7408 | bool VisitBinaryOperator(const BinaryOperator *E) { | ||||
7409 | switch (E->getOpcode()) { | ||||
7410 | default: | ||||
7411 | return Error(E); | ||||
7412 | |||||
7413 | case BO_Comma: | ||||
7414 | VisitIgnoredValue(E->getLHS()); | ||||
7415 | return StmtVisitorTy::Visit(E->getRHS()); | ||||
7416 | |||||
7417 | case BO_PtrMemD: | ||||
7418 | case BO_PtrMemI: { | ||||
7419 | LValue Obj; | ||||
7420 | if (!HandleMemberPointerAccess(Info, E, Obj)) | ||||
7421 | return false; | ||||
7422 | APValue Result; | ||||
7423 | if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) | ||||
7424 | return false; | ||||
7425 | return DerivedSuccess(Result, E); | ||||
7426 | } | ||||
7427 | } | ||||
7428 | } | ||||
7429 | |||||
7430 | bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { | ||||
7431 | return StmtVisitorTy::Visit(E->getSemanticForm()); | ||||
7432 | } | ||||
7433 | |||||
7434 | bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { | ||||
7435 | // Evaluate and cache the common expression. We treat it as a temporary, | ||||
7436 | // even though it's not quite the same thing. | ||||
7437 | LValue CommonLV; | ||||
7438 | if (!Evaluate(Info.CurrentCall->createTemporary( | ||||
7439 | E->getOpaqueValue(), | ||||
7440 | getStorageType(Info.Ctx, E->getOpaqueValue()), | ||||
7441 | ScopeKind::FullExpression, CommonLV), | ||||
7442 | Info, E->getCommon())) | ||||
7443 | return false; | ||||
7444 | |||||
7445 | return HandleConditionalOperator(E); | ||||
7446 | } | ||||
7447 | |||||
7448 | bool VisitConditionalOperator(const ConditionalOperator *E) { | ||||
7449 | bool IsBcpCall = false; | ||||
7450 | // If the condition (ignoring parens) is a __builtin_constant_p call, | ||||
7451 | // the result is a constant expression if it can be folded without | ||||
7452 | // side-effects. This is an important GNU extension. See GCC PR38377 | ||||
7453 | // for discussion. | ||||
7454 | if (const CallExpr *CallCE = | ||||
7455 | dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) | ||||
7456 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) | ||||
7457 | IsBcpCall = true; | ||||
7458 | |||||
7459 | // Always assume __builtin_constant_p(...) ? ... : ... is a potential | ||||
7460 | // constant expression; we can't check whether it's potentially foldable. | ||||
7461 | // FIXME: We should instead treat __builtin_constant_p as non-constant if | ||||
7462 | // it would return 'false' in this mode. | ||||
7463 | if (Info.checkingPotentialConstantExpression() && IsBcpCall) | ||||
7464 | return false; | ||||
7465 | |||||
7466 | FoldConstant Fold(Info, IsBcpCall); | ||||
7467 | if (!HandleConditionalOperator(E)) { | ||||
7468 | Fold.keepDiagnostics(); | ||||
7469 | return false; | ||||
7470 | } | ||||
7471 | |||||
7472 | return true; | ||||
7473 | } | ||||
7474 | |||||
7475 | bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { | ||||
7476 | if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) | ||||
7477 | return DerivedSuccess(*Value, E); | ||||
7478 | |||||
7479 | const Expr *Source = E->getSourceExpr(); | ||||
7480 | if (!Source) | ||||
7481 | return Error(E); | ||||
7482 | if (Source == E) { // sanity checking. | ||||
7483 | assert(0 && "OpaqueValueExpr recursively refers to itself")(static_cast <bool> (0 && "OpaqueValueExpr recursively refers to itself" ) ? void (0) : __assert_fail ("0 && \"OpaqueValueExpr recursively refers to itself\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7483, __extension__ __PRETTY_FUNCTION__)); | ||||
7484 | return Error(E); | ||||
7485 | } | ||||
7486 | return StmtVisitorTy::Visit(Source); | ||||
7487 | } | ||||
7488 | |||||
7489 | bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { | ||||
7490 | for (const Expr *SemE : E->semantics()) { | ||||
7491 | if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { | ||||
7492 | // FIXME: We can't handle the case where an OpaqueValueExpr is also the | ||||
7493 | // result expression: there could be two different LValues that would | ||||
7494 | // refer to the same object in that case, and we can't model that. | ||||
7495 | if (SemE == E->getResultExpr()) | ||||
7496 | return Error(E); | ||||
7497 | |||||
7498 | // Unique OVEs get evaluated if and when we encounter them when | ||||
7499 | // emitting the rest of the semantic form, rather than eagerly. | ||||
7500 | if (OVE->isUnique()) | ||||
7501 | continue; | ||||
7502 | |||||
7503 | LValue LV; | ||||
7504 | if (!Evaluate(Info.CurrentCall->createTemporary( | ||||
7505 | OVE, getStorageType(Info.Ctx, OVE), | ||||
7506 | ScopeKind::FullExpression, LV), | ||||
7507 | Info, OVE->getSourceExpr())) | ||||
7508 | return false; | ||||
7509 | } else if (SemE == E->getResultExpr()) { | ||||
7510 | if (!StmtVisitorTy::Visit(SemE)) | ||||
7511 | return false; | ||||
7512 | } else { | ||||
7513 | if (!EvaluateIgnoredValue(Info, SemE)) | ||||
7514 | return false; | ||||
7515 | } | ||||
7516 | } | ||||
7517 | return true; | ||||
7518 | } | ||||
7519 | |||||
7520 | bool VisitCallExpr(const CallExpr *E) { | ||||
7521 | APValue Result; | ||||
7522 | if (!handleCallExpr(E, Result, nullptr)) | ||||
7523 | return false; | ||||
7524 | return DerivedSuccess(Result, E); | ||||
7525 | } | ||||
7526 | |||||
7527 | bool handleCallExpr(const CallExpr *E, APValue &Result, | ||||
7528 | const LValue *ResultSlot) { | ||||
7529 | CallScopeRAII CallScope(Info); | ||||
7530 | |||||
7531 | const Expr *Callee = E->getCallee()->IgnoreParens(); | ||||
7532 | QualType CalleeType = Callee->getType(); | ||||
7533 | |||||
7534 | const FunctionDecl *FD = nullptr; | ||||
7535 | LValue *This = nullptr, ThisVal; | ||||
7536 | auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); | ||||
7537 | bool HasQualifier = false; | ||||
7538 | |||||
7539 | CallRef Call; | ||||
7540 | |||||
7541 | // Extract function decl and 'this' pointer from the callee. | ||||
7542 | if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { | ||||
7543 | const CXXMethodDecl *Member = nullptr; | ||||
7544 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { | ||||
7545 | // Explicit bound member calls, such as x.f() or p->g(); | ||||
7546 | if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) | ||||
7547 | return false; | ||||
7548 | Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||
7549 | if (!Member) | ||||
7550 | return Error(Callee); | ||||
7551 | This = &ThisVal; | ||||
7552 | HasQualifier = ME->hasQualifier(); | ||||
7553 | } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { | ||||
7554 | // Indirect bound member calls ('.*' or '->*'). | ||||
7555 | const ValueDecl *D = | ||||
7556 | HandleMemberPointerAccess(Info, BE, ThisVal, false); | ||||
7557 | if (!D) | ||||
7558 | return false; | ||||
7559 | Member = dyn_cast<CXXMethodDecl>(D); | ||||
7560 | if (!Member) | ||||
7561 | return Error(Callee); | ||||
7562 | This = &ThisVal; | ||||
7563 | } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { | ||||
7564 | if (!Info.getLangOpts().CPlusPlus20) | ||||
7565 | Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); | ||||
7566 | return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && | ||||
7567 | HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); | ||||
7568 | } else | ||||
7569 | return Error(Callee); | ||||
7570 | FD = Member; | ||||
7571 | } else if (CalleeType->isFunctionPointerType()) { | ||||
7572 | LValue CalleeLV; | ||||
7573 | if (!EvaluatePointer(Callee, CalleeLV, Info)) | ||||
7574 | return false; | ||||
7575 | |||||
7576 | if (!CalleeLV.getLValueOffset().isZero()) | ||||
7577 | return Error(Callee); | ||||
7578 | FD = dyn_cast_or_null<FunctionDecl>( | ||||
7579 | CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); | ||||
7580 | if (!FD) | ||||
7581 | return Error(Callee); | ||||
7582 | // Don't call function pointers which have been cast to some other type. | ||||
7583 | // Per DR (no number yet), the caller and callee can differ in noexcept. | ||||
7584 | if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( | ||||
7585 | CalleeType->getPointeeType(), FD->getType())) { | ||||
7586 | return Error(E); | ||||
7587 | } | ||||
7588 | |||||
7589 | // For an (overloaded) assignment expression, evaluate the RHS before the | ||||
7590 | // LHS. | ||||
7591 | auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); | ||||
7592 | if (OCE && OCE->isAssignmentOp()) { | ||||
7593 | assert(Args.size() == 2 && "wrong number of arguments in assignment")(static_cast <bool> (Args.size() == 2 && "wrong number of arguments in assignment" ) ? void (0) : __assert_fail ("Args.size() == 2 && \"wrong number of arguments in assignment\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7593, __extension__ __PRETTY_FUNCTION__)); | ||||
7594 | Call = Info.CurrentCall->createCall(FD); | ||||
7595 | if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, | ||||
7596 | Info, FD, /*RightToLeft=*/true)) | ||||
7597 | return false; | ||||
7598 | } | ||||
7599 | |||||
7600 | // Overloaded operator calls to member functions are represented as normal | ||||
7601 | // calls with '*this' as the first argument. | ||||
7602 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
7603 | if (MD && !MD->isStatic()) { | ||||
7604 | // FIXME: When selecting an implicit conversion for an overloaded | ||||
7605 | // operator delete, we sometimes try to evaluate calls to conversion | ||||
7606 | // operators without a 'this' parameter! | ||||
7607 | if (Args.empty()) | ||||
7608 | return Error(E); | ||||
7609 | |||||
7610 | if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) | ||||
7611 | return false; | ||||
7612 | This = &ThisVal; | ||||
7613 | Args = Args.slice(1); | ||||
7614 | } else if (MD && MD->isLambdaStaticInvoker()) { | ||||
7615 | // Map the static invoker for the lambda back to the call operator. | ||||
7616 | // Conveniently, we don't have to slice out the 'this' argument (as is | ||||
7617 | // being done for the non-static case), since a static member function | ||||
7618 | // doesn't have an implicit argument passed in. | ||||
7619 | const CXXRecordDecl *ClosureClass = MD->getParent(); | ||||
7620 | assert((static_cast <bool> (ClosureClass->captures_begin() == ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr" ) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7622, __extension__ __PRETTY_FUNCTION__)) | ||||
7621 | ClosureClass->captures_begin() == ClosureClass->captures_end() &&(static_cast <bool> (ClosureClass->captures_begin() == ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr" ) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7622, __extension__ __PRETTY_FUNCTION__)) | ||||
7622 | "Number of captures must be zero for conversion to function-ptr")(static_cast <bool> (ClosureClass->captures_begin() == ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr" ) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7622, __extension__ __PRETTY_FUNCTION__)); | ||||
7623 | |||||
7624 | const CXXMethodDecl *LambdaCallOp = | ||||
7625 | ClosureClass->getLambdaCallOperator(); | ||||
7626 | |||||
7627 | // Set 'FD', the function that will be called below, to the call | ||||
7628 | // operator. If the closure object represents a generic lambda, find | ||||
7629 | // the corresponding specialization of the call operator. | ||||
7630 | |||||
7631 | if (ClosureClass->isGenericLambda()) { | ||||
7632 | assert(MD->isFunctionTemplateSpecialization() &&(static_cast <bool> (MD->isFunctionTemplateSpecialization () && "A generic lambda's static-invoker function must be a " "template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7634, __extension__ __PRETTY_FUNCTION__)) | ||||
7633 | "A generic lambda's static-invoker function must be a "(static_cast <bool> (MD->isFunctionTemplateSpecialization () && "A generic lambda's static-invoker function must be a " "template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7634, __extension__ __PRETTY_FUNCTION__)) | ||||
7634 | "template specialization")(static_cast <bool> (MD->isFunctionTemplateSpecialization () && "A generic lambda's static-invoker function must be a " "template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7634, __extension__ __PRETTY_FUNCTION__)); | ||||
7635 | const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); | ||||
7636 | FunctionTemplateDecl *CallOpTemplate = | ||||
7637 | LambdaCallOp->getDescribedFunctionTemplate(); | ||||
7638 | void *InsertPos = nullptr; | ||||
7639 | FunctionDecl *CorrespondingCallOpSpecialization = | ||||
7640 | CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); | ||||
7641 | assert(CorrespondingCallOpSpecialization &&(static_cast <bool> (CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? void (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7643, __extension__ __PRETTY_FUNCTION__)) | ||||
7642 | "We must always have a function call operator specialization "(static_cast <bool> (CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? void (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7643, __extension__ __PRETTY_FUNCTION__)) | ||||
7643 | "that corresponds to our static invoker specialization")(static_cast <bool> (CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? void (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7643, __extension__ __PRETTY_FUNCTION__)); | ||||
7644 | FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); | ||||
7645 | } else | ||||
7646 | FD = LambdaCallOp; | ||||
7647 | } else if (FD->isReplaceableGlobalAllocationFunction()) { | ||||
7648 | if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || | ||||
7649 | FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { | ||||
7650 | LValue Ptr; | ||||
7651 | if (!HandleOperatorNewCall(Info, E, Ptr)) | ||||
7652 | return false; | ||||
7653 | Ptr.moveInto(Result); | ||||
7654 | return CallScope.destroy(); | ||||
7655 | } else { | ||||
7656 | return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); | ||||
7657 | } | ||||
7658 | } | ||||
7659 | } else | ||||
7660 | return Error(E); | ||||
7661 | |||||
7662 | // Evaluate the arguments now if we've not already done so. | ||||
7663 | if (!Call) { | ||||
7664 | Call = Info.CurrentCall->createCall(FD); | ||||
7665 | if (!EvaluateArgs(Args, Call, Info, FD)) | ||||
7666 | return false; | ||||
7667 | } | ||||
7668 | |||||
7669 | SmallVector<QualType, 4> CovariantAdjustmentPath; | ||||
7670 | if (This) { | ||||
7671 | auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); | ||||
7672 | if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { | ||||
7673 | // Perform virtual dispatch, if necessary. | ||||
7674 | FD = HandleVirtualDispatch(Info, E, *This, NamedMember, | ||||
7675 | CovariantAdjustmentPath); | ||||
7676 | if (!FD) | ||||
7677 | return false; | ||||
7678 | } else { | ||||
7679 | // Check that the 'this' pointer points to an object of the right type. | ||||
7680 | // FIXME: If this is an assignment operator call, we may need to change | ||||
7681 | // the active union member before we check this. | ||||
7682 | if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) | ||||
7683 | return false; | ||||
7684 | } | ||||
7685 | } | ||||
7686 | |||||
7687 | // Destructor calls are different enough that they have their own codepath. | ||||
7688 | if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { | ||||
7689 | assert(This && "no 'this' pointer for destructor call")(static_cast <bool> (This && "no 'this' pointer for destructor call" ) ? void (0) : __assert_fail ("This && \"no 'this' pointer for destructor call\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7689, __extension__ __PRETTY_FUNCTION__)); | ||||
7690 | return HandleDestruction(Info, E, *This, | ||||
7691 | Info.Ctx.getRecordType(DD->getParent())) && | ||||
7692 | CallScope.destroy(); | ||||
7693 | } | ||||
7694 | |||||
7695 | const FunctionDecl *Definition = nullptr; | ||||
7696 | Stmt *Body = FD->getBody(Definition); | ||||
7697 | |||||
7698 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || | ||||
7699 | !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, | ||||
7700 | Body, Info, Result, ResultSlot)) | ||||
7701 | return false; | ||||
7702 | |||||
7703 | if (!CovariantAdjustmentPath.empty() && | ||||
7704 | !HandleCovariantReturnAdjustment(Info, E, Result, | ||||
7705 | CovariantAdjustmentPath)) | ||||
7706 | return false; | ||||
7707 | |||||
7708 | return CallScope.destroy(); | ||||
7709 | } | ||||
7710 | |||||
7711 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { | ||||
7712 | return StmtVisitorTy::Visit(E->getInitializer()); | ||||
7713 | } | ||||
7714 | bool VisitInitListExpr(const InitListExpr *E) { | ||||
7715 | if (E->getNumInits() == 0) | ||||
7716 | return DerivedZeroInitialization(E); | ||||
7717 | if (E->getNumInits() == 1) | ||||
7718 | return StmtVisitorTy::Visit(E->getInit(0)); | ||||
7719 | return Error(E); | ||||
7720 | } | ||||
7721 | bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { | ||||
7722 | return DerivedZeroInitialization(E); | ||||
7723 | } | ||||
7724 | bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { | ||||
7725 | return DerivedZeroInitialization(E); | ||||
7726 | } | ||||
7727 | bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { | ||||
7728 | return DerivedZeroInitialization(E); | ||||
7729 | } | ||||
7730 | |||||
7731 | /// A member expression where the object is a prvalue is itself a prvalue. | ||||
7732 | bool VisitMemberExpr(const MemberExpr *E) { | ||||
7733 | assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&(static_cast <bool> (!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion") ? void (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7734, __extension__ __PRETTY_FUNCTION__)) | ||||
7734 | "missing temporary materialization conversion")(static_cast <bool> (!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion") ? void (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7734, __extension__ __PRETTY_FUNCTION__)); | ||||
7735 | assert(!E->isArrow() && "missing call to bound member function?")(static_cast <bool> (!E->isArrow() && "missing call to bound member function?" ) ? void (0) : __assert_fail ("!E->isArrow() && \"missing call to bound member function?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7735, __extension__ __PRETTY_FUNCTION__)); | ||||
7736 | |||||
7737 | APValue Val; | ||||
7738 | if (!Evaluate(Val, Info, E->getBase())) | ||||
7739 | return false; | ||||
7740 | |||||
7741 | QualType BaseTy = E->getBase()->getType(); | ||||
7742 | |||||
7743 | const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); | ||||
7744 | if (!FD) return Error(E); | ||||
7745 | assert(!FD->getType()->isReferenceType() && "prvalue reference?")(static_cast <bool> (!FD->getType()->isReferenceType () && "prvalue reference?") ? void (0) : __assert_fail ("!FD->getType()->isReferenceType() && \"prvalue reference?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7745, __extension__ __PRETTY_FUNCTION__)); | ||||
7746 | assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==(static_cast <bool> (BaseTy->castAs<RecordType> ()->getDecl()->getCanonicalDecl() == FD->getParent() ->getCanonicalDecl() && "record / field mismatch") ? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7747, __extension__ __PRETTY_FUNCTION__)) | ||||
7747 | FD->getParent()->getCanonicalDecl() && "record / field mismatch")(static_cast <bool> (BaseTy->castAs<RecordType> ()->getDecl()->getCanonicalDecl() == FD->getParent() ->getCanonicalDecl() && "record / field mismatch") ? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7747, __extension__ __PRETTY_FUNCTION__)); | ||||
7748 | |||||
7749 | // Note: there is no lvalue base here. But this case should only ever | ||||
7750 | // happen in C or in C++98, where we cannot be evaluating a constexpr | ||||
7751 | // constructor, which is the only case the base matters. | ||||
7752 | CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); | ||||
7753 | SubobjectDesignator Designator(BaseTy); | ||||
7754 | Designator.addDeclUnchecked(FD); | ||||
7755 | |||||
7756 | APValue Result; | ||||
7757 | return extractSubobject(Info, E, Obj, Designator, Result) && | ||||
7758 | DerivedSuccess(Result, E); | ||||
7759 | } | ||||
7760 | |||||
7761 | bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { | ||||
7762 | APValue Val; | ||||
7763 | if (!Evaluate(Val, Info, E->getBase())) | ||||
7764 | return false; | ||||
7765 | |||||
7766 | if (Val.isVector()) { | ||||
7767 | SmallVector<uint32_t, 4> Indices; | ||||
7768 | E->getEncodedElementAccess(Indices); | ||||
7769 | if (Indices.size() == 1) { | ||||
7770 | // Return scalar. | ||||
7771 | return DerivedSuccess(Val.getVectorElt(Indices[0]), E); | ||||
7772 | } else { | ||||
7773 | // Construct new APValue vector. | ||||
7774 | SmallVector<APValue, 4> Elts; | ||||
7775 | for (unsigned I = 0; I < Indices.size(); ++I) { | ||||
7776 | Elts.push_back(Val.getVectorElt(Indices[I])); | ||||
7777 | } | ||||
7778 | APValue VecResult(Elts.data(), Indices.size()); | ||||
7779 | return DerivedSuccess(VecResult, E); | ||||
7780 | } | ||||
7781 | } | ||||
7782 | |||||
7783 | return false; | ||||
7784 | } | ||||
7785 | |||||
7786 | bool VisitCastExpr(const CastExpr *E) { | ||||
7787 | switch (E->getCastKind()) { | ||||
7788 | default: | ||||
7789 | break; | ||||
7790 | |||||
7791 | case CK_AtomicToNonAtomic: { | ||||
7792 | APValue AtomicVal; | ||||
7793 | // This does not need to be done in place even for class/array types: | ||||
7794 | // atomic-to-non-atomic conversion implies copying the object | ||||
7795 | // representation. | ||||
7796 | if (!Evaluate(AtomicVal, Info, E->getSubExpr())) | ||||
7797 | return false; | ||||
7798 | return DerivedSuccess(AtomicVal, E); | ||||
7799 | } | ||||
7800 | |||||
7801 | case CK_NoOp: | ||||
7802 | case CK_UserDefinedConversion: | ||||
7803 | return StmtVisitorTy::Visit(E->getSubExpr()); | ||||
7804 | |||||
7805 | case CK_LValueToRValue: { | ||||
7806 | LValue LVal; | ||||
7807 | if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) | ||||
7808 | return false; | ||||
7809 | APValue RVal; | ||||
7810 | // Note, we use the subexpression's type in order to retain cv-qualifiers. | ||||
7811 | if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), | ||||
7812 | LVal, RVal)) | ||||
7813 | return false; | ||||
7814 | return DerivedSuccess(RVal, E); | ||||
7815 | } | ||||
7816 | case CK_LValueToRValueBitCast: { | ||||
7817 | APValue DestValue, SourceValue; | ||||
7818 | if (!Evaluate(SourceValue, Info, E->getSubExpr())) | ||||
7819 | return false; | ||||
7820 | if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) | ||||
7821 | return false; | ||||
7822 | return DerivedSuccess(DestValue, E); | ||||
7823 | } | ||||
7824 | |||||
7825 | case CK_AddressSpaceConversion: { | ||||
7826 | APValue Value; | ||||
7827 | if (!Evaluate(Value, Info, E->getSubExpr())) | ||||
7828 | return false; | ||||
7829 | return DerivedSuccess(Value, E); | ||||
7830 | } | ||||
7831 | } | ||||
7832 | |||||
7833 | return Error(E); | ||||
7834 | } | ||||
7835 | |||||
7836 | bool VisitUnaryPostInc(const UnaryOperator *UO) { | ||||
7837 | return VisitUnaryPostIncDec(UO); | ||||
7838 | } | ||||
7839 | bool VisitUnaryPostDec(const UnaryOperator *UO) { | ||||
7840 | return VisitUnaryPostIncDec(UO); | ||||
7841 | } | ||||
7842 | bool VisitUnaryPostIncDec(const UnaryOperator *UO) { | ||||
7843 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||
7844 | return Error(UO); | ||||
7845 | |||||
7846 | LValue LVal; | ||||
7847 | if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) | ||||
7848 | return false; | ||||
7849 | APValue RVal; | ||||
7850 | if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), | ||||
7851 | UO->isIncrementOp(), &RVal)) | ||||
7852 | return false; | ||||
7853 | return DerivedSuccess(RVal, UO); | ||||
7854 | } | ||||
7855 | |||||
7856 | bool VisitStmtExpr(const StmtExpr *E) { | ||||
7857 | // We will have checked the full-expressions inside the statement expression | ||||
7858 | // when they were completed, and don't need to check them again now. | ||||
7859 | llvm::SaveAndRestore<bool> NotCheckingForUB( | ||||
7860 | Info.CheckingForUndefinedBehavior, false); | ||||
7861 | |||||
7862 | const CompoundStmt *CS = E->getSubStmt(); | ||||
7863 | if (CS->body_empty()) | ||||
7864 | return true; | ||||
7865 | |||||
7866 | BlockScopeRAII Scope(Info); | ||||
7867 | for (CompoundStmt::const_body_iterator BI = CS->body_begin(), | ||||
7868 | BE = CS->body_end(); | ||||
7869 | /**/; ++BI) { | ||||
7870 | if (BI + 1 == BE) { | ||||
7871 | const Expr *FinalExpr = dyn_cast<Expr>(*BI); | ||||
7872 | if (!FinalExpr) { | ||||
7873 | Info.FFDiag((*BI)->getBeginLoc(), | ||||
7874 | diag::note_constexpr_stmt_expr_unsupported); | ||||
7875 | return false; | ||||
7876 | } | ||||
7877 | return this->Visit(FinalExpr) && Scope.destroy(); | ||||
7878 | } | ||||
7879 | |||||
7880 | APValue ReturnValue; | ||||
7881 | StmtResult Result = { ReturnValue, nullptr }; | ||||
7882 | EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); | ||||
7883 | if (ESR != ESR_Succeeded) { | ||||
7884 | // FIXME: If the statement-expression terminated due to 'return', | ||||
7885 | // 'break', or 'continue', it would be nice to propagate that to | ||||
7886 | // the outer statement evaluation rather than bailing out. | ||||
7887 | if (ESR != ESR_Failed) | ||||
7888 | Info.FFDiag((*BI)->getBeginLoc(), | ||||
7889 | diag::note_constexpr_stmt_expr_unsupported); | ||||
7890 | return false; | ||||
7891 | } | ||||
7892 | } | ||||
7893 | |||||
7894 | llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above." , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7894); | ||||
7895 | } | ||||
7896 | |||||
7897 | /// Visit a value which is evaluated, but whose value is ignored. | ||||
7898 | void VisitIgnoredValue(const Expr *E) { | ||||
7899 | EvaluateIgnoredValue(Info, E); | ||||
7900 | } | ||||
7901 | |||||
7902 | /// Potentially visit a MemberExpr's base expression. | ||||
7903 | void VisitIgnoredBaseExpression(const Expr *E) { | ||||
7904 | // While MSVC doesn't evaluate the base expression, it does diagnose the | ||||
7905 | // presence of side-effecting behavior. | ||||
7906 | if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) | ||||
7907 | return; | ||||
7908 | VisitIgnoredValue(E); | ||||
7909 | } | ||||
7910 | }; | ||||
7911 | |||||
7912 | } // namespace | ||||
7913 | |||||
7914 | //===----------------------------------------------------------------------===// | ||||
7915 | // Common base class for lvalue and temporary evaluation. | ||||
7916 | //===----------------------------------------------------------------------===// | ||||
7917 | namespace { | ||||
7918 | template<class Derived> | ||||
7919 | class LValueExprEvaluatorBase | ||||
7920 | : public ExprEvaluatorBase<Derived> { | ||||
7921 | protected: | ||||
7922 | LValue &Result; | ||||
7923 | bool InvalidBaseOK; | ||||
7924 | typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; | ||||
7925 | typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; | ||||
7926 | |||||
7927 | bool Success(APValue::LValueBase B) { | ||||
7928 | Result.set(B); | ||||
7929 | return true; | ||||
7930 | } | ||||
7931 | |||||
7932 | bool evaluatePointer(const Expr *E, LValue &Result) { | ||||
7933 | return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); | ||||
7934 | } | ||||
7935 | |||||
7936 | public: | ||||
7937 | LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) | ||||
7938 | : ExprEvaluatorBaseTy(Info), Result(Result), | ||||
7939 | InvalidBaseOK(InvalidBaseOK) {} | ||||
7940 | |||||
7941 | bool Success(const APValue &V, const Expr *E) { | ||||
7942 | Result.setFrom(this->Info.Ctx, V); | ||||
7943 | return true; | ||||
7944 | } | ||||
7945 | |||||
7946 | bool VisitMemberExpr(const MemberExpr *E) { | ||||
7947 | // Handle non-static data members. | ||||
7948 | QualType BaseTy; | ||||
7949 | bool EvalOK; | ||||
7950 | if (E->isArrow()) { | ||||
7951 | EvalOK = evaluatePointer(E->getBase(), Result); | ||||
7952 | BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); | ||||
7953 | } else if (E->getBase()->isPRValue()) { | ||||
7954 | assert(E->getBase()->getType()->isRecordType())(static_cast <bool> (E->getBase()->getType()-> isRecordType()) ? void (0) : __assert_fail ("E->getBase()->getType()->isRecordType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7954, __extension__ __PRETTY_FUNCTION__)); | ||||
7955 | EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); | ||||
7956 | BaseTy = E->getBase()->getType(); | ||||
7957 | } else { | ||||
7958 | EvalOK = this->Visit(E->getBase()); | ||||
7959 | BaseTy = E->getBase()->getType(); | ||||
7960 | } | ||||
7961 | if (!EvalOK) { | ||||
7962 | if (!InvalidBaseOK) | ||||
7963 | return false; | ||||
7964 | Result.setInvalid(E); | ||||
7965 | return true; | ||||
7966 | } | ||||
7967 | |||||
7968 | const ValueDecl *MD = E->getMemberDecl(); | ||||
7969 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { | ||||
7970 | assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==(static_cast <bool> (BaseTy->castAs<RecordType> ()->getDecl()->getCanonicalDecl() == FD->getParent() ->getCanonicalDecl() && "record / field mismatch") ? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7971, __extension__ __PRETTY_FUNCTION__)) | ||||
7971 | FD->getParent()->getCanonicalDecl() && "record / field mismatch")(static_cast <bool> (BaseTy->castAs<RecordType> ()->getDecl()->getCanonicalDecl() == FD->getParent() ->getCanonicalDecl() && "record / field mismatch") ? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 7971, __extension__ __PRETTY_FUNCTION__)); | ||||
7972 | (void)BaseTy; | ||||
7973 | if (!HandleLValueMember(this->Info, E, Result, FD)) | ||||
7974 | return false; | ||||
7975 | } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { | ||||
7976 | if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) | ||||
7977 | return false; | ||||
7978 | } else | ||||
7979 | return this->Error(E); | ||||
7980 | |||||
7981 | if (MD->getType()->isReferenceType()) { | ||||
7982 | APValue RefValue; | ||||
7983 | if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, | ||||
7984 | RefValue)) | ||||
7985 | return false; | ||||
7986 | return Success(RefValue, E); | ||||
7987 | } | ||||
7988 | return true; | ||||
7989 | } | ||||
7990 | |||||
7991 | bool VisitBinaryOperator(const BinaryOperator *E) { | ||||
7992 | switch (E->getOpcode()) { | ||||
7993 | default: | ||||
7994 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
7995 | |||||
7996 | case BO_PtrMemD: | ||||
7997 | case BO_PtrMemI: | ||||
7998 | return HandleMemberPointerAccess(this->Info, E, Result); | ||||
7999 | } | ||||
8000 | } | ||||
8001 | |||||
8002 | bool VisitCastExpr(const CastExpr *E) { | ||||
8003 | switch (E->getCastKind()) { | ||||
8004 | default: | ||||
8005 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
8006 | |||||
8007 | case CK_DerivedToBase: | ||||
8008 | case CK_UncheckedDerivedToBase: | ||||
8009 | if (!this->Visit(E->getSubExpr())) | ||||
8010 | return false; | ||||
8011 | |||||
8012 | // Now figure out the necessary offset to add to the base LV to get from | ||||
8013 | // the derived class to the base class. | ||||
8014 | return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), | ||||
8015 | Result); | ||||
8016 | } | ||||
8017 | } | ||||
8018 | }; | ||||
8019 | } | ||||
8020 | |||||
8021 | //===----------------------------------------------------------------------===// | ||||
8022 | // LValue Evaluation | ||||
8023 | // | ||||
8024 | // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), | ||||
8025 | // function designators (in C), decl references to void objects (in C), and | ||||
8026 | // temporaries (if building with -Wno-address-of-temporary). | ||||
8027 | // | ||||
8028 | // LValue evaluation produces values comprising a base expression of one of the | ||||
8029 | // following types: | ||||
8030 | // - Declarations | ||||
8031 | // * VarDecl | ||||
8032 | // * FunctionDecl | ||||
8033 | // - Literals | ||||
8034 | // * CompoundLiteralExpr in C (and in global scope in C++) | ||||
8035 | // * StringLiteral | ||||
8036 | // * PredefinedExpr | ||||
8037 | // * ObjCStringLiteralExpr | ||||
8038 | // * ObjCEncodeExpr | ||||
8039 | // * AddrLabelExpr | ||||
8040 | // * BlockExpr | ||||
8041 | // * CallExpr for a MakeStringConstant builtin | ||||
8042 | // - typeid(T) expressions, as TypeInfoLValues | ||||
8043 | // - Locals and temporaries | ||||
8044 | // * MaterializeTemporaryExpr | ||||
8045 | // * Any Expr, with a CallIndex indicating the function in which the temporary | ||||
8046 | // was evaluated, for cases where the MaterializeTemporaryExpr is missing | ||||
8047 | // from the AST (FIXME). | ||||
8048 | // * A MaterializeTemporaryExpr that has static storage duration, with no | ||||
8049 | // CallIndex, for a lifetime-extended temporary. | ||||
8050 | // * The ConstantExpr that is currently being evaluated during evaluation of an | ||||
8051 | // immediate invocation. | ||||
8052 | // plus an offset in bytes. | ||||
8053 | //===----------------------------------------------------------------------===// | ||||
8054 | namespace { | ||||
8055 | class LValueExprEvaluator | ||||
8056 | : public LValueExprEvaluatorBase<LValueExprEvaluator> { | ||||
8057 | public: | ||||
8058 | LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : | ||||
8059 | LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} | ||||
8060 | |||||
8061 | bool VisitVarDecl(const Expr *E, const VarDecl *VD); | ||||
8062 | bool VisitUnaryPreIncDec(const UnaryOperator *UO); | ||||
8063 | |||||
8064 | bool VisitDeclRefExpr(const DeclRefExpr *E); | ||||
8065 | bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } | ||||
8066 | bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); | ||||
8067 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); | ||||
8068 | bool VisitMemberExpr(const MemberExpr *E); | ||||
8069 | bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } | ||||
8070 | bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } | ||||
8071 | bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); | ||||
8072 | bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); | ||||
8073 | bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); | ||||
8074 | bool VisitUnaryDeref(const UnaryOperator *E); | ||||
8075 | bool VisitUnaryReal(const UnaryOperator *E); | ||||
8076 | bool VisitUnaryImag(const UnaryOperator *E); | ||||
8077 | bool VisitUnaryPreInc(const UnaryOperator *UO) { | ||||
8078 | return VisitUnaryPreIncDec(UO); | ||||
8079 | } | ||||
8080 | bool VisitUnaryPreDec(const UnaryOperator *UO) { | ||||
8081 | return VisitUnaryPreIncDec(UO); | ||||
8082 | } | ||||
8083 | bool VisitBinAssign(const BinaryOperator *BO); | ||||
8084 | bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); | ||||
8085 | |||||
8086 | bool VisitCastExpr(const CastExpr *E) { | ||||
8087 | switch (E->getCastKind()) { | ||||
8088 | default: | ||||
8089 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
8090 | |||||
8091 | case CK_LValueBitCast: | ||||
8092 | this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||
8093 | if (!Visit(E->getSubExpr())) | ||||
8094 | return false; | ||||
8095 | Result.Designator.setInvalid(); | ||||
8096 | return true; | ||||
8097 | |||||
8098 | case CK_BaseToDerived: | ||||
8099 | if (!Visit(E->getSubExpr())) | ||||
8100 | return false; | ||||
8101 | return HandleBaseToDerivedCast(Info, E, Result); | ||||
8102 | |||||
8103 | case CK_Dynamic: | ||||
8104 | if (!Visit(E->getSubExpr())) | ||||
8105 | return false; | ||||
8106 | return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); | ||||
8107 | } | ||||
8108 | } | ||||
8109 | }; | ||||
8110 | } // end anonymous namespace | ||||
8111 | |||||
8112 | /// Evaluate an expression as an lvalue. This can be legitimately called on | ||||
8113 | /// expressions which are not glvalues, in three cases: | ||||
8114 | /// * function designators in C, and | ||||
8115 | /// * "extern void" objects | ||||
8116 | /// * @selector() expressions in Objective-C | ||||
8117 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, | ||||
8118 | bool InvalidBaseOK) { | ||||
8119 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8119, __extension__ __PRETTY_FUNCTION__)); | ||||
8120 | assert(E->isGLValue() || E->getType()->isFunctionType() ||(static_cast <bool> (E->isGLValue() || E->getType ()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)) ? void (0) : __assert_fail ( "E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8121, __extension__ __PRETTY_FUNCTION__)) | ||||
8121 | E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E))(static_cast <bool> (E->isGLValue() || E->getType ()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)) ? void (0) : __assert_fail ( "E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8121, __extension__ __PRETTY_FUNCTION__)); | ||||
8122 | return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); | ||||
8123 | } | ||||
8124 | |||||
8125 | bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { | ||||
8126 | const NamedDecl *D = E->getDecl(); | ||||
8127 | if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) | ||||
8128 | return Success(cast<ValueDecl>(D)); | ||||
8129 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
8130 | return VisitVarDecl(E, VD); | ||||
8131 | if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) | ||||
8132 | return Visit(BD->getBinding()); | ||||
8133 | return Error(E); | ||||
8134 | } | ||||
8135 | |||||
8136 | |||||
8137 | bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { | ||||
8138 | |||||
8139 | // If we are within a lambda's call operator, check whether the 'VD' referred | ||||
8140 | // to within 'E' actually represents a lambda-capture that maps to a | ||||
8141 | // data-member/field within the closure object, and if so, evaluate to the | ||||
8142 | // field or what the field refers to. | ||||
8143 | if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && | ||||
8144 | isa<DeclRefExpr>(E) && | ||||
8145 | cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { | ||||
8146 | // We don't always have a complete capture-map when checking or inferring if | ||||
8147 | // the function call operator meets the requirements of a constexpr function | ||||
8148 | // - but we don't need to evaluate the captures to determine constexprness | ||||
8149 | // (dcl.constexpr C++17). | ||||
8150 | if (Info.checkingPotentialConstantExpression()) | ||||
8151 | return false; | ||||
8152 | |||||
8153 | if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { | ||||
8154 | // Start with 'Result' referring to the complete closure object... | ||||
8155 | Result = *Info.CurrentCall->This; | ||||
8156 | // ... then update it to refer to the field of the closure object | ||||
8157 | // that represents the capture. | ||||
8158 | if (!HandleLValueMember(Info, E, Result, FD)) | ||||
8159 | return false; | ||||
8160 | // And if the field is of reference type, update 'Result' to refer to what | ||||
8161 | // the field refers to. | ||||
8162 | if (FD->getType()->isReferenceType()) { | ||||
8163 | APValue RVal; | ||||
8164 | if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, | ||||
8165 | RVal)) | ||||
8166 | return false; | ||||
8167 | Result.setFrom(Info.Ctx, RVal); | ||||
8168 | } | ||||
8169 | return true; | ||||
8170 | } | ||||
8171 | } | ||||
8172 | |||||
8173 | CallStackFrame *Frame = nullptr; | ||||
8174 | unsigned Version = 0; | ||||
8175 | if (VD->hasLocalStorage()) { | ||||
8176 | // Only if a local variable was declared in the function currently being | ||||
8177 | // evaluated, do we expect to be able to find its value in the current | ||||
8178 | // frame. (Otherwise it was likely declared in an enclosing context and | ||||
8179 | // could either have a valid evaluatable value (for e.g. a constexpr | ||||
8180 | // variable) or be ill-formed (and trigger an appropriate evaluation | ||||
8181 | // diagnostic)). | ||||
8182 | CallStackFrame *CurrFrame = Info.CurrentCall; | ||||
8183 | if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { | ||||
8184 | // Function parameters are stored in some caller's frame. (Usually the | ||||
8185 | // immediate caller, but for an inherited constructor they may be more | ||||
8186 | // distant.) | ||||
8187 | if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { | ||||
8188 | if (CurrFrame->Arguments) { | ||||
8189 | VD = CurrFrame->Arguments.getOrigParam(PVD); | ||||
8190 | Frame = | ||||
8191 | Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; | ||||
8192 | Version = CurrFrame->Arguments.Version; | ||||
8193 | } | ||||
8194 | } else { | ||||
8195 | Frame = CurrFrame; | ||||
8196 | Version = CurrFrame->getCurrentTemporaryVersion(VD); | ||||
8197 | } | ||||
8198 | } | ||||
8199 | } | ||||
8200 | |||||
8201 | if (!VD->getType()->isReferenceType()) { | ||||
8202 | if (Frame) { | ||||
8203 | Result.set({VD, Frame->Index, Version}); | ||||
8204 | return true; | ||||
8205 | } | ||||
8206 | return Success(VD); | ||||
8207 | } | ||||
8208 | |||||
8209 | if (!Info.getLangOpts().CPlusPlus11) { | ||||
8210 | Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) | ||||
8211 | << VD << VD->getType(); | ||||
8212 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
8213 | } | ||||
8214 | |||||
8215 | APValue *V; | ||||
8216 | if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) | ||||
8217 | return false; | ||||
8218 | if (!V->hasValue()) { | ||||
8219 | // FIXME: Is it possible for V to be indeterminate here? If so, we should | ||||
8220 | // adjust the diagnostic to say that. | ||||
8221 | if (!Info.checkingPotentialConstantExpression()) | ||||
8222 | Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); | ||||
8223 | return false; | ||||
8224 | } | ||||
8225 | return Success(*V, E); | ||||
8226 | } | ||||
8227 | |||||
8228 | bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( | ||||
8229 | const MaterializeTemporaryExpr *E) { | ||||
8230 | // Walk through the expression to find the materialized temporary itself. | ||||
8231 | SmallVector<const Expr *, 2> CommaLHSs; | ||||
8232 | SmallVector<SubobjectAdjustment, 2> Adjustments; | ||||
8233 | const Expr *Inner = | ||||
8234 | E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); | ||||
8235 | |||||
8236 | // If we passed any comma operators, evaluate their LHSs. | ||||
8237 | for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) | ||||
8238 | if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) | ||||
8239 | return false; | ||||
8240 | |||||
8241 | // A materialized temporary with static storage duration can appear within the | ||||
8242 | // result of a constant expression evaluation, so we need to preserve its | ||||
8243 | // value for use outside this evaluation. | ||||
8244 | APValue *Value; | ||||
8245 | if (E->getStorageDuration() == SD_Static) { | ||||
8246 | // FIXME: What about SD_Thread? | ||||
8247 | Value = E->getOrCreateValue(true); | ||||
8248 | *Value = APValue(); | ||||
8249 | Result.set(E); | ||||
8250 | } else { | ||||
8251 | Value = &Info.CurrentCall->createTemporary( | ||||
8252 | E, E->getType(), | ||||
8253 | E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression | ||||
8254 | : ScopeKind::Block, | ||||
8255 | Result); | ||||
8256 | } | ||||
8257 | |||||
8258 | QualType Type = Inner->getType(); | ||||
8259 | |||||
8260 | // Materialize the temporary itself. | ||||
8261 | if (!EvaluateInPlace(*Value, Info, Result, Inner)) { | ||||
8262 | *Value = APValue(); | ||||
8263 | return false; | ||||
8264 | } | ||||
8265 | |||||
8266 | // Adjust our lvalue to refer to the desired subobject. | ||||
8267 | for (unsigned I = Adjustments.size(); I != 0; /**/) { | ||||
8268 | --I; | ||||
8269 | switch (Adjustments[I].Kind) { | ||||
8270 | case SubobjectAdjustment::DerivedToBaseAdjustment: | ||||
8271 | if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, | ||||
8272 | Type, Result)) | ||||
8273 | return false; | ||||
8274 | Type = Adjustments[I].DerivedToBase.BasePath->getType(); | ||||
8275 | break; | ||||
8276 | |||||
8277 | case SubobjectAdjustment::FieldAdjustment: | ||||
8278 | if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) | ||||
8279 | return false; | ||||
8280 | Type = Adjustments[I].Field->getType(); | ||||
8281 | break; | ||||
8282 | |||||
8283 | case SubobjectAdjustment::MemberPointerAdjustment: | ||||
8284 | if (!HandleMemberPointerAccess(this->Info, Type, Result, | ||||
8285 | Adjustments[I].Ptr.RHS)) | ||||
8286 | return false; | ||||
8287 | Type = Adjustments[I].Ptr.MPT->getPointeeType(); | ||||
8288 | break; | ||||
8289 | } | ||||
8290 | } | ||||
8291 | |||||
8292 | return true; | ||||
8293 | } | ||||
8294 | |||||
8295 | bool | ||||
8296 | LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { | ||||
8297 | assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&(static_cast <bool> ((!Info.getLangOpts().CPlusPlus || E ->isFileScope()) && "lvalue compound literal in c++?" ) ? void (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8298, __extension__ __PRETTY_FUNCTION__)) | ||||
8298 | "lvalue compound literal in c++?")(static_cast <bool> ((!Info.getLangOpts().CPlusPlus || E ->isFileScope()) && "lvalue compound literal in c++?" ) ? void (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8298, __extension__ __PRETTY_FUNCTION__)); | ||||
8299 | // Defer visiting the literal until the lvalue-to-rvalue conversion. We can | ||||
8300 | // only see this when folding in C, so there's no standard to follow here. | ||||
8301 | return Success(E); | ||||
8302 | } | ||||
8303 | |||||
8304 | bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { | ||||
8305 | TypeInfoLValue TypeInfo; | ||||
8306 | |||||
8307 | if (!E->isPotentiallyEvaluated()) { | ||||
8308 | if (E->isTypeOperand()) | ||||
8309 | TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); | ||||
8310 | else | ||||
8311 | TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); | ||||
8312 | } else { | ||||
8313 | if (!Info.Ctx.getLangOpts().CPlusPlus20) { | ||||
8314 | Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) | ||||
8315 | << E->getExprOperand()->getType() | ||||
8316 | << E->getExprOperand()->getSourceRange(); | ||||
8317 | } | ||||
8318 | |||||
8319 | if (!Visit(E->getExprOperand())) | ||||
8320 | return false; | ||||
8321 | |||||
8322 | Optional<DynamicType> DynType = | ||||
8323 | ComputeDynamicType(Info, E, Result, AK_TypeId); | ||||
8324 | if (!DynType) | ||||
8325 | return false; | ||||
8326 | |||||
8327 | TypeInfo = | ||||
8328 | TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); | ||||
8329 | } | ||||
8330 | |||||
8331 | return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); | ||||
8332 | } | ||||
8333 | |||||
8334 | bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { | ||||
8335 | return Success(E->getGuidDecl()); | ||||
8336 | } | ||||
8337 | |||||
8338 | bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { | ||||
8339 | // Handle static data members. | ||||
8340 | if (const VarDecl *VD
| ||||
| |||||
8341 | VisitIgnoredBaseExpression(E->getBase()); | ||||
8342 | return VisitVarDecl(E, VD); | ||||
8343 | } | ||||
8344 | |||||
8345 | // Handle static member functions. | ||||
8346 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { | ||||
8347 | if (MD->isStatic()) { | ||||
8348 | VisitIgnoredBaseExpression(E->getBase()); | ||||
8349 | return Success(MD); | ||||
8350 | } | ||||
8351 | } | ||||
8352 | |||||
8353 | // Handle non-static data members. | ||||
8354 | return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); | ||||
8355 | } | ||||
8356 | |||||
8357 | bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { | ||||
8358 | // FIXME: Deal with vectors as array subscript bases. | ||||
8359 | if (E->getBase()->getType()->isVectorType()) | ||||
8360 | return Error(E); | ||||
8361 | |||||
8362 | APSInt Index; | ||||
8363 | bool Success = true; | ||||
8364 | |||||
8365 | // C++17's rules require us to evaluate the LHS first, regardless of which | ||||
8366 | // side is the base. | ||||
8367 | for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { | ||||
8368 | if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) | ||||
8369 | : !EvaluateInteger(SubExpr, Index, Info)) { | ||||
8370 | if (!Info.noteFailure()) | ||||
8371 | return false; | ||||
8372 | Success = false; | ||||
8373 | } | ||||
8374 | } | ||||
8375 | |||||
8376 | return Success && | ||||
8377 | HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); | ||||
8378 | } | ||||
8379 | |||||
8380 | bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { | ||||
8381 | return evaluatePointer(E->getSubExpr(), Result); | ||||
8382 | } | ||||
8383 | |||||
8384 | bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||
8385 | if (!Visit(E->getSubExpr())) | ||||
8386 | return false; | ||||
8387 | // __real is a no-op on scalar lvalues. | ||||
8388 | if (E->getSubExpr()->getType()->isAnyComplexType()) | ||||
8389 | HandleLValueComplexElement(Info, E, Result, E->getType(), false); | ||||
8390 | return true; | ||||
8391 | } | ||||
8392 | |||||
8393 | bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||
8394 | assert(E->getSubExpr()->getType()->isAnyComplexType() &&(static_cast <bool> (E->getSubExpr()->getType()-> isAnyComplexType() && "lvalue __imag__ on scalar?") ? void (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8395, __extension__ __PRETTY_FUNCTION__)) | ||||
8395 | "lvalue __imag__ on scalar?")(static_cast <bool> (E->getSubExpr()->getType()-> isAnyComplexType() && "lvalue __imag__ on scalar?") ? void (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8395, __extension__ __PRETTY_FUNCTION__)); | ||||
8396 | if (!Visit(E->getSubExpr())) | ||||
8397 | return false; | ||||
8398 | HandleLValueComplexElement(Info, E, Result, E->getType(), true); | ||||
8399 | return true; | ||||
8400 | } | ||||
8401 | |||||
8402 | bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { | ||||
8403 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||
8404 | return Error(UO); | ||||
8405 | |||||
8406 | if (!this->Visit(UO->getSubExpr())) | ||||
8407 | return false; | ||||
8408 | |||||
8409 | return handleIncDec( | ||||
8410 | this->Info, UO, Result, UO->getSubExpr()->getType(), | ||||
8411 | UO->isIncrementOp(), nullptr); | ||||
8412 | } | ||||
8413 | |||||
8414 | bool LValueExprEvaluator::VisitCompoundAssignOperator( | ||||
8415 | const CompoundAssignOperator *CAO) { | ||||
8416 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||
8417 | return Error(CAO); | ||||
8418 | |||||
8419 | bool Success = true; | ||||
8420 | |||||
8421 | // C++17 onwards require that we evaluate the RHS first. | ||||
8422 | APValue RHS; | ||||
8423 | if (!Evaluate(RHS, this->Info, CAO->getRHS())) { | ||||
8424 | if (!Info.noteFailure()) | ||||
8425 | return false; | ||||
8426 | Success = false; | ||||
8427 | } | ||||
8428 | |||||
8429 | // The overall lvalue result is the result of evaluating the LHS. | ||||
8430 | if (!this->Visit(CAO->getLHS()) || !Success) | ||||
8431 | return false; | ||||
8432 | |||||
8433 | return handleCompoundAssignment( | ||||
8434 | this->Info, CAO, | ||||
8435 | Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), | ||||
8436 | CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); | ||||
8437 | } | ||||
8438 | |||||
8439 | bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { | ||||
8440 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||
8441 | return Error(E); | ||||
8442 | |||||
8443 | bool Success = true; | ||||
8444 | |||||
8445 | // C++17 onwards require that we evaluate the RHS first. | ||||
8446 | APValue NewVal; | ||||
8447 | if (!Evaluate(NewVal, this->Info, E->getRHS())) { | ||||
8448 | if (!Info.noteFailure()) | ||||
8449 | return false; | ||||
8450 | Success = false; | ||||
8451 | } | ||||
8452 | |||||
8453 | if (!this->Visit(E->getLHS()) || !Success) | ||||
8454 | return false; | ||||
8455 | |||||
8456 | if (Info.getLangOpts().CPlusPlus20 && | ||||
8457 | !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) | ||||
8458 | return false; | ||||
8459 | |||||
8460 | return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), | ||||
8461 | NewVal); | ||||
8462 | } | ||||
8463 | |||||
8464 | //===----------------------------------------------------------------------===// | ||||
8465 | // Pointer Evaluation | ||||
8466 | //===----------------------------------------------------------------------===// | ||||
8467 | |||||
8468 | /// Attempts to compute the number of bytes available at the pointer | ||||
8469 | /// returned by a function with the alloc_size attribute. Returns true if we | ||||
8470 | /// were successful. Places an unsigned number into `Result`. | ||||
8471 | /// | ||||
8472 | /// This expects the given CallExpr to be a call to a function with an | ||||
8473 | /// alloc_size attribute. | ||||
8474 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, | ||||
8475 | const CallExpr *Call, | ||||
8476 | llvm::APInt &Result) { | ||||
8477 | const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); | ||||
8478 | |||||
8479 | assert(AllocSize && AllocSize->getElemSizeParam().isValid())(static_cast <bool> (AllocSize && AllocSize-> getElemSizeParam().isValid()) ? void (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam().isValid()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8479, __extension__ __PRETTY_FUNCTION__)); | ||||
8480 | unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); | ||||
8481 | unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); | ||||
8482 | if (Call->getNumArgs() <= SizeArgNo) | ||||
8483 | return false; | ||||
8484 | |||||
8485 | auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { | ||||
8486 | Expr::EvalResult ExprResult; | ||||
8487 | if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) | ||||
8488 | return false; | ||||
8489 | Into = ExprResult.Val.getInt(); | ||||
8490 | if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) | ||||
8491 | return false; | ||||
8492 | Into = Into.zextOrSelf(BitsInSizeT); | ||||
8493 | return true; | ||||
8494 | }; | ||||
8495 | |||||
8496 | APSInt SizeOfElem; | ||||
8497 | if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) | ||||
8498 | return false; | ||||
8499 | |||||
8500 | if (!AllocSize->getNumElemsParam().isValid()) { | ||||
8501 | Result = std::move(SizeOfElem); | ||||
8502 | return true; | ||||
8503 | } | ||||
8504 | |||||
8505 | APSInt NumberOfElems; | ||||
8506 | unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); | ||||
8507 | if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) | ||||
8508 | return false; | ||||
8509 | |||||
8510 | bool Overflow; | ||||
8511 | llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); | ||||
8512 | if (Overflow) | ||||
8513 | return false; | ||||
8514 | |||||
8515 | Result = std::move(BytesAvailable); | ||||
8516 | return true; | ||||
8517 | } | ||||
8518 | |||||
8519 | /// Convenience function. LVal's base must be a call to an alloc_size | ||||
8520 | /// function. | ||||
8521 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, | ||||
8522 | const LValue &LVal, | ||||
8523 | llvm::APInt &Result) { | ||||
8524 | assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&(static_cast <bool> (isBaseAnAllocSizeCall(LVal.getLValueBase ()) && "Can't get the size of a non alloc_size function" ) ? void (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8525, __extension__ __PRETTY_FUNCTION__)) | ||||
8525 | "Can't get the size of a non alloc_size function")(static_cast <bool> (isBaseAnAllocSizeCall(LVal.getLValueBase ()) && "Can't get the size of a non alloc_size function" ) ? void (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8525, __extension__ __PRETTY_FUNCTION__)); | ||||
8526 | const auto *Base = LVal.getLValueBase().get<const Expr *>(); | ||||
8527 | const CallExpr *CE = tryUnwrapAllocSizeCall(Base); | ||||
8528 | return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); | ||||
8529 | } | ||||
8530 | |||||
8531 | /// Attempts to evaluate the given LValueBase as the result of a call to | ||||
8532 | /// a function with the alloc_size attribute. If it was possible to do so, this | ||||
8533 | /// function will return true, make Result's Base point to said function call, | ||||
8534 | /// and mark Result's Base as invalid. | ||||
8535 | static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, | ||||
8536 | LValue &Result) { | ||||
8537 | if (Base.isNull()) | ||||
8538 | return false; | ||||
8539 | |||||
8540 | // Because we do no form of static analysis, we only support const variables. | ||||
8541 | // | ||||
8542 | // Additionally, we can't support parameters, nor can we support static | ||||
8543 | // variables (in the latter case, use-before-assign isn't UB; in the former, | ||||
8544 | // we have no clue what they'll be assigned to). | ||||
8545 | const auto *VD = | ||||
8546 | dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); | ||||
8547 | if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) | ||||
8548 | return false; | ||||
8549 | |||||
8550 | const Expr *Init = VD->getAnyInitializer(); | ||||
8551 | if (!Init) | ||||
8552 | return false; | ||||
8553 | |||||
8554 | const Expr *E = Init->IgnoreParens(); | ||||
8555 | if (!tryUnwrapAllocSizeCall(E)) | ||||
8556 | return false; | ||||
8557 | |||||
8558 | // Store E instead of E unwrapped so that the type of the LValue's base is | ||||
8559 | // what the user wanted. | ||||
8560 | Result.setInvalid(E); | ||||
8561 | |||||
8562 | QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); | ||||
8563 | Result.addUnsizedArray(Info, E, Pointee); | ||||
8564 | return true; | ||||
8565 | } | ||||
8566 | |||||
8567 | namespace { | ||||
8568 | class PointerExprEvaluator | ||||
8569 | : public ExprEvaluatorBase<PointerExprEvaluator> { | ||||
8570 | LValue &Result; | ||||
8571 | bool InvalidBaseOK; | ||||
8572 | |||||
8573 | bool Success(const Expr *E) { | ||||
8574 | Result.set(E); | ||||
8575 | return true; | ||||
8576 | } | ||||
8577 | |||||
8578 | bool evaluateLValue(const Expr *E, LValue &Result) { | ||||
8579 | return EvaluateLValue(E, Result, Info, InvalidBaseOK); | ||||
8580 | } | ||||
8581 | |||||
8582 | bool evaluatePointer(const Expr *E, LValue &Result) { | ||||
8583 | return EvaluatePointer(E, Result, Info, InvalidBaseOK); | ||||
8584 | } | ||||
8585 | |||||
8586 | bool visitNonBuiltinCallExpr(const CallExpr *E); | ||||
8587 | public: | ||||
8588 | |||||
8589 | PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) | ||||
8590 | : ExprEvaluatorBaseTy(info), Result(Result), | ||||
8591 | InvalidBaseOK(InvalidBaseOK) {} | ||||
8592 | |||||
8593 | bool Success(const APValue &V, const Expr *E) { | ||||
8594 | Result.setFrom(Info.Ctx, V); | ||||
8595 | return true; | ||||
8596 | } | ||||
8597 | bool ZeroInitialization(const Expr *E) { | ||||
8598 | Result.setNull(Info.Ctx, E->getType()); | ||||
8599 | return true; | ||||
8600 | } | ||||
8601 | |||||
8602 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
8603 | bool VisitCastExpr(const CastExpr* E); | ||||
8604 | bool VisitUnaryAddrOf(const UnaryOperator *E); | ||||
8605 | bool VisitObjCStringLiteral(const ObjCStringLiteral *E) | ||||
8606 | { return Success(E); } | ||||
8607 | bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { | ||||
8608 | if (E->isExpressibleAsConstantInitializer()) | ||||
8609 | return Success(E); | ||||
8610 | if (Info.noteFailure()) | ||||
8611 | EvaluateIgnoredValue(Info, E->getSubExpr()); | ||||
8612 | return Error(E); | ||||
8613 | } | ||||
8614 | bool VisitAddrLabelExpr(const AddrLabelExpr *E) | ||||
8615 | { return Success(E); } | ||||
8616 | bool VisitCallExpr(const CallExpr *E); | ||||
8617 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); | ||||
8618 | bool VisitBlockExpr(const BlockExpr *E) { | ||||
8619 | if (!E->getBlockDecl()->hasCaptures()) | ||||
8620 | return Success(E); | ||||
8621 | return Error(E); | ||||
8622 | } | ||||
8623 | bool VisitCXXThisExpr(const CXXThisExpr *E) { | ||||
8624 | // Can't look at 'this' when checking a potential constant expression. | ||||
8625 | if (Info.checkingPotentialConstantExpression()) | ||||
8626 | return false; | ||||
8627 | if (!Info.CurrentCall->This) { | ||||
8628 | if (Info.getLangOpts().CPlusPlus11) | ||||
8629 | Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); | ||||
8630 | else | ||||
8631 | Info.FFDiag(E); | ||||
8632 | return false; | ||||
8633 | } | ||||
8634 | Result = *Info.CurrentCall->This; | ||||
8635 | // If we are inside a lambda's call operator, the 'this' expression refers | ||||
8636 | // to the enclosing '*this' object (either by value or reference) which is | ||||
8637 | // either copied into the closure object's field that represents the '*this' | ||||
8638 | // or refers to '*this'. | ||||
8639 | if (isLambdaCallOperator(Info.CurrentCall->Callee)) { | ||||
8640 | // Ensure we actually have captured 'this'. (an error will have | ||||
8641 | // been previously reported if not). | ||||
8642 | if (!Info.CurrentCall->LambdaThisCaptureField) | ||||
8643 | return false; | ||||
8644 | |||||
8645 | // Update 'Result' to refer to the data member/field of the closure object | ||||
8646 | // that represents the '*this' capture. | ||||
8647 | if (!HandleLValueMember(Info, E, Result, | ||||
8648 | Info.CurrentCall->LambdaThisCaptureField)) | ||||
8649 | return false; | ||||
8650 | // If we captured '*this' by reference, replace the field with its referent. | ||||
8651 | if (Info.CurrentCall->LambdaThisCaptureField->getType() | ||||
8652 | ->isPointerType()) { | ||||
8653 | APValue RVal; | ||||
8654 | if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, | ||||
8655 | RVal)) | ||||
8656 | return false; | ||||
8657 | |||||
8658 | Result.setFrom(Info.Ctx, RVal); | ||||
8659 | } | ||||
8660 | } | ||||
8661 | return true; | ||||
8662 | } | ||||
8663 | |||||
8664 | bool VisitCXXNewExpr(const CXXNewExpr *E); | ||||
8665 | |||||
8666 | bool VisitSourceLocExpr(const SourceLocExpr *E) { | ||||
8667 | assert(E->isStringType() && "SourceLocExpr isn't a pointer type?")(static_cast <bool> (E->isStringType() && "SourceLocExpr isn't a pointer type?" ) ? void (0) : __assert_fail ("E->isStringType() && \"SourceLocExpr isn't a pointer type?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8667, __extension__ __PRETTY_FUNCTION__)); | ||||
8668 | APValue LValResult = E->EvaluateInContext( | ||||
8669 | Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); | ||||
8670 | Result.setFrom(Info.Ctx, LValResult); | ||||
8671 | return true; | ||||
8672 | } | ||||
8673 | |||||
8674 | bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { | ||||
8675 | std::string ResultStr = E->ComputeName(Info.Ctx); | ||||
8676 | |||||
8677 | Info.Ctx.SYCLUniqueStableNameEvaluatedValues[E] = ResultStr; | ||||
8678 | |||||
8679 | QualType CharTy = Info.Ctx.CharTy.withConst(); | ||||
8680 | APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()), | ||||
8681 | ResultStr.size() + 1); | ||||
8682 | QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr, | ||||
8683 | ArrayType::Normal, 0); | ||||
8684 | |||||
8685 | StringLiteral *SL = | ||||
8686 | StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii, | ||||
8687 | /*Pascal*/ false, ArrayTy, E->getLocation()); | ||||
8688 | |||||
8689 | evaluateLValue(SL, Result); | ||||
8690 | Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy)); | ||||
8691 | return true; | ||||
8692 | } | ||||
8693 | |||||
8694 | // FIXME: Missing: @protocol, @selector | ||||
8695 | }; | ||||
8696 | } // end anonymous namespace | ||||
8697 | |||||
8698 | static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, | ||||
8699 | bool InvalidBaseOK) { | ||||
8700 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8700, __extension__ __PRETTY_FUNCTION__)); | ||||
8701 | assert(E->isPRValue() && E->getType()->hasPointerRepresentation())(static_cast <bool> (E->isPRValue() && E-> getType()->hasPointerRepresentation()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->hasPointerRepresentation()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8701, __extension__ __PRETTY_FUNCTION__)); | ||||
8702 | return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); | ||||
8703 | } | ||||
8704 | |||||
8705 | bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
8706 | if (E->getOpcode() != BO_Add && | ||||
8707 | E->getOpcode() != BO_Sub) | ||||
8708 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
8709 | |||||
8710 | const Expr *PExp = E->getLHS(); | ||||
8711 | const Expr *IExp = E->getRHS(); | ||||
8712 | if (IExp->getType()->isPointerType()) | ||||
8713 | std::swap(PExp, IExp); | ||||
8714 | |||||
8715 | bool EvalPtrOK = evaluatePointer(PExp, Result); | ||||
8716 | if (!EvalPtrOK && !Info.noteFailure()) | ||||
8717 | return false; | ||||
8718 | |||||
8719 | llvm::APSInt Offset; | ||||
8720 | if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) | ||||
8721 | return false; | ||||
8722 | |||||
8723 | if (E->getOpcode() == BO_Sub) | ||||
8724 | negateAsSigned(Offset); | ||||
8725 | |||||
8726 | QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); | ||||
8727 | return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); | ||||
8728 | } | ||||
8729 | |||||
8730 | bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { | ||||
8731 | return evaluateLValue(E->getSubExpr(), Result); | ||||
8732 | } | ||||
8733 | |||||
8734 | bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
8735 | const Expr *SubExpr = E->getSubExpr(); | ||||
8736 | |||||
8737 | switch (E->getCastKind()) { | ||||
8738 | default: | ||||
8739 | break; | ||||
8740 | case CK_BitCast: | ||||
8741 | case CK_CPointerToObjCPointerCast: | ||||
8742 | case CK_BlockPointerToObjCPointerCast: | ||||
8743 | case CK_AnyPointerToBlockPointerCast: | ||||
8744 | case CK_AddressSpaceConversion: | ||||
8745 | if (!Visit(SubExpr)) | ||||
8746 | return false; | ||||
8747 | // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are | ||||
8748 | // permitted in constant expressions in C++11. Bitcasts from cv void* are | ||||
8749 | // also static_casts, but we disallow them as a resolution to DR1312. | ||||
8750 | if (!E->getType()->isVoidPointerType()) { | ||||
8751 | if (!Result.InvalidBase && !Result.Designator.Invalid && | ||||
8752 | !Result.IsNullPtr && | ||||
8753 | Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), | ||||
8754 | E->getType()->getPointeeType()) && | ||||
8755 | Info.getStdAllocatorCaller("allocate")) { | ||||
8756 | // Inside a call to std::allocator::allocate and friends, we permit | ||||
8757 | // casting from void* back to cv1 T* for a pointer that points to a | ||||
8758 | // cv2 T. | ||||
8759 | } else { | ||||
8760 | Result.Designator.setInvalid(); | ||||
8761 | if (SubExpr->getType()->isVoidPointerType()) | ||||
8762 | CCEDiag(E, diag::note_constexpr_invalid_cast) | ||||
8763 | << 3 << SubExpr->getType(); | ||||
8764 | else | ||||
8765 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||
8766 | } | ||||
8767 | } | ||||
8768 | if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) | ||||
8769 | ZeroInitialization(E); | ||||
8770 | return true; | ||||
8771 | |||||
8772 | case CK_DerivedToBase: | ||||
8773 | case CK_UncheckedDerivedToBase: | ||||
8774 | if (!evaluatePointer(E->getSubExpr(), Result)) | ||||
8775 | return false; | ||||
8776 | if (!Result.Base && Result.Offset.isZero()) | ||||
8777 | return true; | ||||
8778 | |||||
8779 | // Now figure out the necessary offset to add to the base LV to get from | ||||
8780 | // the derived class to the base class. | ||||
8781 | return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> | ||||
8782 | castAs<PointerType>()->getPointeeType(), | ||||
8783 | Result); | ||||
8784 | |||||
8785 | case CK_BaseToDerived: | ||||
8786 | if (!Visit(E->getSubExpr())) | ||||
8787 | return false; | ||||
8788 | if (!Result.Base && Result.Offset.isZero()) | ||||
8789 | return true; | ||||
8790 | return HandleBaseToDerivedCast(Info, E, Result); | ||||
8791 | |||||
8792 | case CK_Dynamic: | ||||
8793 | if (!Visit(E->getSubExpr())) | ||||
8794 | return false; | ||||
8795 | return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); | ||||
8796 | |||||
8797 | case CK_NullToPointer: | ||||
8798 | VisitIgnoredValue(E->getSubExpr()); | ||||
8799 | return ZeroInitialization(E); | ||||
8800 | |||||
8801 | case CK_IntegralToPointer: { | ||||
8802 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||
8803 | |||||
8804 | APValue Value; | ||||
8805 | if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) | ||||
8806 | break; | ||||
8807 | |||||
8808 | if (Value.isInt()) { | ||||
8809 | unsigned Size = Info.Ctx.getTypeSize(E->getType()); | ||||
8810 | uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); | ||||
8811 | Result.Base = (Expr*)nullptr; | ||||
8812 | Result.InvalidBase = false; | ||||
8813 | Result.Offset = CharUnits::fromQuantity(N); | ||||
8814 | Result.Designator.setInvalid(); | ||||
8815 | Result.IsNullPtr = false; | ||||
8816 | return true; | ||||
8817 | } else { | ||||
8818 | // Cast is of an lvalue, no need to change value. | ||||
8819 | Result.setFrom(Info.Ctx, Value); | ||||
8820 | return true; | ||||
8821 | } | ||||
8822 | } | ||||
8823 | |||||
8824 | case CK_ArrayToPointerDecay: { | ||||
8825 | if (SubExpr->isGLValue()) { | ||||
8826 | if (!evaluateLValue(SubExpr, Result)) | ||||
8827 | return false; | ||||
8828 | } else { | ||||
8829 | APValue &Value = Info.CurrentCall->createTemporary( | ||||
8830 | SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); | ||||
8831 | if (!EvaluateInPlace(Value, Info, Result, SubExpr)) | ||||
8832 | return false; | ||||
8833 | } | ||||
8834 | // The result is a pointer to the first element of the array. | ||||
8835 | auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); | ||||
8836 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) | ||||
8837 | Result.addArray(Info, E, CAT); | ||||
8838 | else | ||||
8839 | Result.addUnsizedArray(Info, E, AT->getElementType()); | ||||
8840 | return true; | ||||
8841 | } | ||||
8842 | |||||
8843 | case CK_FunctionToPointerDecay: | ||||
8844 | return evaluateLValue(SubExpr, Result); | ||||
8845 | |||||
8846 | case CK_LValueToRValue: { | ||||
8847 | LValue LVal; | ||||
8848 | if (!evaluateLValue(E->getSubExpr(), LVal)) | ||||
8849 | return false; | ||||
8850 | |||||
8851 | APValue RVal; | ||||
8852 | // Note, we use the subexpression's type in order to retain cv-qualifiers. | ||||
8853 | if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), | ||||
8854 | LVal, RVal)) | ||||
8855 | return InvalidBaseOK && | ||||
8856 | evaluateLValueAsAllocSize(Info, LVal.Base, Result); | ||||
8857 | return Success(RVal, E); | ||||
8858 | } | ||||
8859 | } | ||||
8860 | |||||
8861 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
8862 | } | ||||
8863 | |||||
8864 | static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, | ||||
8865 | UnaryExprOrTypeTrait ExprKind) { | ||||
8866 | // C++ [expr.alignof]p3: | ||||
8867 | // When alignof is applied to a reference type, the result is the | ||||
8868 | // alignment of the referenced type. | ||||
8869 | if (const ReferenceType *Ref = T->getAs<ReferenceType>()) | ||||
8870 | T = Ref->getPointeeType(); | ||||
8871 | |||||
8872 | if (T.getQualifiers().hasUnaligned()) | ||||
8873 | return CharUnits::One(); | ||||
8874 | |||||
8875 | const bool AlignOfReturnsPreferred = | ||||
8876 | Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; | ||||
8877 | |||||
8878 | // __alignof is defined to return the preferred alignment. | ||||
8879 | // Before 8, clang returned the preferred alignment for alignof and _Alignof | ||||
8880 | // as well. | ||||
8881 | if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) | ||||
8882 | return Info.Ctx.toCharUnitsFromBits( | ||||
8883 | Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); | ||||
8884 | // alignof and _Alignof are defined to return the ABI alignment. | ||||
8885 | else if (ExprKind == UETT_AlignOf) | ||||
8886 | return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); | ||||
8887 | else | ||||
8888 | llvm_unreachable("GetAlignOfType on a non-alignment ExprKind")::llvm::llvm_unreachable_internal("GetAlignOfType on a non-alignment ExprKind" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8888); | ||||
8889 | } | ||||
8890 | |||||
8891 | static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, | ||||
8892 | UnaryExprOrTypeTrait ExprKind) { | ||||
8893 | E = E->IgnoreParens(); | ||||
8894 | |||||
8895 | // The kinds of expressions that we have special-case logic here for | ||||
8896 | // should be kept up to date with the special checks for those | ||||
8897 | // expressions in Sema. | ||||
8898 | |||||
8899 | // alignof decl is always accepted, even if it doesn't make sense: we default | ||||
8900 | // to 1 in those cases. | ||||
8901 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
8902 | return Info.Ctx.getDeclAlign(DRE->getDecl(), | ||||
8903 | /*RefAsPointee*/true); | ||||
8904 | |||||
8905 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||
8906 | return Info.Ctx.getDeclAlign(ME->getMemberDecl(), | ||||
8907 | /*RefAsPointee*/true); | ||||
8908 | |||||
8909 | return GetAlignOfType(Info, E->getType(), ExprKind); | ||||
8910 | } | ||||
8911 | |||||
8912 | static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { | ||||
8913 | if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) | ||||
8914 | return Info.Ctx.getDeclAlign(VD); | ||||
8915 | if (const auto *E = Value.Base.dyn_cast<const Expr *>()) | ||||
8916 | return GetAlignOfExpr(Info, E, UETT_AlignOf); | ||||
8917 | return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); | ||||
8918 | } | ||||
8919 | |||||
8920 | /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, | ||||
8921 | /// __builtin_is_aligned and __builtin_assume_aligned. | ||||
8922 | static bool getAlignmentArgument(const Expr *E, QualType ForType, | ||||
8923 | EvalInfo &Info, APSInt &Alignment) { | ||||
8924 | if (!EvaluateInteger(E, Alignment, Info)) | ||||
8925 | return false; | ||||
8926 | if (Alignment < 0 || !Alignment.isPowerOf2()) { | ||||
8927 | Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; | ||||
8928 | return false; | ||||
8929 | } | ||||
8930 | unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); | ||||
8931 | APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); | ||||
8932 | if (APSInt::compareValues(Alignment, MaxValue) > 0) { | ||||
8933 | Info.FFDiag(E, diag::note_constexpr_alignment_too_big) | ||||
8934 | << MaxValue << ForType << Alignment; | ||||
8935 | return false; | ||||
8936 | } | ||||
8937 | // Ensure both alignment and source value have the same bit width so that we | ||||
8938 | // don't assert when computing the resulting value. | ||||
8939 | APSInt ExtAlignment = | ||||
8940 | APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); | ||||
8941 | assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&(static_cast <bool> (APSInt::compareValues(Alignment, ExtAlignment ) == 0 && "Alignment should not be changed by ext/trunc" ) ? void (0) : __assert_fail ("APSInt::compareValues(Alignment, ExtAlignment) == 0 && \"Alignment should not be changed by ext/trunc\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8942, __extension__ __PRETTY_FUNCTION__)) | ||||
8942 | "Alignment should not be changed by ext/trunc")(static_cast <bool> (APSInt::compareValues(Alignment, ExtAlignment ) == 0 && "Alignment should not be changed by ext/trunc" ) ? void (0) : __assert_fail ("APSInt::compareValues(Alignment, ExtAlignment) == 0 && \"Alignment should not be changed by ext/trunc\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8942, __extension__ __PRETTY_FUNCTION__)); | ||||
8943 | Alignment = ExtAlignment; | ||||
8944 | assert(Alignment.getBitWidth() == SrcWidth)(static_cast <bool> (Alignment.getBitWidth() == SrcWidth ) ? void (0) : __assert_fail ("Alignment.getBitWidth() == SrcWidth" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 8944, __extension__ __PRETTY_FUNCTION__)); | ||||
8945 | return true; | ||||
8946 | } | ||||
8947 | |||||
8948 | // To be clear: this happily visits unsupported builtins. Better name welcomed. | ||||
8949 | bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { | ||||
8950 | if (ExprEvaluatorBaseTy::VisitCallExpr(E)) | ||||
8951 | return true; | ||||
8952 | |||||
8953 | if (!(InvalidBaseOK && getAllocSizeAttr(E))) | ||||
8954 | return false; | ||||
8955 | |||||
8956 | Result.setInvalid(E); | ||||
8957 | QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); | ||||
8958 | Result.addUnsizedArray(Info, E, PointeeTy); | ||||
8959 | return true; | ||||
8960 | } | ||||
8961 | |||||
8962 | bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||
8963 | if (IsStringLiteralCall(E)) | ||||
8964 | return Success(E); | ||||
8965 | |||||
8966 | if (unsigned BuiltinOp = E->getBuiltinCallee()) | ||||
8967 | return VisitBuiltinCallExpr(E, BuiltinOp); | ||||
8968 | |||||
8969 | return visitNonBuiltinCallExpr(E); | ||||
8970 | } | ||||
8971 | |||||
8972 | // Determine if T is a character type for which we guarantee that | ||||
8973 | // sizeof(T) == 1. | ||||
8974 | static bool isOneByteCharacterType(QualType T) { | ||||
8975 | return T->isCharType() || T->isChar8Type(); | ||||
8976 | } | ||||
8977 | |||||
8978 | bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, | ||||
8979 | unsigned BuiltinOp) { | ||||
8980 | switch (BuiltinOp) { | ||||
8981 | case Builtin::BI__builtin_addressof: | ||||
8982 | return evaluateLValue(E->getArg(0), Result); | ||||
8983 | case Builtin::BI__builtin_assume_aligned: { | ||||
8984 | // We need to be very careful here because: if the pointer does not have the | ||||
8985 | // asserted alignment, then the behavior is undefined, and undefined | ||||
8986 | // behavior is non-constant. | ||||
8987 | if (!evaluatePointer(E->getArg(0), Result)) | ||||
8988 | return false; | ||||
8989 | |||||
8990 | LValue OffsetResult(Result); | ||||
8991 | APSInt Alignment; | ||||
8992 | if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, | ||||
8993 | Alignment)) | ||||
8994 | return false; | ||||
8995 | CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); | ||||
8996 | |||||
8997 | if (E->getNumArgs() > 2) { | ||||
8998 | APSInt Offset; | ||||
8999 | if (!EvaluateInteger(E->getArg(2), Offset, Info)) | ||||
9000 | return false; | ||||
9001 | |||||
9002 | int64_t AdditionalOffset = -Offset.getZExtValue(); | ||||
9003 | OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); | ||||
9004 | } | ||||
9005 | |||||
9006 | // If there is a base object, then it must have the correct alignment. | ||||
9007 | if (OffsetResult.Base) { | ||||
9008 | CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); | ||||
9009 | |||||
9010 | if (BaseAlignment < Align) { | ||||
9011 | Result.Designator.setInvalid(); | ||||
9012 | // FIXME: Add support to Diagnostic for long / long long. | ||||
9013 | CCEDiag(E->getArg(0), | ||||
9014 | diag::note_constexpr_baa_insufficient_alignment) << 0 | ||||
9015 | << (unsigned)BaseAlignment.getQuantity() | ||||
9016 | << (unsigned)Align.getQuantity(); | ||||
9017 | return false; | ||||
9018 | } | ||||
9019 | } | ||||
9020 | |||||
9021 | // The offset must also have the correct alignment. | ||||
9022 | if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { | ||||
9023 | Result.Designator.setInvalid(); | ||||
9024 | |||||
9025 | (OffsetResult.Base | ||||
9026 | ? CCEDiag(E->getArg(0), | ||||
9027 | diag::note_constexpr_baa_insufficient_alignment) << 1 | ||||
9028 | : CCEDiag(E->getArg(0), | ||||
9029 | diag::note_constexpr_baa_value_insufficient_alignment)) | ||||
9030 | << (int)OffsetResult.Offset.getQuantity() | ||||
9031 | << (unsigned)Align.getQuantity(); | ||||
9032 | return false; | ||||
9033 | } | ||||
9034 | |||||
9035 | return true; | ||||
9036 | } | ||||
9037 | case Builtin::BI__builtin_align_up: | ||||
9038 | case Builtin::BI__builtin_align_down: { | ||||
9039 | if (!evaluatePointer(E->getArg(0), Result)) | ||||
9040 | return false; | ||||
9041 | APSInt Alignment; | ||||
9042 | if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, | ||||
9043 | Alignment)) | ||||
9044 | return false; | ||||
9045 | CharUnits BaseAlignment = getBaseAlignment(Info, Result); | ||||
9046 | CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); | ||||
9047 | // For align_up/align_down, we can return the same value if the alignment | ||||
9048 | // is known to be greater or equal to the requested value. | ||||
9049 | if (PtrAlign.getQuantity() >= Alignment) | ||||
9050 | return true; | ||||
9051 | |||||
9052 | // The alignment could be greater than the minimum at run-time, so we cannot | ||||
9053 | // infer much about the resulting pointer value. One case is possible: | ||||
9054 | // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we | ||||
9055 | // can infer the correct index if the requested alignment is smaller than | ||||
9056 | // the base alignment so we can perform the computation on the offset. | ||||
9057 | if (BaseAlignment.getQuantity() >= Alignment) { | ||||
9058 | assert(Alignment.getBitWidth() <= 64 &&(static_cast <bool> (Alignment.getBitWidth() <= 64 && "Cannot handle > 64-bit address-space") ? void (0) : __assert_fail ("Alignment.getBitWidth() <= 64 && \"Cannot handle > 64-bit address-space\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9059, __extension__ __PRETTY_FUNCTION__)) | ||||
9059 | "Cannot handle > 64-bit address-space")(static_cast <bool> (Alignment.getBitWidth() <= 64 && "Cannot handle > 64-bit address-space") ? void (0) : __assert_fail ("Alignment.getBitWidth() <= 64 && \"Cannot handle > 64-bit address-space\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9059, __extension__ __PRETTY_FUNCTION__)); | ||||
9060 | uint64_t Alignment64 = Alignment.getZExtValue(); | ||||
9061 | CharUnits NewOffset = CharUnits::fromQuantity( | ||||
9062 | BuiltinOp == Builtin::BI__builtin_align_down | ||||
9063 | ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) | ||||
9064 | : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); | ||||
9065 | Result.adjustOffset(NewOffset - Result.Offset); | ||||
9066 | // TODO: diagnose out-of-bounds values/only allow for arrays? | ||||
9067 | return true; | ||||
9068 | } | ||||
9069 | // Otherwise, we cannot constant-evaluate the result. | ||||
9070 | Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) | ||||
9071 | << Alignment; | ||||
9072 | return false; | ||||
9073 | } | ||||
9074 | case Builtin::BI__builtin_operator_new: | ||||
9075 | return HandleOperatorNewCall(Info, E, Result); | ||||
9076 | case Builtin::BI__builtin_launder: | ||||
9077 | return evaluatePointer(E->getArg(0), Result); | ||||
9078 | case Builtin::BIstrchr: | ||||
9079 | case Builtin::BIwcschr: | ||||
9080 | case Builtin::BImemchr: | ||||
9081 | case Builtin::BIwmemchr: | ||||
9082 | if (Info.getLangOpts().CPlusPlus11) | ||||
9083 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||
9084 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||
9085 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||
9086 | else | ||||
9087 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
9088 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
9089 | case Builtin::BI__builtin_strchr: | ||||
9090 | case Builtin::BI__builtin_wcschr: | ||||
9091 | case Builtin::BI__builtin_memchr: | ||||
9092 | case Builtin::BI__builtin_char_memchr: | ||||
9093 | case Builtin::BI__builtin_wmemchr: { | ||||
9094 | if (!Visit(E->getArg(0))) | ||||
9095 | return false; | ||||
9096 | APSInt Desired; | ||||
9097 | if (!EvaluateInteger(E->getArg(1), Desired, Info)) | ||||
9098 | return false; | ||||
9099 | uint64_t MaxLength = uint64_t(-1); | ||||
9100 | if (BuiltinOp != Builtin::BIstrchr && | ||||
9101 | BuiltinOp != Builtin::BIwcschr && | ||||
9102 | BuiltinOp != Builtin::BI__builtin_strchr && | ||||
9103 | BuiltinOp != Builtin::BI__builtin_wcschr) { | ||||
9104 | APSInt N; | ||||
9105 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||
9106 | return false; | ||||
9107 | MaxLength = N.getExtValue(); | ||||
9108 | } | ||||
9109 | // We cannot find the value if there are no candidates to match against. | ||||
9110 | if (MaxLength == 0u) | ||||
9111 | return ZeroInitialization(E); | ||||
9112 | if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||
9113 | Result.Designator.Invalid) | ||||
9114 | return false; | ||||
9115 | QualType CharTy = Result.Designator.getType(Info.Ctx); | ||||
9116 | bool IsRawByte = BuiltinOp == Builtin::BImemchr || | ||||
9117 | BuiltinOp == Builtin::BI__builtin_memchr; | ||||
9118 | assert(IsRawByte ||(static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType ( CharTy, E->getArg(0)->getType()->getPointeeType()) ) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9120, __extension__ __PRETTY_FUNCTION__)) | ||||
9119 | Info.Ctx.hasSameUnqualifiedType((static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType ( CharTy, E->getArg(0)->getType()->getPointeeType()) ) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9120, __extension__ __PRETTY_FUNCTION__)) | ||||
9120 | CharTy, E->getArg(0)->getType()->getPointeeType()))(static_cast <bool> (IsRawByte || Info.Ctx.hasSameUnqualifiedType ( CharTy, E->getArg(0)->getType()->getPointeeType()) ) ? void (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9120, __extension__ __PRETTY_FUNCTION__)); | ||||
9121 | // Pointers to const void may point to objects of incomplete type. | ||||
9122 | if (IsRawByte && CharTy->isIncompleteType()) { | ||||
9123 | Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; | ||||
9124 | return false; | ||||
9125 | } | ||||
9126 | // Give up on byte-oriented matching against multibyte elements. | ||||
9127 | // FIXME: We can compare the bytes in the correct order. | ||||
9128 | if (IsRawByte && !isOneByteCharacterType(CharTy)) { | ||||
9129 | Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) | ||||
9130 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") | ||||
9131 | << CharTy; | ||||
9132 | return false; | ||||
9133 | } | ||||
9134 | // Figure out what value we're actually looking for (after converting to | ||||
9135 | // the corresponding unsigned type if necessary). | ||||
9136 | uint64_t DesiredVal; | ||||
9137 | bool StopAtNull = false; | ||||
9138 | switch (BuiltinOp) { | ||||
9139 | case Builtin::BIstrchr: | ||||
9140 | case Builtin::BI__builtin_strchr: | ||||
9141 | // strchr compares directly to the passed integer, and therefore | ||||
9142 | // always fails if given an int that is not a char. | ||||
9143 | if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, | ||||
9144 | E->getArg(1)->getType(), | ||||
9145 | Desired), | ||||
9146 | Desired)) | ||||
9147 | return ZeroInitialization(E); | ||||
9148 | StopAtNull = true; | ||||
9149 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
9150 | case Builtin::BImemchr: | ||||
9151 | case Builtin::BI__builtin_memchr: | ||||
9152 | case Builtin::BI__builtin_char_memchr: | ||||
9153 | // memchr compares by converting both sides to unsigned char. That's also | ||||
9154 | // correct for strchr if we get this far (to cope with plain char being | ||||
9155 | // unsigned in the strchr case). | ||||
9156 | DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); | ||||
9157 | break; | ||||
9158 | |||||
9159 | case Builtin::BIwcschr: | ||||
9160 | case Builtin::BI__builtin_wcschr: | ||||
9161 | StopAtNull = true; | ||||
9162 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
9163 | case Builtin::BIwmemchr: | ||||
9164 | case Builtin::BI__builtin_wmemchr: | ||||
9165 | // wcschr and wmemchr are given a wchar_t to look for. Just use it. | ||||
9166 | DesiredVal = Desired.getZExtValue(); | ||||
9167 | break; | ||||
9168 | } | ||||
9169 | |||||
9170 | for (; MaxLength; --MaxLength) { | ||||
9171 | APValue Char; | ||||
9172 | if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || | ||||
9173 | !Char.isInt()) | ||||
9174 | return false; | ||||
9175 | if (Char.getInt().getZExtValue() == DesiredVal) | ||||
9176 | return true; | ||||
9177 | if (StopAtNull && !Char.getInt()) | ||||
9178 | break; | ||||
9179 | if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) | ||||
9180 | return false; | ||||
9181 | } | ||||
9182 | // Not found: return nullptr. | ||||
9183 | return ZeroInitialization(E); | ||||
9184 | } | ||||
9185 | |||||
9186 | case Builtin::BImemcpy: | ||||
9187 | case Builtin::BImemmove: | ||||
9188 | case Builtin::BIwmemcpy: | ||||
9189 | case Builtin::BIwmemmove: | ||||
9190 | if (Info.getLangOpts().CPlusPlus11) | ||||
9191 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||
9192 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||
9193 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||
9194 | else | ||||
9195 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
9196 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
9197 | case Builtin::BI__builtin_memcpy: | ||||
9198 | case Builtin::BI__builtin_memmove: | ||||
9199 | case Builtin::BI__builtin_wmemcpy: | ||||
9200 | case Builtin::BI__builtin_wmemmove: { | ||||
9201 | bool WChar = BuiltinOp == Builtin::BIwmemcpy || | ||||
9202 | BuiltinOp == Builtin::BIwmemmove || | ||||
9203 | BuiltinOp == Builtin::BI__builtin_wmemcpy || | ||||
9204 | BuiltinOp == Builtin::BI__builtin_wmemmove; | ||||
9205 | bool Move = BuiltinOp == Builtin::BImemmove || | ||||
9206 | BuiltinOp == Builtin::BIwmemmove || | ||||
9207 | BuiltinOp == Builtin::BI__builtin_memmove || | ||||
9208 | BuiltinOp == Builtin::BI__builtin_wmemmove; | ||||
9209 | |||||
9210 | // The result of mem* is the first argument. | ||||
9211 | if (!Visit(E->getArg(0))) | ||||
9212 | return false; | ||||
9213 | LValue Dest = Result; | ||||
9214 | |||||
9215 | LValue Src; | ||||
9216 | if (!EvaluatePointer(E->getArg(1), Src, Info)) | ||||
9217 | return false; | ||||
9218 | |||||
9219 | APSInt N; | ||||
9220 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||
9221 | return false; | ||||
9222 | assert(!N.isSigned() && "memcpy and friends take an unsigned size")(static_cast <bool> (!N.isSigned() && "memcpy and friends take an unsigned size" ) ? void (0) : __assert_fail ("!N.isSigned() && \"memcpy and friends take an unsigned size\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9222, __extension__ __PRETTY_FUNCTION__)); | ||||
9223 | |||||
9224 | // If the size is zero, we treat this as always being a valid no-op. | ||||
9225 | // (Even if one of the src and dest pointers is null.) | ||||
9226 | if (!N) | ||||
9227 | return true; | ||||
9228 | |||||
9229 | // Otherwise, if either of the operands is null, we can't proceed. Don't | ||||
9230 | // try to determine the type of the copied objects, because there aren't | ||||
9231 | // any. | ||||
9232 | if (!Src.Base || !Dest.Base) { | ||||
9233 | APValue Val; | ||||
9234 | (!Src.Base ? Src : Dest).moveInto(Val); | ||||
9235 | Info.FFDiag(E, diag::note_constexpr_memcpy_null) | ||||
9236 | << Move << WChar << !!Src.Base | ||||
9237 | << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); | ||||
9238 | return false; | ||||
9239 | } | ||||
9240 | if (Src.Designator.Invalid || Dest.Designator.Invalid) | ||||
9241 | return false; | ||||
9242 | |||||
9243 | // We require that Src and Dest are both pointers to arrays of | ||||
9244 | // trivially-copyable type. (For the wide version, the designator will be | ||||
9245 | // invalid if the designated object is not a wchar_t.) | ||||
9246 | QualType T = Dest.Designator.getType(Info.Ctx); | ||||
9247 | QualType SrcT = Src.Designator.getType(Info.Ctx); | ||||
9248 | if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { | ||||
9249 | // FIXME: Consider using our bit_cast implementation to support this. | ||||
9250 | Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; | ||||
9251 | return false; | ||||
9252 | } | ||||
9253 | if (T->isIncompleteType()) { | ||||
9254 | Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; | ||||
9255 | return false; | ||||
9256 | } | ||||
9257 | if (!T.isTriviallyCopyableType(Info.Ctx)) { | ||||
9258 | Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; | ||||
9259 | return false; | ||||
9260 | } | ||||
9261 | |||||
9262 | // Figure out how many T's we're copying. | ||||
9263 | uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); | ||||
9264 | if (!WChar) { | ||||
9265 | uint64_t Remainder; | ||||
9266 | llvm::APInt OrigN = N; | ||||
9267 | llvm::APInt::udivrem(OrigN, TSize, N, Remainder); | ||||
9268 | if (Remainder) { | ||||
9269 | Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) | ||||
9270 | << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) | ||||
9271 | << (unsigned)TSize; | ||||
9272 | return false; | ||||
9273 | } | ||||
9274 | } | ||||
9275 | |||||
9276 | // Check that the copying will remain within the arrays, just so that we | ||||
9277 | // can give a more meaningful diagnostic. This implicitly also checks that | ||||
9278 | // N fits into 64 bits. | ||||
9279 | uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; | ||||
9280 | uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; | ||||
9281 | if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { | ||||
9282 | Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) | ||||
9283 | << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T | ||||
9284 | << toString(N, 10, /*Signed*/false); | ||||
9285 | return false; | ||||
9286 | } | ||||
9287 | uint64_t NElems = N.getZExtValue(); | ||||
9288 | uint64_t NBytes = NElems * TSize; | ||||
9289 | |||||
9290 | // Check for overlap. | ||||
9291 | int Direction = 1; | ||||
9292 | if (HasSameBase(Src, Dest)) { | ||||
9293 | uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); | ||||
9294 | uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); | ||||
9295 | if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { | ||||
9296 | // Dest is inside the source region. | ||||
9297 | if (!Move) { | ||||
9298 | Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; | ||||
9299 | return false; | ||||
9300 | } | ||||
9301 | // For memmove and friends, copy backwards. | ||||
9302 | if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || | ||||
9303 | !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) | ||||
9304 | return false; | ||||
9305 | Direction = -1; | ||||
9306 | } else if (!Move && SrcOffset >= DestOffset && | ||||
9307 | SrcOffset - DestOffset < NBytes) { | ||||
9308 | // Src is inside the destination region for memcpy: invalid. | ||||
9309 | Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; | ||||
9310 | return false; | ||||
9311 | } | ||||
9312 | } | ||||
9313 | |||||
9314 | while (true) { | ||||
9315 | APValue Val; | ||||
9316 | // FIXME: Set WantObjectRepresentation to true if we're copying a | ||||
9317 | // char-like type? | ||||
9318 | if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || | ||||
9319 | !handleAssignment(Info, E, Dest, T, Val)) | ||||
9320 | return false; | ||||
9321 | // Do not iterate past the last element; if we're copying backwards, that | ||||
9322 | // might take us off the start of the array. | ||||
9323 | if (--NElems == 0) | ||||
9324 | return true; | ||||
9325 | if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || | ||||
9326 | !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) | ||||
9327 | return false; | ||||
9328 | } | ||||
9329 | } | ||||
9330 | |||||
9331 | default: | ||||
9332 | break; | ||||
9333 | } | ||||
9334 | |||||
9335 | return visitNonBuiltinCallExpr(E); | ||||
9336 | } | ||||
9337 | |||||
9338 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, | ||||
9339 | APValue &Result, const InitListExpr *ILE, | ||||
9340 | QualType AllocType); | ||||
9341 | static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, | ||||
9342 | APValue &Result, | ||||
9343 | const CXXConstructExpr *CCE, | ||||
9344 | QualType AllocType); | ||||
9345 | |||||
9346 | bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { | ||||
9347 | if (!Info.getLangOpts().CPlusPlus20) | ||||
9348 | Info.CCEDiag(E, diag::note_constexpr_new); | ||||
9349 | |||||
9350 | // We cannot speculatively evaluate a delete expression. | ||||
9351 | if (Info.SpeculativeEvaluationDepth) | ||||
9352 | return false; | ||||
9353 | |||||
9354 | FunctionDecl *OperatorNew = E->getOperatorNew(); | ||||
9355 | |||||
9356 | bool IsNothrow = false; | ||||
9357 | bool IsPlacement = false; | ||||
9358 | if (OperatorNew->isReservedGlobalPlacementOperator() && | ||||
9359 | Info.CurrentCall->isStdFunction() && !E->isArray()) { | ||||
9360 | // FIXME Support array placement new. | ||||
9361 | assert(E->getNumPlacementArgs() == 1)(static_cast <bool> (E->getNumPlacementArgs() == 1) ? void (0) : __assert_fail ("E->getNumPlacementArgs() == 1" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9361, __extension__ __PRETTY_FUNCTION__)); | ||||
9362 | if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) | ||||
9363 | return false; | ||||
9364 | if (Result.Designator.Invalid) | ||||
9365 | return false; | ||||
9366 | IsPlacement = true; | ||||
9367 | } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { | ||||
9368 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | ||||
9369 | << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; | ||||
9370 | return false; | ||||
9371 | } else if (E->getNumPlacementArgs()) { | ||||
9372 | // The only new-placement list we support is of the form (std::nothrow). | ||||
9373 | // | ||||
9374 | // FIXME: There is no restriction on this, but it's not clear that any | ||||
9375 | // other form makes any sense. We get here for cases such as: | ||||
9376 | // | ||||
9377 | // new (std::align_val_t{N}) X(int) | ||||
9378 | // | ||||
9379 | // (which should presumably be valid only if N is a multiple of | ||||
9380 | // alignof(int), and in any case can't be deallocated unless N is | ||||
9381 | // alignof(X) and X has new-extended alignment). | ||||
9382 | if (E->getNumPlacementArgs() != 1 || | ||||
9383 | !E->getPlacementArg(0)->getType()->isNothrowT()) | ||||
9384 | return Error(E, diag::note_constexpr_new_placement); | ||||
9385 | |||||
9386 | LValue Nothrow; | ||||
9387 | if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) | ||||
9388 | return false; | ||||
9389 | IsNothrow = true; | ||||
9390 | } | ||||
9391 | |||||
9392 | const Expr *Init = E->getInitializer(); | ||||
9393 | const InitListExpr *ResizedArrayILE = nullptr; | ||||
9394 | const CXXConstructExpr *ResizedArrayCCE = nullptr; | ||||
9395 | bool ValueInit = false; | ||||
9396 | |||||
9397 | QualType AllocType = E->getAllocatedType(); | ||||
9398 | if (Optional<const Expr*> ArraySize = E->getArraySize()) { | ||||
9399 | const Expr *Stripped = *ArraySize; | ||||
9400 | for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); | ||||
9401 | Stripped = ICE->getSubExpr()) | ||||
9402 | if (ICE->getCastKind() != CK_NoOp && | ||||
9403 | ICE->getCastKind() != CK_IntegralCast) | ||||
9404 | break; | ||||
9405 | |||||
9406 | llvm::APSInt ArrayBound; | ||||
9407 | if (!EvaluateInteger(Stripped, ArrayBound, Info)) | ||||
9408 | return false; | ||||
9409 | |||||
9410 | // C++ [expr.new]p9: | ||||
9411 | // The expression is erroneous if: | ||||
9412 | // -- [...] its value before converting to size_t [or] applying the | ||||
9413 | // second standard conversion sequence is less than zero | ||||
9414 | if (ArrayBound.isSigned() && ArrayBound.isNegative()) { | ||||
9415 | if (IsNothrow) | ||||
9416 | return ZeroInitialization(E); | ||||
9417 | |||||
9418 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) | ||||
9419 | << ArrayBound << (*ArraySize)->getSourceRange(); | ||||
9420 | return false; | ||||
9421 | } | ||||
9422 | |||||
9423 | // -- its value is such that the size of the allocated object would | ||||
9424 | // exceed the implementation-defined limit | ||||
9425 | if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, | ||||
9426 | ArrayBound) > | ||||
9427 | ConstantArrayType::getMaxSizeBits(Info.Ctx)) { | ||||
9428 | if (IsNothrow) | ||||
9429 | return ZeroInitialization(E); | ||||
9430 | |||||
9431 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) | ||||
9432 | << ArrayBound << (*ArraySize)->getSourceRange(); | ||||
9433 | return false; | ||||
9434 | } | ||||
9435 | |||||
9436 | // -- the new-initializer is a braced-init-list and the number of | ||||
9437 | // array elements for which initializers are provided [...] | ||||
9438 | // exceeds the number of elements to initialize | ||||
9439 | if (!Init) { | ||||
9440 | // No initialization is performed. | ||||
9441 | } else if (isa<CXXScalarValueInitExpr>(Init) || | ||||
9442 | isa<ImplicitValueInitExpr>(Init)) { | ||||
9443 | ValueInit = true; | ||||
9444 | } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { | ||||
9445 | ResizedArrayCCE = CCE; | ||||
9446 | } else { | ||||
9447 | auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); | ||||
9448 | assert(CAT && "unexpected type for array initializer")(static_cast <bool> (CAT && "unexpected type for array initializer" ) ? void (0) : __assert_fail ("CAT && \"unexpected type for array initializer\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9448, __extension__ __PRETTY_FUNCTION__)); | ||||
9449 | |||||
9450 | unsigned Bits = | ||||
9451 | std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); | ||||
9452 | llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); | ||||
9453 | llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); | ||||
9454 | if (InitBound.ugt(AllocBound)) { | ||||
9455 | if (IsNothrow) | ||||
9456 | return ZeroInitialization(E); | ||||
9457 | |||||
9458 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) | ||||
9459 | << toString(AllocBound, 10, /*Signed=*/false) | ||||
9460 | << toString(InitBound, 10, /*Signed=*/false) | ||||
9461 | << (*ArraySize)->getSourceRange(); | ||||
9462 | return false; | ||||
9463 | } | ||||
9464 | |||||
9465 | // If the sizes differ, we must have an initializer list, and we need | ||||
9466 | // special handling for this case when we initialize. | ||||
9467 | if (InitBound != AllocBound) | ||||
9468 | ResizedArrayILE = cast<InitListExpr>(Init); | ||||
9469 | } | ||||
9470 | |||||
9471 | AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, | ||||
9472 | ArrayType::Normal, 0); | ||||
9473 | } else { | ||||
9474 | assert(!AllocType->isArrayType() &&(static_cast <bool> (!AllocType->isArrayType() && "array allocation with non-array new") ? void (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9475, __extension__ __PRETTY_FUNCTION__)) | ||||
9475 | "array allocation with non-array new")(static_cast <bool> (!AllocType->isArrayType() && "array allocation with non-array new") ? void (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9475, __extension__ __PRETTY_FUNCTION__)); | ||||
9476 | } | ||||
9477 | |||||
9478 | APValue *Val; | ||||
9479 | if (IsPlacement) { | ||||
9480 | AccessKinds AK = AK_Construct; | ||||
9481 | struct FindObjectHandler { | ||||
9482 | EvalInfo &Info; | ||||
9483 | const Expr *E; | ||||
9484 | QualType AllocType; | ||||
9485 | const AccessKinds AccessKind; | ||||
9486 | APValue *Value; | ||||
9487 | |||||
9488 | typedef bool result_type; | ||||
9489 | bool failed() { return false; } | ||||
9490 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
9491 | // FIXME: Reject the cases where [basic.life]p8 would not permit the | ||||
9492 | // old name of the object to be used to name the new object. | ||||
9493 | if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { | ||||
9494 | Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << | ||||
9495 | SubobjType << AllocType; | ||||
9496 | return false; | ||||
9497 | } | ||||
9498 | Value = &Subobj; | ||||
9499 | return true; | ||||
9500 | } | ||||
9501 | bool found(APSInt &Value, QualType SubobjType) { | ||||
9502 | Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); | ||||
9503 | return false; | ||||
9504 | } | ||||
9505 | bool found(APFloat &Value, QualType SubobjType) { | ||||
9506 | Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); | ||||
9507 | return false; | ||||
9508 | } | ||||
9509 | } Handler = {Info, E, AllocType, AK, nullptr}; | ||||
9510 | |||||
9511 | CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); | ||||
9512 | if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) | ||||
9513 | return false; | ||||
9514 | |||||
9515 | Val = Handler.Value; | ||||
9516 | |||||
9517 | // [basic.life]p1: | ||||
9518 | // The lifetime of an object o of type T ends when [...] the storage | ||||
9519 | // which the object occupies is [...] reused by an object that is not | ||||
9520 | // nested within o (6.6.2). | ||||
9521 | *Val = APValue(); | ||||
9522 | } else { | ||||
9523 | // Perform the allocation and obtain a pointer to the resulting object. | ||||
9524 | Val = Info.createHeapAlloc(E, AllocType, Result); | ||||
9525 | if (!Val) | ||||
9526 | return false; | ||||
9527 | } | ||||
9528 | |||||
9529 | if (ValueInit) { | ||||
9530 | ImplicitValueInitExpr VIE(AllocType); | ||||
9531 | if (!EvaluateInPlace(*Val, Info, Result, &VIE)) | ||||
9532 | return false; | ||||
9533 | } else if (ResizedArrayILE) { | ||||
9534 | if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, | ||||
9535 | AllocType)) | ||||
9536 | return false; | ||||
9537 | } else if (ResizedArrayCCE) { | ||||
9538 | if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, | ||||
9539 | AllocType)) | ||||
9540 | return false; | ||||
9541 | } else if (Init) { | ||||
9542 | if (!EvaluateInPlace(*Val, Info, Result, Init)) | ||||
9543 | return false; | ||||
9544 | } else if (!getDefaultInitValue(AllocType, *Val)) { | ||||
9545 | return false; | ||||
9546 | } | ||||
9547 | |||||
9548 | // Array new returns a pointer to the first element, not a pointer to the | ||||
9549 | // array. | ||||
9550 | if (auto *AT = AllocType->getAsArrayTypeUnsafe()) | ||||
9551 | Result.addArray(Info, E, cast<ConstantArrayType>(AT)); | ||||
9552 | |||||
9553 | return true; | ||||
9554 | } | ||||
9555 | //===----------------------------------------------------------------------===// | ||||
9556 | // Member Pointer Evaluation | ||||
9557 | //===----------------------------------------------------------------------===// | ||||
9558 | |||||
9559 | namespace { | ||||
9560 | class MemberPointerExprEvaluator | ||||
9561 | : public ExprEvaluatorBase<MemberPointerExprEvaluator> { | ||||
9562 | MemberPtr &Result; | ||||
9563 | |||||
9564 | bool Success(const ValueDecl *D) { | ||||
9565 | Result = MemberPtr(D); | ||||
9566 | return true; | ||||
9567 | } | ||||
9568 | public: | ||||
9569 | |||||
9570 | MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) | ||||
9571 | : ExprEvaluatorBaseTy(Info), Result(Result) {} | ||||
9572 | |||||
9573 | bool Success(const APValue &V, const Expr *E) { | ||||
9574 | Result.setFrom(V); | ||||
9575 | return true; | ||||
9576 | } | ||||
9577 | bool ZeroInitialization(const Expr *E) { | ||||
9578 | return Success((const ValueDecl*)nullptr); | ||||
9579 | } | ||||
9580 | |||||
9581 | bool VisitCastExpr(const CastExpr *E); | ||||
9582 | bool VisitUnaryAddrOf(const UnaryOperator *E); | ||||
9583 | }; | ||||
9584 | } // end anonymous namespace | ||||
9585 | |||||
9586 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, | ||||
9587 | EvalInfo &Info) { | ||||
9588 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9588, __extension__ __PRETTY_FUNCTION__)); | ||||
9589 | assert(E->isPRValue() && E->getType()->isMemberPointerType())(static_cast <bool> (E->isPRValue() && E-> getType()->isMemberPointerType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9589, __extension__ __PRETTY_FUNCTION__)); | ||||
9590 | return MemberPointerExprEvaluator(Info, Result).Visit(E); | ||||
9591 | } | ||||
9592 | |||||
9593 | bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
9594 | switch (E->getCastKind()) { | ||||
9595 | default: | ||||
9596 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
9597 | |||||
9598 | case CK_NullToMemberPointer: | ||||
9599 | VisitIgnoredValue(E->getSubExpr()); | ||||
9600 | return ZeroInitialization(E); | ||||
9601 | |||||
9602 | case CK_BaseToDerivedMemberPointer: { | ||||
9603 | if (!Visit(E->getSubExpr())) | ||||
9604 | return false; | ||||
9605 | if (E->path_empty()) | ||||
9606 | return true; | ||||
9607 | // Base-to-derived member pointer casts store the path in derived-to-base | ||||
9608 | // order, so iterate backwards. The CXXBaseSpecifier also provides us with | ||||
9609 | // the wrong end of the derived->base arc, so stagger the path by one class. | ||||
9610 | typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; | ||||
9611 | for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); | ||||
9612 | PathI != PathE; ++PathI) { | ||||
9613 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase")(static_cast <bool> (!(*PathI)->isVirtual() && "memptr cast through vbase") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9613, __extension__ __PRETTY_FUNCTION__)); | ||||
9614 | const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||
9615 | if (!Result.castToDerived(Derived)) | ||||
9616 | return Error(E); | ||||
9617 | } | ||||
9618 | const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); | ||||
9619 | if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) | ||||
9620 | return Error(E); | ||||
9621 | return true; | ||||
9622 | } | ||||
9623 | |||||
9624 | case CK_DerivedToBaseMemberPointer: | ||||
9625 | if (!Visit(E->getSubExpr())) | ||||
9626 | return false; | ||||
9627 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||
9628 | PathE = E->path_end(); PathI != PathE; ++PathI) { | ||||
9629 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase")(static_cast <bool> (!(*PathI)->isVirtual() && "memptr cast through vbase") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9629, __extension__ __PRETTY_FUNCTION__)); | ||||
9630 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||
9631 | if (!Result.castToBase(Base)) | ||||
9632 | return Error(E); | ||||
9633 | } | ||||
9634 | return true; | ||||
9635 | } | ||||
9636 | } | ||||
9637 | |||||
9638 | bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { | ||||
9639 | // C++11 [expr.unary.op]p3 has very strict rules on how the address of a | ||||
9640 | // member can be formed. | ||||
9641 | return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); | ||||
9642 | } | ||||
9643 | |||||
9644 | //===----------------------------------------------------------------------===// | ||||
9645 | // Record Evaluation | ||||
9646 | //===----------------------------------------------------------------------===// | ||||
9647 | |||||
9648 | namespace { | ||||
9649 | class RecordExprEvaluator | ||||
9650 | : public ExprEvaluatorBase<RecordExprEvaluator> { | ||||
9651 | const LValue &This; | ||||
9652 | APValue &Result; | ||||
9653 | public: | ||||
9654 | |||||
9655 | RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) | ||||
9656 | : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} | ||||
9657 | |||||
9658 | bool Success(const APValue &V, const Expr *E) { | ||||
9659 | Result = V; | ||||
9660 | return true; | ||||
9661 | } | ||||
9662 | bool ZeroInitialization(const Expr *E) { | ||||
9663 | return ZeroInitialization(E, E->getType()); | ||||
9664 | } | ||||
9665 | bool ZeroInitialization(const Expr *E, QualType T); | ||||
9666 | |||||
9667 | bool VisitCallExpr(const CallExpr *E) { | ||||
9668 | return handleCallExpr(E, Result, &This); | ||||
9669 | } | ||||
9670 | bool VisitCastExpr(const CastExpr *E); | ||||
9671 | bool VisitInitListExpr(const InitListExpr *E); | ||||
9672 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||
9673 | return VisitCXXConstructExpr(E, E->getType()); | ||||
9674 | } | ||||
9675 | bool VisitLambdaExpr(const LambdaExpr *E); | ||||
9676 | bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); | ||||
9677 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); | ||||
9678 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); | ||||
9679 | bool VisitBinCmp(const BinaryOperator *E); | ||||
9680 | }; | ||||
9681 | } | ||||
9682 | |||||
9683 | /// Perform zero-initialization on an object of non-union class type. | ||||
9684 | /// C++11 [dcl.init]p5: | ||||
9685 | /// To zero-initialize an object or reference of type T means: | ||||
9686 | /// [...] | ||||
9687 | /// -- if T is a (possibly cv-qualified) non-union class type, | ||||
9688 | /// each non-static data member and each base-class subobject is | ||||
9689 | /// zero-initialized | ||||
9690 | static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, | ||||
9691 | const RecordDecl *RD, | ||||
9692 | const LValue &This, APValue &Result) { | ||||
9693 | assert(!RD->isUnion() && "Expected non-union class type")(static_cast <bool> (!RD->isUnion() && "Expected non-union class type" ) ? void (0) : __assert_fail ("!RD->isUnion() && \"Expected non-union class type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9693, __extension__ __PRETTY_FUNCTION__)); | ||||
9694 | const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); | ||||
9695 | Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, | ||||
9696 | std::distance(RD->field_begin(), RD->field_end())); | ||||
9697 | |||||
9698 | if (RD->isInvalidDecl()) return false; | ||||
9699 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
9700 | |||||
9701 | if (CD) { | ||||
9702 | unsigned Index = 0; | ||||
9703 | for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), | ||||
9704 | End = CD->bases_end(); I != End; ++I, ++Index) { | ||||
9705 | const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); | ||||
9706 | LValue Subobject = This; | ||||
9707 | if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) | ||||
9708 | return false; | ||||
9709 | if (!HandleClassZeroInitialization(Info, E, Base, Subobject, | ||||
9710 | Result.getStructBase(Index))) | ||||
9711 | return false; | ||||
9712 | } | ||||
9713 | } | ||||
9714 | |||||
9715 | for (const auto *I : RD->fields()) { | ||||
9716 | // -- if T is a reference type, no initialization is performed. | ||||
9717 | if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) | ||||
9718 | continue; | ||||
9719 | |||||
9720 | LValue Subobject = This; | ||||
9721 | if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) | ||||
9722 | return false; | ||||
9723 | |||||
9724 | ImplicitValueInitExpr VIE(I->getType()); | ||||
9725 | if (!EvaluateInPlace( | ||||
9726 | Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) | ||||
9727 | return false; | ||||
9728 | } | ||||
9729 | |||||
9730 | return true; | ||||
9731 | } | ||||
9732 | |||||
9733 | bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { | ||||
9734 | const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); | ||||
9735 | if (RD->isInvalidDecl()) return false; | ||||
9736 | if (RD->isUnion()) { | ||||
9737 | // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the | ||||
9738 | // object's first non-static named data member is zero-initialized | ||||
9739 | RecordDecl::field_iterator I = RD->field_begin(); | ||||
9740 | while (I != RD->field_end() && (*I)->isUnnamedBitfield()) | ||||
9741 | ++I; | ||||
9742 | if (I == RD->field_end()) { | ||||
9743 | Result = APValue((const FieldDecl*)nullptr); | ||||
9744 | return true; | ||||
9745 | } | ||||
9746 | |||||
9747 | LValue Subobject = This; | ||||
9748 | if (!HandleLValueMember(Info, E, Subobject, *I)) | ||||
9749 | return false; | ||||
9750 | Result = APValue(*I); | ||||
9751 | ImplicitValueInitExpr VIE(I->getType()); | ||||
9752 | return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); | ||||
9753 | } | ||||
9754 | |||||
9755 | if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { | ||||
9756 | Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; | ||||
9757 | return false; | ||||
9758 | } | ||||
9759 | |||||
9760 | return HandleClassZeroInitialization(Info, E, RD, This, Result); | ||||
9761 | } | ||||
9762 | |||||
9763 | bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
9764 | switch (E->getCastKind()) { | ||||
9765 | default: | ||||
9766 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
9767 | |||||
9768 | case CK_ConstructorConversion: | ||||
9769 | return Visit(E->getSubExpr()); | ||||
9770 | |||||
9771 | case CK_DerivedToBase: | ||||
9772 | case CK_UncheckedDerivedToBase: { | ||||
9773 | APValue DerivedObject; | ||||
9774 | if (!Evaluate(DerivedObject, Info, E->getSubExpr())) | ||||
9775 | return false; | ||||
9776 | if (!DerivedObject.isStruct()) | ||||
9777 | return Error(E->getSubExpr()); | ||||
9778 | |||||
9779 | // Derived-to-base rvalue conversion: just slice off the derived part. | ||||
9780 | APValue *Value = &DerivedObject; | ||||
9781 | const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); | ||||
9782 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||
9783 | PathE = E->path_end(); PathI != PathE; ++PathI) { | ||||
9784 | assert(!(*PathI)->isVirtual() && "record rvalue with virtual base")(static_cast <bool> (!(*PathI)->isVirtual() && "record rvalue with virtual base") ? void (0) : __assert_fail ("!(*PathI)->isVirtual() && \"record rvalue with virtual base\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9784, __extension__ __PRETTY_FUNCTION__)); | ||||
9785 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||
9786 | Value = &Value->getStructBase(getBaseIndex(RD, Base)); | ||||
9787 | RD = Base; | ||||
9788 | } | ||||
9789 | Result = *Value; | ||||
9790 | return true; | ||||
9791 | } | ||||
9792 | } | ||||
9793 | } | ||||
9794 | |||||
9795 | bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||
9796 | if (E->isTransparent()) | ||||
9797 | return Visit(E->getInit(0)); | ||||
9798 | |||||
9799 | const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); | ||||
9800 | if (RD->isInvalidDecl()) return false; | ||||
9801 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
9802 | auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); | ||||
9803 | |||||
9804 | EvalInfo::EvaluatingConstructorRAII EvalObj( | ||||
9805 | Info, | ||||
9806 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, | ||||
9807 | CXXRD && CXXRD->getNumBases()); | ||||
9808 | |||||
9809 | if (RD->isUnion()) { | ||||
9810 | const FieldDecl *Field = E->getInitializedFieldInUnion(); | ||||
9811 | Result = APValue(Field); | ||||
9812 | if (!Field) | ||||
9813 | return true; | ||||
9814 | |||||
9815 | // If the initializer list for a union does not contain any elements, the | ||||
9816 | // first element of the union is value-initialized. | ||||
9817 | // FIXME: The element should be initialized from an initializer list. | ||||
9818 | // Is this difference ever observable for initializer lists which | ||||
9819 | // we don't build? | ||||
9820 | ImplicitValueInitExpr VIE(Field->getType()); | ||||
9821 | const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; | ||||
9822 | |||||
9823 | LValue Subobject = This; | ||||
9824 | if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) | ||||
9825 | return false; | ||||
9826 | |||||
9827 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. | ||||
9828 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, | ||||
9829 | isa<CXXDefaultInitExpr>(InitExpr)); | ||||
9830 | |||||
9831 | if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { | ||||
9832 | if (Field->isBitField()) | ||||
9833 | return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), | ||||
9834 | Field); | ||||
9835 | return true; | ||||
9836 | } | ||||
9837 | |||||
9838 | return false; | ||||
9839 | } | ||||
9840 | |||||
9841 | if (!Result.hasValue()) | ||||
9842 | Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, | ||||
9843 | std::distance(RD->field_begin(), RD->field_end())); | ||||
9844 | unsigned ElementNo = 0; | ||||
9845 | bool Success = true; | ||||
9846 | |||||
9847 | // Initialize base classes. | ||||
9848 | if (CXXRD && CXXRD->getNumBases()) { | ||||
9849 | for (const auto &Base : CXXRD->bases()) { | ||||
9850 | assert(ElementNo < E->getNumInits() && "missing init for base class")(static_cast <bool> (ElementNo < E->getNumInits() && "missing init for base class") ? void (0) : __assert_fail ("ElementNo < E->getNumInits() && \"missing init for base class\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9850, __extension__ __PRETTY_FUNCTION__)); | ||||
9851 | const Expr *Init = E->getInit(ElementNo); | ||||
9852 | |||||
9853 | LValue Subobject = This; | ||||
9854 | if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) | ||||
9855 | return false; | ||||
9856 | |||||
9857 | APValue &FieldVal = Result.getStructBase(ElementNo); | ||||
9858 | if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { | ||||
9859 | if (!Info.noteFailure()) | ||||
9860 | return false; | ||||
9861 | Success = false; | ||||
9862 | } | ||||
9863 | ++ElementNo; | ||||
9864 | } | ||||
9865 | |||||
9866 | EvalObj.finishedConstructingBases(); | ||||
9867 | } | ||||
9868 | |||||
9869 | // Initialize members. | ||||
9870 | for (const auto *Field : RD->fields()) { | ||||
9871 | // Anonymous bit-fields are not considered members of the class for | ||||
9872 | // purposes of aggregate initialization. | ||||
9873 | if (Field->isUnnamedBitfield()) | ||||
9874 | continue; | ||||
9875 | |||||
9876 | LValue Subobject = This; | ||||
9877 | |||||
9878 | bool HaveInit = ElementNo < E->getNumInits(); | ||||
9879 | |||||
9880 | // FIXME: Diagnostics here should point to the end of the initializer | ||||
9881 | // list, not the start. | ||||
9882 | if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, | ||||
9883 | Subobject, Field, &Layout)) | ||||
9884 | return false; | ||||
9885 | |||||
9886 | // Perform an implicit value-initialization for members beyond the end of | ||||
9887 | // the initializer list. | ||||
9888 | ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); | ||||
9889 | const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; | ||||
9890 | |||||
9891 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. | ||||
9892 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, | ||||
9893 | isa<CXXDefaultInitExpr>(Init)); | ||||
9894 | |||||
9895 | APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); | ||||
9896 | if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || | ||||
9897 | (Field->isBitField() && !truncateBitfieldValue(Info, Init, | ||||
9898 | FieldVal, Field))) { | ||||
9899 | if (!Info.noteFailure()) | ||||
9900 | return false; | ||||
9901 | Success = false; | ||||
9902 | } | ||||
9903 | } | ||||
9904 | |||||
9905 | EvalObj.finishedConstructingFields(); | ||||
9906 | |||||
9907 | return Success; | ||||
9908 | } | ||||
9909 | |||||
9910 | bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||
9911 | QualType T) { | ||||
9912 | // Note that E's type is not necessarily the type of our class here; we might | ||||
9913 | // be initializing an array element instead. | ||||
9914 | const CXXConstructorDecl *FD = E->getConstructor(); | ||||
9915 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; | ||||
9916 | |||||
9917 | bool ZeroInit = E->requiresZeroInitialization(); | ||||
9918 | if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { | ||||
9919 | // If we've already performed zero-initialization, we're already done. | ||||
9920 | if (Result.hasValue()) | ||||
9921 | return true; | ||||
9922 | |||||
9923 | if (ZeroInit) | ||||
9924 | return ZeroInitialization(E, T); | ||||
9925 | |||||
9926 | return getDefaultInitValue(T, Result); | ||||
9927 | } | ||||
9928 | |||||
9929 | const FunctionDecl *Definition = nullptr; | ||||
9930 | auto Body = FD->getBody(Definition); | ||||
9931 | |||||
9932 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) | ||||
9933 | return false; | ||||
9934 | |||||
9935 | // Avoid materializing a temporary for an elidable copy/move constructor. | ||||
9936 | if (E->isElidable() && !ZeroInit) | ||||
9937 | if (const MaterializeTemporaryExpr *ME | ||||
9938 | = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) | ||||
9939 | return Visit(ME->getSubExpr()); | ||||
9940 | |||||
9941 | if (ZeroInit && !ZeroInitialization(E, T)) | ||||
9942 | return false; | ||||
9943 | |||||
9944 | auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); | ||||
9945 | return HandleConstructorCall(E, This, Args, | ||||
9946 | cast<CXXConstructorDecl>(Definition), Info, | ||||
9947 | Result); | ||||
9948 | } | ||||
9949 | |||||
9950 | bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( | ||||
9951 | const CXXInheritedCtorInitExpr *E) { | ||||
9952 | if (!Info.CurrentCall) { | ||||
9953 | assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression ()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 9953, __extension__ __PRETTY_FUNCTION__)); | ||||
9954 | return false; | ||||
9955 | } | ||||
9956 | |||||
9957 | const CXXConstructorDecl *FD = E->getConstructor(); | ||||
9958 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) | ||||
9959 | return false; | ||||
9960 | |||||
9961 | const FunctionDecl *Definition = nullptr; | ||||
9962 | auto Body = FD->getBody(Definition); | ||||
9963 | |||||
9964 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) | ||||
9965 | return false; | ||||
9966 | |||||
9967 | return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, | ||||
9968 | cast<CXXConstructorDecl>(Definition), Info, | ||||
9969 | Result); | ||||
9970 | } | ||||
9971 | |||||
9972 | bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( | ||||
9973 | const CXXStdInitializerListExpr *E) { | ||||
9974 | const ConstantArrayType *ArrayType = | ||||
9975 | Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); | ||||
9976 | |||||
9977 | LValue Array; | ||||
9978 | if (!EvaluateLValue(E->getSubExpr(), Array, Info)) | ||||
9979 | return false; | ||||
9980 | |||||
9981 | // Get a pointer to the first element of the array. | ||||
9982 | Array.addArray(Info, E, ArrayType); | ||||
9983 | |||||
9984 | auto InvalidType = [&] { | ||||
9985 | Info.FFDiag(E, diag::note_constexpr_unsupported_layout) | ||||
9986 | << E->getType(); | ||||
9987 | return false; | ||||
9988 | }; | ||||
9989 | |||||
9990 | // FIXME: Perform the checks on the field types in SemaInit. | ||||
9991 | RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); | ||||
9992 | RecordDecl::field_iterator Field = Record->field_begin(); | ||||
9993 | if (Field == Record->field_end()) | ||||
9994 | return InvalidType(); | ||||
9995 | |||||
9996 | // Start pointer. | ||||
9997 | if (!Field->getType()->isPointerType() || | ||||
9998 | !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), | ||||
9999 | ArrayType->getElementType())) | ||||
10000 | return InvalidType(); | ||||
10001 | |||||
10002 | // FIXME: What if the initializer_list type has base classes, etc? | ||||
10003 | Result = APValue(APValue::UninitStruct(), 0, 2); | ||||
10004 | Array.moveInto(Result.getStructField(0)); | ||||
10005 | |||||
10006 | if (++Field == Record->field_end()) | ||||
10007 | return InvalidType(); | ||||
10008 | |||||
10009 | if (Field->getType()->isPointerType() && | ||||
10010 | Info.Ctx.hasSameType(Field->getType()->getPointeeType(), | ||||
10011 | ArrayType->getElementType())) { | ||||
10012 | // End pointer. | ||||
10013 | if (!HandleLValueArrayAdjustment(Info, E, Array, | ||||
10014 | ArrayType->getElementType(), | ||||
10015 | ArrayType->getSize().getZExtValue())) | ||||
10016 | return false; | ||||
10017 | Array.moveInto(Result.getStructField(1)); | ||||
10018 | } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) | ||||
10019 | // Length. | ||||
10020 | Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); | ||||
10021 | else | ||||
10022 | return InvalidType(); | ||||
10023 | |||||
10024 | if (++Field != Record->field_end()) | ||||
10025 | return InvalidType(); | ||||
10026 | |||||
10027 | return true; | ||||
10028 | } | ||||
10029 | |||||
10030 | bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { | ||||
10031 | const CXXRecordDecl *ClosureClass = E->getLambdaClass(); | ||||
10032 | if (ClosureClass->isInvalidDecl()) | ||||
10033 | return false; | ||||
10034 | |||||
10035 | const size_t NumFields = | ||||
10036 | std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); | ||||
10037 | |||||
10038 | assert(NumFields == (size_t)std::distance(E->capture_init_begin(),(static_cast <bool> (NumFields == (size_t)std::distance (E->capture_init_begin(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? void (0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10041, __extension__ __PRETTY_FUNCTION__)) | ||||
10039 | E->capture_init_end()) &&(static_cast <bool> (NumFields == (size_t)std::distance (E->capture_init_begin(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? void (0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10041, __extension__ __PRETTY_FUNCTION__)) | ||||
10040 | "The number of lambda capture initializers should equal the number of "(static_cast <bool> (NumFields == (size_t)std::distance (E->capture_init_begin(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? void (0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10041, __extension__ __PRETTY_FUNCTION__)) | ||||
10041 | "fields within the closure type")(static_cast <bool> (NumFields == (size_t)std::distance (E->capture_init_begin(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? void (0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10041, __extension__ __PRETTY_FUNCTION__)); | ||||
10042 | |||||
10043 | Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); | ||||
10044 | // Iterate through all the lambda's closure object's fields and initialize | ||||
10045 | // them. | ||||
10046 | auto *CaptureInitIt = E->capture_init_begin(); | ||||
10047 | const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); | ||||
10048 | bool Success = true; | ||||
10049 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); | ||||
10050 | for (const auto *Field : ClosureClass->fields()) { | ||||
10051 | assert(CaptureInitIt != E->capture_init_end())(static_cast <bool> (CaptureInitIt != E->capture_init_end ()) ? void (0) : __assert_fail ("CaptureInitIt != E->capture_init_end()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10051, __extension__ __PRETTY_FUNCTION__)); | ||||
10052 | // Get the initializer for this field | ||||
10053 | Expr *const CurFieldInit = *CaptureInitIt++; | ||||
10054 | |||||
10055 | // If there is no initializer, either this is a VLA or an error has | ||||
10056 | // occurred. | ||||
10057 | if (!CurFieldInit) | ||||
10058 | return Error(E); | ||||
10059 | |||||
10060 | LValue Subobject = This; | ||||
10061 | |||||
10062 | if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) | ||||
10063 | return false; | ||||
10064 | |||||
10065 | APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); | ||||
10066 | if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { | ||||
10067 | if (!Info.keepEvaluatingAfterFailure()) | ||||
10068 | return false; | ||||
10069 | Success = false; | ||||
10070 | } | ||||
10071 | ++CaptureIt; | ||||
10072 | } | ||||
10073 | return Success; | ||||
10074 | } | ||||
10075 | |||||
10076 | static bool EvaluateRecord(const Expr *E, const LValue &This, | ||||
10077 | APValue &Result, EvalInfo &Info) { | ||||
10078 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10078, __extension__ __PRETTY_FUNCTION__)); | ||||
10079 | assert(E->isPRValue() && E->getType()->isRecordType() &&(static_cast <bool> (E->isPRValue() && E-> getType()->isRecordType() && "can't evaluate expression as a record rvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10080, __extension__ __PRETTY_FUNCTION__)) | ||||
10080 | "can't evaluate expression as a record rvalue")(static_cast <bool> (E->isPRValue() && E-> getType()->isRecordType() && "can't evaluate expression as a record rvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10080, __extension__ __PRETTY_FUNCTION__)); | ||||
10081 | return RecordExprEvaluator(Info, This, Result).Visit(E); | ||||
10082 | } | ||||
10083 | |||||
10084 | //===----------------------------------------------------------------------===// | ||||
10085 | // Temporary Evaluation | ||||
10086 | // | ||||
10087 | // Temporaries are represented in the AST as rvalues, but generally behave like | ||||
10088 | // lvalues. The full-object of which the temporary is a subobject is implicitly | ||||
10089 | // materialized so that a reference can bind to it. | ||||
10090 | //===----------------------------------------------------------------------===// | ||||
10091 | namespace { | ||||
10092 | class TemporaryExprEvaluator | ||||
10093 | : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { | ||||
10094 | public: | ||||
10095 | TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : | ||||
10096 | LValueExprEvaluatorBaseTy(Info, Result, false) {} | ||||
10097 | |||||
10098 | /// Visit an expression which constructs the value of this temporary. | ||||
10099 | bool VisitConstructExpr(const Expr *E) { | ||||
10100 | APValue &Value = Info.CurrentCall->createTemporary( | ||||
10101 | E, E->getType(), ScopeKind::FullExpression, Result); | ||||
10102 | return EvaluateInPlace(Value, Info, Result, E); | ||||
10103 | } | ||||
10104 | |||||
10105 | bool VisitCastExpr(const CastExpr *E) { | ||||
10106 | switch (E->getCastKind()) { | ||||
10107 | default: | ||||
10108 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
10109 | |||||
10110 | case CK_ConstructorConversion: | ||||
10111 | return VisitConstructExpr(E->getSubExpr()); | ||||
10112 | } | ||||
10113 | } | ||||
10114 | bool VisitInitListExpr(const InitListExpr *E) { | ||||
10115 | return VisitConstructExpr(E); | ||||
10116 | } | ||||
10117 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||
10118 | return VisitConstructExpr(E); | ||||
10119 | } | ||||
10120 | bool VisitCallExpr(const CallExpr *E) { | ||||
10121 | return VisitConstructExpr(E); | ||||
10122 | } | ||||
10123 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { | ||||
10124 | return VisitConstructExpr(E); | ||||
10125 | } | ||||
10126 | bool VisitLambdaExpr(const LambdaExpr *E) { | ||||
10127 | return VisitConstructExpr(E); | ||||
10128 | } | ||||
10129 | }; | ||||
10130 | } // end anonymous namespace | ||||
10131 | |||||
10132 | /// Evaluate an expression of record type as a temporary. | ||||
10133 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { | ||||
10134 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10134, __extension__ __PRETTY_FUNCTION__)); | ||||
10135 | assert(E->isPRValue() && E->getType()->isRecordType())(static_cast <bool> (E->isPRValue() && E-> getType()->isRecordType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRecordType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10135, __extension__ __PRETTY_FUNCTION__)); | ||||
10136 | return TemporaryExprEvaluator(Info, Result).Visit(E); | ||||
10137 | } | ||||
10138 | |||||
10139 | //===----------------------------------------------------------------------===// | ||||
10140 | // Vector Evaluation | ||||
10141 | //===----------------------------------------------------------------------===// | ||||
10142 | |||||
10143 | namespace { | ||||
10144 | class VectorExprEvaluator | ||||
10145 | : public ExprEvaluatorBase<VectorExprEvaluator> { | ||||
10146 | APValue &Result; | ||||
10147 | public: | ||||
10148 | |||||
10149 | VectorExprEvaluator(EvalInfo &info, APValue &Result) | ||||
10150 | : ExprEvaluatorBaseTy(info), Result(Result) {} | ||||
10151 | |||||
10152 | bool Success(ArrayRef<APValue> V, const Expr *E) { | ||||
10153 | assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements())(static_cast <bool> (V.size() == E->getType()->castAs <VectorType>()->getNumElements()) ? void (0) : __assert_fail ("V.size() == E->getType()->castAs<VectorType>()->getNumElements()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10153, __extension__ __PRETTY_FUNCTION__)); | ||||
10154 | // FIXME: remove this APValue copy. | ||||
10155 | Result = APValue(V.data(), V.size()); | ||||
10156 | return true; | ||||
10157 | } | ||||
10158 | bool Success(const APValue &V, const Expr *E) { | ||||
10159 | assert(V.isVector())(static_cast <bool> (V.isVector()) ? void (0) : __assert_fail ("V.isVector()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10159, __extension__ __PRETTY_FUNCTION__)); | ||||
10160 | Result = V; | ||||
10161 | return true; | ||||
10162 | } | ||||
10163 | bool ZeroInitialization(const Expr *E); | ||||
10164 | |||||
10165 | bool VisitUnaryReal(const UnaryOperator *E) | ||||
10166 | { return Visit(E->getSubExpr()); } | ||||
10167 | bool VisitCastExpr(const CastExpr* E); | ||||
10168 | bool VisitInitListExpr(const InitListExpr *E); | ||||
10169 | bool VisitUnaryImag(const UnaryOperator *E); | ||||
10170 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
10171 | // FIXME: Missing: unary -, unary ~, conditional operator (for GNU | ||||
10172 | // conditional select), shufflevector, ExtVectorElementExpr | ||||
10173 | }; | ||||
10174 | } // end anonymous namespace | ||||
10175 | |||||
10176 | static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { | ||||
10177 | assert(E->isPRValue() && E->getType()->isVectorType() &&(static_cast <bool> (E->isPRValue() && E-> getType()->isVectorType() && "not a vector prvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVectorType() && \"not a vector prvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10178, __extension__ __PRETTY_FUNCTION__)) | ||||
10178 | "not a vector prvalue")(static_cast <bool> (E->isPRValue() && E-> getType()->isVectorType() && "not a vector prvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVectorType() && \"not a vector prvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10178, __extension__ __PRETTY_FUNCTION__)); | ||||
10179 | return VectorExprEvaluator(Info, Result).Visit(E); | ||||
10180 | } | ||||
10181 | |||||
10182 | bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
10183 | const VectorType *VTy = E->getType()->castAs<VectorType>(); | ||||
10184 | unsigned NElts = VTy->getNumElements(); | ||||
10185 | |||||
10186 | const Expr *SE = E->getSubExpr(); | ||||
10187 | QualType SETy = SE->getType(); | ||||
10188 | |||||
10189 | switch (E->getCastKind()) { | ||||
10190 | case CK_VectorSplat: { | ||||
10191 | APValue Val = APValue(); | ||||
10192 | if (SETy->isIntegerType()) { | ||||
10193 | APSInt IntResult; | ||||
10194 | if (!EvaluateInteger(SE, IntResult, Info)) | ||||
10195 | return false; | ||||
10196 | Val = APValue(std::move(IntResult)); | ||||
10197 | } else if (SETy->isRealFloatingType()) { | ||||
10198 | APFloat FloatResult(0.0); | ||||
10199 | if (!EvaluateFloat(SE, FloatResult, Info)) | ||||
10200 | return false; | ||||
10201 | Val = APValue(std::move(FloatResult)); | ||||
10202 | } else { | ||||
10203 | return Error(E); | ||||
10204 | } | ||||
10205 | |||||
10206 | // Splat and create vector APValue. | ||||
10207 | SmallVector<APValue, 4> Elts(NElts, Val); | ||||
10208 | return Success(Elts, E); | ||||
10209 | } | ||||
10210 | case CK_BitCast: { | ||||
10211 | // Evaluate the operand into an APInt we can extract from. | ||||
10212 | llvm::APInt SValInt; | ||||
10213 | if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) | ||||
10214 | return false; | ||||
10215 | // Extract the elements | ||||
10216 | QualType EltTy = VTy->getElementType(); | ||||
10217 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); | ||||
10218 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); | ||||
10219 | SmallVector<APValue, 4> Elts; | ||||
10220 | if (EltTy->isRealFloatingType()) { | ||||
10221 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); | ||||
10222 | unsigned FloatEltSize = EltSize; | ||||
10223 | if (&Sem == &APFloat::x87DoubleExtended()) | ||||
10224 | FloatEltSize = 80; | ||||
10225 | for (unsigned i = 0; i < NElts; i++) { | ||||
10226 | llvm::APInt Elt; | ||||
10227 | if (BigEndian) | ||||
10228 | Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); | ||||
10229 | else | ||||
10230 | Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); | ||||
10231 | Elts.push_back(APValue(APFloat(Sem, Elt))); | ||||
10232 | } | ||||
10233 | } else if (EltTy->isIntegerType()) { | ||||
10234 | for (unsigned i = 0; i < NElts; i++) { | ||||
10235 | llvm::APInt Elt; | ||||
10236 | if (BigEndian) | ||||
10237 | Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); | ||||
10238 | else | ||||
10239 | Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); | ||||
10240 | Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); | ||||
10241 | } | ||||
10242 | } else { | ||||
10243 | return Error(E); | ||||
10244 | } | ||||
10245 | return Success(Elts, E); | ||||
10246 | } | ||||
10247 | default: | ||||
10248 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
10249 | } | ||||
10250 | } | ||||
10251 | |||||
10252 | bool | ||||
10253 | VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||
10254 | const VectorType *VT = E->getType()->castAs<VectorType>(); | ||||
10255 | unsigned NumInits = E->getNumInits(); | ||||
10256 | unsigned NumElements = VT->getNumElements(); | ||||
10257 | |||||
10258 | QualType EltTy = VT->getElementType(); | ||||
10259 | SmallVector<APValue, 4> Elements; | ||||
10260 | |||||
10261 | // The number of initializers can be less than the number of | ||||
10262 | // vector elements. For OpenCL, this can be due to nested vector | ||||
10263 | // initialization. For GCC compatibility, missing trailing elements | ||||
10264 | // should be initialized with zeroes. | ||||
10265 | unsigned CountInits = 0, CountElts = 0; | ||||
10266 | while (CountElts < NumElements) { | ||||
10267 | // Handle nested vector initialization. | ||||
10268 | if (CountInits < NumInits | ||||
10269 | && E->getInit(CountInits)->getType()->isVectorType()) { | ||||
10270 | APValue v; | ||||
10271 | if (!EvaluateVector(E->getInit(CountInits), v, Info)) | ||||
10272 | return Error(E); | ||||
10273 | unsigned vlen = v.getVectorLength(); | ||||
10274 | for (unsigned j = 0; j < vlen; j++) | ||||
10275 | Elements.push_back(v.getVectorElt(j)); | ||||
10276 | CountElts += vlen; | ||||
10277 | } else if (EltTy->isIntegerType()) { | ||||
10278 | llvm::APSInt sInt(32); | ||||
10279 | if (CountInits < NumInits) { | ||||
10280 | if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) | ||||
10281 | return false; | ||||
10282 | } else // trailing integer zero. | ||||
10283 | sInt = Info.Ctx.MakeIntValue(0, EltTy); | ||||
10284 | Elements.push_back(APValue(sInt)); | ||||
10285 | CountElts++; | ||||
10286 | } else { | ||||
10287 | llvm::APFloat f(0.0); | ||||
10288 | if (CountInits < NumInits) { | ||||
10289 | if (!EvaluateFloat(E->getInit(CountInits), f, Info)) | ||||
10290 | return false; | ||||
10291 | } else // trailing float zero. | ||||
10292 | f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); | ||||
10293 | Elements.push_back(APValue(f)); | ||||
10294 | CountElts++; | ||||
10295 | } | ||||
10296 | CountInits++; | ||||
10297 | } | ||||
10298 | return Success(Elements, E); | ||||
10299 | } | ||||
10300 | |||||
10301 | bool | ||||
10302 | VectorExprEvaluator::ZeroInitialization(const Expr *E) { | ||||
10303 | const auto *VT = E->getType()->castAs<VectorType>(); | ||||
10304 | QualType EltTy = VT->getElementType(); | ||||
10305 | APValue ZeroElement; | ||||
10306 | if (EltTy->isIntegerType()) | ||||
10307 | ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); | ||||
10308 | else | ||||
10309 | ZeroElement = | ||||
10310 | APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); | ||||
10311 | |||||
10312 | SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); | ||||
10313 | return Success(Elements, E); | ||||
10314 | } | ||||
10315 | |||||
10316 | bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||
10317 | VisitIgnoredValue(E->getSubExpr()); | ||||
10318 | return ZeroInitialization(E); | ||||
10319 | } | ||||
10320 | |||||
10321 | bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
10322 | BinaryOperatorKind Op = E->getOpcode(); | ||||
10323 | assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&(static_cast <bool> (Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && \"Operation not supported on vector types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10324, __extension__ __PRETTY_FUNCTION__)) | ||||
10324 | "Operation not supported on vector types")(static_cast <bool> (Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && \"Operation not supported on vector types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10324, __extension__ __PRETTY_FUNCTION__)); | ||||
10325 | |||||
10326 | if (Op == BO_Comma) | ||||
10327 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
10328 | |||||
10329 | Expr *LHS = E->getLHS(); | ||||
10330 | Expr *RHS = E->getRHS(); | ||||
10331 | |||||
10332 | assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&(static_cast <bool> (LHS->getType()->isVectorType () && RHS->getType()->isVectorType() && "Must both be vector types") ? void (0) : __assert_fail ("LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && \"Must both be vector types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10333, __extension__ __PRETTY_FUNCTION__)) | ||||
10333 | "Must both be vector types")(static_cast <bool> (LHS->getType()->isVectorType () && RHS->getType()->isVectorType() && "Must both be vector types") ? void (0) : __assert_fail ("LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && \"Must both be vector types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10333, __extension__ __PRETTY_FUNCTION__)); | ||||
10334 | // Checking JUST the types are the same would be fine, except shifts don't | ||||
10335 | // need to have their types be the same (since you always shift by an int). | ||||
10336 | assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10340, __extension__ __PRETTY_FUNCTION__)) | ||||
10337 | E->getType()->castAs<VectorType>()->getNumElements() &&(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10340, __extension__ __PRETTY_FUNCTION__)) | ||||
10338 | RHS->getType()->castAs<VectorType>()->getNumElements() ==(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10340, __extension__ __PRETTY_FUNCTION__)) | ||||
10339 | E->getType()->castAs<VectorType>()->getNumElements() &&(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10340, __extension__ __PRETTY_FUNCTION__)) | ||||
10340 | "All operands must be the same size.")(static_cast <bool> (LHS->getType()->castAs<VectorType >()->getNumElements() == E->getType()->castAs< VectorType>()->getNumElements() && RHS->getType ()->castAs<VectorType>()->getNumElements() == E-> getType()->castAs<VectorType>()->getNumElements() && "All operands must be the same size.") ? void (0) : __assert_fail ("LHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && RHS->getType()->castAs<VectorType>()->getNumElements() == E->getType()->castAs<VectorType>()->getNumElements() && \"All operands must be the same size.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10340, __extension__ __PRETTY_FUNCTION__)); | ||||
10341 | |||||
10342 | APValue LHSValue; | ||||
10343 | APValue RHSValue; | ||||
10344 | bool LHSOK = Evaluate(LHSValue, Info, LHS); | ||||
10345 | if (!LHSOK && !Info.noteFailure()) | ||||
10346 | return false; | ||||
10347 | if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) | ||||
10348 | return false; | ||||
10349 | |||||
10350 | if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) | ||||
10351 | return false; | ||||
10352 | |||||
10353 | return Success(LHSValue, E); | ||||
10354 | } | ||||
10355 | |||||
10356 | //===----------------------------------------------------------------------===// | ||||
10357 | // Array Evaluation | ||||
10358 | //===----------------------------------------------------------------------===// | ||||
10359 | |||||
10360 | namespace { | ||||
10361 | class ArrayExprEvaluator | ||||
10362 | : public ExprEvaluatorBase<ArrayExprEvaluator> { | ||||
10363 | const LValue &This; | ||||
10364 | APValue &Result; | ||||
10365 | public: | ||||
10366 | |||||
10367 | ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) | ||||
10368 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} | ||||
10369 | |||||
10370 | bool Success(const APValue &V, const Expr *E) { | ||||
10371 | assert(V.isArray() && "expected array")(static_cast <bool> (V.isArray() && "expected array" ) ? void (0) : __assert_fail ("V.isArray() && \"expected array\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10371, __extension__ __PRETTY_FUNCTION__)); | ||||
10372 | Result = V; | ||||
10373 | return true; | ||||
10374 | } | ||||
10375 | |||||
10376 | bool ZeroInitialization(const Expr *E) { | ||||
10377 | const ConstantArrayType *CAT = | ||||
10378 | Info.Ctx.getAsConstantArrayType(E->getType()); | ||||
10379 | if (!CAT) { | ||||
10380 | if (E->getType()->isIncompleteArrayType()) { | ||||
10381 | // We can be asked to zero-initialize a flexible array member; this | ||||
10382 | // is represented as an ImplicitValueInitExpr of incomplete array | ||||
10383 | // type. In this case, the array has zero elements. | ||||
10384 | Result = APValue(APValue::UninitArray(), 0, 0); | ||||
10385 | return true; | ||||
10386 | } | ||||
10387 | // FIXME: We could handle VLAs here. | ||||
10388 | return Error(E); | ||||
10389 | } | ||||
10390 | |||||
10391 | Result = APValue(APValue::UninitArray(), 0, | ||||
10392 | CAT->getSize().getZExtValue()); | ||||
10393 | if (!Result.hasArrayFiller()) | ||||
10394 | return true; | ||||
10395 | |||||
10396 | // Zero-initialize all elements. | ||||
10397 | LValue Subobject = This; | ||||
10398 | Subobject.addArray(Info, E, CAT); | ||||
10399 | ImplicitValueInitExpr VIE(CAT->getElementType()); | ||||
10400 | return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); | ||||
10401 | } | ||||
10402 | |||||
10403 | bool VisitCallExpr(const CallExpr *E) { | ||||
10404 | return handleCallExpr(E, Result, &This); | ||||
10405 | } | ||||
10406 | bool VisitInitListExpr(const InitListExpr *E, | ||||
10407 | QualType AllocType = QualType()); | ||||
10408 | bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); | ||||
10409 | bool VisitCXXConstructExpr(const CXXConstructExpr *E); | ||||
10410 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||
10411 | const LValue &Subobject, | ||||
10412 | APValue *Value, QualType Type); | ||||
10413 | bool VisitStringLiteral(const StringLiteral *E, | ||||
10414 | QualType AllocType = QualType()) { | ||||
10415 | expandStringLiteral(Info, E, Result, AllocType); | ||||
10416 | return true; | ||||
10417 | } | ||||
10418 | }; | ||||
10419 | } // end anonymous namespace | ||||
10420 | |||||
10421 | static bool EvaluateArray(const Expr *E, const LValue &This, | ||||
10422 | APValue &Result, EvalInfo &Info) { | ||||
10423 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10423, __extension__ __PRETTY_FUNCTION__)); | ||||
10424 | assert(E->isPRValue() && E->getType()->isArrayType() &&(static_cast <bool> (E->isPRValue() && E-> getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isArrayType() && \"not an array prvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10425, __extension__ __PRETTY_FUNCTION__)) | ||||
10425 | "not an array prvalue")(static_cast <bool> (E->isPRValue() && E-> getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isArrayType() && \"not an array prvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10425, __extension__ __PRETTY_FUNCTION__)); | ||||
10426 | return ArrayExprEvaluator(Info, This, Result).Visit(E); | ||||
10427 | } | ||||
10428 | |||||
10429 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, | ||||
10430 | APValue &Result, const InitListExpr *ILE, | ||||
10431 | QualType AllocType) { | ||||
10432 | assert(!ILE->isValueDependent())(static_cast <bool> (!ILE->isValueDependent()) ? void (0) : __assert_fail ("!ILE->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10432, __extension__ __PRETTY_FUNCTION__)); | ||||
10433 | assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&(static_cast <bool> (ILE->isPRValue() && ILE ->getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("ILE->isPRValue() && ILE->getType()->isArrayType() && \"not an array prvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10434, __extension__ __PRETTY_FUNCTION__)) | ||||
10434 | "not an array prvalue")(static_cast <bool> (ILE->isPRValue() && ILE ->getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("ILE->isPRValue() && ILE->getType()->isArrayType() && \"not an array prvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10434, __extension__ __PRETTY_FUNCTION__)); | ||||
10435 | return ArrayExprEvaluator(Info, This, Result) | ||||
10436 | .VisitInitListExpr(ILE, AllocType); | ||||
10437 | } | ||||
10438 | |||||
10439 | static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, | ||||
10440 | APValue &Result, | ||||
10441 | const CXXConstructExpr *CCE, | ||||
10442 | QualType AllocType) { | ||||
10443 | assert(!CCE->isValueDependent())(static_cast <bool> (!CCE->isValueDependent()) ? void (0) : __assert_fail ("!CCE->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10443, __extension__ __PRETTY_FUNCTION__)); | ||||
10444 | assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&(static_cast <bool> (CCE->isPRValue() && CCE ->getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("CCE->isPRValue() && CCE->getType()->isArrayType() && \"not an array prvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10445, __extension__ __PRETTY_FUNCTION__)) | ||||
10445 | "not an array prvalue")(static_cast <bool> (CCE->isPRValue() && CCE ->getType()->isArrayType() && "not an array prvalue" ) ? void (0) : __assert_fail ("CCE->isPRValue() && CCE->getType()->isArrayType() && \"not an array prvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10445, __extension__ __PRETTY_FUNCTION__)); | ||||
10446 | return ArrayExprEvaluator(Info, This, Result) | ||||
10447 | .VisitCXXConstructExpr(CCE, This, &Result, AllocType); | ||||
10448 | } | ||||
10449 | |||||
10450 | // Return true iff the given array filler may depend on the element index. | ||||
10451 | static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { | ||||
10452 | // For now, just allow non-class value-initialization and initialization | ||||
10453 | // lists comprised of them. | ||||
10454 | if (isa<ImplicitValueInitExpr>(FillerExpr)) | ||||
10455 | return false; | ||||
10456 | if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { | ||||
10457 | for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { | ||||
10458 | if (MaybeElementDependentArrayFiller(ILE->getInit(I))) | ||||
10459 | return true; | ||||
10460 | } | ||||
10461 | return false; | ||||
10462 | } | ||||
10463 | return true; | ||||
10464 | } | ||||
10465 | |||||
10466 | bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, | ||||
10467 | QualType AllocType) { | ||||
10468 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( | ||||
10469 | AllocType.isNull() ? E->getType() : AllocType); | ||||
10470 | if (!CAT) | ||||
10471 | return Error(E); | ||||
10472 | |||||
10473 | // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] | ||||
10474 | // an appropriately-typed string literal enclosed in braces. | ||||
10475 | if (E->isStringLiteralInit()) { | ||||
10476 | auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts()); | ||||
10477 | // FIXME: Support ObjCEncodeExpr here once we support it in | ||||
10478 | // ArrayExprEvaluator generally. | ||||
10479 | if (!SL) | ||||
10480 | return Error(E); | ||||
10481 | return VisitStringLiteral(SL, AllocType); | ||||
10482 | } | ||||
10483 | // Any other transparent list init will need proper handling of the | ||||
10484 | // AllocType; we can't just recurse to the inner initializer. | ||||
10485 | assert(!E->isTransparent() &&(static_cast <bool> (!E->isTransparent() && "transparent array list initialization is not string literal init?" ) ? void (0) : __assert_fail ("!E->isTransparent() && \"transparent array list initialization is not string literal init?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10486, __extension__ __PRETTY_FUNCTION__)) | ||||
10486 | "transparent array list initialization is not string literal init?")(static_cast <bool> (!E->isTransparent() && "transparent array list initialization is not string literal init?" ) ? void (0) : __assert_fail ("!E->isTransparent() && \"transparent array list initialization is not string literal init?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10486, __extension__ __PRETTY_FUNCTION__)); | ||||
10487 | |||||
10488 | bool Success = true; | ||||
10489 | |||||
10490 | assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&(static_cast <bool> ((!Result.isArray() || Result.getArrayInitializedElts () == 0) && "zero-initialized array shouldn't have any initialized elts" ) ? void (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10491, __extension__ __PRETTY_FUNCTION__)) | ||||
10491 | "zero-initialized array shouldn't have any initialized elts")(static_cast <bool> ((!Result.isArray() || Result.getArrayInitializedElts () == 0) && "zero-initialized array shouldn't have any initialized elts" ) ? void (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10491, __extension__ __PRETTY_FUNCTION__)); | ||||
10492 | APValue Filler; | ||||
10493 | if (Result.isArray() && Result.hasArrayFiller()) | ||||
10494 | Filler = Result.getArrayFiller(); | ||||
10495 | |||||
10496 | unsigned NumEltsToInit = E->getNumInits(); | ||||
10497 | unsigned NumElts = CAT->getSize().getZExtValue(); | ||||
10498 | const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; | ||||
10499 | |||||
10500 | // If the initializer might depend on the array index, run it for each | ||||
10501 | // array element. | ||||
10502 | if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) | ||||
10503 | NumEltsToInit = NumElts; | ||||
10504 | |||||
10505 | LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: " << NumEltsToInit << ".\n"; } } while (false) | ||||
10506 | << NumEltsToInit << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: " << NumEltsToInit << ".\n"; } } while (false); | ||||
10507 | |||||
10508 | Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); | ||||
10509 | |||||
10510 | // If the array was previously zero-initialized, preserve the | ||||
10511 | // zero-initialized values. | ||||
10512 | if (Filler.hasValue()) { | ||||
10513 | for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) | ||||
10514 | Result.getArrayInitializedElt(I) = Filler; | ||||
10515 | if (Result.hasArrayFiller()) | ||||
10516 | Result.getArrayFiller() = Filler; | ||||
10517 | } | ||||
10518 | |||||
10519 | LValue Subobject = This; | ||||
10520 | Subobject.addArray(Info, E, CAT); | ||||
10521 | for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { | ||||
10522 | const Expr *Init = | ||||
10523 | Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; | ||||
10524 | if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), | ||||
10525 | Info, Subobject, Init) || | ||||
10526 | !HandleLValueArrayAdjustment(Info, Init, Subobject, | ||||
10527 | CAT->getElementType(), 1)) { | ||||
10528 | if (!Info.noteFailure()) | ||||
10529 | return false; | ||||
10530 | Success = false; | ||||
10531 | } | ||||
10532 | } | ||||
10533 | |||||
10534 | if (!Result.hasArrayFiller()) | ||||
10535 | return Success; | ||||
10536 | |||||
10537 | // If we get here, we have a trivial filler, which we can just evaluate | ||||
10538 | // once and splat over the rest of the array elements. | ||||
10539 | assert(FillerExpr && "no array filler for incomplete init list")(static_cast <bool> (FillerExpr && "no array filler for incomplete init list" ) ? void (0) : __assert_fail ("FillerExpr && \"no array filler for incomplete init list\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10539, __extension__ __PRETTY_FUNCTION__)); | ||||
10540 | return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, | ||||
10541 | FillerExpr) && Success; | ||||
10542 | } | ||||
10543 | |||||
10544 | bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { | ||||
10545 | LValue CommonLV; | ||||
10546 | if (E->getCommonExpr() && | ||||
10547 | !Evaluate(Info.CurrentCall->createTemporary( | ||||
10548 | E->getCommonExpr(), | ||||
10549 | getStorageType(Info.Ctx, E->getCommonExpr()), | ||||
10550 | ScopeKind::FullExpression, CommonLV), | ||||
10551 | Info, E->getCommonExpr()->getSourceExpr())) | ||||
10552 | return false; | ||||
10553 | |||||
10554 | auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); | ||||
10555 | |||||
10556 | uint64_t Elements = CAT->getSize().getZExtValue(); | ||||
10557 | Result = APValue(APValue::UninitArray(), Elements, Elements); | ||||
10558 | |||||
10559 | LValue Subobject = This; | ||||
10560 | Subobject.addArray(Info, E, CAT); | ||||
10561 | |||||
10562 | bool Success = true; | ||||
10563 | for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { | ||||
10564 | if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), | ||||
10565 | Info, Subobject, E->getSubExpr()) || | ||||
10566 | !HandleLValueArrayAdjustment(Info, E, Subobject, | ||||
10567 | CAT->getElementType(), 1)) { | ||||
10568 | if (!Info.noteFailure()) | ||||
10569 | return false; | ||||
10570 | Success = false; | ||||
10571 | } | ||||
10572 | } | ||||
10573 | |||||
10574 | return Success; | ||||
10575 | } | ||||
10576 | |||||
10577 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||
10578 | return VisitCXXConstructExpr(E, This, &Result, E->getType()); | ||||
10579 | } | ||||
10580 | |||||
10581 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||
10582 | const LValue &Subobject, | ||||
10583 | APValue *Value, | ||||
10584 | QualType Type) { | ||||
10585 | bool HadZeroInit = Value->hasValue(); | ||||
10586 | |||||
10587 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { | ||||
10588 | unsigned N = CAT->getSize().getZExtValue(); | ||||
10589 | |||||
10590 | // Preserve the array filler if we had prior zero-initialization. | ||||
10591 | APValue Filler = | ||||
10592 | HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() | ||||
10593 | : APValue(); | ||||
10594 | |||||
10595 | *Value = APValue(APValue::UninitArray(), N, N); | ||||
10596 | |||||
10597 | if (HadZeroInit) | ||||
10598 | for (unsigned I = 0; I != N; ++I) | ||||
10599 | Value->getArrayInitializedElt(I) = Filler; | ||||
10600 | |||||
10601 | // Initialize the elements. | ||||
10602 | LValue ArrayElt = Subobject; | ||||
10603 | ArrayElt.addArray(Info, E, CAT); | ||||
10604 | for (unsigned I = 0; I != N; ++I) | ||||
10605 | if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), | ||||
10606 | CAT->getElementType()) || | ||||
10607 | !HandleLValueArrayAdjustment(Info, E, ArrayElt, | ||||
10608 | CAT->getElementType(), 1)) | ||||
10609 | return false; | ||||
10610 | |||||
10611 | return true; | ||||
10612 | } | ||||
10613 | |||||
10614 | if (!Type->isRecordType()) | ||||
10615 | return Error(E); | ||||
10616 | |||||
10617 | return RecordExprEvaluator(Info, Subobject, *Value) | ||||
10618 | .VisitCXXConstructExpr(E, Type); | ||||
10619 | } | ||||
10620 | |||||
10621 | //===----------------------------------------------------------------------===// | ||||
10622 | // Integer Evaluation | ||||
10623 | // | ||||
10624 | // As a GNU extension, we support casting pointers to sufficiently-wide integer | ||||
10625 | // types and back in constant folding. Integer values are thus represented | ||||
10626 | // either as an integer-valued APValue, or as an lvalue-valued APValue. | ||||
10627 | //===----------------------------------------------------------------------===// | ||||
10628 | |||||
10629 | namespace { | ||||
10630 | class IntExprEvaluator | ||||
10631 | : public ExprEvaluatorBase<IntExprEvaluator> { | ||||
10632 | APValue &Result; | ||||
10633 | public: | ||||
10634 | IntExprEvaluator(EvalInfo &info, APValue &result) | ||||
10635 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||
10636 | |||||
10637 | bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { | ||||
10638 | assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10639, __extension__ __PRETTY_FUNCTION__)) | ||||
10639 | "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10639, __extension__ __PRETTY_FUNCTION__)); | ||||
10640 | assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&(static_cast <bool> (SI.isSigned() == E->getType()-> isSignedIntegerOrEnumerationType() && "Invalid evaluation result." ) ? void (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10641, __extension__ __PRETTY_FUNCTION__)) | ||||
10641 | "Invalid evaluation result.")(static_cast <bool> (SI.isSigned() == E->getType()-> isSignedIntegerOrEnumerationType() && "Invalid evaluation result." ) ? void (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10641, __extension__ __PRETTY_FUNCTION__)); | ||||
10642 | assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (SI.getBitWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10643, __extension__ __PRETTY_FUNCTION__)) | ||||
10643 | "Invalid evaluation result.")(static_cast <bool> (SI.getBitWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10643, __extension__ __PRETTY_FUNCTION__)); | ||||
10644 | Result = APValue(SI); | ||||
10645 | return true; | ||||
10646 | } | ||||
10647 | bool Success(const llvm::APSInt &SI, const Expr *E) { | ||||
10648 | return Success(SI, E, Result); | ||||
10649 | } | ||||
10650 | |||||
10651 | bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { | ||||
10652 | assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10653, __extension__ __PRETTY_FUNCTION__)) | ||||
10653 | "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10653, __extension__ __PRETTY_FUNCTION__)); | ||||
10654 | assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (I.getBitWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10655, __extension__ __PRETTY_FUNCTION__)) | ||||
10655 | "Invalid evaluation result.")(static_cast <bool> (I.getBitWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10655, __extension__ __PRETTY_FUNCTION__)); | ||||
10656 | Result = APValue(APSInt(I)); | ||||
10657 | Result.getInt().setIsUnsigned( | ||||
10658 | E->getType()->isUnsignedIntegerOrEnumerationType()); | ||||
10659 | return true; | ||||
10660 | } | ||||
10661 | bool Success(const llvm::APInt &I, const Expr *E) { | ||||
10662 | return Success(I, E, Result); | ||||
10663 | } | ||||
10664 | |||||
10665 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { | ||||
10666 | assert(E->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10667, __extension__ __PRETTY_FUNCTION__)) | ||||
10667 | "Invalid evaluation result.")(static_cast <bool> (E->getType()->isIntegralOrEnumerationType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10667, __extension__ __PRETTY_FUNCTION__)); | ||||
10668 | Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); | ||||
10669 | return true; | ||||
10670 | } | ||||
10671 | bool Success(uint64_t Value, const Expr *E) { | ||||
10672 | return Success(Value, E, Result); | ||||
10673 | } | ||||
10674 | |||||
10675 | bool Success(CharUnits Size, const Expr *E) { | ||||
10676 | return Success(Size.getQuantity(), E); | ||||
10677 | } | ||||
10678 | |||||
10679 | bool Success(const APValue &V, const Expr *E) { | ||||
10680 | if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { | ||||
10681 | Result = V; | ||||
10682 | return true; | ||||
10683 | } | ||||
10684 | return Success(V.getInt(), E); | ||||
10685 | } | ||||
10686 | |||||
10687 | bool ZeroInitialization(const Expr *E) { return Success(0, E); } | ||||
10688 | |||||
10689 | //===--------------------------------------------------------------------===// | ||||
10690 | // Visitor Methods | ||||
10691 | //===--------------------------------------------------------------------===// | ||||
10692 | |||||
10693 | bool VisitIntegerLiteral(const IntegerLiteral *E) { | ||||
10694 | return Success(E->getValue(), E); | ||||
10695 | } | ||||
10696 | bool VisitCharacterLiteral(const CharacterLiteral *E) { | ||||
10697 | return Success(E->getValue(), E); | ||||
10698 | } | ||||
10699 | |||||
10700 | bool CheckReferencedDecl(const Expr *E, const Decl *D); | ||||
10701 | bool VisitDeclRefExpr(const DeclRefExpr *E) { | ||||
10702 | if (CheckReferencedDecl(E, E->getDecl())) | ||||
10703 | return true; | ||||
10704 | |||||
10705 | return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); | ||||
10706 | } | ||||
10707 | bool VisitMemberExpr(const MemberExpr *E) { | ||||
10708 | if (CheckReferencedDecl(E, E->getMemberDecl())) { | ||||
10709 | VisitIgnoredBaseExpression(E->getBase()); | ||||
10710 | return true; | ||||
10711 | } | ||||
10712 | |||||
10713 | return ExprEvaluatorBaseTy::VisitMemberExpr(E); | ||||
10714 | } | ||||
10715 | |||||
10716 | bool VisitCallExpr(const CallExpr *E); | ||||
10717 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); | ||||
10718 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
10719 | bool VisitOffsetOfExpr(const OffsetOfExpr *E); | ||||
10720 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||
10721 | |||||
10722 | bool VisitCastExpr(const CastExpr* E); | ||||
10723 | bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); | ||||
10724 | |||||
10725 | bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { | ||||
10726 | return Success(E->getValue(), E); | ||||
10727 | } | ||||
10728 | |||||
10729 | bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { | ||||
10730 | return Success(E->getValue(), E); | ||||
10731 | } | ||||
10732 | |||||
10733 | bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { | ||||
10734 | if (Info.ArrayInitIndex == uint64_t(-1)) { | ||||
10735 | // We were asked to evaluate this subexpression independent of the | ||||
10736 | // enclosing ArrayInitLoopExpr. We can't do that. | ||||
10737 | Info.FFDiag(E); | ||||
10738 | return false; | ||||
10739 | } | ||||
10740 | return Success(Info.ArrayInitIndex, E); | ||||
10741 | } | ||||
10742 | |||||
10743 | // Note, GNU defines __null as an integer, not a pointer. | ||||
10744 | bool VisitGNUNullExpr(const GNUNullExpr *E) { | ||||
10745 | return ZeroInitialization(E); | ||||
10746 | } | ||||
10747 | |||||
10748 | bool VisitTypeTraitExpr(const TypeTraitExpr *E) { | ||||
10749 | return Success(E->getValue(), E); | ||||
10750 | } | ||||
10751 | |||||
10752 | bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { | ||||
10753 | return Success(E->getValue(), E); | ||||
10754 | } | ||||
10755 | |||||
10756 | bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { | ||||
10757 | return Success(E->getValue(), E); | ||||
10758 | } | ||||
10759 | |||||
10760 | bool VisitUnaryReal(const UnaryOperator *E); | ||||
10761 | bool VisitUnaryImag(const UnaryOperator *E); | ||||
10762 | |||||
10763 | bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); | ||||
10764 | bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); | ||||
10765 | bool VisitSourceLocExpr(const SourceLocExpr *E); | ||||
10766 | bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); | ||||
10767 | bool VisitRequiresExpr(const RequiresExpr *E); | ||||
10768 | // FIXME: Missing: array subscript of vector, member of vector | ||||
10769 | }; | ||||
10770 | |||||
10771 | class FixedPointExprEvaluator | ||||
10772 | : public ExprEvaluatorBase<FixedPointExprEvaluator> { | ||||
10773 | APValue &Result; | ||||
10774 | |||||
10775 | public: | ||||
10776 | FixedPointExprEvaluator(EvalInfo &info, APValue &result) | ||||
10777 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||
10778 | |||||
10779 | bool Success(const llvm::APInt &I, const Expr *E) { | ||||
10780 | return Success( | ||||
10781 | APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); | ||||
10782 | } | ||||
10783 | |||||
10784 | bool Success(uint64_t Value, const Expr *E) { | ||||
10785 | return Success( | ||||
10786 | APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); | ||||
10787 | } | ||||
10788 | |||||
10789 | bool Success(const APValue &V, const Expr *E) { | ||||
10790 | return Success(V.getFixedPoint(), E); | ||||
10791 | } | ||||
10792 | |||||
10793 | bool Success(const APFixedPoint &V, const Expr *E) { | ||||
10794 | assert(E->getType()->isFixedPointType() && "Invalid evaluation result.")(static_cast <bool> (E->getType()->isFixedPointType () && "Invalid evaluation result.") ? void (0) : __assert_fail ("E->getType()->isFixedPointType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10794, __extension__ __PRETTY_FUNCTION__)); | ||||
10795 | assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&(static_cast <bool> (V.getWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10796, __extension__ __PRETTY_FUNCTION__)) | ||||
10796 | "Invalid evaluation result.")(static_cast <bool> (V.getWidth() == Info.Ctx.getIntWidth (E->getType()) && "Invalid evaluation result.") ? void (0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10796, __extension__ __PRETTY_FUNCTION__)); | ||||
10797 | Result = APValue(V); | ||||
10798 | return true; | ||||
10799 | } | ||||
10800 | |||||
10801 | //===--------------------------------------------------------------------===// | ||||
10802 | // Visitor Methods | ||||
10803 | //===--------------------------------------------------------------------===// | ||||
10804 | |||||
10805 | bool VisitFixedPointLiteral(const FixedPointLiteral *E) { | ||||
10806 | return Success(E->getValue(), E); | ||||
10807 | } | ||||
10808 | |||||
10809 | bool VisitCastExpr(const CastExpr *E); | ||||
10810 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||
10811 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
10812 | }; | ||||
10813 | } // end anonymous namespace | ||||
10814 | |||||
10815 | /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and | ||||
10816 | /// produce either the integer value or a pointer. | ||||
10817 | /// | ||||
10818 | /// GCC has a heinous extension which folds casts between pointer types and | ||||
10819 | /// pointer-sized integral types. We support this by allowing the evaluation of | ||||
10820 | /// an integer rvalue to produce a pointer (represented as an lvalue) instead. | ||||
10821 | /// Some simple arithmetic on such values is supported (they are treated much | ||||
10822 | /// like char*). | ||||
10823 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, | ||||
10824 | EvalInfo &Info) { | ||||
10825 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10825, __extension__ __PRETTY_FUNCTION__)); | ||||
10826 | assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->isPRValue() && E-> getType()->isIntegralOrEnumerationType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10826, __extension__ __PRETTY_FUNCTION__)); | ||||
10827 | return IntExprEvaluator(Info, Result).Visit(E); | ||||
10828 | } | ||||
10829 | |||||
10830 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { | ||||
10831 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10831, __extension__ __PRETTY_FUNCTION__)); | ||||
10832 | APValue Val; | ||||
10833 | if (!EvaluateIntegerOrLValue(E, Val, Info)) | ||||
10834 | return false; | ||||
10835 | if (!Val.isInt()) { | ||||
10836 | // FIXME: It would be better to produce the diagnostic for casting | ||||
10837 | // a pointer to an integer. | ||||
10838 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
10839 | return false; | ||||
10840 | } | ||||
10841 | Result = Val.getInt(); | ||||
10842 | return true; | ||||
10843 | } | ||||
10844 | |||||
10845 | bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { | ||||
10846 | APValue Evaluated = E->EvaluateInContext( | ||||
10847 | Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); | ||||
10848 | return Success(Evaluated, E); | ||||
10849 | } | ||||
10850 | |||||
10851 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, | ||||
10852 | EvalInfo &Info) { | ||||
10853 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10853, __extension__ __PRETTY_FUNCTION__)); | ||||
10854 | if (E->getType()->isFixedPointType()) { | ||||
10855 | APValue Val; | ||||
10856 | if (!FixedPointExprEvaluator(Info, Val).Visit(E)) | ||||
10857 | return false; | ||||
10858 | if (!Val.isFixedPoint()) | ||||
10859 | return false; | ||||
10860 | |||||
10861 | Result = Val.getFixedPoint(); | ||||
10862 | return true; | ||||
10863 | } | ||||
10864 | return false; | ||||
10865 | } | ||||
10866 | |||||
10867 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, | ||||
10868 | EvalInfo &Info) { | ||||
10869 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10869, __extension__ __PRETTY_FUNCTION__)); | ||||
10870 | if (E->getType()->isIntegerType()) { | ||||
10871 | auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); | ||||
10872 | APSInt Val; | ||||
10873 | if (!EvaluateInteger(E, Val, Info)) | ||||
10874 | return false; | ||||
10875 | Result = APFixedPoint(Val, FXSema); | ||||
10876 | return true; | ||||
10877 | } else if (E->getType()->isFixedPointType()) { | ||||
10878 | return EvaluateFixedPoint(E, Result, Info); | ||||
10879 | } | ||||
10880 | return false; | ||||
10881 | } | ||||
10882 | |||||
10883 | /// Check whether the given declaration can be directly converted to an integral | ||||
10884 | /// rvalue. If not, no diagnostic is produced; there are other things we can | ||||
10885 | /// try. | ||||
10886 | bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { | ||||
10887 | // Enums are integer constant exprs. | ||||
10888 | if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { | ||||
10889 | // Check for signedness/width mismatches between E type and ECD value. | ||||
10890 | bool SameSign = (ECD->getInitVal().isSigned() | ||||
10891 | == E->getType()->isSignedIntegerOrEnumerationType()); | ||||
10892 | bool SameWidth = (ECD->getInitVal().getBitWidth() | ||||
10893 | == Info.Ctx.getIntWidth(E->getType())); | ||||
10894 | if (SameSign && SameWidth) | ||||
10895 | return Success(ECD->getInitVal(), E); | ||||
10896 | else { | ||||
10897 | // Get rid of mismatch (otherwise Success assertions will fail) | ||||
10898 | // by computing a new value matching the type of E. | ||||
10899 | llvm::APSInt Val = ECD->getInitVal(); | ||||
10900 | if (!SameSign) | ||||
10901 | Val.setIsSigned(!ECD->getInitVal().isSigned()); | ||||
10902 | if (!SameWidth) | ||||
10903 | Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); | ||||
10904 | return Success(Val, E); | ||||
10905 | } | ||||
10906 | } | ||||
10907 | return false; | ||||
10908 | } | ||||
10909 | |||||
10910 | /// Values returned by __builtin_classify_type, chosen to match the values | ||||
10911 | /// produced by GCC's builtin. | ||||
10912 | enum class GCCTypeClass { | ||||
10913 | None = -1, | ||||
10914 | Void = 0, | ||||
10915 | Integer = 1, | ||||
10916 | // GCC reserves 2 for character types, but instead classifies them as | ||||
10917 | // integers. | ||||
10918 | Enum = 3, | ||||
10919 | Bool = 4, | ||||
10920 | Pointer = 5, | ||||
10921 | // GCC reserves 6 for references, but appears to never use it (because | ||||
10922 | // expressions never have reference type, presumably). | ||||
10923 | PointerToDataMember = 7, | ||||
10924 | RealFloat = 8, | ||||
10925 | Complex = 9, | ||||
10926 | // GCC reserves 10 for functions, but does not use it since GCC version 6 due | ||||
10927 | // to decay to pointer. (Prior to version 6 it was only used in C++ mode). | ||||
10928 | // GCC claims to reserve 11 for pointers to member functions, but *actually* | ||||
10929 | // uses 12 for that purpose, same as for a class or struct. Maybe it | ||||
10930 | // internally implements a pointer to member as a struct? Who knows. | ||||
10931 | PointerToMemberFunction = 12, // Not a bug, see above. | ||||
10932 | ClassOrStruct = 12, | ||||
10933 | Union = 13, | ||||
10934 | // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to | ||||
10935 | // decay to pointer. (Prior to version 6 it was only used in C++ mode). | ||||
10936 | // GCC reserves 15 for strings, but actually uses 5 (pointer) for string | ||||
10937 | // literals. | ||||
10938 | }; | ||||
10939 | |||||
10940 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way | ||||
10941 | /// as GCC. | ||||
10942 | static GCCTypeClass | ||||
10943 | EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { | ||||
10944 | assert(!T->isDependentType() && "unexpected dependent type")(static_cast <bool> (!T->isDependentType() && "unexpected dependent type") ? void (0) : __assert_fail ("!T->isDependentType() && \"unexpected dependent type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10944, __extension__ __PRETTY_FUNCTION__)); | ||||
10945 | |||||
10946 | QualType CanTy = T.getCanonicalType(); | ||||
10947 | const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); | ||||
10948 | |||||
10949 | switch (CanTy->getTypeClass()) { | ||||
10950 | #define TYPE(ID, BASE) | ||||
10951 | #define DEPENDENT_TYPE(ID, BASE) case Type::ID: | ||||
10952 | #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: | ||||
10953 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: | ||||
10954 | #include "clang/AST/TypeNodes.inc" | ||||
10955 | case Type::Auto: | ||||
10956 | case Type::DeducedTemplateSpecialization: | ||||
10957 | llvm_unreachable("unexpected non-canonical or dependent type")::llvm::llvm_unreachable_internal("unexpected non-canonical or dependent type" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 10957); | ||||
10958 | |||||
10959 | case Type::Builtin: | ||||
10960 | switch (BT->getKind()) { | ||||
10961 | #define BUILTIN_TYPE(ID, SINGLETON_ID) | ||||
10962 | #define SIGNED_TYPE(ID, SINGLETON_ID) \ | ||||
10963 | case BuiltinType::ID: return GCCTypeClass::Integer; | ||||
10964 | #define FLOATING_TYPE(ID, SINGLETON_ID) \ | ||||
10965 | case BuiltinType::ID: return GCCTypeClass::RealFloat; | ||||
10966 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ | ||||
10967 | case BuiltinType::ID: break; | ||||
10968 | #include "clang/AST/BuiltinTypes.def" | ||||
10969 | case BuiltinType::Void: | ||||
10970 | return GCCTypeClass::Void; | ||||
10971 | |||||
10972 | case BuiltinType::Bool: | ||||
10973 | return GCCTypeClass::Bool; | ||||
10974 | |||||
10975 | case BuiltinType::Char_U: | ||||
10976 | case BuiltinType::UChar: | ||||
10977 | case BuiltinType::WChar_U: | ||||
10978 | case BuiltinType::Char8: | ||||
10979 | case BuiltinType::Char16: | ||||
10980 | case BuiltinType::Char32: | ||||
10981 | case BuiltinType::UShort: | ||||
10982 | case BuiltinType::UInt: | ||||
10983 | case BuiltinType::ULong: | ||||
10984 | case BuiltinType::ULongLong: | ||||
10985 | case BuiltinType::UInt128: | ||||
10986 | return GCCTypeClass::Integer; | ||||
10987 | |||||
10988 | case BuiltinType::UShortAccum: | ||||
10989 | case BuiltinType::UAccum: | ||||
10990 | case BuiltinType::ULongAccum: | ||||
10991 | case BuiltinType::UShortFract: | ||||
10992 | case BuiltinType::UFract: | ||||
10993 | case BuiltinType::ULongFract: | ||||
10994 | case BuiltinType::SatUShortAccum: | ||||
10995 | case BuiltinType::SatUAccum: | ||||
10996 | case BuiltinType::SatULongAccum: | ||||
10997 | case BuiltinType::SatUShortFract: | ||||
10998 | case BuiltinType::SatUFract: | ||||
10999 | case BuiltinType::SatULongFract: | ||||
11000 | return GCCTypeClass::None; | ||||
11001 | |||||
11002 | case BuiltinType::NullPtr: | ||||
11003 | |||||
11004 | case BuiltinType::ObjCId: | ||||
11005 | case BuiltinType::ObjCClass: | ||||
11006 | case BuiltinType::ObjCSel: | ||||
11007 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
11008 | case BuiltinType::Id: | ||||
11009 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
11010 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
11011 | case BuiltinType::Id: | ||||
11012 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
11013 | case BuiltinType::OCLSampler: | ||||
11014 | case BuiltinType::OCLEvent: | ||||
11015 | case BuiltinType::OCLClkEvent: | ||||
11016 | case BuiltinType::OCLQueue: | ||||
11017 | case BuiltinType::OCLReserveID: | ||||
11018 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
11019 | case BuiltinType::Id: | ||||
11020 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
11021 | #define PPC_VECTOR_TYPE(Name, Id, Size) \ | ||||
11022 | case BuiltinType::Id: | ||||
11023 | #include "clang/Basic/PPCTypes.def" | ||||
11024 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: | ||||
11025 | #include "clang/Basic/RISCVVTypes.def" | ||||
11026 | return GCCTypeClass::None; | ||||
11027 | |||||
11028 | case BuiltinType::Dependent: | ||||
11029 | llvm_unreachable("unexpected dependent type")::llvm::llvm_unreachable_internal("unexpected dependent type" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11029); | ||||
11030 | }; | ||||
11031 | llvm_unreachable("unexpected placeholder type")::llvm::llvm_unreachable_internal("unexpected placeholder type" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11031); | ||||
11032 | |||||
11033 | case Type::Enum: | ||||
11034 | return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; | ||||
11035 | |||||
11036 | case Type::Pointer: | ||||
11037 | case Type::ConstantArray: | ||||
11038 | case Type::VariableArray: | ||||
11039 | case Type::IncompleteArray: | ||||
11040 | case Type::FunctionNoProto: | ||||
11041 | case Type::FunctionProto: | ||||
11042 | return GCCTypeClass::Pointer; | ||||
11043 | |||||
11044 | case Type::MemberPointer: | ||||
11045 | return CanTy->isMemberDataPointerType() | ||||
11046 | ? GCCTypeClass::PointerToDataMember | ||||
11047 | : GCCTypeClass::PointerToMemberFunction; | ||||
11048 | |||||
11049 | case Type::Complex: | ||||
11050 | return GCCTypeClass::Complex; | ||||
11051 | |||||
11052 | case Type::Record: | ||||
11053 | return CanTy->isUnionType() ? GCCTypeClass::Union | ||||
11054 | : GCCTypeClass::ClassOrStruct; | ||||
11055 | |||||
11056 | case Type::Atomic: | ||||
11057 | // GCC classifies _Atomic T the same as T. | ||||
11058 | return EvaluateBuiltinClassifyType( | ||||
11059 | CanTy->castAs<AtomicType>()->getValueType(), LangOpts); | ||||
11060 | |||||
11061 | case Type::BlockPointer: | ||||
11062 | case Type::Vector: | ||||
11063 | case Type::ExtVector: | ||||
11064 | case Type::ConstantMatrix: | ||||
11065 | case Type::ObjCObject: | ||||
11066 | case Type::ObjCInterface: | ||||
11067 | case Type::ObjCObjectPointer: | ||||
11068 | case Type::Pipe: | ||||
11069 | case Type::ExtInt: | ||||
11070 | // GCC classifies vectors as None. We follow its lead and classify all | ||||
11071 | // other types that don't fit into the regular classification the same way. | ||||
11072 | return GCCTypeClass::None; | ||||
11073 | |||||
11074 | case Type::LValueReference: | ||||
11075 | case Type::RValueReference: | ||||
11076 | llvm_unreachable("invalid type for expression")::llvm::llvm_unreachable_internal("invalid type for expression" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11076); | ||||
11077 | } | ||||
11078 | |||||
11079 | llvm_unreachable("unexpected type class")::llvm::llvm_unreachable_internal("unexpected type class", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11079); | ||||
11080 | } | ||||
11081 | |||||
11082 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way | ||||
11083 | /// as GCC. | ||||
11084 | static GCCTypeClass | ||||
11085 | EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { | ||||
11086 | // If no argument was supplied, default to None. This isn't | ||||
11087 | // ideal, however it is what gcc does. | ||||
11088 | if (E->getNumArgs() == 0) | ||||
11089 | return GCCTypeClass::None; | ||||
11090 | |||||
11091 | // FIXME: Bizarrely, GCC treats a call with more than one argument as not | ||||
11092 | // being an ICE, but still folds it to a constant using the type of the first | ||||
11093 | // argument. | ||||
11094 | return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); | ||||
11095 | } | ||||
11096 | |||||
11097 | /// EvaluateBuiltinConstantPForLValue - Determine the result of | ||||
11098 | /// __builtin_constant_p when applied to the given pointer. | ||||
11099 | /// | ||||
11100 | /// A pointer is only "constant" if it is null (or a pointer cast to integer) | ||||
11101 | /// or it points to the first character of a string literal. | ||||
11102 | static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { | ||||
11103 | APValue::LValueBase Base = LV.getLValueBase(); | ||||
11104 | if (Base.isNull()) { | ||||
11105 | // A null base is acceptable. | ||||
11106 | return true; | ||||
11107 | } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { | ||||
11108 | if (!isa<StringLiteral>(E)) | ||||
11109 | return false; | ||||
11110 | return LV.getLValueOffset().isZero(); | ||||
11111 | } else if (Base.is<TypeInfoLValue>()) { | ||||
11112 | // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to | ||||
11113 | // evaluate to true. | ||||
11114 | return true; | ||||
11115 | } else { | ||||
11116 | // Any other base is not constant enough for GCC. | ||||
11117 | return false; | ||||
11118 | } | ||||
11119 | } | ||||
11120 | |||||
11121 | /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to | ||||
11122 | /// GCC as we can manage. | ||||
11123 | static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { | ||||
11124 | // This evaluation is not permitted to have side-effects, so evaluate it in | ||||
11125 | // a speculative evaluation context. | ||||
11126 | SpeculativeEvaluationRAII SpeculativeEval(Info); | ||||
11127 | |||||
11128 | // Constant-folding is always enabled for the operand of __builtin_constant_p | ||||
11129 | // (even when the enclosing evaluation context otherwise requires a strict | ||||
11130 | // language-specific constant expression). | ||||
11131 | FoldConstant Fold(Info, true); | ||||
11132 | |||||
11133 | QualType ArgType = Arg->getType(); | ||||
11134 | |||||
11135 | // __builtin_constant_p always has one operand. The rules which gcc follows | ||||
11136 | // are not precisely documented, but are as follows: | ||||
11137 | // | ||||
11138 | // - If the operand is of integral, floating, complex or enumeration type, | ||||
11139 | // and can be folded to a known value of that type, it returns 1. | ||||
11140 | // - If the operand can be folded to a pointer to the first character | ||||
11141 | // of a string literal (or such a pointer cast to an integral type) | ||||
11142 | // or to a null pointer or an integer cast to a pointer, it returns 1. | ||||
11143 | // | ||||
11144 | // Otherwise, it returns 0. | ||||
11145 | // | ||||
11146 | // FIXME: GCC also intends to return 1 for literals of aggregate types, but | ||||
11147 | // its support for this did not work prior to GCC 9 and is not yet well | ||||
11148 | // understood. | ||||
11149 | if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || | ||||
11150 | ArgType->isAnyComplexType() || ArgType->isPointerType() || | ||||
11151 | ArgType->isNullPtrType()) { | ||||
11152 | APValue V; | ||||
11153 | if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { | ||||
11154 | Fold.keepDiagnostics(); | ||||
11155 | return false; | ||||
11156 | } | ||||
11157 | |||||
11158 | // For a pointer (possibly cast to integer), there are special rules. | ||||
11159 | if (V.getKind() == APValue::LValue) | ||||
11160 | return EvaluateBuiltinConstantPForLValue(V); | ||||
11161 | |||||
11162 | // Otherwise, any constant value is good enough. | ||||
11163 | return V.hasValue(); | ||||
11164 | } | ||||
11165 | |||||
11166 | // Anything else isn't considered to be sufficiently constant. | ||||
11167 | return false; | ||||
11168 | } | ||||
11169 | |||||
11170 | /// Retrieves the "underlying object type" of the given expression, | ||||
11171 | /// as used by __builtin_object_size. | ||||
11172 | static QualType getObjectType(APValue::LValueBase B) { | ||||
11173 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | ||||
11174 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
11175 | return VD->getType(); | ||||
11176 | } else if (const Expr *E = B.dyn_cast<const Expr*>()) { | ||||
11177 | if (isa<CompoundLiteralExpr>(E)) | ||||
11178 | return E->getType(); | ||||
11179 | } else if (B.is<TypeInfoLValue>()) { | ||||
11180 | return B.getTypeInfoType(); | ||||
11181 | } else if (B.is<DynamicAllocLValue>()) { | ||||
11182 | return B.getDynamicAllocType(); | ||||
11183 | } | ||||
11184 | |||||
11185 | return QualType(); | ||||
11186 | } | ||||
11187 | |||||
11188 | /// A more selective version of E->IgnoreParenCasts for | ||||
11189 | /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only | ||||
11190 | /// to change the type of E. | ||||
11191 | /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` | ||||
11192 | /// | ||||
11193 | /// Always returns an RValue with a pointer representation. | ||||
11194 | static const Expr *ignorePointerCastsAndParens(const Expr *E) { | ||||
11195 | assert(E->isPRValue() && E->getType()->hasPointerRepresentation())(static_cast <bool> (E->isPRValue() && E-> getType()->hasPointerRepresentation()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->hasPointerRepresentation()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11195, __extension__ __PRETTY_FUNCTION__)); | ||||
11196 | |||||
11197 | auto *NoParens = E->IgnoreParens(); | ||||
11198 | auto *Cast = dyn_cast<CastExpr>(NoParens); | ||||
11199 | if (Cast == nullptr) | ||||
11200 | return NoParens; | ||||
11201 | |||||
11202 | // We only conservatively allow a few kinds of casts, because this code is | ||||
11203 | // inherently a simple solution that seeks to support the common case. | ||||
11204 | auto CastKind = Cast->getCastKind(); | ||||
11205 | if (CastKind != CK_NoOp && CastKind != CK_BitCast && | ||||
11206 | CastKind != CK_AddressSpaceConversion) | ||||
11207 | return NoParens; | ||||
11208 | |||||
11209 | auto *SubExpr = Cast->getSubExpr(); | ||||
11210 | if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue()) | ||||
11211 | return NoParens; | ||||
11212 | return ignorePointerCastsAndParens(SubExpr); | ||||
11213 | } | ||||
11214 | |||||
11215 | /// Checks to see if the given LValue's Designator is at the end of the LValue's | ||||
11216 | /// record layout. e.g. | ||||
11217 | /// struct { struct { int a, b; } fst, snd; } obj; | ||||
11218 | /// obj.fst // no | ||||
11219 | /// obj.snd // yes | ||||
11220 | /// obj.fst.a // no | ||||
11221 | /// obj.fst.b // no | ||||
11222 | /// obj.snd.a // no | ||||
11223 | /// obj.snd.b // yes | ||||
11224 | /// | ||||
11225 | /// Please note: this function is specialized for how __builtin_object_size | ||||
11226 | /// views "objects". | ||||
11227 | /// | ||||
11228 | /// If this encounters an invalid RecordDecl or otherwise cannot determine the | ||||
11229 | /// correct result, it will always return true. | ||||
11230 | static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { | ||||
11231 | assert(!LVal.Designator.Invalid)(static_cast <bool> (!LVal.Designator.Invalid) ? void ( 0) : __assert_fail ("!LVal.Designator.Invalid", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11231, __extension__ __PRETTY_FUNCTION__)); | ||||
11232 | |||||
11233 | auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { | ||||
11234 | const RecordDecl *Parent = FD->getParent(); | ||||
11235 | Invalid = Parent->isInvalidDecl(); | ||||
11236 | if (Invalid || Parent->isUnion()) | ||||
11237 | return true; | ||||
11238 | const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); | ||||
11239 | return FD->getFieldIndex() + 1 == Layout.getFieldCount(); | ||||
11240 | }; | ||||
11241 | |||||
11242 | auto &Base = LVal.getLValueBase(); | ||||
11243 | if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { | ||||
11244 | if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { | ||||
11245 | bool Invalid; | ||||
11246 | if (!IsLastOrInvalidFieldDecl(FD, Invalid)) | ||||
11247 | return Invalid; | ||||
11248 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { | ||||
11249 | for (auto *FD : IFD->chain()) { | ||||
11250 | bool Invalid; | ||||
11251 | if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) | ||||
11252 | return Invalid; | ||||
11253 | } | ||||
11254 | } | ||||
11255 | } | ||||
11256 | |||||
11257 | unsigned I = 0; | ||||
11258 | QualType BaseType = getType(Base); | ||||
11259 | if (LVal.Designator.FirstEntryIsAnUnsizedArray) { | ||||
11260 | // If we don't know the array bound, conservatively assume we're looking at | ||||
11261 | // the final array element. | ||||
11262 | ++I; | ||||
11263 | if (BaseType->isIncompleteArrayType()) | ||||
11264 | BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); | ||||
11265 | else | ||||
11266 | BaseType = BaseType->castAs<PointerType>()->getPointeeType(); | ||||
11267 | } | ||||
11268 | |||||
11269 | for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { | ||||
11270 | const auto &Entry = LVal.Designator.Entries[I]; | ||||
11271 | if (BaseType->isArrayType()) { | ||||
11272 | // Because __builtin_object_size treats arrays as objects, we can ignore | ||||
11273 | // the index iff this is the last array in the Designator. | ||||
11274 | if (I + 1 == E) | ||||
11275 | return true; | ||||
11276 | const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); | ||||
11277 | uint64_t Index = Entry.getAsArrayIndex(); | ||||
11278 | if (Index + 1 != CAT->getSize()) | ||||
11279 | return false; | ||||
11280 | BaseType = CAT->getElementType(); | ||||
11281 | } else if (BaseType->isAnyComplexType()) { | ||||
11282 | const auto *CT = BaseType->castAs<ComplexType>(); | ||||
11283 | uint64_t Index = Entry.getAsArrayIndex(); | ||||
11284 | if (Index != 1) | ||||
11285 | return false; | ||||
11286 | BaseType = CT->getElementType(); | ||||
11287 | } else if (auto *FD = getAsField(Entry)) { | ||||
11288 | bool Invalid; | ||||
11289 | if (!IsLastOrInvalidFieldDecl(FD, Invalid)) | ||||
11290 | return Invalid; | ||||
11291 | BaseType = FD->getType(); | ||||
11292 | } else { | ||||
11293 | assert(getAsBaseClass(Entry) && "Expecting cast to a base class")(static_cast <bool> (getAsBaseClass(Entry) && "Expecting cast to a base class" ) ? void (0) : __assert_fail ("getAsBaseClass(Entry) && \"Expecting cast to a base class\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11293, __extension__ __PRETTY_FUNCTION__)); | ||||
11294 | return false; | ||||
11295 | } | ||||
11296 | } | ||||
11297 | return true; | ||||
11298 | } | ||||
11299 | |||||
11300 | /// Tests to see if the LValue has a user-specified designator (that isn't | ||||
11301 | /// necessarily valid). Note that this always returns 'true' if the LValue has | ||||
11302 | /// an unsized array as its first designator entry, because there's currently no | ||||
11303 | /// way to tell if the user typed *foo or foo[0]. | ||||
11304 | static bool refersToCompleteObject(const LValue &LVal) { | ||||
11305 | if (LVal.Designator.Invalid) | ||||
11306 | return false; | ||||
11307 | |||||
11308 | if (!LVal.Designator.Entries.empty()) | ||||
11309 | return LVal.Designator.isMostDerivedAnUnsizedArray(); | ||||
11310 | |||||
11311 | if (!LVal.InvalidBase) | ||||
11312 | return true; | ||||
11313 | |||||
11314 | // If `E` is a MemberExpr, then the first part of the designator is hiding in | ||||
11315 | // the LValueBase. | ||||
11316 | const auto *E = LVal.Base.dyn_cast<const Expr *>(); | ||||
11317 | return !E || !isa<MemberExpr>(E); | ||||
11318 | } | ||||
11319 | |||||
11320 | /// Attempts to detect a user writing into a piece of memory that's impossible | ||||
11321 | /// to figure out the size of by just using types. | ||||
11322 | static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { | ||||
11323 | const SubobjectDesignator &Designator = LVal.Designator; | ||||
11324 | // Notes: | ||||
11325 | // - Users can only write off of the end when we have an invalid base. Invalid | ||||
11326 | // bases imply we don't know where the memory came from. | ||||
11327 | // - We used to be a bit more aggressive here; we'd only be conservative if | ||||
11328 | // the array at the end was flexible, or if it had 0 or 1 elements. This | ||||
11329 | // broke some common standard library extensions (PR30346), but was | ||||
11330 | // otherwise seemingly fine. It may be useful to reintroduce this behavior | ||||
11331 | // with some sort of list. OTOH, it seems that GCC is always | ||||
11332 | // conservative with the last element in structs (if it's an array), so our | ||||
11333 | // current behavior is more compatible than an explicit list approach would | ||||
11334 | // be. | ||||
11335 | return LVal.InvalidBase && | ||||
11336 | Designator.Entries.size() == Designator.MostDerivedPathLength && | ||||
11337 | Designator.MostDerivedIsArrayElement && | ||||
11338 | isDesignatorAtObjectEnd(Ctx, LVal); | ||||
11339 | } | ||||
11340 | |||||
11341 | /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. | ||||
11342 | /// Fails if the conversion would cause loss of precision. | ||||
11343 | static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, | ||||
11344 | CharUnits &Result) { | ||||
11345 | auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); | ||||
11346 | if (Int.ugt(CharUnitsMax)) | ||||
11347 | return false; | ||||
11348 | Result = CharUnits::fromQuantity(Int.getZExtValue()); | ||||
11349 | return true; | ||||
11350 | } | ||||
11351 | |||||
11352 | /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will | ||||
11353 | /// determine how many bytes exist from the beginning of the object to either | ||||
11354 | /// the end of the current subobject, or the end of the object itself, depending | ||||
11355 | /// on what the LValue looks like + the value of Type. | ||||
11356 | /// | ||||
11357 | /// If this returns false, the value of Result is undefined. | ||||
11358 | static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, | ||||
11359 | unsigned Type, const LValue &LVal, | ||||
11360 | CharUnits &EndOffset) { | ||||
11361 | bool DetermineForCompleteObject = refersToCompleteObject(LVal); | ||||
11362 | |||||
11363 | auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { | ||||
11364 | if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) | ||||
11365 | return false; | ||||
11366 | return HandleSizeof(Info, ExprLoc, Ty, Result); | ||||
11367 | }; | ||||
11368 | |||||
11369 | // We want to evaluate the size of the entire object. This is a valid fallback | ||||
11370 | // for when Type=1 and the designator is invalid, because we're asked for an | ||||
11371 | // upper-bound. | ||||
11372 | if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { | ||||
11373 | // Type=3 wants a lower bound, so we can't fall back to this. | ||||
11374 | if (Type == 3 && !DetermineForCompleteObject) | ||||
11375 | return false; | ||||
11376 | |||||
11377 | llvm::APInt APEndOffset; | ||||
11378 | if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && | ||||
11379 | getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) | ||||
11380 | return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); | ||||
11381 | |||||
11382 | if (LVal.InvalidBase) | ||||
11383 | return false; | ||||
11384 | |||||
11385 | QualType BaseTy = getObjectType(LVal.getLValueBase()); | ||||
11386 | return CheckedHandleSizeof(BaseTy, EndOffset); | ||||
11387 | } | ||||
11388 | |||||
11389 | // We want to evaluate the size of a subobject. | ||||
11390 | const SubobjectDesignator &Designator = LVal.Designator; | ||||
11391 | |||||
11392 | // The following is a moderately common idiom in C: | ||||
11393 | // | ||||
11394 | // struct Foo { int a; char c[1]; }; | ||||
11395 | // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); | ||||
11396 | // strcpy(&F->c[0], Bar); | ||||
11397 | // | ||||
11398 | // In order to not break too much legacy code, we need to support it. | ||||
11399 | if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { | ||||
11400 | // If we can resolve this to an alloc_size call, we can hand that back, | ||||
11401 | // because we know for certain how many bytes there are to write to. | ||||
11402 | llvm::APInt APEndOffset; | ||||
11403 | if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && | ||||
11404 | getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) | ||||
11405 | return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); | ||||
11406 | |||||
11407 | // If we cannot determine the size of the initial allocation, then we can't | ||||
11408 | // given an accurate upper-bound. However, we are still able to give | ||||
11409 | // conservative lower-bounds for Type=3. | ||||
11410 | if (Type == 1) | ||||
11411 | return false; | ||||
11412 | } | ||||
11413 | |||||
11414 | CharUnits BytesPerElem; | ||||
11415 | if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) | ||||
11416 | return false; | ||||
11417 | |||||
11418 | // According to the GCC documentation, we want the size of the subobject | ||||
11419 | // denoted by the pointer. But that's not quite right -- what we actually | ||||
11420 | // want is the size of the immediately-enclosing array, if there is one. | ||||
11421 | int64_t ElemsRemaining; | ||||
11422 | if (Designator.MostDerivedIsArrayElement && | ||||
11423 | Designator.Entries.size() == Designator.MostDerivedPathLength) { | ||||
11424 | uint64_t ArraySize = Designator.getMostDerivedArraySize(); | ||||
11425 | uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); | ||||
11426 | ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; | ||||
11427 | } else { | ||||
11428 | ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; | ||||
11429 | } | ||||
11430 | |||||
11431 | EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; | ||||
11432 | return true; | ||||
11433 | } | ||||
11434 | |||||
11435 | /// Tries to evaluate the __builtin_object_size for @p E. If successful, | ||||
11436 | /// returns true and stores the result in @p Size. | ||||
11437 | /// | ||||
11438 | /// If @p WasError is non-null, this will report whether the failure to evaluate | ||||
11439 | /// is to be treated as an Error in IntExprEvaluator. | ||||
11440 | static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, | ||||
11441 | EvalInfo &Info, uint64_t &Size) { | ||||
11442 | // Determine the denoted object. | ||||
11443 | LValue LVal; | ||||
11444 | { | ||||
11445 | // The operand of __builtin_object_size is never evaluated for side-effects. | ||||
11446 | // If there are any, but we can determine the pointed-to object anyway, then | ||||
11447 | // ignore the side-effects. | ||||
11448 | SpeculativeEvaluationRAII SpeculativeEval(Info); | ||||
11449 | IgnoreSideEffectsRAII Fold(Info); | ||||
11450 | |||||
11451 | if (E->isGLValue()) { | ||||
11452 | // It's possible for us to be given GLValues if we're called via | ||||
11453 | // Expr::tryEvaluateObjectSize. | ||||
11454 | APValue RVal; | ||||
11455 | if (!EvaluateAsRValue(Info, E, RVal)) | ||||
11456 | return false; | ||||
11457 | LVal.setFrom(Info.Ctx, RVal); | ||||
11458 | } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, | ||||
11459 | /*InvalidBaseOK=*/true)) | ||||
11460 | return false; | ||||
11461 | } | ||||
11462 | |||||
11463 | // If we point to before the start of the object, there are no accessible | ||||
11464 | // bytes. | ||||
11465 | if (LVal.getLValueOffset().isNegative()) { | ||||
11466 | Size = 0; | ||||
11467 | return true; | ||||
11468 | } | ||||
11469 | |||||
11470 | CharUnits EndOffset; | ||||
11471 | if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) | ||||
11472 | return false; | ||||
11473 | |||||
11474 | // If we've fallen outside of the end offset, just pretend there's nothing to | ||||
11475 | // write to/read from. | ||||
11476 | if (EndOffset <= LVal.getLValueOffset()) | ||||
11477 | Size = 0; | ||||
11478 | else | ||||
11479 | Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); | ||||
11480 | return true; | ||||
11481 | } | ||||
11482 | |||||
11483 | bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||
11484 | if (unsigned BuiltinOp = E->getBuiltinCallee()) | ||||
11485 | return VisitBuiltinCallExpr(E, BuiltinOp); | ||||
11486 | |||||
11487 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
11488 | } | ||||
11489 | |||||
11490 | static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, | ||||
11491 | APValue &Val, APSInt &Alignment) { | ||||
11492 | QualType SrcTy = E->getArg(0)->getType(); | ||||
11493 | if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) | ||||
11494 | return false; | ||||
11495 | // Even though we are evaluating integer expressions we could get a pointer | ||||
11496 | // argument for the __builtin_is_aligned() case. | ||||
11497 | if (SrcTy->isPointerType()) { | ||||
11498 | LValue Ptr; | ||||
11499 | if (!EvaluatePointer(E->getArg(0), Ptr, Info)) | ||||
11500 | return false; | ||||
11501 | Ptr.moveInto(Val); | ||||
11502 | } else if (!SrcTy->isIntegralOrEnumerationType()) { | ||||
11503 | Info.FFDiag(E->getArg(0)); | ||||
11504 | return false; | ||||
11505 | } else { | ||||
11506 | APSInt SrcInt; | ||||
11507 | if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) | ||||
11508 | return false; | ||||
11509 | assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&(static_cast <bool> (SrcInt.getBitWidth() >= Alignment .getBitWidth() && "Bit widths must be the same") ? void (0) : __assert_fail ("SrcInt.getBitWidth() >= Alignment.getBitWidth() && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11510, __extension__ __PRETTY_FUNCTION__)) | ||||
11510 | "Bit widths must be the same")(static_cast <bool> (SrcInt.getBitWidth() >= Alignment .getBitWidth() && "Bit widths must be the same") ? void (0) : __assert_fail ("SrcInt.getBitWidth() >= Alignment.getBitWidth() && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11510, __extension__ __PRETTY_FUNCTION__)); | ||||
11511 | Val = APValue(SrcInt); | ||||
11512 | } | ||||
11513 | assert(Val.hasValue())(static_cast <bool> (Val.hasValue()) ? void (0) : __assert_fail ("Val.hasValue()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11513, __extension__ __PRETTY_FUNCTION__)); | ||||
11514 | return true; | ||||
11515 | } | ||||
11516 | |||||
11517 | bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, | ||||
11518 | unsigned BuiltinOp) { | ||||
11519 | switch (BuiltinOp) { | ||||
11520 | default: | ||||
11521 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
11522 | |||||
11523 | case Builtin::BI__builtin_dynamic_object_size: | ||||
11524 | case Builtin::BI__builtin_object_size: { | ||||
11525 | // The type was checked when we built the expression. | ||||
11526 | unsigned Type = | ||||
11527 | E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); | ||||
11528 | assert(Type <= 3 && "unexpected type")(static_cast <bool> (Type <= 3 && "unexpected type" ) ? void (0) : __assert_fail ("Type <= 3 && \"unexpected type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11528, __extension__ __PRETTY_FUNCTION__)); | ||||
11529 | |||||
11530 | uint64_t Size; | ||||
11531 | if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) | ||||
11532 | return Success(Size, E); | ||||
11533 | |||||
11534 | if (E->getArg(0)->HasSideEffects(Info.Ctx)) | ||||
11535 | return Success((Type & 2) ? 0 : -1, E); | ||||
11536 | |||||
11537 | // Expression had no side effects, but we couldn't statically determine the | ||||
11538 | // size of the referenced object. | ||||
11539 | switch (Info.EvalMode) { | ||||
11540 | case EvalInfo::EM_ConstantExpression: | ||||
11541 | case EvalInfo::EM_ConstantFold: | ||||
11542 | case EvalInfo::EM_IgnoreSideEffects: | ||||
11543 | // Leave it to IR generation. | ||||
11544 | return Error(E); | ||||
11545 | case EvalInfo::EM_ConstantExpressionUnevaluated: | ||||
11546 | // Reduce it to a constant now. | ||||
11547 | return Success((Type & 2) ? 0 : -1, E); | ||||
11548 | } | ||||
11549 | |||||
11550 | llvm_unreachable("unexpected EvalMode")::llvm::llvm_unreachable_internal("unexpected EvalMode", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11550); | ||||
11551 | } | ||||
11552 | |||||
11553 | case Builtin::BI__builtin_os_log_format_buffer_size: { | ||||
11554 | analyze_os_log::OSLogBufferLayout Layout; | ||||
11555 | analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); | ||||
11556 | return Success(Layout.size().getQuantity(), E); | ||||
11557 | } | ||||
11558 | |||||
11559 | case Builtin::BI__builtin_is_aligned: { | ||||
11560 | APValue Src; | ||||
11561 | APSInt Alignment; | ||||
11562 | if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) | ||||
11563 | return false; | ||||
11564 | if (Src.isLValue()) { | ||||
11565 | // If we evaluated a pointer, check the minimum known alignment. | ||||
11566 | LValue Ptr; | ||||
11567 | Ptr.setFrom(Info.Ctx, Src); | ||||
11568 | CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); | ||||
11569 | CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); | ||||
11570 | // We can return true if the known alignment at the computed offset is | ||||
11571 | // greater than the requested alignment. | ||||
11572 | assert(PtrAlign.isPowerOfTwo())(static_cast <bool> (PtrAlign.isPowerOfTwo()) ? void (0 ) : __assert_fail ("PtrAlign.isPowerOfTwo()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11572, __extension__ __PRETTY_FUNCTION__)); | ||||
11573 | assert(Alignment.isPowerOf2())(static_cast <bool> (Alignment.isPowerOf2()) ? void (0) : __assert_fail ("Alignment.isPowerOf2()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11573, __extension__ __PRETTY_FUNCTION__)); | ||||
11574 | if (PtrAlign.getQuantity() >= Alignment) | ||||
11575 | return Success(1, E); | ||||
11576 | // If the alignment is not known to be sufficient, some cases could still | ||||
11577 | // be aligned at run time. However, if the requested alignment is less or | ||||
11578 | // equal to the base alignment and the offset is not aligned, we know that | ||||
11579 | // the run-time value can never be aligned. | ||||
11580 | if (BaseAlignment.getQuantity() >= Alignment && | ||||
11581 | PtrAlign.getQuantity() < Alignment) | ||||
11582 | return Success(0, E); | ||||
11583 | // Otherwise we can't infer whether the value is sufficiently aligned. | ||||
11584 | // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) | ||||
11585 | // in cases where we can't fully evaluate the pointer. | ||||
11586 | Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) | ||||
11587 | << Alignment; | ||||
11588 | return false; | ||||
11589 | } | ||||
11590 | assert(Src.isInt())(static_cast <bool> (Src.isInt()) ? void (0) : __assert_fail ("Src.isInt()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11590, __extension__ __PRETTY_FUNCTION__)); | ||||
11591 | return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); | ||||
11592 | } | ||||
11593 | case Builtin::BI__builtin_align_up: { | ||||
11594 | APValue Src; | ||||
11595 | APSInt Alignment; | ||||
11596 | if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) | ||||
11597 | return false; | ||||
11598 | if (!Src.isInt()) | ||||
11599 | return Error(E); | ||||
11600 | APSInt AlignedVal = | ||||
11601 | APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), | ||||
11602 | Src.getInt().isUnsigned()); | ||||
11603 | assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth())(static_cast <bool> (AlignedVal.getBitWidth() == Src.getInt ().getBitWidth()) ? void (0) : __assert_fail ("AlignedVal.getBitWidth() == Src.getInt().getBitWidth()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11603, __extension__ __PRETTY_FUNCTION__)); | ||||
11604 | return Success(AlignedVal, E); | ||||
11605 | } | ||||
11606 | case Builtin::BI__builtin_align_down: { | ||||
11607 | APValue Src; | ||||
11608 | APSInt Alignment; | ||||
11609 | if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) | ||||
11610 | return false; | ||||
11611 | if (!Src.isInt()) | ||||
11612 | return Error(E); | ||||
11613 | APSInt AlignedVal = | ||||
11614 | APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); | ||||
11615 | assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth())(static_cast <bool> (AlignedVal.getBitWidth() == Src.getInt ().getBitWidth()) ? void (0) : __assert_fail ("AlignedVal.getBitWidth() == Src.getInt().getBitWidth()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11615, __extension__ __PRETTY_FUNCTION__)); | ||||
11616 | return Success(AlignedVal, E); | ||||
11617 | } | ||||
11618 | |||||
11619 | case Builtin::BI__builtin_bitreverse8: | ||||
11620 | case Builtin::BI__builtin_bitreverse16: | ||||
11621 | case Builtin::BI__builtin_bitreverse32: | ||||
11622 | case Builtin::BI__builtin_bitreverse64: { | ||||
11623 | APSInt Val; | ||||
11624 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
11625 | return false; | ||||
11626 | |||||
11627 | return Success(Val.reverseBits(), E); | ||||
11628 | } | ||||
11629 | |||||
11630 | case Builtin::BI__builtin_bswap16: | ||||
11631 | case Builtin::BI__builtin_bswap32: | ||||
11632 | case Builtin::BI__builtin_bswap64: { | ||||
11633 | APSInt Val; | ||||
11634 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
11635 | return false; | ||||
11636 | |||||
11637 | return Success(Val.byteSwap(), E); | ||||
11638 | } | ||||
11639 | |||||
11640 | case Builtin::BI__builtin_classify_type: | ||||
11641 | return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); | ||||
11642 | |||||
11643 | case Builtin::BI__builtin_clrsb: | ||||
11644 | case Builtin::BI__builtin_clrsbl: | ||||
11645 | case Builtin::BI__builtin_clrsbll: { | ||||
11646 | APSInt Val; | ||||
11647 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
11648 | return false; | ||||
11649 | |||||
11650 | return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); | ||||
11651 | } | ||||
11652 | |||||
11653 | case Builtin::BI__builtin_clz: | ||||
11654 | case Builtin::BI__builtin_clzl: | ||||
11655 | case Builtin::BI__builtin_clzll: | ||||
11656 | case Builtin::BI__builtin_clzs: { | ||||
11657 | APSInt Val; | ||||
11658 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
11659 | return false; | ||||
11660 | if (!Val) | ||||
11661 | return Error(E); | ||||
11662 | |||||
11663 | return Success(Val.countLeadingZeros(), E); | ||||
11664 | } | ||||
11665 | |||||
11666 | case Builtin::BI__builtin_constant_p: { | ||||
11667 | const Expr *Arg = E->getArg(0); | ||||
11668 | if (EvaluateBuiltinConstantP(Info, Arg)) | ||||
11669 | return Success(true, E); | ||||
11670 | if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { | ||||
11671 | // Outside a constant context, eagerly evaluate to false in the presence | ||||
11672 | // of side-effects in order to avoid -Wunsequenced false-positives in | ||||
11673 | // a branch on __builtin_constant_p(expr). | ||||
11674 | return Success(false, E); | ||||
11675 | } | ||||
11676 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
11677 | return false; | ||||
11678 | } | ||||
11679 | |||||
11680 | case Builtin::BI__builtin_is_constant_evaluated: { | ||||
11681 | const auto *Callee = Info.CurrentCall->getCallee(); | ||||
11682 | if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && | ||||
11683 | (Info.CallStackDepth == 1 || | ||||
11684 | (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && | ||||
11685 | Callee->getIdentifier() && | ||||
11686 | Callee->getIdentifier()->isStr("is_constant_evaluated")))) { | ||||
11687 | // FIXME: Find a better way to avoid duplicated diagnostics. | ||||
11688 | if (Info.EvalStatus.Diag) | ||||
11689 | Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() | ||||
11690 | : Info.CurrentCall->CallLoc, | ||||
11691 | diag::warn_is_constant_evaluated_always_true_constexpr) | ||||
11692 | << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" | ||||
11693 | : "std::is_constant_evaluated"); | ||||
11694 | } | ||||
11695 | |||||
11696 | return Success(Info.InConstantContext, E); | ||||
11697 | } | ||||
11698 | |||||
11699 | case Builtin::BI__builtin_ctz: | ||||
11700 | case Builtin::BI__builtin_ctzl: | ||||
11701 | case Builtin::BI__builtin_ctzll: | ||||
11702 | case Builtin::BI__builtin_ctzs: { | ||||
11703 | APSInt Val; | ||||
11704 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
11705 | return false; | ||||
11706 | if (!Val) | ||||
11707 | return Error(E); | ||||
11708 | |||||
11709 | return Success(Val.countTrailingZeros(), E); | ||||
11710 | } | ||||
11711 | |||||
11712 | case Builtin::BI__builtin_eh_return_data_regno: { | ||||
11713 | int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); | ||||
11714 | Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); | ||||
11715 | return Success(Operand, E); | ||||
11716 | } | ||||
11717 | |||||
11718 | case Builtin::BI__builtin_expect: | ||||
11719 | case Builtin::BI__builtin_expect_with_probability: | ||||
11720 | return Visit(E->getArg(0)); | ||||
11721 | |||||
11722 | case Builtin::BI__builtin_ffs: | ||||
11723 | case Builtin::BI__builtin_ffsl: | ||||
11724 | case Builtin::BI__builtin_ffsll: { | ||||
11725 | APSInt Val; | ||||
11726 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
11727 | return false; | ||||
11728 | |||||
11729 | unsigned N = Val.countTrailingZeros(); | ||||
11730 | return Success(N == Val.getBitWidth() ? 0 : N + 1, E); | ||||
11731 | } | ||||
11732 | |||||
11733 | case Builtin::BI__builtin_fpclassify: { | ||||
11734 | APFloat Val(0.0); | ||||
11735 | if (!EvaluateFloat(E->getArg(5), Val, Info)) | ||||
11736 | return false; | ||||
11737 | unsigned Arg; | ||||
11738 | switch (Val.getCategory()) { | ||||
11739 | case APFloat::fcNaN: Arg = 0; break; | ||||
11740 | case APFloat::fcInfinity: Arg = 1; break; | ||||
11741 | case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; | ||||
11742 | case APFloat::fcZero: Arg = 4; break; | ||||
11743 | } | ||||
11744 | return Visit(E->getArg(Arg)); | ||||
11745 | } | ||||
11746 | |||||
11747 | case Builtin::BI__builtin_isinf_sign: { | ||||
11748 | APFloat Val(0.0); | ||||
11749 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
11750 | Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); | ||||
11751 | } | ||||
11752 | |||||
11753 | case Builtin::BI__builtin_isinf: { | ||||
11754 | APFloat Val(0.0); | ||||
11755 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
11756 | Success(Val.isInfinity() ? 1 : 0, E); | ||||
11757 | } | ||||
11758 | |||||
11759 | case Builtin::BI__builtin_isfinite: { | ||||
11760 | APFloat Val(0.0); | ||||
11761 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
11762 | Success(Val.isFinite() ? 1 : 0, E); | ||||
11763 | } | ||||
11764 | |||||
11765 | case Builtin::BI__builtin_isnan: { | ||||
11766 | APFloat Val(0.0); | ||||
11767 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
11768 | Success(Val.isNaN() ? 1 : 0, E); | ||||
11769 | } | ||||
11770 | |||||
11771 | case Builtin::BI__builtin_isnormal: { | ||||
11772 | APFloat Val(0.0); | ||||
11773 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
11774 | Success(Val.isNormal() ? 1 : 0, E); | ||||
11775 | } | ||||
11776 | |||||
11777 | case Builtin::BI__builtin_parity: | ||||
11778 | case Builtin::BI__builtin_parityl: | ||||
11779 | case Builtin::BI__builtin_parityll: { | ||||
11780 | APSInt Val; | ||||
11781 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
11782 | return false; | ||||
11783 | |||||
11784 | return Success(Val.countPopulation() % 2, E); | ||||
11785 | } | ||||
11786 | |||||
11787 | case Builtin::BI__builtin_popcount: | ||||
11788 | case Builtin::BI__builtin_popcountl: | ||||
11789 | case Builtin::BI__builtin_popcountll: { | ||||
11790 | APSInt Val; | ||||
11791 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
11792 | return false; | ||||
11793 | |||||
11794 | return Success(Val.countPopulation(), E); | ||||
11795 | } | ||||
11796 | |||||
11797 | case Builtin::BI__builtin_rotateleft8: | ||||
11798 | case Builtin::BI__builtin_rotateleft16: | ||||
11799 | case Builtin::BI__builtin_rotateleft32: | ||||
11800 | case Builtin::BI__builtin_rotateleft64: | ||||
11801 | case Builtin::BI_rotl8: // Microsoft variants of rotate right | ||||
11802 | case Builtin::BI_rotl16: | ||||
11803 | case Builtin::BI_rotl: | ||||
11804 | case Builtin::BI_lrotl: | ||||
11805 | case Builtin::BI_rotl64: { | ||||
11806 | APSInt Val, Amt; | ||||
11807 | if (!EvaluateInteger(E->getArg(0), Val, Info) || | ||||
11808 | !EvaluateInteger(E->getArg(1), Amt, Info)) | ||||
11809 | return false; | ||||
11810 | |||||
11811 | return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); | ||||
11812 | } | ||||
11813 | |||||
11814 | case Builtin::BI__builtin_rotateright8: | ||||
11815 | case Builtin::BI__builtin_rotateright16: | ||||
11816 | case Builtin::BI__builtin_rotateright32: | ||||
11817 | case Builtin::BI__builtin_rotateright64: | ||||
11818 | case Builtin::BI_rotr8: // Microsoft variants of rotate right | ||||
11819 | case Builtin::BI_rotr16: | ||||
11820 | case Builtin::BI_rotr: | ||||
11821 | case Builtin::BI_lrotr: | ||||
11822 | case Builtin::BI_rotr64: { | ||||
11823 | APSInt Val, Amt; | ||||
11824 | if (!EvaluateInteger(E->getArg(0), Val, Info) || | ||||
11825 | !EvaluateInteger(E->getArg(1), Amt, Info)) | ||||
11826 | return false; | ||||
11827 | |||||
11828 | return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); | ||||
11829 | } | ||||
11830 | |||||
11831 | case Builtin::BIstrlen: | ||||
11832 | case Builtin::BIwcslen: | ||||
11833 | // A call to strlen is not a constant expression. | ||||
11834 | if (Info.getLangOpts().CPlusPlus11) | ||||
11835 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||
11836 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||
11837 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||
11838 | else | ||||
11839 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
11840 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
11841 | case Builtin::BI__builtin_strlen: | ||||
11842 | case Builtin::BI__builtin_wcslen: { | ||||
11843 | // As an extension, we support __builtin_strlen() as a constant expression, | ||||
11844 | // and support folding strlen() to a constant. | ||||
11845 | uint64_t StrLen; | ||||
11846 | if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info)) | ||||
11847 | return Success(StrLen, E); | ||||
11848 | return false; | ||||
11849 | } | ||||
11850 | |||||
11851 | case Builtin::BIstrcmp: | ||||
11852 | case Builtin::BIwcscmp: | ||||
11853 | case Builtin::BIstrncmp: | ||||
11854 | case Builtin::BIwcsncmp: | ||||
11855 | case Builtin::BImemcmp: | ||||
11856 | case Builtin::BIbcmp: | ||||
11857 | case Builtin::BIwmemcmp: | ||||
11858 | // A call to strlen is not a constant expression. | ||||
11859 | if (Info.getLangOpts().CPlusPlus11) | ||||
11860 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||
11861 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||
11862 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||
11863 | else | ||||
11864 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
11865 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
11866 | case Builtin::BI__builtin_strcmp: | ||||
11867 | case Builtin::BI__builtin_wcscmp: | ||||
11868 | case Builtin::BI__builtin_strncmp: | ||||
11869 | case Builtin::BI__builtin_wcsncmp: | ||||
11870 | case Builtin::BI__builtin_memcmp: | ||||
11871 | case Builtin::BI__builtin_bcmp: | ||||
11872 | case Builtin::BI__builtin_wmemcmp: { | ||||
11873 | LValue String1, String2; | ||||
11874 | if (!EvaluatePointer(E->getArg(0), String1, Info) || | ||||
11875 | !EvaluatePointer(E->getArg(1), String2, Info)) | ||||
11876 | return false; | ||||
11877 | |||||
11878 | uint64_t MaxLength = uint64_t(-1); | ||||
11879 | if (BuiltinOp != Builtin::BIstrcmp && | ||||
11880 | BuiltinOp != Builtin::BIwcscmp && | ||||
11881 | BuiltinOp != Builtin::BI__builtin_strcmp && | ||||
11882 | BuiltinOp != Builtin::BI__builtin_wcscmp) { | ||||
11883 | APSInt N; | ||||
11884 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||
11885 | return false; | ||||
11886 | MaxLength = N.getExtValue(); | ||||
11887 | } | ||||
11888 | |||||
11889 | // Empty substrings compare equal by definition. | ||||
11890 | if (MaxLength == 0u) | ||||
11891 | return Success(0, E); | ||||
11892 | |||||
11893 | if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||
11894 | !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||
11895 | String1.Designator.Invalid || String2.Designator.Invalid) | ||||
11896 | return false; | ||||
11897 | |||||
11898 | QualType CharTy1 = String1.Designator.getType(Info.Ctx); | ||||
11899 | QualType CharTy2 = String2.Designator.getType(Info.Ctx); | ||||
11900 | |||||
11901 | bool IsRawByte = BuiltinOp == Builtin::BImemcmp || | ||||
11902 | BuiltinOp == Builtin::BIbcmp || | ||||
11903 | BuiltinOp == Builtin::BI__builtin_memcmp || | ||||
11904 | BuiltinOp == Builtin::BI__builtin_bcmp; | ||||
11905 | |||||
11906 | assert(IsRawByte ||(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType ( CharTy1, E->getArg(0)->getType()->getPointeeType() ) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2 ))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11909, __extension__ __PRETTY_FUNCTION__)) | ||||
11907 | (Info.Ctx.hasSameUnqualifiedType((static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType ( CharTy1, E->getArg(0)->getType()->getPointeeType() ) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2 ))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11909, __extension__ __PRETTY_FUNCTION__)) | ||||
11908 | CharTy1, E->getArg(0)->getType()->getPointeeType()) &&(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType ( CharTy1, E->getArg(0)->getType()->getPointeeType() ) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2 ))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11909, __extension__ __PRETTY_FUNCTION__)) | ||||
11909 | Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)))(static_cast <bool> (IsRawByte || (Info.Ctx.hasSameUnqualifiedType ( CharTy1, E->getArg(0)->getType()->getPointeeType() ) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2 ))) ? void (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11909, __extension__ __PRETTY_FUNCTION__)); | ||||
11910 | |||||
11911 | // For memcmp, allow comparing any arrays of '[[un]signed] char' or | ||||
11912 | // 'char8_t', but no other types. | ||||
11913 | if (IsRawByte && | ||||
11914 | !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { | ||||
11915 | // FIXME: Consider using our bit_cast implementation to support this. | ||||
11916 | Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) | ||||
11917 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") | ||||
11918 | << CharTy1 << CharTy2; | ||||
11919 | return false; | ||||
11920 | } | ||||
11921 | |||||
11922 | const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { | ||||
11923 | return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && | ||||
11924 | handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && | ||||
11925 | Char1.isInt() && Char2.isInt(); | ||||
11926 | }; | ||||
11927 | const auto &AdvanceElems = [&] { | ||||
11928 | return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && | ||||
11929 | HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); | ||||
11930 | }; | ||||
11931 | |||||
11932 | bool StopAtNull = | ||||
11933 | (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && | ||||
11934 | BuiltinOp != Builtin::BIwmemcmp && | ||||
11935 | BuiltinOp != Builtin::BI__builtin_memcmp && | ||||
11936 | BuiltinOp != Builtin::BI__builtin_bcmp && | ||||
11937 | BuiltinOp != Builtin::BI__builtin_wmemcmp); | ||||
11938 | bool IsWide = BuiltinOp == Builtin::BIwcscmp || | ||||
11939 | BuiltinOp == Builtin::BIwcsncmp || | ||||
11940 | BuiltinOp == Builtin::BIwmemcmp || | ||||
11941 | BuiltinOp == Builtin::BI__builtin_wcscmp || | ||||
11942 | BuiltinOp == Builtin::BI__builtin_wcsncmp || | ||||
11943 | BuiltinOp == Builtin::BI__builtin_wmemcmp; | ||||
11944 | |||||
11945 | for (; MaxLength; --MaxLength) { | ||||
11946 | APValue Char1, Char2; | ||||
11947 | if (!ReadCurElems(Char1, Char2)) | ||||
11948 | return false; | ||||
11949 | if (Char1.getInt().ne(Char2.getInt())) { | ||||
11950 | if (IsWide) // wmemcmp compares with wchar_t signedness. | ||||
11951 | return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); | ||||
11952 | // memcmp always compares unsigned chars. | ||||
11953 | return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); | ||||
11954 | } | ||||
11955 | if (StopAtNull && !Char1.getInt()) | ||||
11956 | return Success(0, E); | ||||
11957 | assert(!(StopAtNull && !Char2.getInt()))(static_cast <bool> (!(StopAtNull && !Char2.getInt ())) ? void (0) : __assert_fail ("!(StopAtNull && !Char2.getInt())" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 11957, __extension__ __PRETTY_FUNCTION__)); | ||||
11958 | if (!AdvanceElems()) | ||||
11959 | return false; | ||||
11960 | } | ||||
11961 | // We hit the strncmp / memcmp limit. | ||||
11962 | return Success(0, E); | ||||
11963 | } | ||||
11964 | |||||
11965 | case Builtin::BI__atomic_always_lock_free: | ||||
11966 | case Builtin::BI__atomic_is_lock_free: | ||||
11967 | case Builtin::BI__c11_atomic_is_lock_free: { | ||||
11968 | APSInt SizeVal; | ||||
11969 | if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) | ||||
11970 | return false; | ||||
11971 | |||||
11972 | // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power | ||||
11973 | // of two less than or equal to the maximum inline atomic width, we know it | ||||
11974 | // is lock-free. If the size isn't a power of two, or greater than the | ||||
11975 | // maximum alignment where we promote atomics, we know it is not lock-free | ||||
11976 | // (at least not in the sense of atomic_is_lock_free). Otherwise, | ||||
11977 | // the answer can only be determined at runtime; for example, 16-byte | ||||
11978 | // atomics have lock-free implementations on some, but not all, | ||||
11979 | // x86-64 processors. | ||||
11980 | |||||
11981 | // Check power-of-two. | ||||
11982 | CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); | ||||
11983 | if (Size.isPowerOfTwo()) { | ||||
11984 | // Check against inlining width. | ||||
11985 | unsigned InlineWidthBits = | ||||
11986 | Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); | ||||
11987 | if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { | ||||
11988 | if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || | ||||
11989 | Size == CharUnits::One() || | ||||
11990 | E->getArg(1)->isNullPointerConstant(Info.Ctx, | ||||
11991 | Expr::NPC_NeverValueDependent)) | ||||
11992 | // OK, we will inline appropriately-aligned operations of this size, | ||||
11993 | // and _Atomic(T) is appropriately-aligned. | ||||
11994 | return Success(1, E); | ||||
11995 | |||||
11996 | QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> | ||||
11997 | castAs<PointerType>()->getPointeeType(); | ||||
11998 | if (!PointeeType->isIncompleteType() && | ||||
11999 | Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { | ||||
12000 | // OK, we will inline operations on this object. | ||||
12001 | return Success(1, E); | ||||
12002 | } | ||||
12003 | } | ||||
12004 | } | ||||
12005 | |||||
12006 | return BuiltinOp == Builtin::BI__atomic_always_lock_free ? | ||||
12007 | Success(0, E) : Error(E); | ||||
12008 | } | ||||
12009 | case Builtin::BI__builtin_add_overflow: | ||||
12010 | case Builtin::BI__builtin_sub_overflow: | ||||
12011 | case Builtin::BI__builtin_mul_overflow: | ||||
12012 | case Builtin::BI__builtin_sadd_overflow: | ||||
12013 | case Builtin::BI__builtin_uadd_overflow: | ||||
12014 | case Builtin::BI__builtin_uaddl_overflow: | ||||
12015 | case Builtin::BI__builtin_uaddll_overflow: | ||||
12016 | case Builtin::BI__builtin_usub_overflow: | ||||
12017 | case Builtin::BI__builtin_usubl_overflow: | ||||
12018 | case Builtin::BI__builtin_usubll_overflow: | ||||
12019 | case Builtin::BI__builtin_umul_overflow: | ||||
12020 | case Builtin::BI__builtin_umull_overflow: | ||||
12021 | case Builtin::BI__builtin_umulll_overflow: | ||||
12022 | case Builtin::BI__builtin_saddl_overflow: | ||||
12023 | case Builtin::BI__builtin_saddll_overflow: | ||||
12024 | case Builtin::BI__builtin_ssub_overflow: | ||||
12025 | case Builtin::BI__builtin_ssubl_overflow: | ||||
12026 | case Builtin::BI__builtin_ssubll_overflow: | ||||
12027 | case Builtin::BI__builtin_smul_overflow: | ||||
12028 | case Builtin::BI__builtin_smull_overflow: | ||||
12029 | case Builtin::BI__builtin_smulll_overflow: { | ||||
12030 | LValue ResultLValue; | ||||
12031 | APSInt LHS, RHS; | ||||
12032 | |||||
12033 | QualType ResultType = E->getArg(2)->getType()->getPointeeType(); | ||||
12034 | if (!EvaluateInteger(E->getArg(0), LHS, Info) || | ||||
12035 | !EvaluateInteger(E->getArg(1), RHS, Info) || | ||||
12036 | !EvaluatePointer(E->getArg(2), ResultLValue, Info)) | ||||
12037 | return false; | ||||
12038 | |||||
12039 | APSInt Result; | ||||
12040 | bool DidOverflow = false; | ||||
12041 | |||||
12042 | // If the types don't have to match, enlarge all 3 to the largest of them. | ||||
12043 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || | ||||
12044 | BuiltinOp == Builtin::BI__builtin_sub_overflow || | ||||
12045 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { | ||||
12046 | bool IsSigned = LHS.isSigned() || RHS.isSigned() || | ||||
12047 | ResultType->isSignedIntegerOrEnumerationType(); | ||||
12048 | bool AllSigned = LHS.isSigned() && RHS.isSigned() && | ||||
12049 | ResultType->isSignedIntegerOrEnumerationType(); | ||||
12050 | uint64_t LHSSize = LHS.getBitWidth(); | ||||
12051 | uint64_t RHSSize = RHS.getBitWidth(); | ||||
12052 | uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); | ||||
12053 | uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); | ||||
12054 | |||||
12055 | // Add an additional bit if the signedness isn't uniformly agreed to. We | ||||
12056 | // could do this ONLY if there is a signed and an unsigned that both have | ||||
12057 | // MaxBits, but the code to check that is pretty nasty. The issue will be | ||||
12058 | // caught in the shrink-to-result later anyway. | ||||
12059 | if (IsSigned && !AllSigned) | ||||
12060 | ++MaxBits; | ||||
12061 | |||||
12062 | LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); | ||||
12063 | RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); | ||||
12064 | Result = APSInt(MaxBits, !IsSigned); | ||||
12065 | } | ||||
12066 | |||||
12067 | // Find largest int. | ||||
12068 | switch (BuiltinOp) { | ||||
12069 | default: | ||||
12070 | llvm_unreachable("Invalid value for BuiltinOp")::llvm::llvm_unreachable_internal("Invalid value for BuiltinOp" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12070); | ||||
12071 | case Builtin::BI__builtin_add_overflow: | ||||
12072 | case Builtin::BI__builtin_sadd_overflow: | ||||
12073 | case Builtin::BI__builtin_saddl_overflow: | ||||
12074 | case Builtin::BI__builtin_saddll_overflow: | ||||
12075 | case Builtin::BI__builtin_uadd_overflow: | ||||
12076 | case Builtin::BI__builtin_uaddl_overflow: | ||||
12077 | case Builtin::BI__builtin_uaddll_overflow: | ||||
12078 | Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) | ||||
12079 | : LHS.uadd_ov(RHS, DidOverflow); | ||||
12080 | break; | ||||
12081 | case Builtin::BI__builtin_sub_overflow: | ||||
12082 | case Builtin::BI__builtin_ssub_overflow: | ||||
12083 | case Builtin::BI__builtin_ssubl_overflow: | ||||
12084 | case Builtin::BI__builtin_ssubll_overflow: | ||||
12085 | case Builtin::BI__builtin_usub_overflow: | ||||
12086 | case Builtin::BI__builtin_usubl_overflow: | ||||
12087 | case Builtin::BI__builtin_usubll_overflow: | ||||
12088 | Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) | ||||
12089 | : LHS.usub_ov(RHS, DidOverflow); | ||||
12090 | break; | ||||
12091 | case Builtin::BI__builtin_mul_overflow: | ||||
12092 | case Builtin::BI__builtin_smul_overflow: | ||||
12093 | case Builtin::BI__builtin_smull_overflow: | ||||
12094 | case Builtin::BI__builtin_smulll_overflow: | ||||
12095 | case Builtin::BI__builtin_umul_overflow: | ||||
12096 | case Builtin::BI__builtin_umull_overflow: | ||||
12097 | case Builtin::BI__builtin_umulll_overflow: | ||||
12098 | Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) | ||||
12099 | : LHS.umul_ov(RHS, DidOverflow); | ||||
12100 | break; | ||||
12101 | } | ||||
12102 | |||||
12103 | // In the case where multiple sizes are allowed, truncate and see if | ||||
12104 | // the values are the same. | ||||
12105 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || | ||||
12106 | BuiltinOp == Builtin::BI__builtin_sub_overflow || | ||||
12107 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { | ||||
12108 | // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, | ||||
12109 | // since it will give us the behavior of a TruncOrSelf in the case where | ||||
12110 | // its parameter <= its size. We previously set Result to be at least the | ||||
12111 | // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth | ||||
12112 | // will work exactly like TruncOrSelf. | ||||
12113 | APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); | ||||
12114 | Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); | ||||
12115 | |||||
12116 | if (!APSInt::isSameValue(Temp, Result)) | ||||
12117 | DidOverflow = true; | ||||
12118 | Result = Temp; | ||||
12119 | } | ||||
12120 | |||||
12121 | APValue APV{Result}; | ||||
12122 | if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) | ||||
12123 | return false; | ||||
12124 | return Success(DidOverflow, E); | ||||
12125 | } | ||||
12126 | } | ||||
12127 | } | ||||
12128 | |||||
12129 | /// Determine whether this is a pointer past the end of the complete | ||||
12130 | /// object referred to by the lvalue. | ||||
12131 | static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, | ||||
12132 | const LValue &LV) { | ||||
12133 | // A null pointer can be viewed as being "past the end" but we don't | ||||
12134 | // choose to look at it that way here. | ||||
12135 | if (!LV.getLValueBase()) | ||||
12136 | return false; | ||||
12137 | |||||
12138 | // If the designator is valid and refers to a subobject, we're not pointing | ||||
12139 | // past the end. | ||||
12140 | if (!LV.getLValueDesignator().Invalid && | ||||
12141 | !LV.getLValueDesignator().isOnePastTheEnd()) | ||||
12142 | return false; | ||||
12143 | |||||
12144 | // A pointer to an incomplete type might be past-the-end if the type's size is | ||||
12145 | // zero. We cannot tell because the type is incomplete. | ||||
12146 | QualType Ty = getType(LV.getLValueBase()); | ||||
12147 | if (Ty->isIncompleteType()) | ||||
12148 | return true; | ||||
12149 | |||||
12150 | // We're a past-the-end pointer if we point to the byte after the object, | ||||
12151 | // no matter what our type or path is. | ||||
12152 | auto Size = Ctx.getTypeSizeInChars(Ty); | ||||
12153 | return LV.getLValueOffset() == Size; | ||||
12154 | } | ||||
12155 | |||||
12156 | namespace { | ||||
12157 | |||||
12158 | /// Data recursive integer evaluator of certain binary operators. | ||||
12159 | /// | ||||
12160 | /// We use a data recursive algorithm for binary operators so that we are able | ||||
12161 | /// to handle extreme cases of chained binary operators without causing stack | ||||
12162 | /// overflow. | ||||
12163 | class DataRecursiveIntBinOpEvaluator { | ||||
12164 | struct EvalResult { | ||||
12165 | APValue Val; | ||||
12166 | bool Failed; | ||||
12167 | |||||
12168 | EvalResult() : Failed(false) { } | ||||
12169 | |||||
12170 | void swap(EvalResult &RHS) { | ||||
12171 | Val.swap(RHS.Val); | ||||
12172 | Failed = RHS.Failed; | ||||
12173 | RHS.Failed = false; | ||||
12174 | } | ||||
12175 | }; | ||||
12176 | |||||
12177 | struct Job { | ||||
12178 | const Expr *E; | ||||
12179 | EvalResult LHSResult; // meaningful only for binary operator expression. | ||||
12180 | enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; | ||||
12181 | |||||
12182 | Job() = default; | ||||
12183 | Job(Job &&) = default; | ||||
12184 | |||||
12185 | void startSpeculativeEval(EvalInfo &Info) { | ||||
12186 | SpecEvalRAII = SpeculativeEvaluationRAII(Info); | ||||
12187 | } | ||||
12188 | |||||
12189 | private: | ||||
12190 | SpeculativeEvaluationRAII SpecEvalRAII; | ||||
12191 | }; | ||||
12192 | |||||
12193 | SmallVector<Job, 16> Queue; | ||||
12194 | |||||
12195 | IntExprEvaluator &IntEval; | ||||
12196 | EvalInfo &Info; | ||||
12197 | APValue &FinalResult; | ||||
12198 | |||||
12199 | public: | ||||
12200 | DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) | ||||
12201 | : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } | ||||
12202 | |||||
12203 | /// True if \param E is a binary operator that we are going to handle | ||||
12204 | /// data recursively. | ||||
12205 | /// We handle binary operators that are comma, logical, or that have operands | ||||
12206 | /// with integral or enumeration type. | ||||
12207 | static bool shouldEnqueue(const BinaryOperator *E) { | ||||
12208 | return E->getOpcode() == BO_Comma || E->isLogicalOp() || | ||||
12209 | (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && | ||||
12210 | E->getLHS()->getType()->isIntegralOrEnumerationType() && | ||||
12211 | E->getRHS()->getType()->isIntegralOrEnumerationType()); | ||||
12212 | } | ||||
12213 | |||||
12214 | bool Traverse(const BinaryOperator *E) { | ||||
12215 | enqueue(E); | ||||
12216 | EvalResult PrevResult; | ||||
12217 | while (!Queue.empty()) | ||||
12218 | process(PrevResult); | ||||
12219 | |||||
12220 | if (PrevResult.Failed) return false; | ||||
12221 | |||||
12222 | FinalResult.swap(PrevResult.Val); | ||||
12223 | return true; | ||||
12224 | } | ||||
12225 | |||||
12226 | private: | ||||
12227 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { | ||||
12228 | return IntEval.Success(Value, E, Result); | ||||
12229 | } | ||||
12230 | bool Success(const APSInt &Value, const Expr *E, APValue &Result) { | ||||
12231 | return IntEval.Success(Value, E, Result); | ||||
12232 | } | ||||
12233 | bool Error(const Expr *E) { | ||||
12234 | return IntEval.Error(E); | ||||
12235 | } | ||||
12236 | bool Error(const Expr *E, diag::kind D) { | ||||
12237 | return IntEval.Error(E, D); | ||||
12238 | } | ||||
12239 | |||||
12240 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { | ||||
12241 | return Info.CCEDiag(E, D); | ||||
12242 | } | ||||
12243 | |||||
12244 | // Returns true if visiting the RHS is necessary, false otherwise. | ||||
12245 | bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, | ||||
12246 | bool &SuppressRHSDiags); | ||||
12247 | |||||
12248 | bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, | ||||
12249 | const BinaryOperator *E, APValue &Result); | ||||
12250 | |||||
12251 | void EvaluateExpr(const Expr *E, EvalResult &Result) { | ||||
12252 | Result.Failed = !Evaluate(Result.Val, Info, E); | ||||
12253 | if (Result.Failed) | ||||
12254 | Result.Val = APValue(); | ||||
12255 | } | ||||
12256 | |||||
12257 | void process(EvalResult &Result); | ||||
12258 | |||||
12259 | void enqueue(const Expr *E) { | ||||
12260 | E = E->IgnoreParens(); | ||||
12261 | Queue.resize(Queue.size()+1); | ||||
12262 | Queue.back().E = E; | ||||
12263 | Queue.back().Kind = Job::AnyExprKind; | ||||
12264 | } | ||||
12265 | }; | ||||
12266 | |||||
12267 | } | ||||
12268 | |||||
12269 | bool DataRecursiveIntBinOpEvaluator:: | ||||
12270 | VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, | ||||
12271 | bool &SuppressRHSDiags) { | ||||
12272 | if (E->getOpcode() == BO_Comma) { | ||||
12273 | // Ignore LHS but note if we could not evaluate it. | ||||
12274 | if (LHSResult.Failed) | ||||
12275 | return Info.noteSideEffect(); | ||||
12276 | return true; | ||||
12277 | } | ||||
12278 | |||||
12279 | if (E->isLogicalOp()) { | ||||
12280 | bool LHSAsBool; | ||||
12281 | if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { | ||||
12282 | // We were able to evaluate the LHS, see if we can get away with not | ||||
12283 | // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 | ||||
12284 | if (LHSAsBool == (E->getOpcode() == BO_LOr)) { | ||||
12285 | Success(LHSAsBool, E, LHSResult.Val); | ||||
12286 | return false; // Ignore RHS | ||||
12287 | } | ||||
12288 | } else { | ||||
12289 | LHSResult.Failed = true; | ||||
12290 | |||||
12291 | // Since we weren't able to evaluate the left hand side, it | ||||
12292 | // might have had side effects. | ||||
12293 | if (!Info.noteSideEffect()) | ||||
12294 | return false; | ||||
12295 | |||||
12296 | // We can't evaluate the LHS; however, sometimes the result | ||||
12297 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. | ||||
12298 | // Don't ignore RHS and suppress diagnostics from this arm. | ||||
12299 | SuppressRHSDiags = true; | ||||
12300 | } | ||||
12301 | |||||
12302 | return true; | ||||
12303 | } | ||||
12304 | |||||
12305 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12306, __extension__ __PRETTY_FUNCTION__)) | ||||
12306 | E->getRHS()->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12306, __extension__ __PRETTY_FUNCTION__)); | ||||
12307 | |||||
12308 | if (LHSResult.Failed && !Info.noteFailure()) | ||||
12309 | return false; // Ignore RHS; | ||||
12310 | |||||
12311 | return true; | ||||
12312 | } | ||||
12313 | |||||
12314 | static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, | ||||
12315 | bool IsSub) { | ||||
12316 | // Compute the new offset in the appropriate width, wrapping at 64 bits. | ||||
12317 | // FIXME: When compiling for a 32-bit target, we should use 32-bit | ||||
12318 | // offsets. | ||||
12319 | assert(!LVal.hasLValuePath() && "have designator for integer lvalue")(static_cast <bool> (!LVal.hasLValuePath() && "have designator for integer lvalue" ) ? void (0) : __assert_fail ("!LVal.hasLValuePath() && \"have designator for integer lvalue\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12319, __extension__ __PRETTY_FUNCTION__)); | ||||
12320 | CharUnits &Offset = LVal.getLValueOffset(); | ||||
12321 | uint64_t Offset64 = Offset.getQuantity(); | ||||
12322 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); | ||||
12323 | Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 | ||||
12324 | : Offset64 + Index64); | ||||
12325 | } | ||||
12326 | |||||
12327 | bool DataRecursiveIntBinOpEvaluator:: | ||||
12328 | VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, | ||||
12329 | const BinaryOperator *E, APValue &Result) { | ||||
12330 | if (E->getOpcode() == BO_Comma) { | ||||
12331 | if (RHSResult.Failed) | ||||
12332 | return false; | ||||
12333 | Result = RHSResult.Val; | ||||
12334 | return true; | ||||
12335 | } | ||||
12336 | |||||
12337 | if (E->isLogicalOp()) { | ||||
12338 | bool lhsResult, rhsResult; | ||||
12339 | bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); | ||||
12340 | bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); | ||||
12341 | |||||
12342 | if (LHSIsOK) { | ||||
12343 | if (RHSIsOK) { | ||||
12344 | if (E->getOpcode() == BO_LOr) | ||||
12345 | return Success(lhsResult || rhsResult, E, Result); | ||||
12346 | else | ||||
12347 | return Success(lhsResult && rhsResult, E, Result); | ||||
12348 | } | ||||
12349 | } else { | ||||
12350 | if (RHSIsOK) { | ||||
12351 | // We can't evaluate the LHS; however, sometimes the result | ||||
12352 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. | ||||
12353 | if (rhsResult == (E->getOpcode() == BO_LOr)) | ||||
12354 | return Success(rhsResult, E, Result); | ||||
12355 | } | ||||
12356 | } | ||||
12357 | |||||
12358 | return false; | ||||
12359 | } | ||||
12360 | |||||
12361 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12362, __extension__ __PRETTY_FUNCTION__)) | ||||
12362 | E->getRHS()->getType()->isIntegralOrEnumerationType())(static_cast <bool> (E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? void (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12362, __extension__ __PRETTY_FUNCTION__)); | ||||
12363 | |||||
12364 | if (LHSResult.Failed || RHSResult.Failed) | ||||
12365 | return false; | ||||
12366 | |||||
12367 | const APValue &LHSVal = LHSResult.Val; | ||||
12368 | const APValue &RHSVal = RHSResult.Val; | ||||
12369 | |||||
12370 | // Handle cases like (unsigned long)&a + 4. | ||||
12371 | if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { | ||||
12372 | Result = LHSVal; | ||||
12373 | addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); | ||||
12374 | return true; | ||||
12375 | } | ||||
12376 | |||||
12377 | // Handle cases like 4 + (unsigned long)&a | ||||
12378 | if (E->getOpcode() == BO_Add && | ||||
12379 | RHSVal.isLValue() && LHSVal.isInt()) { | ||||
12380 | Result = RHSVal; | ||||
12381 | addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); | ||||
12382 | return true; | ||||
12383 | } | ||||
12384 | |||||
12385 | if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { | ||||
12386 | // Handle (intptr_t)&&A - (intptr_t)&&B. | ||||
12387 | if (!LHSVal.getLValueOffset().isZero() || | ||||
12388 | !RHSVal.getLValueOffset().isZero()) | ||||
12389 | return false; | ||||
12390 | const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); | ||||
12391 | const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); | ||||
12392 | if (!LHSExpr || !RHSExpr) | ||||
12393 | return false; | ||||
12394 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); | ||||
12395 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); | ||||
12396 | if (!LHSAddrExpr || !RHSAddrExpr) | ||||
12397 | return false; | ||||
12398 | // Make sure both labels come from the same function. | ||||
12399 | if (LHSAddrExpr->getLabel()->getDeclContext() != | ||||
12400 | RHSAddrExpr->getLabel()->getDeclContext()) | ||||
12401 | return false; | ||||
12402 | Result = APValue(LHSAddrExpr, RHSAddrExpr); | ||||
12403 | return true; | ||||
12404 | } | ||||
12405 | |||||
12406 | // All the remaining cases expect both operands to be an integer | ||||
12407 | if (!LHSVal.isInt() || !RHSVal.isInt()) | ||||
12408 | return Error(E); | ||||
12409 | |||||
12410 | // Set up the width and signedness manually, in case it can't be deduced | ||||
12411 | // from the operation we're performing. | ||||
12412 | // FIXME: Don't do this in the cases where we can deduce it. | ||||
12413 | APSInt Value(Info.Ctx.getIntWidth(E->getType()), | ||||
12414 | E->getType()->isUnsignedIntegerOrEnumerationType()); | ||||
12415 | if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), | ||||
12416 | RHSVal.getInt(), Value)) | ||||
12417 | return false; | ||||
12418 | return Success(Value, E, Result); | ||||
12419 | } | ||||
12420 | |||||
12421 | void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { | ||||
12422 | Job &job = Queue.back(); | ||||
12423 | |||||
12424 | switch (job.Kind) { | ||||
12425 | case Job::AnyExprKind: { | ||||
12426 | if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { | ||||
12427 | if (shouldEnqueue(Bop)) { | ||||
12428 | job.Kind = Job::BinOpKind; | ||||
12429 | enqueue(Bop->getLHS()); | ||||
12430 | return; | ||||
12431 | } | ||||
12432 | } | ||||
12433 | |||||
12434 | EvaluateExpr(job.E, Result); | ||||
12435 | Queue.pop_back(); | ||||
12436 | return; | ||||
12437 | } | ||||
12438 | |||||
12439 | case Job::BinOpKind: { | ||||
12440 | const BinaryOperator *Bop = cast<BinaryOperator>(job.E); | ||||
12441 | bool SuppressRHSDiags = false; | ||||
12442 | if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { | ||||
12443 | Queue.pop_back(); | ||||
12444 | return; | ||||
12445 | } | ||||
12446 | if (SuppressRHSDiags) | ||||
12447 | job.startSpeculativeEval(Info); | ||||
12448 | job.LHSResult.swap(Result); | ||||
12449 | job.Kind = Job::BinOpVisitedLHSKind; | ||||
12450 | enqueue(Bop->getRHS()); | ||||
12451 | return; | ||||
12452 | } | ||||
12453 | |||||
12454 | case Job::BinOpVisitedLHSKind: { | ||||
12455 | const BinaryOperator *Bop = cast<BinaryOperator>(job.E); | ||||
12456 | EvalResult RHS; | ||||
12457 | RHS.swap(Result); | ||||
12458 | Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); | ||||
12459 | Queue.pop_back(); | ||||
12460 | return; | ||||
12461 | } | ||||
12462 | } | ||||
12463 | |||||
12464 | llvm_unreachable("Invalid Job::Kind!")::llvm::llvm_unreachable_internal("Invalid Job::Kind!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12464); | ||||
12465 | } | ||||
12466 | |||||
12467 | namespace { | ||||
12468 | enum class CmpResult { | ||||
12469 | Unequal, | ||||
12470 | Less, | ||||
12471 | Equal, | ||||
12472 | Greater, | ||||
12473 | Unordered, | ||||
12474 | }; | ||||
12475 | } | ||||
12476 | |||||
12477 | template <class SuccessCB, class AfterCB> | ||||
12478 | static bool | ||||
12479 | EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, | ||||
12480 | SuccessCB &&Success, AfterCB &&DoAfter) { | ||||
12481 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12481, __extension__ __PRETTY_FUNCTION__)); | ||||
12482 | assert(E->isComparisonOp() && "expected comparison operator")(static_cast <bool> (E->isComparisonOp() && "expected comparison operator" ) ? void (0) : __assert_fail ("E->isComparisonOp() && \"expected comparison operator\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12482, __extension__ __PRETTY_FUNCTION__)); | ||||
12483 | assert((E->getOpcode() == BO_Cmp ||(static_cast <bool> ((E->getOpcode() == BO_Cmp || E-> getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation" ) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12485, __extension__ __PRETTY_FUNCTION__)) | ||||
12484 | E->getType()->isIntegralOrEnumerationType()) &&(static_cast <bool> ((E->getOpcode() == BO_Cmp || E-> getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation" ) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12485, __extension__ __PRETTY_FUNCTION__)) | ||||
12485 | "unsupported binary expression evaluation")(static_cast <bool> ((E->getOpcode() == BO_Cmp || E-> getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation" ) ? void (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12485, __extension__ __PRETTY_FUNCTION__)); | ||||
12486 | auto Error = [&](const Expr *E) { | ||||
12487 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
12488 | return false; | ||||
12489 | }; | ||||
12490 | |||||
12491 | bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; | ||||
12492 | bool IsEquality = E->isEqualityOp(); | ||||
12493 | |||||
12494 | QualType LHSTy = E->getLHS()->getType(); | ||||
12495 | QualType RHSTy = E->getRHS()->getType(); | ||||
12496 | |||||
12497 | if (LHSTy->isIntegralOrEnumerationType() && | ||||
12498 | RHSTy->isIntegralOrEnumerationType()) { | ||||
12499 | APSInt LHS, RHS; | ||||
12500 | bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); | ||||
12501 | if (!LHSOK && !Info.noteFailure()) | ||||
12502 | return false; | ||||
12503 | if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) | ||||
12504 | return false; | ||||
12505 | if (LHS < RHS) | ||||
12506 | return Success(CmpResult::Less, E); | ||||
12507 | if (LHS > RHS) | ||||
12508 | return Success(CmpResult::Greater, E); | ||||
12509 | return Success(CmpResult::Equal, E); | ||||
12510 | } | ||||
12511 | |||||
12512 | if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { | ||||
12513 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); | ||||
12514 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); | ||||
12515 | |||||
12516 | bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); | ||||
12517 | if (!LHSOK && !Info.noteFailure()) | ||||
12518 | return false; | ||||
12519 | if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) | ||||
12520 | return false; | ||||
12521 | if (LHSFX < RHSFX) | ||||
12522 | return Success(CmpResult::Less, E); | ||||
12523 | if (LHSFX > RHSFX) | ||||
12524 | return Success(CmpResult::Greater, E); | ||||
12525 | return Success(CmpResult::Equal, E); | ||||
12526 | } | ||||
12527 | |||||
12528 | if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { | ||||
12529 | ComplexValue LHS, RHS; | ||||
12530 | bool LHSOK; | ||||
12531 | if (E->isAssignmentOp()) { | ||||
12532 | LValue LV; | ||||
12533 | EvaluateLValue(E->getLHS(), LV, Info); | ||||
12534 | LHSOK = false; | ||||
12535 | } else if (LHSTy->isRealFloatingType()) { | ||||
12536 | LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); | ||||
12537 | if (LHSOK) { | ||||
12538 | LHS.makeComplexFloat(); | ||||
12539 | LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); | ||||
12540 | } | ||||
12541 | } else { | ||||
12542 | LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); | ||||
12543 | } | ||||
12544 | if (!LHSOK && !Info.noteFailure()) | ||||
12545 | return false; | ||||
12546 | |||||
12547 | if (E->getRHS()->getType()->isRealFloatingType()) { | ||||
12548 | if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) | ||||
12549 | return false; | ||||
12550 | RHS.makeComplexFloat(); | ||||
12551 | RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); | ||||
12552 | } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) | ||||
12553 | return false; | ||||
12554 | |||||
12555 | if (LHS.isComplexFloat()) { | ||||
12556 | APFloat::cmpResult CR_r = | ||||
12557 | LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); | ||||
12558 | APFloat::cmpResult CR_i = | ||||
12559 | LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); | ||||
12560 | bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; | ||||
12561 | return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); | ||||
12562 | } else { | ||||
12563 | assert(IsEquality && "invalid complex comparison")(static_cast <bool> (IsEquality && "invalid complex comparison" ) ? void (0) : __assert_fail ("IsEquality && \"invalid complex comparison\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12563, __extension__ __PRETTY_FUNCTION__)); | ||||
12564 | bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && | ||||
12565 | LHS.getComplexIntImag() == RHS.getComplexIntImag(); | ||||
12566 | return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); | ||||
12567 | } | ||||
12568 | } | ||||
12569 | |||||
12570 | if (LHSTy->isRealFloatingType() && | ||||
12571 | RHSTy->isRealFloatingType()) { | ||||
12572 | APFloat RHS(0.0), LHS(0.0); | ||||
12573 | |||||
12574 | bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); | ||||
12575 | if (!LHSOK && !Info.noteFailure()) | ||||
12576 | return false; | ||||
12577 | |||||
12578 | if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) | ||||
12579 | return false; | ||||
12580 | |||||
12581 | assert(E->isComparisonOp() && "Invalid binary operator!")(static_cast <bool> (E->isComparisonOp() && "Invalid binary operator!" ) ? void (0) : __assert_fail ("E->isComparisonOp() && \"Invalid binary operator!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12581, __extension__ __PRETTY_FUNCTION__)); | ||||
12582 | llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); | ||||
12583 | if (!Info.InConstantContext && | ||||
12584 | APFloatCmpResult == APFloat::cmpUnordered && | ||||
12585 | E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { | ||||
12586 | // Note: Compares may raise invalid in some cases involving NaN or sNaN. | ||||
12587 | Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); | ||||
12588 | return false; | ||||
12589 | } | ||||
12590 | auto GetCmpRes = [&]() { | ||||
12591 | switch (APFloatCmpResult) { | ||||
12592 | case APFloat::cmpEqual: | ||||
12593 | return CmpResult::Equal; | ||||
12594 | case APFloat::cmpLessThan: | ||||
12595 | return CmpResult::Less; | ||||
12596 | case APFloat::cmpGreaterThan: | ||||
12597 | return CmpResult::Greater; | ||||
12598 | case APFloat::cmpUnordered: | ||||
12599 | return CmpResult::Unordered; | ||||
12600 | } | ||||
12601 | llvm_unreachable("Unrecognised APFloat::cmpResult enum")::llvm::llvm_unreachable_internal("Unrecognised APFloat::cmpResult enum" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12601); | ||||
12602 | }; | ||||
12603 | return Success(GetCmpRes(), E); | ||||
12604 | } | ||||
12605 | |||||
12606 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) { | ||||
12607 | LValue LHSValue, RHSValue; | ||||
12608 | |||||
12609 | bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); | ||||
12610 | if (!LHSOK && !Info.noteFailure()) | ||||
12611 | return false; | ||||
12612 | |||||
12613 | if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) | ||||
12614 | return false; | ||||
12615 | |||||
12616 | // Reject differing bases from the normal codepath; we special-case | ||||
12617 | // comparisons to null. | ||||
12618 | if (!HasSameBase(LHSValue, RHSValue)) { | ||||
12619 | // Inequalities and subtractions between unrelated pointers have | ||||
12620 | // unspecified or undefined behavior. | ||||
12621 | if (!IsEquality) { | ||||
12622 | Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); | ||||
12623 | return false; | ||||
12624 | } | ||||
12625 | // A constant address may compare equal to the address of a symbol. | ||||
12626 | // The one exception is that address of an object cannot compare equal | ||||
12627 | // to a null pointer constant. | ||||
12628 | if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || | ||||
12629 | (!RHSValue.Base && !RHSValue.Offset.isZero())) | ||||
12630 | return Error(E); | ||||
12631 | // It's implementation-defined whether distinct literals will have | ||||
12632 | // distinct addresses. In clang, the result of such a comparison is | ||||
12633 | // unspecified, so it is not a constant expression. However, we do know | ||||
12634 | // that the address of a literal will be non-null. | ||||
12635 | if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && | ||||
12636 | LHSValue.Base && RHSValue.Base) | ||||
12637 | return Error(E); | ||||
12638 | // We can't tell whether weak symbols will end up pointing to the same | ||||
12639 | // object. | ||||
12640 | if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) | ||||
12641 | return Error(E); | ||||
12642 | // We can't compare the address of the start of one object with the | ||||
12643 | // past-the-end address of another object, per C++ DR1652. | ||||
12644 | if ((LHSValue.Base && LHSValue.Offset.isZero() && | ||||
12645 | isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || | ||||
12646 | (RHSValue.Base && RHSValue.Offset.isZero() && | ||||
12647 | isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) | ||||
12648 | return Error(E); | ||||
12649 | // We can't tell whether an object is at the same address as another | ||||
12650 | // zero sized object. | ||||
12651 | if ((RHSValue.Base && isZeroSized(LHSValue)) || | ||||
12652 | (LHSValue.Base && isZeroSized(RHSValue))) | ||||
12653 | return Error(E); | ||||
12654 | return Success(CmpResult::Unequal, E); | ||||
12655 | } | ||||
12656 | |||||
12657 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); | ||||
12658 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); | ||||
12659 | |||||
12660 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); | ||||
12661 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); | ||||
12662 | |||||
12663 | // C++11 [expr.rel]p3: | ||||
12664 | // Pointers to void (after pointer conversions) can be compared, with a | ||||
12665 | // result defined as follows: If both pointers represent the same | ||||
12666 | // address or are both the null pointer value, the result is true if the | ||||
12667 | // operator is <= or >= and false otherwise; otherwise the result is | ||||
12668 | // unspecified. | ||||
12669 | // We interpret this as applying to pointers to *cv* void. | ||||
12670 | if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) | ||||
12671 | Info.CCEDiag(E, diag::note_constexpr_void_comparison); | ||||
12672 | |||||
12673 | // C++11 [expr.rel]p2: | ||||
12674 | // - If two pointers point to non-static data members of the same object, | ||||
12675 | // or to subobjects or array elements fo such members, recursively, the | ||||
12676 | // pointer to the later declared member compares greater provided the | ||||
12677 | // two members have the same access control and provided their class is | ||||
12678 | // not a union. | ||||
12679 | // [...] | ||||
12680 | // - Otherwise pointer comparisons are unspecified. | ||||
12681 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { | ||||
12682 | bool WasArrayIndex; | ||||
12683 | unsigned Mismatch = FindDesignatorMismatch( | ||||
12684 | getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); | ||||
12685 | // At the point where the designators diverge, the comparison has a | ||||
12686 | // specified value if: | ||||
12687 | // - we are comparing array indices | ||||
12688 | // - we are comparing fields of a union, or fields with the same access | ||||
12689 | // Otherwise, the result is unspecified and thus the comparison is not a | ||||
12690 | // constant expression. | ||||
12691 | if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && | ||||
12692 | Mismatch < RHSDesignator.Entries.size()) { | ||||
12693 | const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); | ||||
12694 | const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); | ||||
12695 | if (!LF && !RF) | ||||
12696 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); | ||||
12697 | else if (!LF) | ||||
12698 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) | ||||
12699 | << getAsBaseClass(LHSDesignator.Entries[Mismatch]) | ||||
12700 | << RF->getParent() << RF; | ||||
12701 | else if (!RF) | ||||
12702 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) | ||||
12703 | << getAsBaseClass(RHSDesignator.Entries[Mismatch]) | ||||
12704 | << LF->getParent() << LF; | ||||
12705 | else if (!LF->getParent()->isUnion() && | ||||
12706 | LF->getAccess() != RF->getAccess()) | ||||
12707 | Info.CCEDiag(E, | ||||
12708 | diag::note_constexpr_pointer_comparison_differing_access) | ||||
12709 | << LF << LF->getAccess() << RF << RF->getAccess() | ||||
12710 | << LF->getParent(); | ||||
12711 | } | ||||
12712 | } | ||||
12713 | |||||
12714 | // The comparison here must be unsigned, and performed with the same | ||||
12715 | // width as the pointer. | ||||
12716 | unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); | ||||
12717 | uint64_t CompareLHS = LHSOffset.getQuantity(); | ||||
12718 | uint64_t CompareRHS = RHSOffset.getQuantity(); | ||||
12719 | assert(PtrSize <= 64 && "Unexpected pointer width")(static_cast <bool> (PtrSize <= 64 && "Unexpected pointer width" ) ? void (0) : __assert_fail ("PtrSize <= 64 && \"Unexpected pointer width\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12719, __extension__ __PRETTY_FUNCTION__)); | ||||
12720 | uint64_t Mask = ~0ULL >> (64 - PtrSize); | ||||
12721 | CompareLHS &= Mask; | ||||
12722 | CompareRHS &= Mask; | ||||
12723 | |||||
12724 | // If there is a base and this is a relational operator, we can only | ||||
12725 | // compare pointers within the object in question; otherwise, the result | ||||
12726 | // depends on where the object is located in memory. | ||||
12727 | if (!LHSValue.Base.isNull() && IsRelational) { | ||||
12728 | QualType BaseTy = getType(LHSValue.Base); | ||||
12729 | if (BaseTy->isIncompleteType()) | ||||
12730 | return Error(E); | ||||
12731 | CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); | ||||
12732 | uint64_t OffsetLimit = Size.getQuantity(); | ||||
12733 | if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) | ||||
12734 | return Error(E); | ||||
12735 | } | ||||
12736 | |||||
12737 | if (CompareLHS < CompareRHS) | ||||
12738 | return Success(CmpResult::Less, E); | ||||
12739 | if (CompareLHS > CompareRHS) | ||||
12740 | return Success(CmpResult::Greater, E); | ||||
12741 | return Success(CmpResult::Equal, E); | ||||
12742 | } | ||||
12743 | |||||
12744 | if (LHSTy->isMemberPointerType()) { | ||||
12745 | assert(IsEquality && "unexpected member pointer operation")(static_cast <bool> (IsEquality && "unexpected member pointer operation" ) ? void (0) : __assert_fail ("IsEquality && \"unexpected member pointer operation\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12745, __extension__ __PRETTY_FUNCTION__)); | ||||
12746 | assert(RHSTy->isMemberPointerType() && "invalid comparison")(static_cast <bool> (RHSTy->isMemberPointerType() && "invalid comparison") ? void (0) : __assert_fail ("RHSTy->isMemberPointerType() && \"invalid comparison\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12746, __extension__ __PRETTY_FUNCTION__)); | ||||
12747 | |||||
12748 | MemberPtr LHSValue, RHSValue; | ||||
12749 | |||||
12750 | bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); | ||||
12751 | if (!LHSOK && !Info.noteFailure()) | ||||
12752 | return false; | ||||
12753 | |||||
12754 | if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) | ||||
12755 | return false; | ||||
12756 | |||||
12757 | // C++11 [expr.eq]p2: | ||||
12758 | // If both operands are null, they compare equal. Otherwise if only one is | ||||
12759 | // null, they compare unequal. | ||||
12760 | if (!LHSValue.getDecl() || !RHSValue.getDecl()) { | ||||
12761 | bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); | ||||
12762 | return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); | ||||
12763 | } | ||||
12764 | |||||
12765 | // Otherwise if either is a pointer to a virtual member function, the | ||||
12766 | // result is unspecified. | ||||
12767 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) | ||||
12768 | if (MD->isVirtual()) | ||||
12769 | Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; | ||||
12770 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) | ||||
12771 | if (MD->isVirtual()) | ||||
12772 | Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; | ||||
12773 | |||||
12774 | // Otherwise they compare equal if and only if they would refer to the | ||||
12775 | // same member of the same most derived object or the same subobject if | ||||
12776 | // they were dereferenced with a hypothetical object of the associated | ||||
12777 | // class type. | ||||
12778 | bool Equal = LHSValue == RHSValue; | ||||
12779 | return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); | ||||
12780 | } | ||||
12781 | |||||
12782 | if (LHSTy->isNullPtrType()) { | ||||
12783 | assert(E->isComparisonOp() && "unexpected nullptr operation")(static_cast <bool> (E->isComparisonOp() && "unexpected nullptr operation" ) ? void (0) : __assert_fail ("E->isComparisonOp() && \"unexpected nullptr operation\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12783, __extension__ __PRETTY_FUNCTION__)); | ||||
12784 | assert(RHSTy->isNullPtrType() && "missing pointer conversion")(static_cast <bool> (RHSTy->isNullPtrType() && "missing pointer conversion") ? void (0) : __assert_fail ("RHSTy->isNullPtrType() && \"missing pointer conversion\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12784, __extension__ __PRETTY_FUNCTION__)); | ||||
12785 | // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t | ||||
12786 | // are compared, the result is true of the operator is <=, >= or ==, and | ||||
12787 | // false otherwise. | ||||
12788 | return Success(CmpResult::Equal, E); | ||||
12789 | } | ||||
12790 | |||||
12791 | return DoAfter(); | ||||
12792 | } | ||||
12793 | |||||
12794 | bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { | ||||
12795 | if (!CheckLiteralType(Info, E)) | ||||
12796 | return false; | ||||
12797 | |||||
12798 | auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { | ||||
12799 | ComparisonCategoryResult CCR; | ||||
12800 | switch (CR) { | ||||
12801 | case CmpResult::Unequal: | ||||
12802 | llvm_unreachable("should never produce Unequal for three-way comparison")::llvm::llvm_unreachable_internal("should never produce Unequal for three-way comparison" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12802); | ||||
12803 | case CmpResult::Less: | ||||
12804 | CCR = ComparisonCategoryResult::Less; | ||||
12805 | break; | ||||
12806 | case CmpResult::Equal: | ||||
12807 | CCR = ComparisonCategoryResult::Equal; | ||||
12808 | break; | ||||
12809 | case CmpResult::Greater: | ||||
12810 | CCR = ComparisonCategoryResult::Greater; | ||||
12811 | break; | ||||
12812 | case CmpResult::Unordered: | ||||
12813 | CCR = ComparisonCategoryResult::Unordered; | ||||
12814 | break; | ||||
12815 | } | ||||
12816 | // Evaluation succeeded. Lookup the information for the comparison category | ||||
12817 | // type and fetch the VarDecl for the result. | ||||
12818 | const ComparisonCategoryInfo &CmpInfo = | ||||
12819 | Info.Ctx.CompCategories.getInfoForType(E->getType()); | ||||
12820 | const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; | ||||
12821 | // Check and evaluate the result as a constant expression. | ||||
12822 | LValue LV; | ||||
12823 | LV.set(VD); | ||||
12824 | if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) | ||||
12825 | return false; | ||||
12826 | return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, | ||||
12827 | ConstantExprKind::Normal); | ||||
12828 | }; | ||||
12829 | return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { | ||||
12830 | return ExprEvaluatorBaseTy::VisitBinCmp(E); | ||||
12831 | }); | ||||
12832 | } | ||||
12833 | |||||
12834 | bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
12835 | // We don't support assignment in C. C++ assignments don't get here because | ||||
12836 | // assignment is an lvalue in C++. | ||||
12837 | if (E->isAssignmentOp()) { | ||||
12838 | Error(E); | ||||
12839 | if (!Info.noteFailure()) | ||||
12840 | return false; | ||||
12841 | } | ||||
12842 | |||||
12843 | if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) | ||||
12844 | return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); | ||||
12845 | |||||
12846 | assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||(static_cast <bool> ((!E->getLHS()->getType()-> isIntegralOrEnumerationType() || !E->getRHS()->getType( )->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12848, __extension__ __PRETTY_FUNCTION__)) | ||||
12847 | !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&(static_cast <bool> ((!E->getLHS()->getType()-> isIntegralOrEnumerationType() || !E->getRHS()->getType( )->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12848, __extension__ __PRETTY_FUNCTION__)) | ||||
12848 | "DataRecursiveIntBinOpEvaluator should have handled integral types")(static_cast <bool> ((!E->getLHS()->getType()-> isIntegralOrEnumerationType() || !E->getRHS()->getType( )->isIntegralOrEnumerationType()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? void (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12848, __extension__ __PRETTY_FUNCTION__)); | ||||
12849 | |||||
12850 | if (E->isComparisonOp()) { | ||||
12851 | // Evaluate builtin binary comparisons by evaluating them as three-way | ||||
12852 | // comparisons and then translating the result. | ||||
12853 | auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { | ||||
12854 | assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&(static_cast <bool> ((CR != CmpResult::Unequal || E-> isEqualityOp()) && "should only produce Unequal for equality comparisons" ) ? void (0) : __assert_fail ("(CR != CmpResult::Unequal || E->isEqualityOp()) && \"should only produce Unequal for equality comparisons\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12855, __extension__ __PRETTY_FUNCTION__)) | ||||
12855 | "should only produce Unequal for equality comparisons")(static_cast <bool> ((CR != CmpResult::Unequal || E-> isEqualityOp()) && "should only produce Unequal for equality comparisons" ) ? void (0) : __assert_fail ("(CR != CmpResult::Unequal || E->isEqualityOp()) && \"should only produce Unequal for equality comparisons\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12855, __extension__ __PRETTY_FUNCTION__)); | ||||
12856 | bool IsEqual = CR == CmpResult::Equal, | ||||
12857 | IsLess = CR == CmpResult::Less, | ||||
12858 | IsGreater = CR == CmpResult::Greater; | ||||
12859 | auto Op = E->getOpcode(); | ||||
12860 | switch (Op) { | ||||
12861 | default: | ||||
12862 | llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 12862); | ||||
12863 | case BO_EQ: | ||||
12864 | case BO_NE: | ||||
12865 | return Success(IsEqual == (Op == BO_EQ), E); | ||||
12866 | case BO_LT: | ||||
12867 | return Success(IsLess, E); | ||||
12868 | case BO_GT: | ||||
12869 | return Success(IsGreater, E); | ||||
12870 | case BO_LE: | ||||
12871 | return Success(IsEqual || IsLess, E); | ||||
12872 | case BO_GE: | ||||
12873 | return Success(IsEqual || IsGreater, E); | ||||
12874 | } | ||||
12875 | }; | ||||
12876 | return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { | ||||
12877 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
12878 | }); | ||||
12879 | } | ||||
12880 | |||||
12881 | QualType LHSTy = E->getLHS()->getType(); | ||||
12882 | QualType RHSTy = E->getRHS()->getType(); | ||||
12883 | |||||
12884 | if (LHSTy->isPointerType() && RHSTy->isPointerType() && | ||||
12885 | E->getOpcode() == BO_Sub) { | ||||
12886 | LValue LHSValue, RHSValue; | ||||
12887 | |||||
12888 | bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); | ||||
12889 | if (!LHSOK && !Info.noteFailure()) | ||||
12890 | return false; | ||||
12891 | |||||
12892 | if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) | ||||
12893 | return false; | ||||
12894 | |||||
12895 | // Reject differing bases from the normal codepath; we special-case | ||||
12896 | // comparisons to null. | ||||
12897 | if (!HasSameBase(LHSValue, RHSValue)) { | ||||
12898 | // Handle &&A - &&B. | ||||
12899 | if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) | ||||
12900 | return Error(E); | ||||
12901 | const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); | ||||
12902 | const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); | ||||
12903 | if (!LHSExpr || !RHSExpr) | ||||
12904 | return Error(E); | ||||
12905 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); | ||||
12906 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); | ||||
12907 | if (!LHSAddrExpr || !RHSAddrExpr) | ||||
12908 | return Error(E); | ||||
12909 | // Make sure both labels come from the same function. | ||||
12910 | if (LHSAddrExpr->getLabel()->getDeclContext() != | ||||
12911 | RHSAddrExpr->getLabel()->getDeclContext()) | ||||
12912 | return Error(E); | ||||
12913 | return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); | ||||
12914 | } | ||||
12915 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); | ||||
12916 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); | ||||
12917 | |||||
12918 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); | ||||
12919 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); | ||||
12920 | |||||
12921 | // C++11 [expr.add]p6: | ||||
12922 | // Unless both pointers point to elements of the same array object, or | ||||
12923 | // one past the last element of the array object, the behavior is | ||||
12924 | // undefined. | ||||
12925 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && | ||||
12926 | !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, | ||||
12927 | RHSDesignator)) | ||||
12928 | Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); | ||||
12929 | |||||
12930 | QualType Type = E->getLHS()->getType(); | ||||
12931 | QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); | ||||
12932 | |||||
12933 | CharUnits ElementSize; | ||||
12934 | if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) | ||||
12935 | return false; | ||||
12936 | |||||
12937 | // As an extension, a type may have zero size (empty struct or union in | ||||
12938 | // C, array of zero length). Pointer subtraction in such cases has | ||||
12939 | // undefined behavior, so is not constant. | ||||
12940 | if (ElementSize.isZero()) { | ||||
12941 | Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) | ||||
12942 | << ElementType; | ||||
12943 | return false; | ||||
12944 | } | ||||
12945 | |||||
12946 | // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, | ||||
12947 | // and produce incorrect results when it overflows. Such behavior | ||||
12948 | // appears to be non-conforming, but is common, so perhaps we should | ||||
12949 | // assume the standard intended for such cases to be undefined behavior | ||||
12950 | // and check for them. | ||||
12951 | |||||
12952 | // Compute (LHSOffset - RHSOffset) / Size carefully, checking for | ||||
12953 | // overflow in the final conversion to ptrdiff_t. | ||||
12954 | APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); | ||||
12955 | APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); | ||||
12956 | APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), | ||||
12957 | false); | ||||
12958 | APSInt TrueResult = (LHS - RHS) / ElemSize; | ||||
12959 | APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); | ||||
12960 | |||||
12961 | if (Result.extend(65) != TrueResult && | ||||
12962 | !HandleOverflow(Info, E, TrueResult, E->getType())) | ||||
12963 | return false; | ||||
12964 | return Success(Result, E); | ||||
12965 | } | ||||
12966 | |||||
12967 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
12968 | } | ||||
12969 | |||||
12970 | /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with | ||||
12971 | /// a result as the expression's type. | ||||
12972 | bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( | ||||
12973 | const UnaryExprOrTypeTraitExpr *E) { | ||||
12974 | switch(E->getKind()) { | ||||
12975 | case UETT_PreferredAlignOf: | ||||
12976 | case UETT_AlignOf: { | ||||
12977 | if (E->isArgumentType()) | ||||
12978 | return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), | ||||
12979 | E); | ||||
12980 | else | ||||
12981 | return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), | ||||
12982 | E); | ||||
12983 | } | ||||
12984 | |||||
12985 | case UETT_VecStep: { | ||||
12986 | QualType Ty = E->getTypeOfArgument(); | ||||
12987 | |||||
12988 | if (Ty->isVectorType()) { | ||||
12989 | unsigned n = Ty->castAs<VectorType>()->getNumElements(); | ||||
12990 | |||||
12991 | // The vec_step built-in functions that take a 3-component | ||||
12992 | // vector return 4. (OpenCL 1.1 spec 6.11.12) | ||||
12993 | if (n == 3) | ||||
12994 | n = 4; | ||||
12995 | |||||
12996 | return Success(n, E); | ||||
12997 | } else | ||||
12998 | return Success(1, E); | ||||
12999 | } | ||||
13000 | |||||
13001 | case UETT_SizeOf: { | ||||
13002 | QualType SrcTy = E->getTypeOfArgument(); | ||||
13003 | // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, | ||||
13004 | // the result is the size of the referenced type." | ||||
13005 | if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) | ||||
13006 | SrcTy = Ref->getPointeeType(); | ||||
13007 | |||||
13008 | CharUnits Sizeof; | ||||
13009 | if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) | ||||
13010 | return false; | ||||
13011 | return Success(Sizeof, E); | ||||
13012 | } | ||||
13013 | case UETT_OpenMPRequiredSimdAlign: | ||||
13014 | assert(E->isArgumentType())(static_cast <bool> (E->isArgumentType()) ? void (0) : __assert_fail ("E->isArgumentType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13014, __extension__ __PRETTY_FUNCTION__)); | ||||
13015 | return Success( | ||||
13016 | Info.Ctx.toCharUnitsFromBits( | ||||
13017 | Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) | ||||
13018 | .getQuantity(), | ||||
13019 | E); | ||||
13020 | } | ||||
13021 | |||||
13022 | llvm_unreachable("unknown expr/type trait")::llvm::llvm_unreachable_internal("unknown expr/type trait", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13022); | ||||
13023 | } | ||||
13024 | |||||
13025 | bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { | ||||
13026 | CharUnits Result; | ||||
13027 | unsigned n = OOE->getNumComponents(); | ||||
13028 | if (n == 0) | ||||
13029 | return Error(OOE); | ||||
13030 | QualType CurrentType = OOE->getTypeSourceInfo()->getType(); | ||||
13031 | for (unsigned i = 0; i != n; ++i) { | ||||
13032 | OffsetOfNode ON = OOE->getComponent(i); | ||||
13033 | switch (ON.getKind()) { | ||||
13034 | case OffsetOfNode::Array: { | ||||
13035 | const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); | ||||
13036 | APSInt IdxResult; | ||||
13037 | if (!EvaluateInteger(Idx, IdxResult, Info)) | ||||
13038 | return false; | ||||
13039 | const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); | ||||
13040 | if (!AT) | ||||
13041 | return Error(OOE); | ||||
13042 | CurrentType = AT->getElementType(); | ||||
13043 | CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); | ||||
13044 | Result += IdxResult.getSExtValue() * ElementSize; | ||||
13045 | break; | ||||
13046 | } | ||||
13047 | |||||
13048 | case OffsetOfNode::Field: { | ||||
13049 | FieldDecl *MemberDecl = ON.getField(); | ||||
13050 | const RecordType *RT = CurrentType->getAs<RecordType>(); | ||||
13051 | if (!RT) | ||||
13052 | return Error(OOE); | ||||
13053 | RecordDecl *RD = RT->getDecl(); | ||||
13054 | if (RD->isInvalidDecl()) return false; | ||||
13055 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); | ||||
13056 | unsigned i = MemberDecl->getFieldIndex(); | ||||
13057 | assert(i < RL.getFieldCount() && "offsetof field in wrong type")(static_cast <bool> (i < RL.getFieldCount() && "offsetof field in wrong type") ? void (0) : __assert_fail ( "i < RL.getFieldCount() && \"offsetof field in wrong type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13057, __extension__ __PRETTY_FUNCTION__)); | ||||
13058 | Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); | ||||
13059 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||
13060 | break; | ||||
13061 | } | ||||
13062 | |||||
13063 | case OffsetOfNode::Identifier: | ||||
13064 | llvm_unreachable("dependent __builtin_offsetof")::llvm::llvm_unreachable_internal("dependent __builtin_offsetof" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13064); | ||||
13065 | |||||
13066 | case OffsetOfNode::Base: { | ||||
13067 | CXXBaseSpecifier *BaseSpec = ON.getBase(); | ||||
13068 | if (BaseSpec->isVirtual()) | ||||
13069 | return Error(OOE); | ||||
13070 | |||||
13071 | // Find the layout of the class whose base we are looking into. | ||||
13072 | const RecordType *RT = CurrentType->getAs<RecordType>(); | ||||
13073 | if (!RT) | ||||
13074 | return Error(OOE); | ||||
13075 | RecordDecl *RD = RT->getDecl(); | ||||
13076 | if (RD->isInvalidDecl()) return false; | ||||
13077 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); | ||||
13078 | |||||
13079 | // Find the base class itself. | ||||
13080 | CurrentType = BaseSpec->getType(); | ||||
13081 | const RecordType *BaseRT = CurrentType->getAs<RecordType>(); | ||||
13082 | if (!BaseRT) | ||||
13083 | return Error(OOE); | ||||
13084 | |||||
13085 | // Add the offset to the base. | ||||
13086 | Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); | ||||
13087 | break; | ||||
13088 | } | ||||
13089 | } | ||||
13090 | } | ||||
13091 | return Success(Result, OOE); | ||||
13092 | } | ||||
13093 | |||||
13094 | bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||
13095 | switch (E->getOpcode()) { | ||||
13096 | default: | ||||
13097 | // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. | ||||
13098 | // See C99 6.6p3. | ||||
13099 | return Error(E); | ||||
13100 | case UO_Extension: | ||||
13101 | // FIXME: Should extension allow i-c-e extension expressions in its scope? | ||||
13102 | // If so, we could clear the diagnostic ID. | ||||
13103 | return Visit(E->getSubExpr()); | ||||
13104 | case UO_Plus: | ||||
13105 | // The result is just the value. | ||||
13106 | return Visit(E->getSubExpr()); | ||||
13107 | case UO_Minus: { | ||||
13108 | if (!Visit(E->getSubExpr())) | ||||
13109 | return false; | ||||
13110 | if (!Result.isInt()) return Error(E); | ||||
13111 | const APSInt &Value = Result.getInt(); | ||||
13112 | if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && | ||||
13113 | !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), | ||||
13114 | E->getType())) | ||||
13115 | return false; | ||||
13116 | return Success(-Value, E); | ||||
13117 | } | ||||
13118 | case UO_Not: { | ||||
13119 | if (!Visit(E->getSubExpr())) | ||||
13120 | return false; | ||||
13121 | if (!Result.isInt()) return Error(E); | ||||
13122 | return Success(~Result.getInt(), E); | ||||
13123 | } | ||||
13124 | case UO_LNot: { | ||||
13125 | bool bres; | ||||
13126 | if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) | ||||
13127 | return false; | ||||
13128 | return Success(!bres, E); | ||||
13129 | } | ||||
13130 | } | ||||
13131 | } | ||||
13132 | |||||
13133 | /// HandleCast - This is used to evaluate implicit or explicit casts where the | ||||
13134 | /// result type is integer. | ||||
13135 | bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
13136 | const Expr *SubExpr = E->getSubExpr(); | ||||
13137 | QualType DestType = E->getType(); | ||||
13138 | QualType SrcType = SubExpr->getType(); | ||||
13139 | |||||
13140 | switch (E->getCastKind()) { | ||||
13141 | case CK_BaseToDerived: | ||||
13142 | case CK_DerivedToBase: | ||||
13143 | case CK_UncheckedDerivedToBase: | ||||
13144 | case CK_Dynamic: | ||||
13145 | case CK_ToUnion: | ||||
13146 | case CK_ArrayToPointerDecay: | ||||
13147 | case CK_FunctionToPointerDecay: | ||||
13148 | case CK_NullToPointer: | ||||
13149 | case CK_NullToMemberPointer: | ||||
13150 | case CK_BaseToDerivedMemberPointer: | ||||
13151 | case CK_DerivedToBaseMemberPointer: | ||||
13152 | case CK_ReinterpretMemberPointer: | ||||
13153 | case CK_ConstructorConversion: | ||||
13154 | case CK_IntegralToPointer: | ||||
13155 | case CK_ToVoid: | ||||
13156 | case CK_VectorSplat: | ||||
13157 | case CK_IntegralToFloating: | ||||
13158 | case CK_FloatingCast: | ||||
13159 | case CK_CPointerToObjCPointerCast: | ||||
13160 | case CK_BlockPointerToObjCPointerCast: | ||||
13161 | case CK_AnyPointerToBlockPointerCast: | ||||
13162 | case CK_ObjCObjectLValueCast: | ||||
13163 | case CK_FloatingRealToComplex: | ||||
13164 | case CK_FloatingComplexToReal: | ||||
13165 | case CK_FloatingComplexCast: | ||||
13166 | case CK_FloatingComplexToIntegralComplex: | ||||
13167 | case CK_IntegralRealToComplex: | ||||
13168 | case CK_IntegralComplexCast: | ||||
13169 | case CK_IntegralComplexToFloatingComplex: | ||||
13170 | case CK_BuiltinFnToFnPtr: | ||||
13171 | case CK_ZeroToOCLOpaqueType: | ||||
13172 | case CK_NonAtomicToAtomic: | ||||
13173 | case CK_AddressSpaceConversion: | ||||
13174 | case CK_IntToOCLSampler: | ||||
13175 | case CK_FloatingToFixedPoint: | ||||
13176 | case CK_FixedPointToFloating: | ||||
13177 | case CK_FixedPointCast: | ||||
13178 | case CK_IntegralToFixedPoint: | ||||
13179 | case CK_MatrixCast: | ||||
13180 | llvm_unreachable("invalid cast kind for integral value")::llvm::llvm_unreachable_internal("invalid cast kind for integral value" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13180); | ||||
13181 | |||||
13182 | case CK_BitCast: | ||||
13183 | case CK_Dependent: | ||||
13184 | case CK_LValueBitCast: | ||||
13185 | case CK_ARCProduceObject: | ||||
13186 | case CK_ARCConsumeObject: | ||||
13187 | case CK_ARCReclaimReturnedObject: | ||||
13188 | case CK_ARCExtendBlockObject: | ||||
13189 | case CK_CopyAndAutoreleaseBlockObject: | ||||
13190 | return Error(E); | ||||
13191 | |||||
13192 | case CK_UserDefinedConversion: | ||||
13193 | case CK_LValueToRValue: | ||||
13194 | case CK_AtomicToNonAtomic: | ||||
13195 | case CK_NoOp: | ||||
13196 | case CK_LValueToRValueBitCast: | ||||
13197 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
13198 | |||||
13199 | case CK_MemberPointerToBoolean: | ||||
13200 | case CK_PointerToBoolean: | ||||
13201 | case CK_IntegralToBoolean: | ||||
13202 | case CK_FloatingToBoolean: | ||||
13203 | case CK_BooleanToSignedIntegral: | ||||
13204 | case CK_FloatingComplexToBoolean: | ||||
13205 | case CK_IntegralComplexToBoolean: { | ||||
13206 | bool BoolResult; | ||||
13207 | if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) | ||||
13208 | return false; | ||||
13209 | uint64_t IntResult = BoolResult; | ||||
13210 | if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) | ||||
13211 | IntResult = (uint64_t)-1; | ||||
13212 | return Success(IntResult, E); | ||||
13213 | } | ||||
13214 | |||||
13215 | case CK_FixedPointToIntegral: { | ||||
13216 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); | ||||
13217 | if (!EvaluateFixedPoint(SubExpr, Src, Info)) | ||||
13218 | return false; | ||||
13219 | bool Overflowed; | ||||
13220 | llvm::APSInt Result = Src.convertToInt( | ||||
13221 | Info.Ctx.getIntWidth(DestType), | ||||
13222 | DestType->isSignedIntegerOrEnumerationType(), &Overflowed); | ||||
13223 | if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) | ||||
13224 | return false; | ||||
13225 | return Success(Result, E); | ||||
13226 | } | ||||
13227 | |||||
13228 | case CK_FixedPointToBoolean: { | ||||
13229 | // Unsigned padding does not affect this. | ||||
13230 | APValue Val; | ||||
13231 | if (!Evaluate(Val, Info, SubExpr)) | ||||
13232 | return false; | ||||
13233 | return Success(Val.getFixedPoint().getBoolValue(), E); | ||||
13234 | } | ||||
13235 | |||||
13236 | case CK_IntegralCast: { | ||||
13237 | if (!Visit(SubExpr)) | ||||
13238 | return false; | ||||
13239 | |||||
13240 | if (!Result.isInt()) { | ||||
13241 | // Allow casts of address-of-label differences if they are no-ops | ||||
13242 | // or narrowing. (The narrowing case isn't actually guaranteed to | ||||
13243 | // be constant-evaluatable except in some narrow cases which are hard | ||||
13244 | // to detect here. We let it through on the assumption the user knows | ||||
13245 | // what they are doing.) | ||||
13246 | if (Result.isAddrLabelDiff()) | ||||
13247 | return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); | ||||
13248 | // Only allow casts of lvalues if they are lossless. | ||||
13249 | return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); | ||||
13250 | } | ||||
13251 | |||||
13252 | return Success(HandleIntToIntCast(Info, E, DestType, SrcType, | ||||
13253 | Result.getInt()), E); | ||||
13254 | } | ||||
13255 | |||||
13256 | case CK_PointerToIntegral: { | ||||
13257 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||
13258 | |||||
13259 | LValue LV; | ||||
13260 | if (!EvaluatePointer(SubExpr, LV, Info)) | ||||
13261 | return false; | ||||
13262 | |||||
13263 | if (LV.getLValueBase()) { | ||||
13264 | // Only allow based lvalue casts if they are lossless. | ||||
13265 | // FIXME: Allow a larger integer size than the pointer size, and allow | ||||
13266 | // narrowing back down to pointer width in subsequent integral casts. | ||||
13267 | // FIXME: Check integer type's active bits, not its type size. | ||||
13268 | if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) | ||||
13269 | return Error(E); | ||||
13270 | |||||
13271 | LV.Designator.setInvalid(); | ||||
13272 | LV.moveInto(Result); | ||||
13273 | return true; | ||||
13274 | } | ||||
13275 | |||||
13276 | APSInt AsInt; | ||||
13277 | APValue V; | ||||
13278 | LV.moveInto(V); | ||||
13279 | if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) | ||||
13280 | llvm_unreachable("Can't cast this!")::llvm::llvm_unreachable_internal("Can't cast this!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13280); | ||||
13281 | |||||
13282 | return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); | ||||
13283 | } | ||||
13284 | |||||
13285 | case CK_IntegralComplexToReal: { | ||||
13286 | ComplexValue C; | ||||
13287 | if (!EvaluateComplex(SubExpr, C, Info)) | ||||
13288 | return false; | ||||
13289 | return Success(C.getComplexIntReal(), E); | ||||
13290 | } | ||||
13291 | |||||
13292 | case CK_FloatingToIntegral: { | ||||
13293 | APFloat F(0.0); | ||||
13294 | if (!EvaluateFloat(SubExpr, F, Info)) | ||||
13295 | return false; | ||||
13296 | |||||
13297 | APSInt Value; | ||||
13298 | if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) | ||||
13299 | return false; | ||||
13300 | return Success(Value, E); | ||||
13301 | } | ||||
13302 | } | ||||
13303 | |||||
13304 | llvm_unreachable("unknown cast resulting in integral value")::llvm::llvm_unreachable_internal("unknown cast resulting in integral value" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13304); | ||||
13305 | } | ||||
13306 | |||||
13307 | bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||
13308 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||
13309 | ComplexValue LV; | ||||
13310 | if (!EvaluateComplex(E->getSubExpr(), LV, Info)) | ||||
13311 | return false; | ||||
13312 | if (!LV.isComplexInt()) | ||||
13313 | return Error(E); | ||||
13314 | return Success(LV.getComplexIntReal(), E); | ||||
13315 | } | ||||
13316 | |||||
13317 | return Visit(E->getSubExpr()); | ||||
13318 | } | ||||
13319 | |||||
13320 | bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||
13321 | if (E->getSubExpr()->getType()->isComplexIntegerType()) { | ||||
13322 | ComplexValue LV; | ||||
13323 | if (!EvaluateComplex(E->getSubExpr(), LV, Info)) | ||||
13324 | return false; | ||||
13325 | if (!LV.isComplexInt()) | ||||
13326 | return Error(E); | ||||
13327 | return Success(LV.getComplexIntImag(), E); | ||||
13328 | } | ||||
13329 | |||||
13330 | VisitIgnoredValue(E->getSubExpr()); | ||||
13331 | return Success(0, E); | ||||
13332 | } | ||||
13333 | |||||
13334 | bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { | ||||
13335 | return Success(E->getPackLength(), E); | ||||
13336 | } | ||||
13337 | |||||
13338 | bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { | ||||
13339 | return Success(E->getValue(), E); | ||||
13340 | } | ||||
13341 | |||||
13342 | bool IntExprEvaluator::VisitConceptSpecializationExpr( | ||||
13343 | const ConceptSpecializationExpr *E) { | ||||
13344 | return Success(E->isSatisfied(), E); | ||||
13345 | } | ||||
13346 | |||||
13347 | bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { | ||||
13348 | return Success(E->isSatisfied(), E); | ||||
13349 | } | ||||
13350 | |||||
13351 | bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||
13352 | switch (E->getOpcode()) { | ||||
13353 | default: | ||||
13354 | // Invalid unary operators | ||||
13355 | return Error(E); | ||||
13356 | case UO_Plus: | ||||
13357 | // The result is just the value. | ||||
13358 | return Visit(E->getSubExpr()); | ||||
13359 | case UO_Minus: { | ||||
13360 | if (!Visit(E->getSubExpr())) return false; | ||||
13361 | if (!Result.isFixedPoint()) | ||||
13362 | return Error(E); | ||||
13363 | bool Overflowed; | ||||
13364 | APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); | ||||
13365 | if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) | ||||
13366 | return false; | ||||
13367 | return Success(Negated, E); | ||||
13368 | } | ||||
13369 | case UO_LNot: { | ||||
13370 | bool bres; | ||||
13371 | if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) | ||||
13372 | return false; | ||||
13373 | return Success(!bres, E); | ||||
13374 | } | ||||
13375 | } | ||||
13376 | } | ||||
13377 | |||||
13378 | bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
13379 | const Expr *SubExpr = E->getSubExpr(); | ||||
13380 | QualType DestType = E->getType(); | ||||
13381 | assert(DestType->isFixedPointType() &&(static_cast <bool> (DestType->isFixedPointType() && "Expected destination type to be a fixed point type") ? void (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13382, __extension__ __PRETTY_FUNCTION__)) | ||||
13382 | "Expected destination type to be a fixed point type")(static_cast <bool> (DestType->isFixedPointType() && "Expected destination type to be a fixed point type") ? void (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13382, __extension__ __PRETTY_FUNCTION__)); | ||||
13383 | auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); | ||||
13384 | |||||
13385 | switch (E->getCastKind()) { | ||||
13386 | case CK_FixedPointCast: { | ||||
13387 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); | ||||
13388 | if (!EvaluateFixedPoint(SubExpr, Src, Info)) | ||||
13389 | return false; | ||||
13390 | bool Overflowed; | ||||
13391 | APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); | ||||
13392 | if (Overflowed) { | ||||
13393 | if (Info.checkingForUndefinedBehavior()) | ||||
13394 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | ||||
13395 | diag::warn_fixedpoint_constant_overflow) | ||||
13396 | << Result.toString() << E->getType(); | ||||
13397 | if (!HandleOverflow(Info, E, Result, E->getType())) | ||||
13398 | return false; | ||||
13399 | } | ||||
13400 | return Success(Result, E); | ||||
13401 | } | ||||
13402 | case CK_IntegralToFixedPoint: { | ||||
13403 | APSInt Src; | ||||
13404 | if (!EvaluateInteger(SubExpr, Src, Info)) | ||||
13405 | return false; | ||||
13406 | |||||
13407 | bool Overflowed; | ||||
13408 | APFixedPoint IntResult = APFixedPoint::getFromIntValue( | ||||
13409 | Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); | ||||
13410 | |||||
13411 | if (Overflowed) { | ||||
13412 | if (Info.checkingForUndefinedBehavior()) | ||||
13413 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | ||||
13414 | diag::warn_fixedpoint_constant_overflow) | ||||
13415 | << IntResult.toString() << E->getType(); | ||||
13416 | if (!HandleOverflow(Info, E, IntResult, E->getType())) | ||||
13417 | return false; | ||||
13418 | } | ||||
13419 | |||||
13420 | return Success(IntResult, E); | ||||
13421 | } | ||||
13422 | case CK_FloatingToFixedPoint: { | ||||
13423 | APFloat Src(0.0); | ||||
13424 | if (!EvaluateFloat(SubExpr, Src, Info)) | ||||
13425 | return false; | ||||
13426 | |||||
13427 | bool Overflowed; | ||||
13428 | APFixedPoint Result = APFixedPoint::getFromFloatValue( | ||||
13429 | Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); | ||||
13430 | |||||
13431 | if (Overflowed) { | ||||
13432 | if (Info.checkingForUndefinedBehavior()) | ||||
13433 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | ||||
13434 | diag::warn_fixedpoint_constant_overflow) | ||||
13435 | << Result.toString() << E->getType(); | ||||
13436 | if (!HandleOverflow(Info, E, Result, E->getType())) | ||||
13437 | return false; | ||||
13438 | } | ||||
13439 | |||||
13440 | return Success(Result, E); | ||||
13441 | } | ||||
13442 | case CK_NoOp: | ||||
13443 | case CK_LValueToRValue: | ||||
13444 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
13445 | default: | ||||
13446 | return Error(E); | ||||
13447 | } | ||||
13448 | } | ||||
13449 | |||||
13450 | bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
13451 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | ||||
13452 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
13453 | |||||
13454 | const Expr *LHS = E->getLHS(); | ||||
13455 | const Expr *RHS = E->getRHS(); | ||||
13456 | FixedPointSemantics ResultFXSema = | ||||
13457 | Info.Ctx.getFixedPointSemantics(E->getType()); | ||||
13458 | |||||
13459 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); | ||||
13460 | if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) | ||||
13461 | return false; | ||||
13462 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); | ||||
13463 | if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) | ||||
13464 | return false; | ||||
13465 | |||||
13466 | bool OpOverflow = false, ConversionOverflow = false; | ||||
13467 | APFixedPoint Result(LHSFX.getSemantics()); | ||||
13468 | switch (E->getOpcode()) { | ||||
13469 | case BO_Add: { | ||||
13470 | Result = LHSFX.add(RHSFX, &OpOverflow) | ||||
13471 | .convert(ResultFXSema, &ConversionOverflow); | ||||
13472 | break; | ||||
13473 | } | ||||
13474 | case BO_Sub: { | ||||
13475 | Result = LHSFX.sub(RHSFX, &OpOverflow) | ||||
13476 | .convert(ResultFXSema, &ConversionOverflow); | ||||
13477 | break; | ||||
13478 | } | ||||
13479 | case BO_Mul: { | ||||
13480 | Result = LHSFX.mul(RHSFX, &OpOverflow) | ||||
13481 | .convert(ResultFXSema, &ConversionOverflow); | ||||
13482 | break; | ||||
13483 | } | ||||
13484 | case BO_Div: { | ||||
13485 | if (RHSFX.getValue() == 0) { | ||||
13486 | Info.FFDiag(E, diag::note_expr_divide_by_zero); | ||||
13487 | return false; | ||||
13488 | } | ||||
13489 | Result = LHSFX.div(RHSFX, &OpOverflow) | ||||
13490 | .convert(ResultFXSema, &ConversionOverflow); | ||||
13491 | break; | ||||
13492 | } | ||||
13493 | case BO_Shl: | ||||
13494 | case BO_Shr: { | ||||
13495 | FixedPointSemantics LHSSema = LHSFX.getSemantics(); | ||||
13496 | llvm::APSInt RHSVal = RHSFX.getValue(); | ||||
13497 | |||||
13498 | unsigned ShiftBW = | ||||
13499 | LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); | ||||
13500 | unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); | ||||
13501 | // Embedded-C 4.1.6.2.2: | ||||
13502 | // The right operand must be nonnegative and less than the total number | ||||
13503 | // of (nonpadding) bits of the fixed-point operand ... | ||||
13504 | if (RHSVal.isNegative()) | ||||
13505 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; | ||||
13506 | else if (Amt != RHSVal) | ||||
13507 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | ||||
13508 | << RHSVal << E->getType() << ShiftBW; | ||||
13509 | |||||
13510 | if (E->getOpcode() == BO_Shl) | ||||
13511 | Result = LHSFX.shl(Amt, &OpOverflow); | ||||
13512 | else | ||||
13513 | Result = LHSFX.shr(Amt, &OpOverflow); | ||||
13514 | break; | ||||
13515 | } | ||||
13516 | default: | ||||
13517 | return false; | ||||
13518 | } | ||||
13519 | if (OpOverflow || ConversionOverflow) { | ||||
13520 | if (Info.checkingForUndefinedBehavior()) | ||||
13521 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | ||||
13522 | diag::warn_fixedpoint_constant_overflow) | ||||
13523 | << Result.toString() << E->getType(); | ||||
13524 | if (!HandleOverflow(Info, E, Result, E->getType())) | ||||
13525 | return false; | ||||
13526 | } | ||||
13527 | return Success(Result, E); | ||||
13528 | } | ||||
13529 | |||||
13530 | //===----------------------------------------------------------------------===// | ||||
13531 | // Float Evaluation | ||||
13532 | //===----------------------------------------------------------------------===// | ||||
13533 | |||||
13534 | namespace { | ||||
13535 | class FloatExprEvaluator | ||||
13536 | : public ExprEvaluatorBase<FloatExprEvaluator> { | ||||
13537 | APFloat &Result; | ||||
13538 | public: | ||||
13539 | FloatExprEvaluator(EvalInfo &info, APFloat &result) | ||||
13540 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||
13541 | |||||
13542 | bool Success(const APValue &V, const Expr *e) { | ||||
13543 | Result = V.getFloat(); | ||||
13544 | return true; | ||||
13545 | } | ||||
13546 | |||||
13547 | bool ZeroInitialization(const Expr *E) { | ||||
13548 | Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); | ||||
13549 | return true; | ||||
13550 | } | ||||
13551 | |||||
13552 | bool VisitCallExpr(const CallExpr *E); | ||||
13553 | |||||
13554 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||
13555 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
13556 | bool VisitFloatingLiteral(const FloatingLiteral *E); | ||||
13557 | bool VisitCastExpr(const CastExpr *E); | ||||
13558 | |||||
13559 | bool VisitUnaryReal(const UnaryOperator *E); | ||||
13560 | bool VisitUnaryImag(const UnaryOperator *E); | ||||
13561 | |||||
13562 | // FIXME: Missing: array subscript of vector, member of vector | ||||
13563 | }; | ||||
13564 | } // end anonymous namespace | ||||
13565 | |||||
13566 | static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { | ||||
13567 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13567, __extension__ __PRETTY_FUNCTION__)); | ||||
13568 | assert(E->isPRValue() && E->getType()->isRealFloatingType())(static_cast <bool> (E->isPRValue() && E-> getType()->isRealFloatingType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isRealFloatingType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13568, __extension__ __PRETTY_FUNCTION__)); | ||||
13569 | return FloatExprEvaluator(Info, Result).Visit(E); | ||||
13570 | } | ||||
13571 | |||||
13572 | static bool TryEvaluateBuiltinNaN(const ASTContext &Context, | ||||
13573 | QualType ResultTy, | ||||
13574 | const Expr *Arg, | ||||
13575 | bool SNaN, | ||||
13576 | llvm::APFloat &Result) { | ||||
13577 | const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); | ||||
13578 | if (!S) return false; | ||||
13579 | |||||
13580 | const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); | ||||
13581 | |||||
13582 | llvm::APInt fill; | ||||
13583 | |||||
13584 | // Treat empty strings as if they were zero. | ||||
13585 | if (S->getString().empty()) | ||||
13586 | fill = llvm::APInt(32, 0); | ||||
13587 | else if (S->getString().getAsInteger(0, fill)) | ||||
13588 | return false; | ||||
13589 | |||||
13590 | if (Context.getTargetInfo().isNan2008()) { | ||||
13591 | if (SNaN) | ||||
13592 | Result = llvm::APFloat::getSNaN(Sem, false, &fill); | ||||
13593 | else | ||||
13594 | Result = llvm::APFloat::getQNaN(Sem, false, &fill); | ||||
13595 | } else { | ||||
13596 | // Prior to IEEE 754-2008, architectures were allowed to choose whether | ||||
13597 | // the first bit of their significand was set for qNaN or sNaN. MIPS chose | ||||
13598 | // a different encoding to what became a standard in 2008, and for pre- | ||||
13599 | // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as | ||||
13600 | // sNaN. This is now known as "legacy NaN" encoding. | ||||
13601 | if (SNaN) | ||||
13602 | Result = llvm::APFloat::getQNaN(Sem, false, &fill); | ||||
13603 | else | ||||
13604 | Result = llvm::APFloat::getSNaN(Sem, false, &fill); | ||||
13605 | } | ||||
13606 | |||||
13607 | return true; | ||||
13608 | } | ||||
13609 | |||||
13610 | bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||
13611 | switch (E->getBuiltinCallee()) { | ||||
13612 | default: | ||||
13613 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
13614 | |||||
13615 | case Builtin::BI__builtin_huge_val: | ||||
13616 | case Builtin::BI__builtin_huge_valf: | ||||
13617 | case Builtin::BI__builtin_huge_vall: | ||||
13618 | case Builtin::BI__builtin_huge_valf128: | ||||
13619 | case Builtin::BI__builtin_inf: | ||||
13620 | case Builtin::BI__builtin_inff: | ||||
13621 | case Builtin::BI__builtin_infl: | ||||
13622 | case Builtin::BI__builtin_inff128: { | ||||
13623 | const llvm::fltSemantics &Sem = | ||||
13624 | Info.Ctx.getFloatTypeSemantics(E->getType()); | ||||
13625 | Result = llvm::APFloat::getInf(Sem); | ||||
13626 | return true; | ||||
13627 | } | ||||
13628 | |||||
13629 | case Builtin::BI__builtin_nans: | ||||
13630 | case Builtin::BI__builtin_nansf: | ||||
13631 | case Builtin::BI__builtin_nansl: | ||||
13632 | case Builtin::BI__builtin_nansf128: | ||||
13633 | if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), | ||||
13634 | true, Result)) | ||||
13635 | return Error(E); | ||||
13636 | return true; | ||||
13637 | |||||
13638 | case Builtin::BI__builtin_nan: | ||||
13639 | case Builtin::BI__builtin_nanf: | ||||
13640 | case Builtin::BI__builtin_nanl: | ||||
13641 | case Builtin::BI__builtin_nanf128: | ||||
13642 | // If this is __builtin_nan() turn this into a nan, otherwise we | ||||
13643 | // can't constant fold it. | ||||
13644 | if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), | ||||
13645 | false, Result)) | ||||
13646 | return Error(E); | ||||
13647 | return true; | ||||
13648 | |||||
13649 | case Builtin::BI__builtin_fabs: | ||||
13650 | case Builtin::BI__builtin_fabsf: | ||||
13651 | case Builtin::BI__builtin_fabsl: | ||||
13652 | case Builtin::BI__builtin_fabsf128: | ||||
13653 | // The C standard says "fabs raises no floating-point exceptions, | ||||
13654 | // even if x is a signaling NaN. The returned value is independent of | ||||
13655 | // the current rounding direction mode." Therefore constant folding can | ||||
13656 | // proceed without regard to the floating point settings. | ||||
13657 | // Reference, WG14 N2478 F.10.4.3 | ||||
13658 | if (!EvaluateFloat(E->getArg(0), Result, Info)) | ||||
13659 | return false; | ||||
13660 | |||||
13661 | if (Result.isNegative()) | ||||
13662 | Result.changeSign(); | ||||
13663 | return true; | ||||
13664 | |||||
13665 | case Builtin::BI__arithmetic_fence: | ||||
13666 | return EvaluateFloat(E->getArg(0), Result, Info); | ||||
13667 | |||||
13668 | // FIXME: Builtin::BI__builtin_powi | ||||
13669 | // FIXME: Builtin::BI__builtin_powif | ||||
13670 | // FIXME: Builtin::BI__builtin_powil | ||||
13671 | |||||
13672 | case Builtin::BI__builtin_copysign: | ||||
13673 | case Builtin::BI__builtin_copysignf: | ||||
13674 | case Builtin::BI__builtin_copysignl: | ||||
13675 | case Builtin::BI__builtin_copysignf128: { | ||||
13676 | APFloat RHS(0.); | ||||
13677 | if (!EvaluateFloat(E->getArg(0), Result, Info) || | ||||
13678 | !EvaluateFloat(E->getArg(1), RHS, Info)) | ||||
13679 | return false; | ||||
13680 | Result.copySign(RHS); | ||||
13681 | return true; | ||||
13682 | } | ||||
13683 | } | ||||
13684 | } | ||||
13685 | |||||
13686 | bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||
13687 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||
13688 | ComplexValue CV; | ||||
13689 | if (!EvaluateComplex(E->getSubExpr(), CV, Info)) | ||||
13690 | return false; | ||||
13691 | Result = CV.FloatReal; | ||||
13692 | return true; | ||||
13693 | } | ||||
13694 | |||||
13695 | return Visit(E->getSubExpr()); | ||||
13696 | } | ||||
13697 | |||||
13698 | bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||
13699 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||
13700 | ComplexValue CV; | ||||
13701 | if (!EvaluateComplex(E->getSubExpr(), CV, Info)) | ||||
13702 | return false; | ||||
13703 | Result = CV.FloatImag; | ||||
13704 | return true; | ||||
13705 | } | ||||
13706 | |||||
13707 | VisitIgnoredValue(E->getSubExpr()); | ||||
13708 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); | ||||
13709 | Result = llvm::APFloat::getZero(Sem); | ||||
13710 | return true; | ||||
13711 | } | ||||
13712 | |||||
13713 | bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||
13714 | switch (E->getOpcode()) { | ||||
13715 | default: return Error(E); | ||||
13716 | case UO_Plus: | ||||
13717 | return EvaluateFloat(E->getSubExpr(), Result, Info); | ||||
13718 | case UO_Minus: | ||||
13719 | // In C standard, WG14 N2478 F.3 p4 | ||||
13720 | // "the unary - raises no floating point exceptions, | ||||
13721 | // even if the operand is signalling." | ||||
13722 | if (!EvaluateFloat(E->getSubExpr(), Result, Info)) | ||||
13723 | return false; | ||||
13724 | Result.changeSign(); | ||||
13725 | return true; | ||||
13726 | } | ||||
13727 | } | ||||
13728 | |||||
13729 | bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
13730 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | ||||
13731 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
13732 | |||||
13733 | APFloat RHS(0.0); | ||||
13734 | bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); | ||||
13735 | if (!LHSOK && !Info.noteFailure()) | ||||
13736 | return false; | ||||
13737 | return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && | ||||
13738 | handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); | ||||
13739 | } | ||||
13740 | |||||
13741 | bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { | ||||
13742 | Result = E->getValue(); | ||||
13743 | return true; | ||||
13744 | } | ||||
13745 | |||||
13746 | bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
13747 | const Expr* SubExpr = E->getSubExpr(); | ||||
13748 | |||||
13749 | switch (E->getCastKind()) { | ||||
13750 | default: | ||||
13751 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
13752 | |||||
13753 | case CK_IntegralToFloating: { | ||||
13754 | APSInt IntResult; | ||||
13755 | const FPOptions FPO = E->getFPFeaturesInEffect( | ||||
13756 | Info.Ctx.getLangOpts()); | ||||
13757 | return EvaluateInteger(SubExpr, IntResult, Info) && | ||||
13758 | HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), | ||||
13759 | IntResult, E->getType(), Result); | ||||
13760 | } | ||||
13761 | |||||
13762 | case CK_FixedPointToFloating: { | ||||
13763 | APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); | ||||
13764 | if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) | ||||
13765 | return false; | ||||
13766 | Result = | ||||
13767 | FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); | ||||
13768 | return true; | ||||
13769 | } | ||||
13770 | |||||
13771 | case CK_FloatingCast: { | ||||
13772 | if (!Visit(SubExpr)) | ||||
13773 | return false; | ||||
13774 | return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), | ||||
13775 | Result); | ||||
13776 | } | ||||
13777 | |||||
13778 | case CK_FloatingComplexToReal: { | ||||
13779 | ComplexValue V; | ||||
13780 | if (!EvaluateComplex(SubExpr, V, Info)) | ||||
13781 | return false; | ||||
13782 | Result = V.getComplexFloatReal(); | ||||
13783 | return true; | ||||
13784 | } | ||||
13785 | } | ||||
13786 | } | ||||
13787 | |||||
13788 | //===----------------------------------------------------------------------===// | ||||
13789 | // Complex Evaluation (for float and integer) | ||||
13790 | //===----------------------------------------------------------------------===// | ||||
13791 | |||||
13792 | namespace { | ||||
13793 | class ComplexExprEvaluator | ||||
13794 | : public ExprEvaluatorBase<ComplexExprEvaluator> { | ||||
13795 | ComplexValue &Result; | ||||
13796 | |||||
13797 | public: | ||||
13798 | ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) | ||||
13799 | : ExprEvaluatorBaseTy(info), Result(Result) {} | ||||
13800 | |||||
13801 | bool Success(const APValue &V, const Expr *e) { | ||||
13802 | Result.setFrom(V); | ||||
13803 | return true; | ||||
13804 | } | ||||
13805 | |||||
13806 | bool ZeroInitialization(const Expr *E); | ||||
13807 | |||||
13808 | //===--------------------------------------------------------------------===// | ||||
13809 | // Visitor Methods | ||||
13810 | //===--------------------------------------------------------------------===// | ||||
13811 | |||||
13812 | bool VisitImaginaryLiteral(const ImaginaryLiteral *E); | ||||
13813 | bool VisitCastExpr(const CastExpr *E); | ||||
13814 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
13815 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||
13816 | bool VisitInitListExpr(const InitListExpr *E); | ||||
13817 | bool VisitCallExpr(const CallExpr *E); | ||||
13818 | }; | ||||
13819 | } // end anonymous namespace | ||||
13820 | |||||
13821 | static bool EvaluateComplex(const Expr *E, ComplexValue &Result, | ||||
13822 | EvalInfo &Info) { | ||||
13823 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13823, __extension__ __PRETTY_FUNCTION__)); | ||||
13824 | assert(E->isPRValue() && E->getType()->isAnyComplexType())(static_cast <bool> (E->isPRValue() && E-> getType()->isAnyComplexType()) ? void (0) : __assert_fail ( "E->isPRValue() && E->getType()->isAnyComplexType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13824, __extension__ __PRETTY_FUNCTION__)); | ||||
13825 | return ComplexExprEvaluator(Info, Result).Visit(E); | ||||
13826 | } | ||||
13827 | |||||
13828 | bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { | ||||
13829 | QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); | ||||
13830 | if (ElemTy->isRealFloatingType()) { | ||||
13831 | Result.makeComplexFloat(); | ||||
13832 | APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); | ||||
13833 | Result.FloatReal = Zero; | ||||
13834 | Result.FloatImag = Zero; | ||||
13835 | } else { | ||||
13836 | Result.makeComplexInt(); | ||||
13837 | APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); | ||||
13838 | Result.IntReal = Zero; | ||||
13839 | Result.IntImag = Zero; | ||||
13840 | } | ||||
13841 | return true; | ||||
13842 | } | ||||
13843 | |||||
13844 | bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { | ||||
13845 | const Expr* SubExpr = E->getSubExpr(); | ||||
13846 | |||||
13847 | if (SubExpr->getType()->isRealFloatingType()) { | ||||
13848 | Result.makeComplexFloat(); | ||||
13849 | APFloat &Imag = Result.FloatImag; | ||||
13850 | if (!EvaluateFloat(SubExpr, Imag, Info)) | ||||
13851 | return false; | ||||
13852 | |||||
13853 | Result.FloatReal = APFloat(Imag.getSemantics()); | ||||
13854 | return true; | ||||
13855 | } else { | ||||
13856 | assert(SubExpr->getType()->isIntegerType() &&(static_cast <bool> (SubExpr->getType()->isIntegerType () && "Unexpected imaginary literal.") ? void (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13857, __extension__ __PRETTY_FUNCTION__)) | ||||
13857 | "Unexpected imaginary literal.")(static_cast <bool> (SubExpr->getType()->isIntegerType () && "Unexpected imaginary literal.") ? void (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13857, __extension__ __PRETTY_FUNCTION__)); | ||||
13858 | |||||
13859 | Result.makeComplexInt(); | ||||
13860 | APSInt &Imag = Result.IntImag; | ||||
13861 | if (!EvaluateInteger(SubExpr, Imag, Info)) | ||||
13862 | return false; | ||||
13863 | |||||
13864 | Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); | ||||
13865 | return true; | ||||
13866 | } | ||||
13867 | } | ||||
13868 | |||||
13869 | bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
13870 | |||||
13871 | switch (E->getCastKind()) { | ||||
13872 | case CK_BitCast: | ||||
13873 | case CK_BaseToDerived: | ||||
13874 | case CK_DerivedToBase: | ||||
13875 | case CK_UncheckedDerivedToBase: | ||||
13876 | case CK_Dynamic: | ||||
13877 | case CK_ToUnion: | ||||
13878 | case CK_ArrayToPointerDecay: | ||||
13879 | case CK_FunctionToPointerDecay: | ||||
13880 | case CK_NullToPointer: | ||||
13881 | case CK_NullToMemberPointer: | ||||
13882 | case CK_BaseToDerivedMemberPointer: | ||||
13883 | case CK_DerivedToBaseMemberPointer: | ||||
13884 | case CK_MemberPointerToBoolean: | ||||
13885 | case CK_ReinterpretMemberPointer: | ||||
13886 | case CK_ConstructorConversion: | ||||
13887 | case CK_IntegralToPointer: | ||||
13888 | case CK_PointerToIntegral: | ||||
13889 | case CK_PointerToBoolean: | ||||
13890 | case CK_ToVoid: | ||||
13891 | case CK_VectorSplat: | ||||
13892 | case CK_IntegralCast: | ||||
13893 | case CK_BooleanToSignedIntegral: | ||||
13894 | case CK_IntegralToBoolean: | ||||
13895 | case CK_IntegralToFloating: | ||||
13896 | case CK_FloatingToIntegral: | ||||
13897 | case CK_FloatingToBoolean: | ||||
13898 | case CK_FloatingCast: | ||||
13899 | case CK_CPointerToObjCPointerCast: | ||||
13900 | case CK_BlockPointerToObjCPointerCast: | ||||
13901 | case CK_AnyPointerToBlockPointerCast: | ||||
13902 | case CK_ObjCObjectLValueCast: | ||||
13903 | case CK_FloatingComplexToReal: | ||||
13904 | case CK_FloatingComplexToBoolean: | ||||
13905 | case CK_IntegralComplexToReal: | ||||
13906 | case CK_IntegralComplexToBoolean: | ||||
13907 | case CK_ARCProduceObject: | ||||
13908 | case CK_ARCConsumeObject: | ||||
13909 | case CK_ARCReclaimReturnedObject: | ||||
13910 | case CK_ARCExtendBlockObject: | ||||
13911 | case CK_CopyAndAutoreleaseBlockObject: | ||||
13912 | case CK_BuiltinFnToFnPtr: | ||||
13913 | case CK_ZeroToOCLOpaqueType: | ||||
13914 | case CK_NonAtomicToAtomic: | ||||
13915 | case CK_AddressSpaceConversion: | ||||
13916 | case CK_IntToOCLSampler: | ||||
13917 | case CK_FloatingToFixedPoint: | ||||
13918 | case CK_FixedPointToFloating: | ||||
13919 | case CK_FixedPointCast: | ||||
13920 | case CK_FixedPointToBoolean: | ||||
13921 | case CK_FixedPointToIntegral: | ||||
13922 | case CK_IntegralToFixedPoint: | ||||
13923 | case CK_MatrixCast: | ||||
13924 | llvm_unreachable("invalid cast kind for complex value")::llvm::llvm_unreachable_internal("invalid cast kind for complex value" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 13924); | ||||
13925 | |||||
13926 | case CK_LValueToRValue: | ||||
13927 | case CK_AtomicToNonAtomic: | ||||
13928 | case CK_NoOp: | ||||
13929 | case CK_LValueToRValueBitCast: | ||||
13930 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
13931 | |||||
13932 | case CK_Dependent: | ||||
13933 | case CK_LValueBitCast: | ||||
13934 | case CK_UserDefinedConversion: | ||||
13935 | return Error(E); | ||||
13936 | |||||
13937 | case CK_FloatingRealToComplex: { | ||||
13938 | APFloat &Real = Result.FloatReal; | ||||
13939 | if (!EvaluateFloat(E->getSubExpr(), Real, Info)) | ||||
13940 | return false; | ||||
13941 | |||||
13942 | Result.makeComplexFloat(); | ||||
13943 | Result.FloatImag = APFloat(Real.getSemantics()); | ||||
13944 | return true; | ||||
13945 | } | ||||
13946 | |||||
13947 | case CK_FloatingComplexCast: { | ||||
13948 | if (!Visit(E->getSubExpr())) | ||||
13949 | return false; | ||||
13950 | |||||
13951 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | ||||
13952 | QualType From | ||||
13953 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | ||||
13954 | |||||
13955 | return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && | ||||
13956 | HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); | ||||
13957 | } | ||||
13958 | |||||
13959 | case CK_FloatingComplexToIntegralComplex: { | ||||
13960 | if (!Visit(E->getSubExpr())) | ||||
13961 | return false; | ||||
13962 | |||||
13963 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | ||||
13964 | QualType From | ||||
13965 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | ||||
13966 | Result.makeComplexInt(); | ||||
13967 | return HandleFloatToIntCast(Info, E, From, Result.FloatReal, | ||||
13968 | To, Result.IntReal) && | ||||
13969 | HandleFloatToIntCast(Info, E, From, Result.FloatImag, | ||||
13970 | To, Result.IntImag); | ||||
13971 | } | ||||
13972 | |||||
13973 | case CK_IntegralRealToComplex: { | ||||
13974 | APSInt &Real = Result.IntReal; | ||||
13975 | if (!EvaluateInteger(E->getSubExpr(), Real, Info)) | ||||
13976 | return false; | ||||
13977 | |||||
13978 | Result.makeComplexInt(); | ||||
13979 | Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); | ||||
13980 | return true; | ||||
13981 | } | ||||
13982 | |||||
13983 | case CK_IntegralComplexCast: { | ||||
13984 | if (!Visit(E->getSubExpr())) | ||||
13985 | return false; | ||||
13986 | |||||
13987 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | ||||
13988 | QualType From | ||||
13989 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | ||||
13990 | |||||
13991 | Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); | ||||
13992 | Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); | ||||
13993 | return true; | ||||
13994 | } | ||||
13995 | |||||
13996 | case CK_IntegralComplexToFloatingComplex: { | ||||
13997 | if (!Visit(E->getSubExpr())) | ||||
13998 | return false; | ||||
13999 | |||||
14000 | const FPOptions FPO = E->getFPFeaturesInEffect( | ||||
14001 | Info.Ctx.getLangOpts()); | ||||
14002 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | ||||
14003 | QualType From | ||||
14004 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | ||||
14005 | Result.makeComplexFloat(); | ||||
14006 | return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, | ||||
14007 | To, Result.FloatReal) && | ||||
14008 | HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, | ||||
14009 | To, Result.FloatImag); | ||||
14010 | } | ||||
14011 | } | ||||
14012 | |||||
14013 | llvm_unreachable("unknown cast resulting in complex value")::llvm::llvm_unreachable_internal("unknown cast resulting in complex value" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14013); | ||||
14014 | } | ||||
14015 | |||||
14016 | bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
14017 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | ||||
14018 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
14019 | |||||
14020 | // Track whether the LHS or RHS is real at the type system level. When this is | ||||
14021 | // the case we can simplify our evaluation strategy. | ||||
14022 | bool LHSReal = false, RHSReal = false; | ||||
14023 | |||||
14024 | bool LHSOK; | ||||
14025 | if (E->getLHS()->getType()->isRealFloatingType()) { | ||||
14026 | LHSReal = true; | ||||
14027 | APFloat &Real = Result.FloatReal; | ||||
14028 | LHSOK = EvaluateFloat(E->getLHS(), Real, Info); | ||||
14029 | if (LHSOK) { | ||||
14030 | Result.makeComplexFloat(); | ||||
14031 | Result.FloatImag = APFloat(Real.getSemantics()); | ||||
14032 | } | ||||
14033 | } else { | ||||
14034 | LHSOK = Visit(E->getLHS()); | ||||
14035 | } | ||||
14036 | if (!LHSOK && !Info.noteFailure()) | ||||
14037 | return false; | ||||
14038 | |||||
14039 | ComplexValue RHS; | ||||
14040 | if (E->getRHS()->getType()->isRealFloatingType()) { | ||||
14041 | RHSReal = true; | ||||
14042 | APFloat &Real = RHS.FloatReal; | ||||
14043 | if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) | ||||
14044 | return false; | ||||
14045 | RHS.makeComplexFloat(); | ||||
14046 | RHS.FloatImag = APFloat(Real.getSemantics()); | ||||
14047 | } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) | ||||
14048 | return false; | ||||
14049 | |||||
14050 | assert(!(LHSReal && RHSReal) &&(static_cast <bool> (!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real.") ? void (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14051, __extension__ __PRETTY_FUNCTION__)) | ||||
14051 | "Cannot have both operands of a complex operation be real.")(static_cast <bool> (!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real.") ? void (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14051, __extension__ __PRETTY_FUNCTION__)); | ||||
14052 | switch (E->getOpcode()) { | ||||
14053 | default: return Error(E); | ||||
14054 | case BO_Add: | ||||
14055 | if (Result.isComplexFloat()) { | ||||
14056 | Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), | ||||
14057 | APFloat::rmNearestTiesToEven); | ||||
14058 | if (LHSReal) | ||||
14059 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); | ||||
14060 | else if (!RHSReal) | ||||
14061 | Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), | ||||
14062 | APFloat::rmNearestTiesToEven); | ||||
14063 | } else { | ||||
14064 | Result.getComplexIntReal() += RHS.getComplexIntReal(); | ||||
14065 | Result.getComplexIntImag() += RHS.getComplexIntImag(); | ||||
14066 | } | ||||
14067 | break; | ||||
14068 | case BO_Sub: | ||||
14069 | if (Result.isComplexFloat()) { | ||||
14070 | Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), | ||||
14071 | APFloat::rmNearestTiesToEven); | ||||
14072 | if (LHSReal) { | ||||
14073 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); | ||||
14074 | Result.getComplexFloatImag().changeSign(); | ||||
14075 | } else if (!RHSReal) { | ||||
14076 | Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), | ||||
14077 | APFloat::rmNearestTiesToEven); | ||||
14078 | } | ||||
14079 | } else { | ||||
14080 | Result.getComplexIntReal() -= RHS.getComplexIntReal(); | ||||
14081 | Result.getComplexIntImag() -= RHS.getComplexIntImag(); | ||||
14082 | } | ||||
14083 | break; | ||||
14084 | case BO_Mul: | ||||
14085 | if (Result.isComplexFloat()) { | ||||
14086 | // This is an implementation of complex multiplication according to the | ||||
14087 | // constraints laid out in C11 Annex G. The implementation uses the | ||||
14088 | // following naming scheme: | ||||
14089 | // (a + ib) * (c + id) | ||||
14090 | ComplexValue LHS = Result; | ||||
14091 | APFloat &A = LHS.getComplexFloatReal(); | ||||
14092 | APFloat &B = LHS.getComplexFloatImag(); | ||||
14093 | APFloat &C = RHS.getComplexFloatReal(); | ||||
14094 | APFloat &D = RHS.getComplexFloatImag(); | ||||
14095 | APFloat &ResR = Result.getComplexFloatReal(); | ||||
14096 | APFloat &ResI = Result.getComplexFloatImag(); | ||||
14097 | if (LHSReal) { | ||||
14098 | assert(!RHSReal && "Cannot have two real operands for a complex op!")(static_cast <bool> (!RHSReal && "Cannot have two real operands for a complex op!" ) ? void (0) : __assert_fail ("!RHSReal && \"Cannot have two real operands for a complex op!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14098, __extension__ __PRETTY_FUNCTION__)); | ||||
14099 | ResR = A * C; | ||||
14100 | ResI = A * D; | ||||
14101 | } else if (RHSReal) { | ||||
14102 | ResR = C * A; | ||||
14103 | ResI = C * B; | ||||
14104 | } else { | ||||
14105 | // In the fully general case, we need to handle NaNs and infinities | ||||
14106 | // robustly. | ||||
14107 | APFloat AC = A * C; | ||||
14108 | APFloat BD = B * D; | ||||
14109 | APFloat AD = A * D; | ||||
14110 | APFloat BC = B * C; | ||||
14111 | ResR = AC - BD; | ||||
14112 | ResI = AD + BC; | ||||
14113 | if (ResR.isNaN() && ResI.isNaN()) { | ||||
14114 | bool Recalc = false; | ||||
14115 | if (A.isInfinity() || B.isInfinity()) { | ||||
14116 | A = APFloat::copySign( | ||||
14117 | APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); | ||||
14118 | B = APFloat::copySign( | ||||
14119 | APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); | ||||
14120 | if (C.isNaN()) | ||||
14121 | C = APFloat::copySign(APFloat(C.getSemantics()), C); | ||||
14122 | if (D.isNaN()) | ||||
14123 | D = APFloat::copySign(APFloat(D.getSemantics()), D); | ||||
14124 | Recalc = true; | ||||
14125 | } | ||||
14126 | if (C.isInfinity() || D.isInfinity()) { | ||||
14127 | C = APFloat::copySign( | ||||
14128 | APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); | ||||
14129 | D = APFloat::copySign( | ||||
14130 | APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); | ||||
14131 | if (A.isNaN()) | ||||
14132 | A = APFloat::copySign(APFloat(A.getSemantics()), A); | ||||
14133 | if (B.isNaN()) | ||||
14134 | B = APFloat::copySign(APFloat(B.getSemantics()), B); | ||||
14135 | Recalc = true; | ||||
14136 | } | ||||
14137 | if (!Recalc && (AC.isInfinity() || BD.isInfinity() || | ||||
14138 | AD.isInfinity() || BC.isInfinity())) { | ||||
14139 | if (A.isNaN()) | ||||
14140 | A = APFloat::copySign(APFloat(A.getSemantics()), A); | ||||
14141 | if (B.isNaN()) | ||||
14142 | B = APFloat::copySign(APFloat(B.getSemantics()), B); | ||||
14143 | if (C.isNaN()) | ||||
14144 | C = APFloat::copySign(APFloat(C.getSemantics()), C); | ||||
14145 | if (D.isNaN()) | ||||
14146 | D = APFloat::copySign(APFloat(D.getSemantics()), D); | ||||
14147 | Recalc = true; | ||||
14148 | } | ||||
14149 | if (Recalc) { | ||||
14150 | ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); | ||||
14151 | ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); | ||||
14152 | } | ||||
14153 | } | ||||
14154 | } | ||||
14155 | } else { | ||||
14156 | ComplexValue LHS = Result; | ||||
14157 | Result.getComplexIntReal() = | ||||
14158 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() - | ||||
14159 | LHS.getComplexIntImag() * RHS.getComplexIntImag()); | ||||
14160 | Result.getComplexIntImag() = | ||||
14161 | (LHS.getComplexIntReal() * RHS.getComplexIntImag() + | ||||
14162 | LHS.getComplexIntImag() * RHS.getComplexIntReal()); | ||||
14163 | } | ||||
14164 | break; | ||||
14165 | case BO_Div: | ||||
14166 | if (Result.isComplexFloat()) { | ||||
14167 | // This is an implementation of complex division according to the | ||||
14168 | // constraints laid out in C11 Annex G. The implementation uses the | ||||
14169 | // following naming scheme: | ||||
14170 | // (a + ib) / (c + id) | ||||
14171 | ComplexValue LHS = Result; | ||||
14172 | APFloat &A = LHS.getComplexFloatReal(); | ||||
14173 | APFloat &B = LHS.getComplexFloatImag(); | ||||
14174 | APFloat &C = RHS.getComplexFloatReal(); | ||||
14175 | APFloat &D = RHS.getComplexFloatImag(); | ||||
14176 | APFloat &ResR = Result.getComplexFloatReal(); | ||||
14177 | APFloat &ResI = Result.getComplexFloatImag(); | ||||
14178 | if (RHSReal) { | ||||
14179 | ResR = A / C; | ||||
14180 | ResI = B / C; | ||||
14181 | } else { | ||||
14182 | if (LHSReal) { | ||||
14183 | // No real optimizations we can do here, stub out with zero. | ||||
14184 | B = APFloat::getZero(A.getSemantics()); | ||||
14185 | } | ||||
14186 | int DenomLogB = 0; | ||||
14187 | APFloat MaxCD = maxnum(abs(C), abs(D)); | ||||
14188 | if (MaxCD.isFinite()) { | ||||
14189 | DenomLogB = ilogb(MaxCD); | ||||
14190 | C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); | ||||
14191 | D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); | ||||
14192 | } | ||||
14193 | APFloat Denom = C * C + D * D; | ||||
14194 | ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, | ||||
14195 | APFloat::rmNearestTiesToEven); | ||||
14196 | ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, | ||||
14197 | APFloat::rmNearestTiesToEven); | ||||
14198 | if (ResR.isNaN() && ResI.isNaN()) { | ||||
14199 | if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { | ||||
14200 | ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; | ||||
14201 | ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; | ||||
14202 | } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && | ||||
14203 | D.isFinite()) { | ||||
14204 | A = APFloat::copySign( | ||||
14205 | APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); | ||||
14206 | B = APFloat::copySign( | ||||
14207 | APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); | ||||
14208 | ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); | ||||
14209 | ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); | ||||
14210 | } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { | ||||
14211 | C = APFloat::copySign( | ||||
14212 | APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); | ||||
14213 | D = APFloat::copySign( | ||||
14214 | APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); | ||||
14215 | ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); | ||||
14216 | ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); | ||||
14217 | } | ||||
14218 | } | ||||
14219 | } | ||||
14220 | } else { | ||||
14221 | if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) | ||||
14222 | return Error(E, diag::note_expr_divide_by_zero); | ||||
14223 | |||||
14224 | ComplexValue LHS = Result; | ||||
14225 | APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + | ||||
14226 | RHS.getComplexIntImag() * RHS.getComplexIntImag(); | ||||
14227 | Result.getComplexIntReal() = | ||||
14228 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() + | ||||
14229 | LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; | ||||
14230 | Result.getComplexIntImag() = | ||||
14231 | (LHS.getComplexIntImag() * RHS.getComplexIntReal() - | ||||
14232 | LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; | ||||
14233 | } | ||||
14234 | break; | ||||
14235 | } | ||||
14236 | |||||
14237 | return true; | ||||
14238 | } | ||||
14239 | |||||
14240 | bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||
14241 | // Get the operand value into 'Result'. | ||||
14242 | if (!Visit(E->getSubExpr())) | ||||
14243 | return false; | ||||
14244 | |||||
14245 | switch (E->getOpcode()) { | ||||
14246 | default: | ||||
14247 | return Error(E); | ||||
14248 | case UO_Extension: | ||||
14249 | return true; | ||||
14250 | case UO_Plus: | ||||
14251 | // The result is always just the subexpr. | ||||
14252 | return true; | ||||
14253 | case UO_Minus: | ||||
14254 | if (Result.isComplexFloat()) { | ||||
14255 | Result.getComplexFloatReal().changeSign(); | ||||
14256 | Result.getComplexFloatImag().changeSign(); | ||||
14257 | } | ||||
14258 | else { | ||||
14259 | Result.getComplexIntReal() = -Result.getComplexIntReal(); | ||||
14260 | Result.getComplexIntImag() = -Result.getComplexIntImag(); | ||||
14261 | } | ||||
14262 | return true; | ||||
14263 | case UO_Not: | ||||
14264 | if (Result.isComplexFloat()) | ||||
14265 | Result.getComplexFloatImag().changeSign(); | ||||
14266 | else | ||||
14267 | Result.getComplexIntImag() = -Result.getComplexIntImag(); | ||||
14268 | return true; | ||||
14269 | } | ||||
14270 | } | ||||
14271 | |||||
14272 | bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||
14273 | if (E->getNumInits() == 2) { | ||||
14274 | if (E->getType()->isComplexType()) { | ||||
14275 | Result.makeComplexFloat(); | ||||
14276 | if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) | ||||
14277 | return false; | ||||
14278 | if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) | ||||
14279 | return false; | ||||
14280 | } else { | ||||
14281 | Result.makeComplexInt(); | ||||
14282 | if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) | ||||
14283 | return false; | ||||
14284 | if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) | ||||
14285 | return false; | ||||
14286 | } | ||||
14287 | return true; | ||||
14288 | } | ||||
14289 | return ExprEvaluatorBaseTy::VisitInitListExpr(E); | ||||
14290 | } | ||||
14291 | |||||
14292 | bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||
14293 | switch (E->getBuiltinCallee()) { | ||||
14294 | case Builtin::BI__builtin_complex: | ||||
14295 | Result.makeComplexFloat(); | ||||
14296 | if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) | ||||
14297 | return false; | ||||
14298 | if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) | ||||
14299 | return false; | ||||
14300 | return true; | ||||
14301 | |||||
14302 | default: | ||||
14303 | break; | ||||
14304 | } | ||||
14305 | |||||
14306 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
14307 | } | ||||
14308 | |||||
14309 | //===----------------------------------------------------------------------===// | ||||
14310 | // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic | ||||
14311 | // implicit conversion. | ||||
14312 | //===----------------------------------------------------------------------===// | ||||
14313 | |||||
14314 | namespace { | ||||
14315 | class AtomicExprEvaluator : | ||||
14316 | public ExprEvaluatorBase<AtomicExprEvaluator> { | ||||
14317 | const LValue *This; | ||||
14318 | APValue &Result; | ||||
14319 | public: | ||||
14320 | AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) | ||||
14321 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} | ||||
14322 | |||||
14323 | bool Success(const APValue &V, const Expr *E) { | ||||
14324 | Result = V; | ||||
14325 | return true; | ||||
14326 | } | ||||
14327 | |||||
14328 | bool ZeroInitialization(const Expr *E) { | ||||
14329 | ImplicitValueInitExpr VIE( | ||||
14330 | E->getType()->castAs<AtomicType>()->getValueType()); | ||||
14331 | // For atomic-qualified class (and array) types in C++, initialize the | ||||
14332 | // _Atomic-wrapped subobject directly, in-place. | ||||
14333 | return This ? EvaluateInPlace(Result, Info, *This, &VIE) | ||||
14334 | : Evaluate(Result, Info, &VIE); | ||||
14335 | } | ||||
14336 | |||||
14337 | bool VisitCastExpr(const CastExpr *E) { | ||||
14338 | switch (E->getCastKind()) { | ||||
14339 | default: | ||||
14340 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
14341 | case CK_NonAtomicToAtomic: | ||||
14342 | return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) | ||||
14343 | : Evaluate(Result, Info, E->getSubExpr()); | ||||
14344 | } | ||||
14345 | } | ||||
14346 | }; | ||||
14347 | } // end anonymous namespace | ||||
14348 | |||||
14349 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, | ||||
14350 | EvalInfo &Info) { | ||||
14351 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14351, __extension__ __PRETTY_FUNCTION__)); | ||||
14352 | assert(E->isPRValue() && E->getType()->isAtomicType())(static_cast <bool> (E->isPRValue() && E-> getType()->isAtomicType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isAtomicType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14352, __extension__ __PRETTY_FUNCTION__)); | ||||
14353 | return AtomicExprEvaluator(Info, This, Result).Visit(E); | ||||
14354 | } | ||||
14355 | |||||
14356 | //===----------------------------------------------------------------------===// | ||||
14357 | // Void expression evaluation, primarily for a cast to void on the LHS of a | ||||
14358 | // comma operator | ||||
14359 | //===----------------------------------------------------------------------===// | ||||
14360 | |||||
14361 | namespace { | ||||
14362 | class VoidExprEvaluator | ||||
14363 | : public ExprEvaluatorBase<VoidExprEvaluator> { | ||||
14364 | public: | ||||
14365 | VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} | ||||
14366 | |||||
14367 | bool Success(const APValue &V, const Expr *e) { return true; } | ||||
14368 | |||||
14369 | bool ZeroInitialization(const Expr *E) { return true; } | ||||
14370 | |||||
14371 | bool VisitCastExpr(const CastExpr *E) { | ||||
14372 | switch (E->getCastKind()) { | ||||
14373 | default: | ||||
14374 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
14375 | case CK_ToVoid: | ||||
14376 | VisitIgnoredValue(E->getSubExpr()); | ||||
14377 | return true; | ||||
14378 | } | ||||
14379 | } | ||||
14380 | |||||
14381 | bool VisitCallExpr(const CallExpr *E) { | ||||
14382 | switch (E->getBuiltinCallee()) { | ||||
14383 | case Builtin::BI__assume: | ||||
14384 | case Builtin::BI__builtin_assume: | ||||
14385 | // The argument is not evaluated! | ||||
14386 | return true; | ||||
14387 | |||||
14388 | case Builtin::BI__builtin_operator_delete: | ||||
14389 | return HandleOperatorDeleteCall(Info, E); | ||||
14390 | |||||
14391 | default: | ||||
14392 | break; | ||||
14393 | } | ||||
14394 | |||||
14395 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
14396 | } | ||||
14397 | |||||
14398 | bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); | ||||
14399 | }; | ||||
14400 | } // end anonymous namespace | ||||
14401 | |||||
14402 | bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { | ||||
14403 | // We cannot speculatively evaluate a delete expression. | ||||
14404 | if (Info.SpeculativeEvaluationDepth) | ||||
14405 | return false; | ||||
14406 | |||||
14407 | FunctionDecl *OperatorDelete = E->getOperatorDelete(); | ||||
14408 | if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { | ||||
14409 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | ||||
14410 | << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; | ||||
14411 | return false; | ||||
14412 | } | ||||
14413 | |||||
14414 | const Expr *Arg = E->getArgument(); | ||||
14415 | |||||
14416 | LValue Pointer; | ||||
14417 | if (!EvaluatePointer(Arg, Pointer, Info)) | ||||
14418 | return false; | ||||
14419 | if (Pointer.Designator.Invalid) | ||||
14420 | return false; | ||||
14421 | |||||
14422 | // Deleting a null pointer has no effect. | ||||
14423 | if (Pointer.isNullPointer()) { | ||||
14424 | // This is the only case where we need to produce an extension warning: | ||||
14425 | // the only other way we can succeed is if we find a dynamic allocation, | ||||
14426 | // and we will have warned when we allocated it in that case. | ||||
14427 | if (!Info.getLangOpts().CPlusPlus20) | ||||
14428 | Info.CCEDiag(E, diag::note_constexpr_new); | ||||
14429 | return true; | ||||
14430 | } | ||||
14431 | |||||
14432 | Optional<DynAlloc *> Alloc = CheckDeleteKind( | ||||
14433 | Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); | ||||
14434 | if (!Alloc) | ||||
14435 | return false; | ||||
14436 | QualType AllocType = Pointer.Base.getDynamicAllocType(); | ||||
14437 | |||||
14438 | // For the non-array case, the designator must be empty if the static type | ||||
14439 | // does not have a virtual destructor. | ||||
14440 | if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && | ||||
14441 | !hasVirtualDestructor(Arg->getType()->getPointeeType())) { | ||||
14442 | Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) | ||||
14443 | << Arg->getType()->getPointeeType() << AllocType; | ||||
14444 | return false; | ||||
14445 | } | ||||
14446 | |||||
14447 | // For a class type with a virtual destructor, the selected operator delete | ||||
14448 | // is the one looked up when building the destructor. | ||||
14449 | if (!E->isArrayForm() && !E->isGlobalDelete()) { | ||||
14450 | const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); | ||||
14451 | if (VirtualDelete && | ||||
14452 | !VirtualDelete->isReplaceableGlobalAllocationFunction()) { | ||||
14453 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | ||||
14454 | << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; | ||||
14455 | return false; | ||||
14456 | } | ||||
14457 | } | ||||
14458 | |||||
14459 | if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), | ||||
14460 | (*Alloc)->Value, AllocType)) | ||||
14461 | return false; | ||||
14462 | |||||
14463 | if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { | ||||
14464 | // The element was already erased. This means the destructor call also | ||||
14465 | // deleted the object. | ||||
14466 | // FIXME: This probably results in undefined behavior before we get this | ||||
14467 | // far, and should be diagnosed elsewhere first. | ||||
14468 | Info.FFDiag(E, diag::note_constexpr_double_delete); | ||||
14469 | return false; | ||||
14470 | } | ||||
14471 | |||||
14472 | return true; | ||||
14473 | } | ||||
14474 | |||||
14475 | static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { | ||||
14476 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14476, __extension__ __PRETTY_FUNCTION__)); | ||||
14477 | assert(E->isPRValue() && E->getType()->isVoidType())(static_cast <bool> (E->isPRValue() && E-> getType()->isVoidType()) ? void (0) : __assert_fail ("E->isPRValue() && E->getType()->isVoidType()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14477, __extension__ __PRETTY_FUNCTION__)); | ||||
14478 | return VoidExprEvaluator(Info).Visit(E); | ||||
14479 | } | ||||
14480 | |||||
14481 | //===----------------------------------------------------------------------===// | ||||
14482 | // Top level Expr::EvaluateAsRValue method. | ||||
14483 | //===----------------------------------------------------------------------===// | ||||
14484 | |||||
14485 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { | ||||
14486 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14486, __extension__ __PRETTY_FUNCTION__)); | ||||
14487 | // In C, function designators are not lvalues, but we evaluate them as if they | ||||
14488 | // are. | ||||
14489 | QualType T = E->getType(); | ||||
14490 | if (E->isGLValue() || T->isFunctionType()) { | ||||
14491 | LValue LV; | ||||
14492 | if (!EvaluateLValue(E, LV, Info)) | ||||
14493 | return false; | ||||
14494 | LV.moveInto(Result); | ||||
14495 | } else if (T->isVectorType()) { | ||||
14496 | if (!EvaluateVector(E, Result, Info)) | ||||
14497 | return false; | ||||
14498 | } else if (T->isIntegralOrEnumerationType()) { | ||||
14499 | if (!IntExprEvaluator(Info, Result).Visit(E)) | ||||
14500 | return false; | ||||
14501 | } else if (T->hasPointerRepresentation()) { | ||||
14502 | LValue LV; | ||||
14503 | if (!EvaluatePointer(E, LV, Info)) | ||||
14504 | return false; | ||||
14505 | LV.moveInto(Result); | ||||
14506 | } else if (T->isRealFloatingType()) { | ||||
14507 | llvm::APFloat F(0.0); | ||||
14508 | if (!EvaluateFloat(E, F, Info)) | ||||
14509 | return false; | ||||
14510 | Result = APValue(F); | ||||
14511 | } else if (T->isAnyComplexType()) { | ||||
14512 | ComplexValue C; | ||||
14513 | if (!EvaluateComplex(E, C, Info)) | ||||
14514 | return false; | ||||
14515 | C.moveInto(Result); | ||||
14516 | } else if (T->isFixedPointType()) { | ||||
14517 | if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; | ||||
14518 | } else if (T->isMemberPointerType()) { | ||||
14519 | MemberPtr P; | ||||
14520 | if (!EvaluateMemberPointer(E, P, Info)) | ||||
14521 | return false; | ||||
14522 | P.moveInto(Result); | ||||
14523 | return true; | ||||
14524 | } else if (T->isArrayType()) { | ||||
14525 | LValue LV; | ||||
14526 | APValue &Value = | ||||
14527 | Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); | ||||
14528 | if (!EvaluateArray(E, LV, Value, Info)) | ||||
14529 | return false; | ||||
14530 | Result = Value; | ||||
14531 | } else if (T->isRecordType()) { | ||||
14532 | LValue LV; | ||||
14533 | APValue &Value = | ||||
14534 | Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); | ||||
14535 | if (!EvaluateRecord(E, LV, Value, Info)) | ||||
14536 | return false; | ||||
14537 | Result = Value; | ||||
14538 | } else if (T->isVoidType()) { | ||||
14539 | if (!Info.getLangOpts().CPlusPlus11) | ||||
14540 | Info.CCEDiag(E, diag::note_constexpr_nonliteral) | ||||
14541 | << E->getType(); | ||||
14542 | if (!EvaluateVoid(E, Info)) | ||||
14543 | return false; | ||||
14544 | } else if (T->isAtomicType()) { | ||||
14545 | QualType Unqual = T.getAtomicUnqualifiedType(); | ||||
14546 | if (Unqual->isArrayType() || Unqual->isRecordType()) { | ||||
14547 | LValue LV; | ||||
14548 | APValue &Value = Info.CurrentCall->createTemporary( | ||||
14549 | E, Unqual, ScopeKind::FullExpression, LV); | ||||
14550 | if (!EvaluateAtomic(E, &LV, Value, Info)) | ||||
14551 | return false; | ||||
14552 | } else { | ||||
14553 | if (!EvaluateAtomic(E, nullptr, Result, Info)) | ||||
14554 | return false; | ||||
14555 | } | ||||
14556 | } else if (Info.getLangOpts().CPlusPlus11) { | ||||
14557 | Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); | ||||
14558 | return false; | ||||
14559 | } else { | ||||
14560 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
14561 | return false; | ||||
14562 | } | ||||
14563 | |||||
14564 | return true; | ||||
14565 | } | ||||
14566 | |||||
14567 | /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some | ||||
14568 | /// cases, the in-place evaluation is essential, since later initializers for | ||||
14569 | /// an object can indirectly refer to subobjects which were initialized earlier. | ||||
14570 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, | ||||
14571 | const Expr *E, bool AllowNonLiteralTypes) { | ||||
14572 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14572, __extension__ __PRETTY_FUNCTION__)); | ||||
14573 | |||||
14574 | if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) | ||||
14575 | return false; | ||||
14576 | |||||
14577 | if (E->isPRValue()) { | ||||
14578 | // Evaluate arrays and record types in-place, so that later initializers can | ||||
14579 | // refer to earlier-initialized members of the object. | ||||
14580 | QualType T = E->getType(); | ||||
14581 | if (T->isArrayType()) | ||||
14582 | return EvaluateArray(E, This, Result, Info); | ||||
14583 | else if (T->isRecordType()) | ||||
14584 | return EvaluateRecord(E, This, Result, Info); | ||||
14585 | else if (T->isAtomicType()) { | ||||
14586 | QualType Unqual = T.getAtomicUnqualifiedType(); | ||||
14587 | if (Unqual->isArrayType() || Unqual->isRecordType()) | ||||
14588 | return EvaluateAtomic(E, &This, Result, Info); | ||||
14589 | } | ||||
14590 | } | ||||
14591 | |||||
14592 | // For any other type, in-place evaluation is unimportant. | ||||
14593 | return Evaluate(Result, Info, E); | ||||
14594 | } | ||||
14595 | |||||
14596 | /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit | ||||
14597 | /// lvalue-to-rvalue cast if it is an lvalue. | ||||
14598 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { | ||||
14599 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14599, __extension__ __PRETTY_FUNCTION__)); | ||||
14600 | if (Info.EnableNewConstInterp) { | ||||
14601 | if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) | ||||
14602 | return false; | ||||
14603 | } else { | ||||
14604 | if (E->getType().isNull()) | ||||
14605 | return false; | ||||
14606 | |||||
14607 | if (!CheckLiteralType(Info, E)) | ||||
14608 | return false; | ||||
14609 | |||||
14610 | if (!::Evaluate(Result, Info, E)) | ||||
14611 | return false; | ||||
14612 | |||||
14613 | if (E->isGLValue()) { | ||||
14614 | LValue LV; | ||||
14615 | LV.setFrom(Info.Ctx, Result); | ||||
14616 | if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) | ||||
14617 | return false; | ||||
14618 | } | ||||
14619 | } | ||||
14620 | |||||
14621 | // Check this core constant expression is a constant expression. | ||||
14622 | return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, | ||||
14623 | ConstantExprKind::Normal) && | ||||
14624 | CheckMemoryLeaks(Info); | ||||
14625 | } | ||||
14626 | |||||
14627 | static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, | ||||
14628 | const ASTContext &Ctx, bool &IsConst) { | ||||
14629 | // Fast-path evaluations of integer literals, since we sometimes see files | ||||
14630 | // containing vast quantities of these. | ||||
14631 | if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { | ||||
14632 | Result.Val = APValue(APSInt(L->getValue(), | ||||
14633 | L->getType()->isUnsignedIntegerType())); | ||||
14634 | IsConst = true; | ||||
14635 | return true; | ||||
14636 | } | ||||
14637 | |||||
14638 | // This case should be rare, but we need to check it before we check on | ||||
14639 | // the type below. | ||||
14640 | if (Exp->getType().isNull()) { | ||||
14641 | IsConst = false; | ||||
14642 | return true; | ||||
14643 | } | ||||
14644 | |||||
14645 | // FIXME: Evaluating values of large array and record types can cause | ||||
14646 | // performance problems. Only do so in C++11 for now. | ||||
14647 | if (Exp->isPRValue() && | ||||
14648 | (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) && | ||||
14649 | !Ctx.getLangOpts().CPlusPlus11) { | ||||
14650 | IsConst = false; | ||||
14651 | return true; | ||||
14652 | } | ||||
14653 | return false; | ||||
14654 | } | ||||
14655 | |||||
14656 | static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, | ||||
14657 | Expr::SideEffectsKind SEK) { | ||||
14658 | return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || | ||||
14659 | (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); | ||||
14660 | } | ||||
14661 | |||||
14662 | static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, | ||||
14663 | const ASTContext &Ctx, EvalInfo &Info) { | ||||
14664 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14664, __extension__ __PRETTY_FUNCTION__)); | ||||
14665 | bool IsConst; | ||||
14666 | if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) | ||||
14667 | return IsConst; | ||||
14668 | |||||
14669 | return EvaluateAsRValue(Info, E, Result.Val); | ||||
14670 | } | ||||
14671 | |||||
14672 | static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, | ||||
14673 | const ASTContext &Ctx, | ||||
14674 | Expr::SideEffectsKind AllowSideEffects, | ||||
14675 | EvalInfo &Info) { | ||||
14676 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14676, __extension__ __PRETTY_FUNCTION__)); | ||||
14677 | if (!E->getType()->isIntegralOrEnumerationType()) | ||||
14678 | return false; | ||||
14679 | |||||
14680 | if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || | ||||
14681 | !ExprResult.Val.isInt() || | ||||
14682 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||
14683 | return false; | ||||
14684 | |||||
14685 | return true; | ||||
14686 | } | ||||
14687 | |||||
14688 | static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, | ||||
14689 | const ASTContext &Ctx, | ||||
14690 | Expr::SideEffectsKind AllowSideEffects, | ||||
14691 | EvalInfo &Info) { | ||||
14692 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14692, __extension__ __PRETTY_FUNCTION__)); | ||||
14693 | if (!E->getType()->isFixedPointType()) | ||||
14694 | return false; | ||||
14695 | |||||
14696 | if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) | ||||
14697 | return false; | ||||
14698 | |||||
14699 | if (!ExprResult.Val.isFixedPoint() || | ||||
14700 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||
14701 | return false; | ||||
14702 | |||||
14703 | return true; | ||||
14704 | } | ||||
14705 | |||||
14706 | /// EvaluateAsRValue - Return true if this is a constant which we can fold using | ||||
14707 | /// any crazy technique (that has nothing to do with language standards) that | ||||
14708 | /// we want to. If this function returns true, it returns the folded constant | ||||
14709 | /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion | ||||
14710 | /// will be applied to the result. | ||||
14711 | bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, | ||||
14712 | bool InConstantContext) const { | ||||
14713 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14714, __extension__ __PRETTY_FUNCTION__)) | ||||
14714 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14714, __extension__ __PRETTY_FUNCTION__)); | ||||
14715 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||
14716 | Info.InConstantContext = InConstantContext; | ||||
14717 | return ::EvaluateAsRValue(this, Result, Ctx, Info); | ||||
14718 | } | ||||
14719 | |||||
14720 | bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, | ||||
14721 | bool InConstantContext) const { | ||||
14722 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14723, __extension__ __PRETTY_FUNCTION__)) | ||||
14723 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14723, __extension__ __PRETTY_FUNCTION__)); | ||||
14724 | EvalResult Scratch; | ||||
14725 | return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && | ||||
14726 | HandleConversionToBool(Scratch.Val, Result); | ||||
14727 | } | ||||
14728 | |||||
14729 | bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, | ||||
14730 | SideEffectsKind AllowSideEffects, | ||||
14731 | bool InConstantContext) const { | ||||
14732 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14733, __extension__ __PRETTY_FUNCTION__)) | ||||
14733 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14733, __extension__ __PRETTY_FUNCTION__)); | ||||
14734 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||
14735 | Info.InConstantContext = InConstantContext; | ||||
14736 | return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); | ||||
14737 | } | ||||
14738 | |||||
14739 | bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, | ||||
14740 | SideEffectsKind AllowSideEffects, | ||||
14741 | bool InConstantContext) const { | ||||
14742 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14743, __extension__ __PRETTY_FUNCTION__)) | ||||
14743 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14743, __extension__ __PRETTY_FUNCTION__)); | ||||
14744 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||
14745 | Info.InConstantContext = InConstantContext; | ||||
14746 | return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); | ||||
14747 | } | ||||
14748 | |||||
14749 | bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, | ||||
14750 | SideEffectsKind AllowSideEffects, | ||||
14751 | bool InConstantContext) const { | ||||
14752 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14753, __extension__ __PRETTY_FUNCTION__)) | ||||
14753 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14753, __extension__ __PRETTY_FUNCTION__)); | ||||
14754 | |||||
14755 | if (!getType()->isRealFloatingType()) | ||||
14756 | return false; | ||||
14757 | |||||
14758 | EvalResult ExprResult; | ||||
14759 | if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || | ||||
14760 | !ExprResult.Val.isFloat() || | ||||
14761 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||
14762 | return false; | ||||
14763 | |||||
14764 | Result = ExprResult.Val.getFloat(); | ||||
14765 | return true; | ||||
14766 | } | ||||
14767 | |||||
14768 | bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, | ||||
14769 | bool InConstantContext) const { | ||||
14770 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14771, __extension__ __PRETTY_FUNCTION__)) | ||||
14771 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14771, __extension__ __PRETTY_FUNCTION__)); | ||||
14772 | |||||
14773 | EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); | ||||
14774 | Info.InConstantContext = InConstantContext; | ||||
14775 | LValue LV; | ||||
14776 | CheckedTemporaries CheckedTemps; | ||||
14777 | if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || | ||||
14778 | Result.HasSideEffects || | ||||
14779 | !CheckLValueConstantExpression(Info, getExprLoc(), | ||||
14780 | Ctx.getLValueReferenceType(getType()), LV, | ||||
14781 | ConstantExprKind::Normal, CheckedTemps)) | ||||
14782 | return false; | ||||
14783 | |||||
14784 | LV.moveInto(Result.Val); | ||||
14785 | return true; | ||||
14786 | } | ||||
14787 | |||||
14788 | static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, | ||||
14789 | APValue DestroyedValue, QualType Type, | ||||
14790 | SourceLocation Loc, Expr::EvalStatus &EStatus, | ||||
14791 | bool IsConstantDestruction) { | ||||
14792 | EvalInfo Info(Ctx, EStatus, | ||||
14793 | IsConstantDestruction ? EvalInfo::EM_ConstantExpression | ||||
14794 | : EvalInfo::EM_ConstantFold); | ||||
14795 | Info.setEvaluatingDecl(Base, DestroyedValue, | ||||
14796 | EvalInfo::EvaluatingDeclKind::Dtor); | ||||
14797 | Info.InConstantContext = IsConstantDestruction; | ||||
14798 | |||||
14799 | LValue LVal; | ||||
14800 | LVal.set(Base); | ||||
14801 | |||||
14802 | if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || | ||||
14803 | EStatus.HasSideEffects) | ||||
14804 | return false; | ||||
14805 | |||||
14806 | if (!Info.discardCleanups()) | ||||
14807 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14807); | ||||
14808 | |||||
14809 | return true; | ||||
14810 | } | ||||
14811 | |||||
14812 | bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, | ||||
14813 | ConstantExprKind Kind) const { | ||||
14814 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14815, __extension__ __PRETTY_FUNCTION__)) | ||||
14815 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14815, __extension__ __PRETTY_FUNCTION__)); | ||||
14816 | |||||
14817 | EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; | ||||
14818 | EvalInfo Info(Ctx, Result, EM); | ||||
14819 | Info.InConstantContext = true; | ||||
14820 | |||||
14821 | // The type of the object we're initializing is 'const T' for a class NTTP. | ||||
14822 | QualType T = getType(); | ||||
14823 | if (Kind == ConstantExprKind::ClassTemplateArgument) | ||||
14824 | T.addConst(); | ||||
14825 | |||||
14826 | // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to | ||||
14827 | // represent the result of the evaluation. CheckConstantExpression ensures | ||||
14828 | // this doesn't escape. | ||||
14829 | MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); | ||||
14830 | APValue::LValueBase Base(&BaseMTE); | ||||
14831 | |||||
14832 | Info.setEvaluatingDecl(Base, Result.Val); | ||||
14833 | LValue LVal; | ||||
14834 | LVal.set(Base); | ||||
14835 | |||||
14836 | if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) | ||||
14837 | return false; | ||||
14838 | |||||
14839 | if (!Info.discardCleanups()) | ||||
14840 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14840); | ||||
14841 | |||||
14842 | if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), | ||||
14843 | Result.Val, Kind)) | ||||
14844 | return false; | ||||
14845 | if (!CheckMemoryLeaks(Info)) | ||||
14846 | return false; | ||||
14847 | |||||
14848 | // If this is a class template argument, it's required to have constant | ||||
14849 | // destruction too. | ||||
14850 | if (Kind == ConstantExprKind::ClassTemplateArgument && | ||||
14851 | (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, | ||||
14852 | true) || | ||||
14853 | Result.HasSideEffects)) { | ||||
14854 | // FIXME: Prefix a note to indicate that the problem is lack of constant | ||||
14855 | // destruction. | ||||
14856 | return false; | ||||
14857 | } | ||||
14858 | |||||
14859 | return true; | ||||
14860 | } | ||||
14861 | |||||
14862 | bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, | ||||
14863 | const VarDecl *VD, | ||||
14864 | SmallVectorImpl<PartialDiagnosticAt> &Notes, | ||||
14865 | bool IsConstantInitialization) const { | ||||
14866 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14867, __extension__ __PRETTY_FUNCTION__)) | ||||
14867 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14867, __extension__ __PRETTY_FUNCTION__)); | ||||
14868 | |||||
14869 | // FIXME: Evaluating initializers for large array and record types can cause | ||||
14870 | // performance problems. Only do so in C++11 for now. | ||||
14871 | if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) && | ||||
14872 | !Ctx.getLangOpts().CPlusPlus11) | ||||
14873 | return false; | ||||
14874 | |||||
14875 | Expr::EvalStatus EStatus; | ||||
14876 | EStatus.Diag = &Notes; | ||||
14877 | |||||
14878 | EvalInfo Info(Ctx, EStatus, | ||||
14879 | (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) | ||||
14880 | ? EvalInfo::EM_ConstantExpression | ||||
14881 | : EvalInfo::EM_ConstantFold); | ||||
14882 | Info.setEvaluatingDecl(VD, Value); | ||||
14883 | Info.InConstantContext = IsConstantInitialization; | ||||
14884 | |||||
14885 | SourceLocation DeclLoc = VD->getLocation(); | ||||
14886 | QualType DeclTy = VD->getType(); | ||||
14887 | |||||
14888 | if (Info.EnableNewConstInterp) { | ||||
14889 | auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); | ||||
14890 | if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) | ||||
14891 | return false; | ||||
14892 | } else { | ||||
14893 | LValue LVal; | ||||
14894 | LVal.set(VD); | ||||
14895 | |||||
14896 | if (!EvaluateInPlace(Value, Info, LVal, this, | ||||
14897 | /*AllowNonLiteralTypes=*/true) || | ||||
14898 | EStatus.HasSideEffects) | ||||
14899 | return false; | ||||
14900 | |||||
14901 | // At this point, any lifetime-extended temporaries are completely | ||||
14902 | // initialized. | ||||
14903 | Info.performLifetimeExtension(); | ||||
14904 | |||||
14905 | if (!Info.discardCleanups()) | ||||
14906 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14906); | ||||
14907 | } | ||||
14908 | return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, | ||||
14909 | ConstantExprKind::Normal) && | ||||
14910 | CheckMemoryLeaks(Info); | ||||
14911 | } | ||||
14912 | |||||
14913 | bool VarDecl::evaluateDestruction( | ||||
14914 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const { | ||||
14915 | Expr::EvalStatus EStatus; | ||||
14916 | EStatus.Diag = &Notes; | ||||
14917 | |||||
14918 | // Only treat the destruction as constant destruction if we formally have | ||||
14919 | // constant initialization (or are usable in a constant expression). | ||||
14920 | bool IsConstantDestruction = hasConstantInitialization(); | ||||
14921 | |||||
14922 | // Make a copy of the value for the destructor to mutate, if we know it. | ||||
14923 | // Otherwise, treat the value as default-initialized; if the destructor works | ||||
14924 | // anyway, then the destruction is constant (and must be essentially empty). | ||||
14925 | APValue DestroyedValue; | ||||
14926 | if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) | ||||
14927 | DestroyedValue = *getEvaluatedValue(); | ||||
14928 | else if (!getDefaultInitValue(getType(), DestroyedValue)) | ||||
14929 | return false; | ||||
14930 | |||||
14931 | if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), | ||||
14932 | getType(), getLocation(), EStatus, | ||||
14933 | IsConstantDestruction) || | ||||
14934 | EStatus.HasSideEffects) | ||||
14935 | return false; | ||||
14936 | |||||
14937 | ensureEvaluatedStmt()->HasConstantDestruction = true; | ||||
14938 | return true; | ||||
14939 | } | ||||
14940 | |||||
14941 | /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be | ||||
14942 | /// constant folded, but discard the result. | ||||
14943 | bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { | ||||
14944 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14945, __extension__ __PRETTY_FUNCTION__)) | ||||
14945 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14945, __extension__ __PRETTY_FUNCTION__)); | ||||
14946 | |||||
14947 | EvalResult Result; | ||||
14948 | return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && | ||||
14949 | !hasUnacceptableSideEffect(Result, SEK); | ||||
14950 | } | ||||
14951 | |||||
14952 | APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, | ||||
14953 | SmallVectorImpl<PartialDiagnosticAt> *Diag) const { | ||||
14954 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14955, __extension__ __PRETTY_FUNCTION__)) | ||||
14955 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14955, __extension__ __PRETTY_FUNCTION__)); | ||||
14956 | |||||
14957 | EvalResult EVResult; | ||||
14958 | EVResult.Diag = Diag; | ||||
14959 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||
14960 | Info.InConstantContext = true; | ||||
14961 | |||||
14962 | bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); | ||||
14963 | (void)Result; | ||||
14964 | assert(Result && "Could not evaluate expression")(static_cast <bool> (Result && "Could not evaluate expression" ) ? void (0) : __assert_fail ("Result && \"Could not evaluate expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14964, __extension__ __PRETTY_FUNCTION__)); | ||||
14965 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")(static_cast <bool> (EVResult.Val.isInt() && "Expression did not evaluate to integer" ) ? void (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14965, __extension__ __PRETTY_FUNCTION__)); | ||||
14966 | |||||
14967 | return EVResult.Val.getInt(); | ||||
14968 | } | ||||
14969 | |||||
14970 | APSInt Expr::EvaluateKnownConstIntCheckOverflow( | ||||
14971 | const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { | ||||
14972 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14973, __extension__ __PRETTY_FUNCTION__)) | ||||
14973 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14973, __extension__ __PRETTY_FUNCTION__)); | ||||
14974 | |||||
14975 | EvalResult EVResult; | ||||
14976 | EVResult.Diag = Diag; | ||||
14977 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||
14978 | Info.InConstantContext = true; | ||||
14979 | Info.CheckingForUndefinedBehavior = true; | ||||
14980 | |||||
14981 | bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); | ||||
14982 | (void)Result; | ||||
14983 | assert(Result && "Could not evaluate expression")(static_cast <bool> (Result && "Could not evaluate expression" ) ? void (0) : __assert_fail ("Result && \"Could not evaluate expression\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14983, __extension__ __PRETTY_FUNCTION__)); | ||||
14984 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")(static_cast <bool> (EVResult.Val.isInt() && "Expression did not evaluate to integer" ) ? void (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14984, __extension__ __PRETTY_FUNCTION__)); | ||||
14985 | |||||
14986 | return EVResult.Val.getInt(); | ||||
14987 | } | ||||
14988 | |||||
14989 | void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { | ||||
14990 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14991, __extension__ __PRETTY_FUNCTION__)) | ||||
14991 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 14991, __extension__ __PRETTY_FUNCTION__)); | ||||
14992 | |||||
14993 | bool IsConst; | ||||
14994 | EvalResult EVResult; | ||||
14995 | if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { | ||||
14996 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||
14997 | Info.CheckingForUndefinedBehavior = true; | ||||
14998 | (void)::EvaluateAsRValue(Info, this, EVResult.Val); | ||||
14999 | } | ||||
15000 | } | ||||
15001 | |||||
15002 | bool Expr::EvalResult::isGlobalLValue() const { | ||||
15003 | assert(Val.isLValue())(static_cast <bool> (Val.isLValue()) ? void (0) : __assert_fail ("Val.isLValue()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15003, __extension__ __PRETTY_FUNCTION__)); | ||||
15004 | return IsGlobalLValue(Val.getLValueBase()); | ||||
15005 | } | ||||
15006 | |||||
15007 | /// isIntegerConstantExpr - this recursive routine will test if an expression is | ||||
15008 | /// an integer constant expression. | ||||
15009 | |||||
15010 | /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, | ||||
15011 | /// comma, etc | ||||
15012 | |||||
15013 | // CheckICE - This function does the fundamental ICE checking: the returned | ||||
15014 | // ICEDiag contains an ICEKind indicating whether the expression is an ICE, | ||||
15015 | // and a (possibly null) SourceLocation indicating the location of the problem. | ||||
15016 | // | ||||
15017 | // Note that to reduce code duplication, this helper does no evaluation | ||||
15018 | // itself; the caller checks whether the expression is evaluatable, and | ||||
15019 | // in the rare cases where CheckICE actually cares about the evaluated | ||||
15020 | // value, it calls into Evaluate. | ||||
15021 | |||||
15022 | namespace { | ||||
15023 | |||||
15024 | enum ICEKind { | ||||
15025 | /// This expression is an ICE. | ||||
15026 | IK_ICE, | ||||
15027 | /// This expression is not an ICE, but if it isn't evaluated, it's | ||||
15028 | /// a legal subexpression for an ICE. This return value is used to handle | ||||
15029 | /// the comma operator in C99 mode, and non-constant subexpressions. | ||||
15030 | IK_ICEIfUnevaluated, | ||||
15031 | /// This expression is not an ICE, and is not a legal subexpression for one. | ||||
15032 | IK_NotICE | ||||
15033 | }; | ||||
15034 | |||||
15035 | struct ICEDiag { | ||||
15036 | ICEKind Kind; | ||||
15037 | SourceLocation Loc; | ||||
15038 | |||||
15039 | ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} | ||||
15040 | }; | ||||
15041 | |||||
15042 | } | ||||
15043 | |||||
15044 | static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } | ||||
15045 | |||||
15046 | static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } | ||||
15047 | |||||
15048 | static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { | ||||
15049 | Expr::EvalResult EVResult; | ||||
15050 | Expr::EvalStatus Status; | ||||
15051 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); | ||||
15052 | |||||
15053 | Info.InConstantContext = true; | ||||
15054 | if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || | ||||
15055 | !EVResult.Val.isInt()) | ||||
15056 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15057 | |||||
15058 | return NoDiag(); | ||||
15059 | } | ||||
15060 | |||||
15061 | static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { | ||||
15062 | assert(!E->isValueDependent() && "Should not see value dependent exprs!")(static_cast <bool> (!E->isValueDependent() && "Should not see value dependent exprs!") ? void (0) : __assert_fail ("!E->isValueDependent() && \"Should not see value dependent exprs!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15062, __extension__ __PRETTY_FUNCTION__)); | ||||
15063 | if (!E->getType()->isIntegralOrEnumerationType()) | ||||
15064 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15065 | |||||
15066 | switch (E->getStmtClass()) { | ||||
15067 | #define ABSTRACT_STMT(Node) | ||||
15068 | #define STMT(Node, Base) case Expr::Node##Class: | ||||
15069 | #define EXPR(Node, Base) | ||||
15070 | #include "clang/AST/StmtNodes.inc" | ||||
15071 | case Expr::PredefinedExprClass: | ||||
15072 | case Expr::FloatingLiteralClass: | ||||
15073 | case Expr::ImaginaryLiteralClass: | ||||
15074 | case Expr::StringLiteralClass: | ||||
15075 | case Expr::ArraySubscriptExprClass: | ||||
15076 | case Expr::MatrixSubscriptExprClass: | ||||
15077 | case Expr::OMPArraySectionExprClass: | ||||
15078 | case Expr::OMPArrayShapingExprClass: | ||||
15079 | case Expr::OMPIteratorExprClass: | ||||
15080 | case Expr::MemberExprClass: | ||||
15081 | case Expr::CompoundAssignOperatorClass: | ||||
15082 | case Expr::CompoundLiteralExprClass: | ||||
15083 | case Expr::ExtVectorElementExprClass: | ||||
15084 | case Expr::DesignatedInitExprClass: | ||||
15085 | case Expr::ArrayInitLoopExprClass: | ||||
15086 | case Expr::ArrayInitIndexExprClass: | ||||
15087 | case Expr::NoInitExprClass: | ||||
15088 | case Expr::DesignatedInitUpdateExprClass: | ||||
15089 | case Expr::ImplicitValueInitExprClass: | ||||
15090 | case Expr::ParenListExprClass: | ||||
15091 | case Expr::VAArgExprClass: | ||||
15092 | case Expr::AddrLabelExprClass: | ||||
15093 | case Expr::StmtExprClass: | ||||
15094 | case Expr::CXXMemberCallExprClass: | ||||
15095 | case Expr::CUDAKernelCallExprClass: | ||||
15096 | case Expr::CXXAddrspaceCastExprClass: | ||||
15097 | case Expr::CXXDynamicCastExprClass: | ||||
15098 | case Expr::CXXTypeidExprClass: | ||||
15099 | case Expr::CXXUuidofExprClass: | ||||
15100 | case Expr::MSPropertyRefExprClass: | ||||
15101 | case Expr::MSPropertySubscriptExprClass: | ||||
15102 | case Expr::CXXNullPtrLiteralExprClass: | ||||
15103 | case Expr::UserDefinedLiteralClass: | ||||
15104 | case Expr::CXXThisExprClass: | ||||
15105 | case Expr::CXXThrowExprClass: | ||||
15106 | case Expr::CXXNewExprClass: | ||||
15107 | case Expr::CXXDeleteExprClass: | ||||
15108 | case Expr::CXXPseudoDestructorExprClass: | ||||
15109 | case Expr::UnresolvedLookupExprClass: | ||||
15110 | case Expr::TypoExprClass: | ||||
15111 | case Expr::RecoveryExprClass: | ||||
15112 | case Expr::DependentScopeDeclRefExprClass: | ||||
15113 | case Expr::CXXConstructExprClass: | ||||
15114 | case Expr::CXXInheritedCtorInitExprClass: | ||||
15115 | case Expr::CXXStdInitializerListExprClass: | ||||
15116 | case Expr::CXXBindTemporaryExprClass: | ||||
15117 | case Expr::ExprWithCleanupsClass: | ||||
15118 | case Expr::CXXTemporaryObjectExprClass: | ||||
15119 | case Expr::CXXUnresolvedConstructExprClass: | ||||
15120 | case Expr::CXXDependentScopeMemberExprClass: | ||||
15121 | case Expr::UnresolvedMemberExprClass: | ||||
15122 | case Expr::ObjCStringLiteralClass: | ||||
15123 | case Expr::ObjCBoxedExprClass: | ||||
15124 | case Expr::ObjCArrayLiteralClass: | ||||
15125 | case Expr::ObjCDictionaryLiteralClass: | ||||
15126 | case Expr::ObjCEncodeExprClass: | ||||
15127 | case Expr::ObjCMessageExprClass: | ||||
15128 | case Expr::ObjCSelectorExprClass: | ||||
15129 | case Expr::ObjCProtocolExprClass: | ||||
15130 | case Expr::ObjCIvarRefExprClass: | ||||
15131 | case Expr::ObjCPropertyRefExprClass: | ||||
15132 | case Expr::ObjCSubscriptRefExprClass: | ||||
15133 | case Expr::ObjCIsaExprClass: | ||||
15134 | case Expr::ObjCAvailabilityCheckExprClass: | ||||
15135 | case Expr::ShuffleVectorExprClass: | ||||
15136 | case Expr::ConvertVectorExprClass: | ||||
15137 | case Expr::BlockExprClass: | ||||
15138 | case Expr::NoStmtClass: | ||||
15139 | case Expr::OpaqueValueExprClass: | ||||
15140 | case Expr::PackExpansionExprClass: | ||||
15141 | case Expr::SubstNonTypeTemplateParmPackExprClass: | ||||
15142 | case Expr::FunctionParmPackExprClass: | ||||
15143 | case Expr::AsTypeExprClass: | ||||
15144 | case Expr::ObjCIndirectCopyRestoreExprClass: | ||||
15145 | case Expr::MaterializeTemporaryExprClass: | ||||
15146 | case Expr::PseudoObjectExprClass: | ||||
15147 | case Expr::AtomicExprClass: | ||||
15148 | case Expr::LambdaExprClass: | ||||
15149 | case Expr::CXXFoldExprClass: | ||||
15150 | case Expr::CoawaitExprClass: | ||||
15151 | case Expr::DependentCoawaitExprClass: | ||||
15152 | case Expr::CoyieldExprClass: | ||||
15153 | case Expr::SYCLUniqueStableNameExprClass: | ||||
15154 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15155 | |||||
15156 | case Expr::InitListExprClass: { | ||||
15157 | // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the | ||||
15158 | // form "T x = { a };" is equivalent to "T x = a;". | ||||
15159 | // Unless we're initializing a reference, T is a scalar as it is known to be | ||||
15160 | // of integral or enumeration type. | ||||
15161 | if (E->isPRValue()) | ||||
15162 | if (cast<InitListExpr>(E)->getNumInits() == 1) | ||||
15163 | return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); | ||||
15164 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15165 | } | ||||
15166 | |||||
15167 | case Expr::SizeOfPackExprClass: | ||||
15168 | case Expr::GNUNullExprClass: | ||||
15169 | case Expr::SourceLocExprClass: | ||||
15170 | return NoDiag(); | ||||
15171 | |||||
15172 | case Expr::SubstNonTypeTemplateParmExprClass: | ||||
15173 | return | ||||
15174 | CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); | ||||
15175 | |||||
15176 | case Expr::ConstantExprClass: | ||||
15177 | return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); | ||||
15178 | |||||
15179 | case Expr::ParenExprClass: | ||||
15180 | return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); | ||||
15181 | case Expr::GenericSelectionExprClass: | ||||
15182 | return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); | ||||
15183 | case Expr::IntegerLiteralClass: | ||||
15184 | case Expr::FixedPointLiteralClass: | ||||
15185 | case Expr::CharacterLiteralClass: | ||||
15186 | case Expr::ObjCBoolLiteralExprClass: | ||||
15187 | case Expr::CXXBoolLiteralExprClass: | ||||
15188 | case Expr::CXXScalarValueInitExprClass: | ||||
15189 | case Expr::TypeTraitExprClass: | ||||
15190 | case Expr::ConceptSpecializationExprClass: | ||||
15191 | case Expr::RequiresExprClass: | ||||
15192 | case Expr::ArrayTypeTraitExprClass: | ||||
15193 | case Expr::ExpressionTraitExprClass: | ||||
15194 | case Expr::CXXNoexceptExprClass: | ||||
15195 | return NoDiag(); | ||||
15196 | case Expr::CallExprClass: | ||||
15197 | case Expr::CXXOperatorCallExprClass: { | ||||
15198 | // C99 6.6/3 allows function calls within unevaluated subexpressions of | ||||
15199 | // constant expressions, but they can never be ICEs because an ICE cannot | ||||
15200 | // contain an operand of (pointer to) function type. | ||||
15201 | const CallExpr *CE = cast<CallExpr>(E); | ||||
15202 | if (CE->getBuiltinCallee()) | ||||
15203 | return CheckEvalInICE(E, Ctx); | ||||
15204 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15205 | } | ||||
15206 | case Expr::CXXRewrittenBinaryOperatorClass: | ||||
15207 | return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), | ||||
15208 | Ctx); | ||||
15209 | case Expr::DeclRefExprClass: { | ||||
15210 | const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); | ||||
15211 | if (isa<EnumConstantDecl>(D)) | ||||
15212 | return NoDiag(); | ||||
15213 | |||||
15214 | // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified | ||||
15215 | // integer variables in constant expressions: | ||||
15216 | // | ||||
15217 | // C++ 7.1.5.1p2 | ||||
15218 | // A variable of non-volatile const-qualified integral or enumeration | ||||
15219 | // type initialized by an ICE can be used in ICEs. | ||||
15220 | // | ||||
15221 | // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In | ||||
15222 | // that mode, use of reference variables should not be allowed. | ||||
15223 | const VarDecl *VD = dyn_cast<VarDecl>(D); | ||||
15224 | if (VD && VD->isUsableInConstantExpressions(Ctx) && | ||||
15225 | !VD->getType()->isReferenceType()) | ||||
15226 | return NoDiag(); | ||||
15227 | |||||
15228 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15229 | } | ||||
15230 | case Expr::UnaryOperatorClass: { | ||||
15231 | const UnaryOperator *Exp = cast<UnaryOperator>(E); | ||||
15232 | switch (Exp->getOpcode()) { | ||||
15233 | case UO_PostInc: | ||||
15234 | case UO_PostDec: | ||||
15235 | case UO_PreInc: | ||||
15236 | case UO_PreDec: | ||||
15237 | case UO_AddrOf: | ||||
15238 | case UO_Deref: | ||||
15239 | case UO_Coawait: | ||||
15240 | // C99 6.6/3 allows increment and decrement within unevaluated | ||||
15241 | // subexpressions of constant expressions, but they can never be ICEs | ||||
15242 | // because an ICE cannot contain an lvalue operand. | ||||
15243 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15244 | case UO_Extension: | ||||
15245 | case UO_LNot: | ||||
15246 | case UO_Plus: | ||||
15247 | case UO_Minus: | ||||
15248 | case UO_Not: | ||||
15249 | case UO_Real: | ||||
15250 | case UO_Imag: | ||||
15251 | return CheckICE(Exp->getSubExpr(), Ctx); | ||||
15252 | } | ||||
15253 | llvm_unreachable("invalid unary operator class")::llvm::llvm_unreachable_internal("invalid unary operator class" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15253); | ||||
15254 | } | ||||
15255 | case Expr::OffsetOfExprClass: { | ||||
15256 | // Note that per C99, offsetof must be an ICE. And AFAIK, using | ||||
15257 | // EvaluateAsRValue matches the proposed gcc behavior for cases like | ||||
15258 | // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect | ||||
15259 | // compliance: we should warn earlier for offsetof expressions with | ||||
15260 | // array subscripts that aren't ICEs, and if the array subscripts | ||||
15261 | // are ICEs, the value of the offsetof must be an integer constant. | ||||
15262 | return CheckEvalInICE(E, Ctx); | ||||
15263 | } | ||||
15264 | case Expr::UnaryExprOrTypeTraitExprClass: { | ||||
15265 | const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); | ||||
15266 | if ((Exp->getKind() == UETT_SizeOf) && | ||||
15267 | Exp->getTypeOfArgument()->isVariableArrayType()) | ||||
15268 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15269 | return NoDiag(); | ||||
15270 | } | ||||
15271 | case Expr::BinaryOperatorClass: { | ||||
15272 | const BinaryOperator *Exp = cast<BinaryOperator>(E); | ||||
15273 | switch (Exp->getOpcode()) { | ||||
15274 | case BO_PtrMemD: | ||||
15275 | case BO_PtrMemI: | ||||
15276 | case BO_Assign: | ||||
15277 | case BO_MulAssign: | ||||
15278 | case BO_DivAssign: | ||||
15279 | case BO_RemAssign: | ||||
15280 | case BO_AddAssign: | ||||
15281 | case BO_SubAssign: | ||||
15282 | case BO_ShlAssign: | ||||
15283 | case BO_ShrAssign: | ||||
15284 | case BO_AndAssign: | ||||
15285 | case BO_XorAssign: | ||||
15286 | case BO_OrAssign: | ||||
15287 | // C99 6.6/3 allows assignments within unevaluated subexpressions of | ||||
15288 | // constant expressions, but they can never be ICEs because an ICE cannot | ||||
15289 | // contain an lvalue operand. | ||||
15290 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15291 | |||||
15292 | case BO_Mul: | ||||
15293 | case BO_Div: | ||||
15294 | case BO_Rem: | ||||
15295 | case BO_Add: | ||||
15296 | case BO_Sub: | ||||
15297 | case BO_Shl: | ||||
15298 | case BO_Shr: | ||||
15299 | case BO_LT: | ||||
15300 | case BO_GT: | ||||
15301 | case BO_LE: | ||||
15302 | case BO_GE: | ||||
15303 | case BO_EQ: | ||||
15304 | case BO_NE: | ||||
15305 | case BO_And: | ||||
15306 | case BO_Xor: | ||||
15307 | case BO_Or: | ||||
15308 | case BO_Comma: | ||||
15309 | case BO_Cmp: { | ||||
15310 | ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); | ||||
15311 | ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); | ||||
15312 | if (Exp->getOpcode() == BO_Div || | ||||
15313 | Exp->getOpcode() == BO_Rem) { | ||||
15314 | // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure | ||||
15315 | // we don't evaluate one. | ||||
15316 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { | ||||
15317 | llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); | ||||
15318 | if (REval == 0) | ||||
15319 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||
15320 | if (REval.isSigned() && REval.isAllOnesValue()) { | ||||
15321 | llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); | ||||
15322 | if (LEval.isMinSignedValue()) | ||||
15323 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||
15324 | } | ||||
15325 | } | ||||
15326 | } | ||||
15327 | if (Exp->getOpcode() == BO_Comma) { | ||||
15328 | if (Ctx.getLangOpts().C99) { | ||||
15329 | // C99 6.6p3 introduces a strange edge case: comma can be in an ICE | ||||
15330 | // if it isn't evaluated. | ||||
15331 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) | ||||
15332 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||
15333 | } else { | ||||
15334 | // In both C89 and C++, commas in ICEs are illegal. | ||||
15335 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15336 | } | ||||
15337 | } | ||||
15338 | return Worst(LHSResult, RHSResult); | ||||
15339 | } | ||||
15340 | case BO_LAnd: | ||||
15341 | case BO_LOr: { | ||||
15342 | ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); | ||||
15343 | ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); | ||||
15344 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { | ||||
15345 | // Rare case where the RHS has a comma "side-effect"; we need | ||||
15346 | // to actually check the condition to see whether the side | ||||
15347 | // with the comma is evaluated. | ||||
15348 | if ((Exp->getOpcode() == BO_LAnd) != | ||||
15349 | (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) | ||||
15350 | return RHSResult; | ||||
15351 | return NoDiag(); | ||||
15352 | } | ||||
15353 | |||||
15354 | return Worst(LHSResult, RHSResult); | ||||
15355 | } | ||||
15356 | } | ||||
15357 | llvm_unreachable("invalid binary operator kind")::llvm::llvm_unreachable_internal("invalid binary operator kind" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15357); | ||||
15358 | } | ||||
15359 | case Expr::ImplicitCastExprClass: | ||||
15360 | case Expr::CStyleCastExprClass: | ||||
15361 | case Expr::CXXFunctionalCastExprClass: | ||||
15362 | case Expr::CXXStaticCastExprClass: | ||||
15363 | case Expr::CXXReinterpretCastExprClass: | ||||
15364 | case Expr::CXXConstCastExprClass: | ||||
15365 | case Expr::ObjCBridgedCastExprClass: { | ||||
15366 | const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); | ||||
15367 | if (isa<ExplicitCastExpr>(E)) { | ||||
15368 | if (const FloatingLiteral *FL | ||||
15369 | = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { | ||||
15370 | unsigned DestWidth = Ctx.getIntWidth(E->getType()); | ||||
15371 | bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); | ||||
15372 | APSInt IgnoredVal(DestWidth, !DestSigned); | ||||
15373 | bool Ignored; | ||||
15374 | // If the value does not fit in the destination type, the behavior is | ||||
15375 | // undefined, so we are not required to treat it as a constant | ||||
15376 | // expression. | ||||
15377 | if (FL->getValue().convertToInteger(IgnoredVal, | ||||
15378 | llvm::APFloat::rmTowardZero, | ||||
15379 | &Ignored) & APFloat::opInvalidOp) | ||||
15380 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15381 | return NoDiag(); | ||||
15382 | } | ||||
15383 | } | ||||
15384 | switch (cast<CastExpr>(E)->getCastKind()) { | ||||
15385 | case CK_LValueToRValue: | ||||
15386 | case CK_AtomicToNonAtomic: | ||||
15387 | case CK_NonAtomicToAtomic: | ||||
15388 | case CK_NoOp: | ||||
15389 | case CK_IntegralToBoolean: | ||||
15390 | case CK_IntegralCast: | ||||
15391 | return CheckICE(SubExpr, Ctx); | ||||
15392 | default: | ||||
15393 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15394 | } | ||||
15395 | } | ||||
15396 | case Expr::BinaryConditionalOperatorClass: { | ||||
15397 | const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); | ||||
15398 | ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); | ||||
15399 | if (CommonResult.Kind == IK_NotICE) return CommonResult; | ||||
15400 | ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); | ||||
15401 | if (FalseResult.Kind == IK_NotICE) return FalseResult; | ||||
15402 | if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; | ||||
15403 | if (FalseResult.Kind == IK_ICEIfUnevaluated && | ||||
15404 | Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); | ||||
15405 | return FalseResult; | ||||
15406 | } | ||||
15407 | case Expr::ConditionalOperatorClass: { | ||||
15408 | const ConditionalOperator *Exp = cast<ConditionalOperator>(E); | ||||
15409 | // If the condition (ignoring parens) is a __builtin_constant_p call, | ||||
15410 | // then only the true side is actually considered in an integer constant | ||||
15411 | // expression, and it is fully evaluated. This is an important GNU | ||||
15412 | // extension. See GCC PR38377 for discussion. | ||||
15413 | if (const CallExpr *CallCE | ||||
15414 | = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) | ||||
15415 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) | ||||
15416 | return CheckEvalInICE(E, Ctx); | ||||
15417 | ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); | ||||
15418 | if (CondResult.Kind == IK_NotICE) | ||||
15419 | return CondResult; | ||||
15420 | |||||
15421 | ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); | ||||
15422 | ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); | ||||
15423 | |||||
15424 | if (TrueResult.Kind == IK_NotICE) | ||||
15425 | return TrueResult; | ||||
15426 | if (FalseResult.Kind == IK_NotICE) | ||||
15427 | return FalseResult; | ||||
15428 | if (CondResult.Kind == IK_ICEIfUnevaluated) | ||||
15429 | return CondResult; | ||||
15430 | if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) | ||||
15431 | return NoDiag(); | ||||
15432 | // Rare case where the diagnostics depend on which side is evaluated | ||||
15433 | // Note that if we get here, CondResult is 0, and at least one of | ||||
15434 | // TrueResult and FalseResult is non-zero. | ||||
15435 | if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) | ||||
15436 | return FalseResult; | ||||
15437 | return TrueResult; | ||||
15438 | } | ||||
15439 | case Expr::CXXDefaultArgExprClass: | ||||
15440 | return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); | ||||
15441 | case Expr::CXXDefaultInitExprClass: | ||||
15442 | return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); | ||||
15443 | case Expr::ChooseExprClass: { | ||||
15444 | return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); | ||||
15445 | } | ||||
15446 | case Expr::BuiltinBitCastExprClass: { | ||||
15447 | if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) | ||||
15448 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
15449 | return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); | ||||
15450 | } | ||||
15451 | } | ||||
15452 | |||||
15453 | llvm_unreachable("Invalid StmtClass!")::llvm::llvm_unreachable_internal("Invalid StmtClass!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15453); | ||||
15454 | } | ||||
15455 | |||||
15456 | /// Evaluate an expression as a C++11 integral constant expression. | ||||
15457 | static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, | ||||
15458 | const Expr *E, | ||||
15459 | llvm::APSInt *Value, | ||||
15460 | SourceLocation *Loc) { | ||||
15461 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||
15462 | if (Loc) *Loc = E->getExprLoc(); | ||||
15463 | return false; | ||||
15464 | } | ||||
15465 | |||||
15466 | APValue Result; | ||||
15467 | if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) | ||||
15468 | return false; | ||||
15469 | |||||
15470 | if (!Result.isInt()) { | ||||
15471 | if (Loc) *Loc = E->getExprLoc(); | ||||
15472 | return false; | ||||
15473 | } | ||||
15474 | |||||
15475 | if (Value) *Value = Result.getInt(); | ||||
15476 | return true; | ||||
15477 | } | ||||
15478 | |||||
15479 | bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, | ||||
15480 | SourceLocation *Loc) const { | ||||
15481 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15482, __extension__ __PRETTY_FUNCTION__)) | ||||
15482 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15482, __extension__ __PRETTY_FUNCTION__)); | ||||
15483 | |||||
15484 | if (Ctx.getLangOpts().CPlusPlus11) | ||||
15485 | return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); | ||||
15486 | |||||
15487 | ICEDiag D = CheckICE(this, Ctx); | ||||
15488 | if (D.Kind != IK_ICE) { | ||||
15489 | if (Loc) *Loc = D.Loc; | ||||
15490 | return false; | ||||
15491 | } | ||||
15492 | return true; | ||||
15493 | } | ||||
15494 | |||||
15495 | Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, | ||||
15496 | SourceLocation *Loc, | ||||
15497 | bool isEvaluated) const { | ||||
15498 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15499, __extension__ __PRETTY_FUNCTION__)) | ||||
15499 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15499, __extension__ __PRETTY_FUNCTION__)); | ||||
15500 | |||||
15501 | APSInt Value; | ||||
15502 | |||||
15503 | if (Ctx.getLangOpts().CPlusPlus11) { | ||||
15504 | if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) | ||||
15505 | return Value; | ||||
15506 | return None; | ||||
15507 | } | ||||
15508 | |||||
15509 | if (!isIntegerConstantExpr(Ctx, Loc)) | ||||
15510 | return None; | ||||
15511 | |||||
15512 | // The only possible side-effects here are due to UB discovered in the | ||||
15513 | // evaluation (for instance, INT_MAX + 1). In such a case, we are still | ||||
15514 | // required to treat the expression as an ICE, so we produce the folded | ||||
15515 | // value. | ||||
15516 | EvalResult ExprResult; | ||||
15517 | Expr::EvalStatus Status; | ||||
15518 | EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); | ||||
15519 | Info.InConstantContext = true; | ||||
15520 | |||||
15521 | if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) | ||||
15522 | llvm_unreachable("ICE cannot be evaluated!")::llvm::llvm_unreachable_internal("ICE cannot be evaluated!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15522); | ||||
15523 | |||||
15524 | return ExprResult.Val.getInt(); | ||||
15525 | } | ||||
15526 | |||||
15527 | bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { | ||||
15528 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15529, __extension__ __PRETTY_FUNCTION__)) | ||||
15529 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15529, __extension__ __PRETTY_FUNCTION__)); | ||||
15530 | |||||
15531 | return CheckICE(this, Ctx).Kind == IK_ICE; | ||||
15532 | } | ||||
15533 | |||||
15534 | bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, | ||||
15535 | SourceLocation *Loc) const { | ||||
15536 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15537, __extension__ __PRETTY_FUNCTION__)) | ||||
15537 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15537, __extension__ __PRETTY_FUNCTION__)); | ||||
15538 | |||||
15539 | // We support this checking in C++98 mode in order to diagnose compatibility | ||||
15540 | // issues. | ||||
15541 | assert(Ctx.getLangOpts().CPlusPlus)(static_cast <bool> (Ctx.getLangOpts().CPlusPlus) ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15541, __extension__ __PRETTY_FUNCTION__)); | ||||
15542 | |||||
15543 | // Build evaluation settings. | ||||
15544 | Expr::EvalStatus Status; | ||||
15545 | SmallVector<PartialDiagnosticAt, 8> Diags; | ||||
15546 | Status.Diag = &Diags; | ||||
15547 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); | ||||
15548 | |||||
15549 | APValue Scratch; | ||||
15550 | bool IsConstExpr = | ||||
15551 | ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && | ||||
15552 | // FIXME: We don't produce a diagnostic for this, but the callers that | ||||
15553 | // call us on arbitrary full-expressions should generally not care. | ||||
15554 | Info.discardCleanups() && !Status.HasSideEffects; | ||||
15555 | |||||
15556 | if (!Diags.empty()) { | ||||
15557 | IsConstExpr = false; | ||||
15558 | if (Loc) *Loc = Diags[0].first; | ||||
15559 | } else if (!IsConstExpr) { | ||||
15560 | // FIXME: This shouldn't happen. | ||||
15561 | if (Loc) *Loc = getExprLoc(); | ||||
15562 | } | ||||
15563 | |||||
15564 | return IsConstExpr; | ||||
15565 | } | ||||
15566 | |||||
15567 | bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, | ||||
15568 | const FunctionDecl *Callee, | ||||
15569 | ArrayRef<const Expr*> Args, | ||||
15570 | const Expr *This) const { | ||||
15571 | assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15572, __extension__ __PRETTY_FUNCTION__)) | ||||
15572 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15572, __extension__ __PRETTY_FUNCTION__)); | ||||
15573 | |||||
15574 | Expr::EvalStatus Status; | ||||
15575 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); | ||||
15576 | Info.InConstantContext = true; | ||||
15577 | |||||
15578 | LValue ThisVal; | ||||
15579 | const LValue *ThisPtr = nullptr; | ||||
15580 | if (This) { | ||||
15581 | #ifndef NDEBUG | ||||
15582 | auto *MD = dyn_cast<CXXMethodDecl>(Callee); | ||||
15583 | assert(MD && "Don't provide `this` for non-methods.")(static_cast <bool> (MD && "Don't provide `this` for non-methods." ) ? void (0) : __assert_fail ("MD && \"Don't provide `this` for non-methods.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15583, __extension__ __PRETTY_FUNCTION__)); | ||||
15584 | assert(!MD->isStatic() && "Don't provide `this` for static methods.")(static_cast <bool> (!MD->isStatic() && "Don't provide `this` for static methods." ) ? void (0) : __assert_fail ("!MD->isStatic() && \"Don't provide `this` for static methods.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15584, __extension__ __PRETTY_FUNCTION__)); | ||||
15585 | #endif | ||||
15586 | if (!This->isValueDependent() && | ||||
15587 | EvaluateObjectArgument(Info, This, ThisVal) && | ||||
15588 | !Info.EvalStatus.HasSideEffects) | ||||
15589 | ThisPtr = &ThisVal; | ||||
15590 | |||||
15591 | // Ignore any side-effects from a failed evaluation. This is safe because | ||||
15592 | // they can't interfere with any other argument evaluation. | ||||
15593 | Info.EvalStatus.HasSideEffects = false; | ||||
15594 | } | ||||
15595 | |||||
15596 | CallRef Call = Info.CurrentCall->createCall(Callee); | ||||
15597 | for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); | ||||
15598 | I != E; ++I) { | ||||
15599 | unsigned Idx = I - Args.begin(); | ||||
15600 | if (Idx >= Callee->getNumParams()) | ||||
15601 | break; | ||||
15602 | const ParmVarDecl *PVD = Callee->getParamDecl(Idx); | ||||
15603 | if ((*I)->isValueDependent() || | ||||
15604 | !EvaluateCallArg(PVD, *I, Call, Info) || | ||||
15605 | Info.EvalStatus.HasSideEffects) { | ||||
15606 | // If evaluation fails, throw away the argument entirely. | ||||
15607 | if (APValue *Slot = Info.getParamSlot(Call, PVD)) | ||||
15608 | *Slot = APValue(); | ||||
15609 | } | ||||
15610 | |||||
15611 | // Ignore any side-effects from a failed evaluation. This is safe because | ||||
15612 | // they can't interfere with any other argument evaluation. | ||||
15613 | Info.EvalStatus.HasSideEffects = false; | ||||
15614 | } | ||||
15615 | |||||
15616 | // Parameter cleanups happen in the caller and are not part of this | ||||
15617 | // evaluation. | ||||
15618 | Info.discardCleanups(); | ||||
15619 | Info.EvalStatus.HasSideEffects = false; | ||||
15620 | |||||
15621 | // Build fake call to Callee. | ||||
15622 | CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); | ||||
15623 | // FIXME: Missing ExprWithCleanups in enable_if conditions? | ||||
15624 | FullExpressionRAII Scope(Info); | ||||
15625 | return Evaluate(Value, Info, this) && Scope.destroy() && | ||||
15626 | !Info.EvalStatus.HasSideEffects; | ||||
15627 | } | ||||
15628 | |||||
15629 | bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, | ||||
15630 | SmallVectorImpl< | ||||
15631 | PartialDiagnosticAt> &Diags) { | ||||
15632 | // FIXME: It would be useful to check constexpr function templates, but at the | ||||
15633 | // moment the constant expression evaluator cannot cope with the non-rigorous | ||||
15634 | // ASTs which we build for dependent expressions. | ||||
15635 | if (FD->isDependentContext()) | ||||
15636 | return true; | ||||
15637 | |||||
15638 | Expr::EvalStatus Status; | ||||
15639 | Status.Diag = &Diags; | ||||
15640 | |||||
15641 | EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); | ||||
15642 | Info.InConstantContext = true; | ||||
15643 | Info.CheckingPotentialConstantExpression = true; | ||||
15644 | |||||
15645 | // The constexpr VM attempts to compile all methods to bytecode here. | ||||
15646 | if (Info.EnableNewConstInterp) { | ||||
15647 | Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); | ||||
15648 | return Diags.empty(); | ||||
15649 | } | ||||
15650 | |||||
15651 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
15652 | const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; | ||||
15653 | |||||
15654 | // Fabricate an arbitrary expression on the stack and pretend that it | ||||
15655 | // is a temporary being used as the 'this' pointer. | ||||
15656 | LValue This; | ||||
15657 | ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); | ||||
15658 | This.set({&VIE, Info.CurrentCall->Index}); | ||||
15659 | |||||
15660 | ArrayRef<const Expr*> Args; | ||||
15661 | |||||
15662 | APValue Scratch; | ||||
15663 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { | ||||
15664 | // Evaluate the call as a constant initializer, to allow the construction | ||||
15665 | // of objects of non-literal types. | ||||
15666 | Info.setEvaluatingDecl(This.getLValueBase(), Scratch); | ||||
15667 | HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); | ||||
15668 | } else { | ||||
15669 | SourceLocation Loc = FD->getLocation(); | ||||
15670 | HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, | ||||
15671 | Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); | ||||
15672 | } | ||||
15673 | |||||
15674 | return Diags.empty(); | ||||
15675 | } | ||||
15676 | |||||
15677 | bool Expr::isPotentialConstantExprUnevaluated(Expr *E, | ||||
15678 | const FunctionDecl *FD, | ||||
15679 | SmallVectorImpl< | ||||
15680 | PartialDiagnosticAt> &Diags) { | ||||
15681 | assert(!E->isValueDependent() &&(static_cast <bool> (!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15682, __extension__ __PRETTY_FUNCTION__)) | ||||
15682 | "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? void (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ExprConstant.cpp" , 15682, __extension__ __PRETTY_FUNCTION__)); | ||||
15683 | |||||
15684 | Expr::EvalStatus Status; | ||||
15685 | Status.Diag = &Diags; | ||||
15686 | |||||
15687 | EvalInfo Info(FD->getASTContext(), Status, | ||||
15688 | EvalInfo::EM_ConstantExpressionUnevaluated); | ||||
15689 | Info.InConstantContext = true; | ||||
15690 | Info.CheckingPotentialConstantExpression = true; | ||||
15691 | |||||
15692 | // Fabricate a call stack frame to give the arguments a plausible cover story. | ||||
15693 | CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); | ||||
15694 | |||||
15695 | APValue ResultScratch; | ||||
15696 | Evaluate(ResultScratch, Info, E); | ||||
15697 | return Diags.empty(); | ||||
15698 | } | ||||
15699 | |||||
15700 | bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, | ||||
15701 | unsigned Type) const { | ||||
15702 | if (!getType()->isPointerType()) | ||||
15703 | return false; | ||||
15704 | |||||
15705 | Expr::EvalStatus Status; | ||||
15706 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); | ||||
15707 | return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); | ||||
15708 | } | ||||
15709 | |||||
15710 | static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, | ||||
15711 | EvalInfo &Info) { | ||||
15712 | if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) | ||||
15713 | return false; | ||||
15714 | |||||
15715 | LValue String; | ||||
15716 | |||||
15717 | if (!EvaluatePointer(E, String, Info)) | ||||
15718 | return false; | ||||
15719 | |||||
15720 | QualType CharTy = E->getType()->getPointeeType(); | ||||
15721 | |||||
15722 | // Fast path: if it's a string literal, search the string value. | ||||
15723 | if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( | ||||
15724 | String.getLValueBase().dyn_cast<const Expr *>())) { | ||||
15725 | StringRef Str = S->getBytes(); | ||||
15726 | int64_t Off = String.Offset.getQuantity(); | ||||
15727 | if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && | ||||
15728 | S->getCharByteWidth() == 1 && | ||||
15729 | // FIXME: Add fast-path for wchar_t too. | ||||
15730 | Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { | ||||
15731 | Str = Str.substr(Off); | ||||
15732 | |||||
15733 | StringRef::size_type Pos = Str.find(0); | ||||
15734 | if (Pos != StringRef::npos) | ||||
15735 | Str = Str.substr(0, Pos); | ||||
15736 | |||||
15737 | Result = Str.size(); | ||||
15738 | return true; | ||||
15739 | } | ||||
15740 | |||||
15741 | // Fall through to slow path. | ||||
15742 | } | ||||
15743 | |||||
15744 | // Slow path: scan the bytes of the string looking for the terminating 0. | ||||
15745 | for (uint64_t Strlen = 0; /**/; ++Strlen) { | ||||
15746 | APValue Char; | ||||
15747 | if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || | ||||
15748 | !Char.isInt()) | ||||
15749 | return false; | ||||
15750 | if (!Char.getInt()) { | ||||
15751 | Result = Strlen; | ||||
15752 | return true; | ||||
15753 | } | ||||
15754 | if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) | ||||
15755 | return false; | ||||
15756 | } | ||||
15757 | } | ||||
15758 | |||||
15759 | bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const { | ||||
15760 | Expr::EvalStatus Status; | ||||
15761 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); | ||||
15762 | return EvaluateBuiltinStrLen(this, Result, Info); | ||||
15763 | } |
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")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 282, __extension__ __PRETTY_FUNCTION__)); |
283 | Mask = (Mask & ~CVRMask) | mask; |
284 | } |
285 | void removeCVRQualifiers(unsigned mask) { |
286 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 286, __extension__ __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")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 293, __extension__ __PRETTY_FUNCTION__)); |
294 | Mask |= mask; |
295 | } |
296 | void addCVRUQualifiers(unsigned mask) { |
297 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")(static_cast <bool> (!(mask & ~CVRMask & ~UMask ) && "bitmask contains non-CVRU bits") ? void (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 297, __extension__ __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)(static_cast <bool> (type) ? void (0) : __assert_fail ( "type", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 315, __extension__ __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)(static_cast <bool> (type) ? void (0) : __assert_fail ( "type", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 343, __extension__ __PRETTY_FUNCTION__)); |
344 | assert(!hasObjCLifetime())(static_cast <bool> (!hasObjCLifetime()) ? void (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 344, __extension__ __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())(static_cast <bool> (Addr == LangAS::Default || hasTargetSpecificAddressSpace ()) ? void (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 373, __extension__ __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)(static_cast <bool> ((unsigned)space <= MaxAddressSpace ) ? void (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 382, __extension__ __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)(static_cast <bool> (space != LangAS::Default) ? void ( 0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 388, __extension__ __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")(static_cast <bool> (!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 397, __extension__ __PRETTY_FUNCTION__)); |
398 | Mask = (Mask & ~FastMask) | mask; |
399 | } |
400 | void removeFastQualifiers(unsigned mask) { |
401 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 401, __extension__ __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")(static_cast <bool> (!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 408, __extension__ __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() ||(static_cast <bool> (getAddressSpace() == qs.getAddressSpace () || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 463, __extension__ __PRETTY_FUNCTION__)) |
463 | !hasAddressSpace() || !qs.hasAddressSpace())(static_cast <bool> (getAddressSpace() == qs.getAddressSpace () || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 463, __extension__ __PRETTY_FUNCTION__)); |
464 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr () || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 465, __extension__ __PRETTY_FUNCTION__)) |
465 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr () || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 465, __extension__ __PRETTY_FUNCTION__)); |
466 | assert(getObjCLifetime() == qs.getObjCLifetime() ||(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime () || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 467, __extension__ __PRETTY_FUNCTION__)) |
467 | !hasObjCLifetime() || !qs.hasObjCLifetime())(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime () || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 467, __extension__ __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 | (A == LangAS::sycl_global && (B == LangAS::sycl_global_device || |
490 | B == LangAS::sycl_global_host)) || |
491 | // Consider pointer size address spaces to be equivalent to default. |
492 | ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && |
493 | (isPtrSizeAddressSpace(B) || B == LangAS::Default)) || |
494 | // Default is a superset of SYCL address spaces. |
495 | (A == LangAS::Default && |
496 | (B == LangAS::sycl_private || B == LangAS::sycl_local || |
497 | B == LangAS::sycl_global || B == LangAS::sycl_global_device || |
498 | B == LangAS::sycl_global_host)) || |
499 | // In HIP device compilation, any cuda address space is allowed |
500 | // to implicitly cast into the default address space. |
501 | (A == LangAS::Default && |
502 | (B == LangAS::cuda_constant || B == LangAS::cuda_device || |
503 | B == LangAS::cuda_shared)); |
504 | } |
505 | |
506 | /// Returns true if the address space in these qualifiers is equal to or |
507 | /// a superset of the address space in the argument qualifiers. |
508 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
509 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
510 | } |
511 | |
512 | /// Determines if these qualifiers compatibly include another set. |
513 | /// Generally this answers the question of whether an object with the other |
514 | /// qualifiers can be safely used as an object with these qualifiers. |
515 | bool compatiblyIncludes(Qualifiers other) const { |
516 | return isAddressSpaceSupersetOf(other) && |
517 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
518 | // be changed. |
519 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
520 | !other.hasObjCGCAttr()) && |
521 | // ObjC lifetime qualifiers must match exactly. |
522 | getObjCLifetime() == other.getObjCLifetime() && |
523 | // CVR qualifiers may subset. |
524 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
525 | // U qualifier may superset. |
526 | (!other.hasUnaligned() || hasUnaligned()); |
527 | } |
528 | |
529 | /// Determines if these qualifiers compatibly include another set of |
530 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
531 | /// |
532 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
533 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
534 | /// including set also contains the 'const' qualifier, or both are non-__weak |
535 | /// and one is None (which can only happen in non-ARC modes). |
536 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
537 | if (getObjCLifetime() == other.getObjCLifetime()) |
538 | return true; |
539 | |
540 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
541 | return false; |
542 | |
543 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
544 | return true; |
545 | |
546 | return hasConst(); |
547 | } |
548 | |
549 | /// Determine whether this set of qualifiers is a strict superset of |
550 | /// another set of qualifiers, not considering qualifier compatibility. |
551 | bool isStrictSupersetOf(Qualifiers Other) const; |
552 | |
553 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
554 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
555 | |
556 | explicit operator bool() const { return hasQualifiers(); } |
557 | |
558 | Qualifiers &operator+=(Qualifiers R) { |
559 | addQualifiers(R); |
560 | return *this; |
561 | } |
562 | |
563 | // Union two qualifier sets. If an enumerated qualifier appears |
564 | // in both sets, use the one from the right. |
565 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
566 | L += R; |
567 | return L; |
568 | } |
569 | |
570 | Qualifiers &operator-=(Qualifiers R) { |
571 | removeQualifiers(R); |
572 | return *this; |
573 | } |
574 | |
575 | /// Compute the difference between two qualifier sets. |
576 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
577 | L -= R; |
578 | return L; |
579 | } |
580 | |
581 | std::string getAsString() const; |
582 | std::string getAsString(const PrintingPolicy &Policy) const; |
583 | |
584 | static std::string getAddrSpaceAsString(LangAS AS); |
585 | |
586 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
587 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
588 | bool appendSpaceIfNonEmpty = false) const; |
589 | |
590 | void Profile(llvm::FoldingSetNodeID &ID) const { |
591 | ID.AddInteger(Mask); |
592 | } |
593 | |
594 | private: |
595 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
596 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
597 | uint32_t Mask = 0; |
598 | |
599 | static const uint32_t UMask = 0x8; |
600 | static const uint32_t UShift = 3; |
601 | static const uint32_t GCAttrMask = 0x30; |
602 | static const uint32_t GCAttrShift = 4; |
603 | static const uint32_t LifetimeMask = 0x1C0; |
604 | static const uint32_t LifetimeShift = 6; |
605 | static const uint32_t AddressSpaceMask = |
606 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
607 | static const uint32_t AddressSpaceShift = 9; |
608 | }; |
609 | |
610 | /// A std::pair-like structure for storing a qualified type split |
611 | /// into its local qualifiers and its locally-unqualified type. |
612 | struct SplitQualType { |
613 | /// The locally-unqualified type. |
614 | const Type *Ty = nullptr; |
615 | |
616 | /// The local qualifiers. |
617 | Qualifiers Quals; |
618 | |
619 | SplitQualType() = default; |
620 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
621 | |
622 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
623 | |
624 | // Make std::tie work. |
625 | std::pair<const Type *,Qualifiers> asPair() const { |
626 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
627 | } |
628 | |
629 | friend bool operator==(SplitQualType a, SplitQualType b) { |
630 | return a.Ty == b.Ty && a.Quals == b.Quals; |
631 | } |
632 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
633 | return a.Ty != b.Ty || a.Quals != b.Quals; |
634 | } |
635 | }; |
636 | |
637 | /// The kind of type we are substituting Objective-C type arguments into. |
638 | /// |
639 | /// The kind of substitution affects the replacement of type parameters when |
640 | /// no concrete type information is provided, e.g., when dealing with an |
641 | /// unspecialized type. |
642 | enum class ObjCSubstitutionContext { |
643 | /// An ordinary type. |
644 | Ordinary, |
645 | |
646 | /// The result type of a method or function. |
647 | Result, |
648 | |
649 | /// The parameter type of a method or function. |
650 | Parameter, |
651 | |
652 | /// The type of a property. |
653 | Property, |
654 | |
655 | /// The superclass of a type. |
656 | Superclass, |
657 | }; |
658 | |
659 | /// A (possibly-)qualified type. |
660 | /// |
661 | /// For efficiency, we don't store CV-qualified types as nodes on their |
662 | /// own: instead each reference to a type stores the qualifiers. This |
663 | /// greatly reduces the number of nodes we need to allocate for types (for |
664 | /// example we only need one for 'int', 'const int', 'volatile int', |
665 | /// 'const volatile int', etc). |
666 | /// |
667 | /// As an added efficiency bonus, instead of making this a pair, we |
668 | /// just store the two bits we care about in the low bits of the |
669 | /// pointer. To handle the packing/unpacking, we make QualType be a |
670 | /// simple wrapper class that acts like a smart pointer. A third bit |
671 | /// indicates whether there are extended qualifiers present, in which |
672 | /// case the pointer points to a special structure. |
673 | class QualType { |
674 | friend class QualifierCollector; |
675 | |
676 | // Thankfully, these are efficiently composable. |
677 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
678 | Qualifiers::FastWidth> Value; |
679 | |
680 | const ExtQuals *getExtQualsUnsafe() const { |
681 | return Value.getPointer().get<const ExtQuals*>(); |
682 | } |
683 | |
684 | const Type *getTypePtrUnsafe() const { |
685 | return Value.getPointer().get<const Type*>(); |
686 | } |
687 | |
688 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
689 | assert(!isNull() && "Cannot retrieve a NULL type pointer")(static_cast <bool> (!isNull() && "Cannot retrieve a NULL type pointer" ) ? void (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 689, __extension__ __PRETTY_FUNCTION__)); |
690 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
691 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
692 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
693 | } |
694 | |
695 | public: |
696 | QualType() = default; |
697 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
698 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
699 | |
700 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
701 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
702 | |
703 | /// Retrieves a pointer to the underlying (unqualified) type. |
704 | /// |
705 | /// This function requires that the type not be NULL. If the type might be |
706 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
707 | const Type *getTypePtr() const; |
708 | |
709 | const Type *getTypePtrOrNull() const; |
710 | |
711 | /// Retrieves a pointer to the name of the base type. |
712 | const IdentifierInfo *getBaseTypeIdentifier() const; |
713 | |
714 | /// Divides a QualType into its unqualified type and a set of local |
715 | /// qualifiers. |
716 | SplitQualType split() const; |
717 | |
718 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
719 | |
720 | static QualType getFromOpaquePtr(const void *Ptr) { |
721 | QualType T; |
722 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
723 | return T; |
724 | } |
725 | |
726 | const Type &operator*() const { |
727 | return *getTypePtr(); |
728 | } |
729 | |
730 | const Type *operator->() const { |
731 | return getTypePtr(); |
732 | } |
733 | |
734 | bool isCanonical() const; |
735 | bool isCanonicalAsParam() const; |
736 | |
737 | /// Return true if this QualType doesn't point to a type yet. |
738 | bool isNull() const { |
739 | return Value.getPointer().isNull(); |
740 | } |
741 | |
742 | /// Determine whether this particular QualType instance has the |
743 | /// "const" qualifier set, without looking through typedefs that may have |
744 | /// added "const" at a different level. |
745 | bool isLocalConstQualified() const { |
746 | return (getLocalFastQualifiers() & Qualifiers::Const); |
747 | } |
748 | |
749 | /// Determine whether this type is const-qualified. |
750 | bool isConstQualified() const; |
751 | |
752 | /// Determine whether this particular QualType instance has the |
753 | /// "restrict" qualifier set, without looking through typedefs that may have |
754 | /// added "restrict" at a different level. |
755 | bool isLocalRestrictQualified() const { |
756 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
757 | } |
758 | |
759 | /// Determine whether this type is restrict-qualified. |
760 | bool isRestrictQualified() const; |
761 | |
762 | /// Determine whether this particular QualType instance has the |
763 | /// "volatile" qualifier set, without looking through typedefs that may have |
764 | /// added "volatile" at a different level. |
765 | bool isLocalVolatileQualified() const { |
766 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
767 | } |
768 | |
769 | /// Determine whether this type is volatile-qualified. |
770 | bool isVolatileQualified() const; |
771 | |
772 | /// Determine whether this particular QualType instance has any |
773 | /// qualifiers, without looking through any typedefs that might add |
774 | /// qualifiers at a different level. |
775 | bool hasLocalQualifiers() const { |
776 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
777 | } |
778 | |
779 | /// Determine whether this type has any qualifiers. |
780 | bool hasQualifiers() const; |
781 | |
782 | /// Determine whether this particular QualType instance has any |
783 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
784 | /// instance. |
785 | bool hasLocalNonFastQualifiers() const { |
786 | return Value.getPointer().is<const ExtQuals*>(); |
787 | } |
788 | |
789 | /// Retrieve the set of qualifiers local to this particular QualType |
790 | /// instance, not including any qualifiers acquired through typedefs or |
791 | /// other sugar. |
792 | Qualifiers getLocalQualifiers() const; |
793 | |
794 | /// Retrieve the set of qualifiers applied to this type. |
795 | Qualifiers getQualifiers() const; |
796 | |
797 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
798 | /// local to this particular QualType instance, not including any qualifiers |
799 | /// acquired through typedefs or other sugar. |
800 | unsigned getLocalCVRQualifiers() const { |
801 | return getLocalFastQualifiers(); |
802 | } |
803 | |
804 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
805 | /// applied to this type. |
806 | unsigned getCVRQualifiers() const; |
807 | |
808 | bool isConstant(const ASTContext& Ctx) const { |
809 | return QualType::isConstant(*this, Ctx); |
810 | } |
811 | |
812 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
813 | bool isPODType(const ASTContext &Context) const; |
814 | |
815 | /// Return true if this is a POD type according to the rules of the C++98 |
816 | /// standard, regardless of the current compilation's language. |
817 | bool isCXX98PODType(const ASTContext &Context) const; |
818 | |
819 | /// Return true if this is a POD type according to the more relaxed rules |
820 | /// of the C++11 standard, regardless of the current compilation's language. |
821 | /// (C++0x [basic.types]p9). Note that, unlike |
822 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
823 | bool isCXX11PODType(const ASTContext &Context) const; |
824 | |
825 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
826 | bool isTrivialType(const ASTContext &Context) const; |
827 | |
828 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
829 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
830 | |
831 | |
832 | /// Returns true if it is a class and it might be dynamic. |
833 | bool mayBeDynamicClass() const; |
834 | |
835 | /// Returns true if it is not a class or if the class might not be dynamic. |
836 | bool mayBeNotDynamicClass() const; |
837 | |
838 | // Don't promise in the API that anything besides 'const' can be |
839 | // easily added. |
840 | |
841 | /// Add the `const` type qualifier to this QualType. |
842 | void addConst() { |
843 | addFastQualifiers(Qualifiers::Const); |
844 | } |
845 | QualType withConst() const { |
846 | return withFastQualifiers(Qualifiers::Const); |
847 | } |
848 | |
849 | /// Add the `volatile` type qualifier to this QualType. |
850 | void addVolatile() { |
851 | addFastQualifiers(Qualifiers::Volatile); |
852 | } |
853 | QualType withVolatile() const { |
854 | return withFastQualifiers(Qualifiers::Volatile); |
855 | } |
856 | |
857 | /// Add the `restrict` qualifier to this QualType. |
858 | void addRestrict() { |
859 | addFastQualifiers(Qualifiers::Restrict); |
860 | } |
861 | QualType withRestrict() const { |
862 | return withFastQualifiers(Qualifiers::Restrict); |
863 | } |
864 | |
865 | QualType withCVRQualifiers(unsigned CVR) const { |
866 | return withFastQualifiers(CVR); |
867 | } |
868 | |
869 | void addFastQualifiers(unsigned TQs) { |
870 | assert(!(TQs & ~Qualifiers::FastMask)(static_cast <bool> (!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!") ? void (0 ) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 871, __extension__ __PRETTY_FUNCTION__)) |
871 | && "non-fast qualifier bits set in mask!")(static_cast <bool> (!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!") ? void (0 ) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 871, __extension__ __PRETTY_FUNCTION__)); |
872 | Value.setInt(Value.getInt() | TQs); |
873 | } |
874 | |
875 | void removeLocalConst(); |
876 | void removeLocalVolatile(); |
877 | void removeLocalRestrict(); |
878 | void removeLocalCVRQualifiers(unsigned Mask); |
879 | |
880 | void removeLocalFastQualifiers() { Value.setInt(0); } |
881 | void removeLocalFastQualifiers(unsigned Mask) { |
882 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")(static_cast <bool> (!(Mask & ~Qualifiers::FastMask ) && "mask has non-fast qualifiers") ? void (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 882, __extension__ __PRETTY_FUNCTION__)); |
883 | Value.setInt(Value.getInt() & ~Mask); |
884 | } |
885 | |
886 | // Creates a type with the given qualifiers in addition to any |
887 | // qualifiers already on this type. |
888 | QualType withFastQualifiers(unsigned TQs) const { |
889 | QualType T = *this; |
890 | T.addFastQualifiers(TQs); |
891 | return T; |
892 | } |
893 | |
894 | // Creates a type with exactly the given fast qualifiers, removing |
895 | // any existing fast qualifiers. |
896 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
897 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
898 | } |
899 | |
900 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
901 | QualType withoutLocalFastQualifiers() const { |
902 | QualType T = *this; |
903 | T.removeLocalFastQualifiers(); |
904 | return T; |
905 | } |
906 | |
907 | QualType getCanonicalType() const; |
908 | |
909 | /// Return this type with all of the instance-specific qualifiers |
910 | /// removed, but without removing any qualifiers that may have been applied |
911 | /// through typedefs. |
912 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
913 | |
914 | /// Retrieve the unqualified variant of the given type, |
915 | /// removing as little sugar as possible. |
916 | /// |
917 | /// This routine looks through various kinds of sugar to find the |
918 | /// least-desugared type that is unqualified. For example, given: |
919 | /// |
920 | /// \code |
921 | /// typedef int Integer; |
922 | /// typedef const Integer CInteger; |
923 | /// typedef CInteger DifferenceType; |
924 | /// \endcode |
925 | /// |
926 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
927 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
928 | /// |
929 | /// The resulting type might still be qualified if it's sugar for an array |
930 | /// type. To strip qualifiers even from within a sugared array type, use |
931 | /// ASTContext::getUnqualifiedArrayType. |
932 | inline QualType getUnqualifiedType() const; |
933 | |
934 | /// Retrieve the unqualified variant of the given type, removing as little |
935 | /// sugar as possible. |
936 | /// |
937 | /// Like getUnqualifiedType(), but also returns the set of |
938 | /// qualifiers that were built up. |
939 | /// |
940 | /// The resulting type might still be qualified if it's sugar for an array |
941 | /// type. To strip qualifiers even from within a sugared array type, use |
942 | /// ASTContext::getUnqualifiedArrayType. |
943 | inline SplitQualType getSplitUnqualifiedType() const; |
944 | |
945 | /// Determine whether this type is more qualified than the other |
946 | /// given type, requiring exact equality for non-CVR qualifiers. |
947 | bool isMoreQualifiedThan(QualType Other) const; |
948 | |
949 | /// Determine whether this type is at least as qualified as the other |
950 | /// given type, requiring exact equality for non-CVR qualifiers. |
951 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
952 | |
953 | QualType getNonReferenceType() const; |
954 | |
955 | /// Determine the type of a (typically non-lvalue) expression with the |
956 | /// specified result type. |
957 | /// |
958 | /// This routine should be used for expressions for which the return type is |
959 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
960 | /// an lvalue. It removes a top-level reference (since there are no |
961 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
962 | /// from non-class types (in C++) or all types (in C). |
963 | QualType getNonLValueExprType(const ASTContext &Context) const; |
964 | |
965 | /// Remove an outer pack expansion type (if any) from this type. Used as part |
966 | /// of converting the type of a declaration to the type of an expression that |
967 | /// references that expression. It's meaningless for an expression to have a |
968 | /// pack expansion type. |
969 | QualType getNonPackExpansionType() const; |
970 | |
971 | /// Return the specified type with any "sugar" removed from |
972 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
973 | /// the type is already concrete, it returns it unmodified. This is similar |
974 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
975 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
976 | /// concrete. |
977 | /// |
978 | /// Qualifiers are left in place. |
979 | QualType getDesugaredType(const ASTContext &Context) const { |
980 | return getDesugaredType(*this, Context); |
981 | } |
982 | |
983 | SplitQualType getSplitDesugaredType() const { |
984 | return getSplitDesugaredType(*this); |
985 | } |
986 | |
987 | /// Return the specified type with one level of "sugar" removed from |
988 | /// the type. |
989 | /// |
990 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
991 | /// of the type is already concrete, it returns it unmodified. |
992 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
993 | return getSingleStepDesugaredTypeImpl(*this, Context); |
994 | } |
995 | |
996 | /// Returns the specified type after dropping any |
997 | /// outer-level parentheses. |
998 | QualType IgnoreParens() const { |
999 | if (isa<ParenType>(*this)) |
1000 | return QualType::IgnoreParens(*this); |
1001 | return *this; |
1002 | } |
1003 | |
1004 | /// Indicate whether the specified types and qualifiers are identical. |
1005 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
1006 | return LHS.Value == RHS.Value; |
1007 | } |
1008 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
1009 | return LHS.Value != RHS.Value; |
1010 | } |
1011 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
1012 | return LHS.Value < RHS.Value; |
1013 | } |
1014 | |
1015 | static std::string getAsString(SplitQualType split, |
1016 | const PrintingPolicy &Policy) { |
1017 | return getAsString(split.Ty, split.Quals, Policy); |
1018 | } |
1019 | static std::string getAsString(const Type *ty, Qualifiers qs, |
1020 | const PrintingPolicy &Policy); |
1021 | |
1022 | std::string getAsString() const; |
1023 | std::string getAsString(const PrintingPolicy &Policy) const; |
1024 | |
1025 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
1026 | const Twine &PlaceHolder = Twine(), |
1027 | unsigned Indentation = 0) const; |
1028 | |
1029 | static void print(SplitQualType split, raw_ostream &OS, |
1030 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
1031 | unsigned Indentation = 0) { |
1032 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
1033 | } |
1034 | |
1035 | static void print(const Type *ty, Qualifiers qs, |
1036 | raw_ostream &OS, const PrintingPolicy &policy, |
1037 | const Twine &PlaceHolder, |
1038 | unsigned Indentation = 0); |
1039 | |
1040 | void getAsStringInternal(std::string &Str, |
1041 | const PrintingPolicy &Policy) const; |
1042 | |
1043 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1044 | const PrintingPolicy &policy) { |
1045 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1046 | } |
1047 | |
1048 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1049 | std::string &out, |
1050 | const PrintingPolicy &policy); |
1051 | |
1052 | class StreamedQualTypeHelper { |
1053 | const QualType &T; |
1054 | const PrintingPolicy &Policy; |
1055 | const Twine &PlaceHolder; |
1056 | unsigned Indentation; |
1057 | |
1058 | public: |
1059 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1060 | const Twine &PlaceHolder, unsigned Indentation) |
1061 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1062 | Indentation(Indentation) {} |
1063 | |
1064 | friend raw_ostream &operator<<(raw_ostream &OS, |
1065 | const StreamedQualTypeHelper &SQT) { |
1066 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1067 | return OS; |
1068 | } |
1069 | }; |
1070 | |
1071 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1072 | const Twine &PlaceHolder = Twine(), |
1073 | unsigned Indentation = 0) const { |
1074 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1075 | } |
1076 | |
1077 | void dump(const char *s) const; |
1078 | void dump() const; |
1079 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
1080 | |
1081 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1082 | ID.AddPointer(getAsOpaquePtr()); |
1083 | } |
1084 | |
1085 | /// Check if this type has any address space qualifier. |
1086 | inline bool hasAddressSpace() const; |
1087 | |
1088 | /// Return the address space of this type. |
1089 | inline LangAS getAddressSpace() const; |
1090 | |
1091 | /// Returns true if address space qualifiers overlap with T address space |
1092 | /// qualifiers. |
1093 | /// OpenCL C defines conversion rules for pointers to different address spaces |
1094 | /// and notion of overlapping address spaces. |
1095 | /// CL1.1 or CL1.2: |
1096 | /// address spaces overlap iff they are they same. |
1097 | /// OpenCL C v2.0 s6.5.5 adds: |
1098 | /// __generic overlaps with any address space except for __constant. |
1099 | bool isAddressSpaceOverlapping(QualType T) const { |
1100 | Qualifiers Q = getQualifiers(); |
1101 | Qualifiers TQ = T.getQualifiers(); |
1102 | // Address spaces overlap if at least one of them is a superset of another |
1103 | return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q); |
1104 | } |
1105 | |
1106 | /// Returns gc attribute of this type. |
1107 | inline Qualifiers::GC getObjCGCAttr() const; |
1108 | |
1109 | /// true when Type is objc's weak. |
1110 | bool isObjCGCWeak() const { |
1111 | return getObjCGCAttr() == Qualifiers::Weak; |
1112 | } |
1113 | |
1114 | /// true when Type is objc's strong. |
1115 | bool isObjCGCStrong() const { |
1116 | return getObjCGCAttr() == Qualifiers::Strong; |
1117 | } |
1118 | |
1119 | /// Returns lifetime attribute of this type. |
1120 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1121 | return getQualifiers().getObjCLifetime(); |
1122 | } |
1123 | |
1124 | bool hasNonTrivialObjCLifetime() const { |
1125 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1126 | } |
1127 | |
1128 | bool hasStrongOrWeakObjCLifetime() const { |
1129 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1130 | } |
1131 | |
1132 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1133 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1134 | |
1135 | enum PrimitiveDefaultInitializeKind { |
1136 | /// The type does not fall into any of the following categories. Note that |
1137 | /// this case is zero-valued so that values of this enum can be used as a |
1138 | /// boolean condition for non-triviality. |
1139 | PDIK_Trivial, |
1140 | |
1141 | /// The type is an Objective-C retainable pointer type that is qualified |
1142 | /// with the ARC __strong qualifier. |
1143 | PDIK_ARCStrong, |
1144 | |
1145 | /// The type is an Objective-C retainable pointer type that is qualified |
1146 | /// with the ARC __weak qualifier. |
1147 | PDIK_ARCWeak, |
1148 | |
1149 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1150 | PDIK_Struct |
1151 | }; |
1152 | |
1153 | /// Functions to query basic properties of non-trivial C struct types. |
1154 | |
1155 | /// Check if this is a non-trivial type that would cause a C struct |
1156 | /// transitively containing this type to be non-trivial to default initialize |
1157 | /// and return the kind. |
1158 | PrimitiveDefaultInitializeKind |
1159 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1160 | |
1161 | enum PrimitiveCopyKind { |
1162 | /// The type does not fall into any of the following categories. Note that |
1163 | /// this case is zero-valued so that values of this enum can be used as a |
1164 | /// boolean condition for non-triviality. |
1165 | PCK_Trivial, |
1166 | |
1167 | /// The type would be trivial except that it is volatile-qualified. Types |
1168 | /// that fall into one of the other non-trivial cases may additionally be |
1169 | /// volatile-qualified. |
1170 | PCK_VolatileTrivial, |
1171 | |
1172 | /// The type is an Objective-C retainable pointer type that is qualified |
1173 | /// with the ARC __strong qualifier. |
1174 | PCK_ARCStrong, |
1175 | |
1176 | /// The type is an Objective-C retainable pointer type that is qualified |
1177 | /// with the ARC __weak qualifier. |
1178 | PCK_ARCWeak, |
1179 | |
1180 | /// The type is a struct containing a field whose type is neither |
1181 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1182 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1183 | /// semantics are too complex to express here, in part because they depend |
1184 | /// on the exact constructor or assignment operator that is chosen by |
1185 | /// overload resolution to do the copy. |
1186 | PCK_Struct |
1187 | }; |
1188 | |
1189 | /// Check if this is a non-trivial type that would cause a C struct |
1190 | /// transitively containing this type to be non-trivial to copy and return the |
1191 | /// kind. |
1192 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1193 | |
1194 | /// Check if this is a non-trivial type that would cause a C struct |
1195 | /// transitively containing this type to be non-trivial to destructively |
1196 | /// move and return the kind. Destructive move in this context is a C++-style |
1197 | /// move in which the source object is placed in a valid but unspecified state |
1198 | /// after it is moved, as opposed to a truly destructive move in which the |
1199 | /// source object is placed in an uninitialized state. |
1200 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1201 | |
1202 | enum DestructionKind { |
1203 | DK_none, |
1204 | DK_cxx_destructor, |
1205 | DK_objc_strong_lifetime, |
1206 | DK_objc_weak_lifetime, |
1207 | DK_nontrivial_c_struct |
1208 | }; |
1209 | |
1210 | /// Returns a nonzero value if objects of this type require |
1211 | /// non-trivial work to clean up after. Non-zero because it's |
1212 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1213 | /// something require destruction. |
1214 | DestructionKind isDestructedType() const { |
1215 | return isDestructedTypeImpl(*this); |
1216 | } |
1217 | |
1218 | /// Check if this is or contains a C union that is non-trivial to |
1219 | /// default-initialize, which is a union that has a member that is non-trivial |
1220 | /// to default-initialize. If this returns true, |
1221 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1222 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1223 | |
1224 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1225 | /// which is a union that has a member that is non-trivial to destruct. If |
1226 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1227 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1228 | |
1229 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1230 | /// is a union that has a member that is non-trivial to copy. If this returns |
1231 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1232 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1233 | |
1234 | /// Determine whether expressions of the given type are forbidden |
1235 | /// from being lvalues in C. |
1236 | /// |
1237 | /// The expression types that are forbidden to be lvalues are: |
1238 | /// - 'void', but not qualified void |
1239 | /// - function types |
1240 | /// |
1241 | /// The exact rule here is C99 6.3.2.1: |
1242 | /// An lvalue is an expression with an object type or an incomplete |
1243 | /// type other than void. |
1244 | bool isCForbiddenLValueType() const; |
1245 | |
1246 | /// Substitute type arguments for the Objective-C type parameters used in the |
1247 | /// subject type. |
1248 | /// |
1249 | /// \param ctx ASTContext in which the type exists. |
1250 | /// |
1251 | /// \param typeArgs The type arguments that will be substituted for the |
1252 | /// Objective-C type parameters in the subject type, which are generally |
1253 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1254 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1255 | /// for the context. |
1256 | /// |
1257 | /// \param context The context in which the subject type was written. |
1258 | /// |
1259 | /// \returns the resulting type. |
1260 | QualType substObjCTypeArgs(ASTContext &ctx, |
1261 | ArrayRef<QualType> typeArgs, |
1262 | ObjCSubstitutionContext context) const; |
1263 | |
1264 | /// Substitute type arguments from an object type for the Objective-C type |
1265 | /// parameters used in the subject type. |
1266 | /// |
1267 | /// This operation combines the computation of type arguments for |
1268 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1269 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1270 | /// callers that need to perform a single substitution in isolation. |
1271 | /// |
1272 | /// \param objectType The type of the object whose member type we're |
1273 | /// substituting into. For example, this might be the receiver of a message |
1274 | /// or the base of a property access. |
1275 | /// |
1276 | /// \param dc The declaration context from which the subject type was |
1277 | /// retrieved, which indicates (for example) which type parameters should |
1278 | /// be substituted. |
1279 | /// |
1280 | /// \param context The context in which the subject type was written. |
1281 | /// |
1282 | /// \returns the subject type after replacing all of the Objective-C type |
1283 | /// parameters with their corresponding arguments. |
1284 | QualType substObjCMemberType(QualType objectType, |
1285 | const DeclContext *dc, |
1286 | ObjCSubstitutionContext context) const; |
1287 | |
1288 | /// Strip Objective-C "__kindof" types from the given type. |
1289 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1290 | |
1291 | /// Remove all qualifiers including _Atomic. |
1292 | QualType getAtomicUnqualifiedType() const; |
1293 | |
1294 | private: |
1295 | // These methods are implemented in a separate translation unit; |
1296 | // "static"-ize them to avoid creating temporary QualTypes in the |
1297 | // caller. |
1298 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1299 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1300 | static SplitQualType getSplitDesugaredType(QualType T); |
1301 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1302 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1303 | const ASTContext &C); |
1304 | static QualType IgnoreParens(QualType T); |
1305 | static DestructionKind isDestructedTypeImpl(QualType type); |
1306 | |
1307 | /// Check if \param RD is or contains a non-trivial C union. |
1308 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1309 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1310 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1311 | }; |
1312 | |
1313 | } // namespace clang |
1314 | |
1315 | namespace llvm { |
1316 | |
1317 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1318 | /// to a specific Type class. |
1319 | template<> struct simplify_type< ::clang::QualType> { |
1320 | using SimpleType = const ::clang::Type *; |
1321 | |
1322 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1323 | return Val.getTypePtr(); |
1324 | } |
1325 | }; |
1326 | |
1327 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1328 | template<> |
1329 | struct PointerLikeTypeTraits<clang::QualType> { |
1330 | static inline void *getAsVoidPointer(clang::QualType P) { |
1331 | return P.getAsOpaquePtr(); |
1332 | } |
1333 | |
1334 | static inline clang::QualType getFromVoidPointer(void *P) { |
1335 | return clang::QualType::getFromOpaquePtr(P); |
1336 | } |
1337 | |
1338 | // Various qualifiers go in low bits. |
1339 | static constexpr int NumLowBitsAvailable = 0; |
1340 | }; |
1341 | |
1342 | } // namespace llvm |
1343 | |
1344 | namespace clang { |
1345 | |
1346 | /// Base class that is common to both the \c ExtQuals and \c Type |
1347 | /// classes, which allows \c QualType to access the common fields between the |
1348 | /// two. |
1349 | class ExtQualsTypeCommonBase { |
1350 | friend class ExtQuals; |
1351 | friend class QualType; |
1352 | friend class Type; |
1353 | |
1354 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1355 | /// a self-referential pointer (for \c Type). |
1356 | /// |
1357 | /// This pointer allows an efficient mapping from a QualType to its |
1358 | /// underlying type pointer. |
1359 | const Type *const BaseType; |
1360 | |
1361 | /// The canonical type of this type. A QualType. |
1362 | QualType CanonicalType; |
1363 | |
1364 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1365 | : BaseType(baseType), CanonicalType(canon) {} |
1366 | }; |
1367 | |
1368 | /// We can encode up to four bits in the low bits of a |
1369 | /// type pointer, but there are many more type qualifiers that we want |
1370 | /// to be able to apply to an arbitrary type. Therefore we have this |
1371 | /// struct, intended to be heap-allocated and used by QualType to |
1372 | /// store qualifiers. |
1373 | /// |
1374 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1375 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1376 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1377 | /// Objective-C GC attributes) are much more rare. |
1378 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1379 | // NOTE: changing the fast qualifiers should be straightforward as |
1380 | // long as you don't make 'const' non-fast. |
1381 | // 1. Qualifiers: |
1382 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1383 | // Fast qualifiers must occupy the low-order bits. |
1384 | // b) Update Qualifiers::FastWidth and FastMask. |
1385 | // 2. QualType: |
1386 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1387 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1388 | // this header. |
1389 | // 3. ASTContext: |
1390 | // a) Update get{Volatile,Restrict}Type. |
1391 | |
1392 | /// The immutable set of qualifiers applied by this node. Always contains |
1393 | /// extended qualifiers. |
1394 | Qualifiers Quals; |
1395 | |
1396 | ExtQuals *this_() { return this; } |
1397 | |
1398 | public: |
1399 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1400 | : ExtQualsTypeCommonBase(baseType, |
1401 | canon.isNull() ? QualType(this_(), 0) : canon), |
1402 | Quals(quals) { |
1403 | assert(Quals.hasNonFastQualifiers()(static_cast <bool> (Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 1404, __extension__ __PRETTY_FUNCTION__)) |
1404 | && "ExtQuals created with no fast qualifiers")(static_cast <bool> (Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 1404, __extension__ __PRETTY_FUNCTION__)); |
1405 | assert(!Quals.hasFastQualifiers()(static_cast <bool> (!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers") ? void (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 1406, __extension__ __PRETTY_FUNCTION__)) |
1406 | && "ExtQuals created with fast qualifiers")(static_cast <bool> (!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers") ? void (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 1406, __extension__ __PRETTY_FUNCTION__)); |
1407 | } |
1408 | |
1409 | Qualifiers getQualifiers() const { return Quals; } |
1410 | |
1411 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1412 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1413 | |
1414 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1415 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1416 | return Quals.getObjCLifetime(); |
1417 | } |
1418 | |
1419 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1420 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1421 | |
1422 | const Type *getBaseType() const { return BaseType; } |
1423 | |
1424 | public: |
1425 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1426 | Profile(ID, getBaseType(), Quals); |
1427 | } |
1428 | |
1429 | static void Profile(llvm::FoldingSetNodeID &ID, |
1430 | const Type *BaseType, |
1431 | Qualifiers Quals) { |
1432 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")(static_cast <bool> (!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!") ? void (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 1432, __extension__ __PRETTY_FUNCTION__)); |
1433 | ID.AddPointer(BaseType); |
1434 | Quals.Profile(ID); |
1435 | } |
1436 | }; |
1437 | |
1438 | /// The kind of C++11 ref-qualifier associated with a function type. |
1439 | /// This determines whether a member function's "this" object can be an |
1440 | /// lvalue, rvalue, or neither. |
1441 | enum RefQualifierKind { |
1442 | /// No ref-qualifier was provided. |
1443 | RQ_None = 0, |
1444 | |
1445 | /// An lvalue ref-qualifier was provided (\c &). |
1446 | RQ_LValue, |
1447 | |
1448 | /// An rvalue ref-qualifier was provided (\c &&). |
1449 | RQ_RValue |
1450 | }; |
1451 | |
1452 | /// Which keyword(s) were used to create an AutoType. |
1453 | enum class AutoTypeKeyword { |
1454 | /// auto |
1455 | Auto, |
1456 | |
1457 | /// decltype(auto) |
1458 | DecltypeAuto, |
1459 | |
1460 | /// __auto_type (GNU extension) |
1461 | GNUAutoType |
1462 | }; |
1463 | |
1464 | /// The base class of the type hierarchy. |
1465 | /// |
1466 | /// A central concept with types is that each type always has a canonical |
1467 | /// type. A canonical type is the type with any typedef names stripped out |
1468 | /// of it or the types it references. For example, consider: |
1469 | /// |
1470 | /// typedef int foo; |
1471 | /// typedef foo* bar; |
1472 | /// 'int *' 'foo *' 'bar' |
1473 | /// |
1474 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1475 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1476 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1477 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1478 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1479 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1480 | /// is also 'int*'. |
1481 | /// |
1482 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1483 | /// information about typedefs being used. Canonical types are useful for type |
1484 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1485 | /// about whether something has a particular form (e.g. is a function type), |
1486 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1487 | /// |
1488 | /// Types, once created, are immutable. |
1489 | /// |
1490 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1491 | public: |
1492 | enum TypeClass { |
1493 | #define TYPE(Class, Base) Class, |
1494 | #define LAST_TYPE(Class) TypeLast = Class |
1495 | #define ABSTRACT_TYPE(Class, Base) |
1496 | #include "clang/AST/TypeNodes.inc" |
1497 | }; |
1498 | |
1499 | private: |
1500 | /// Bitfields required by the Type class. |
1501 | class TypeBitfields { |
1502 | friend class Type; |
1503 | template <class T> friend class TypePropertyCache; |
1504 | |
1505 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1506 | unsigned TC : 8; |
1507 | |
1508 | /// Store information on the type dependency. |
1509 | unsigned Dependence : llvm::BitWidth<TypeDependence>; |
1510 | |
1511 | /// True if the cache (i.e. the bitfields here starting with |
1512 | /// 'Cache') is valid. |
1513 | mutable unsigned CacheValid : 1; |
1514 | |
1515 | /// Linkage of this type. |
1516 | mutable unsigned CachedLinkage : 3; |
1517 | |
1518 | /// Whether this type involves and local or unnamed types. |
1519 | mutable unsigned CachedLocalOrUnnamed : 1; |
1520 | |
1521 | /// Whether this type comes from an AST file. |
1522 | mutable unsigned FromAST : 1; |
1523 | |
1524 | bool isCacheValid() const { |
1525 | return CacheValid; |
1526 | } |
1527 | |
1528 | Linkage getLinkage() const { |
1529 | assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache" ) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 1529, __extension__ __PRETTY_FUNCTION__)); |
1530 | return static_cast<Linkage>(CachedLinkage); |
1531 | } |
1532 | |
1533 | bool hasLocalOrUnnamedType() const { |
1534 | assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache" ) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 1534, __extension__ __PRETTY_FUNCTION__)); |
1535 | return CachedLocalOrUnnamed; |
1536 | } |
1537 | }; |
1538 | enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 }; |
1539 | |
1540 | protected: |
1541 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1542 | // into Type. |
1543 | |
1544 | class ArrayTypeBitfields { |
1545 | friend class ArrayType; |
1546 | |
1547 | unsigned : NumTypeBits; |
1548 | |
1549 | /// CVR qualifiers from declarations like |
1550 | /// 'int X[static restrict 4]'. For function parameters only. |
1551 | unsigned IndexTypeQuals : 3; |
1552 | |
1553 | /// Storage class qualifiers from declarations like |
1554 | /// 'int X[static restrict 4]'. For function parameters only. |
1555 | /// Actually an ArrayType::ArraySizeModifier. |
1556 | unsigned SizeModifier : 3; |
1557 | }; |
1558 | |
1559 | class ConstantArrayTypeBitfields { |
1560 | friend class ConstantArrayType; |
1561 | |
1562 | unsigned : NumTypeBits + 3 + 3; |
1563 | |
1564 | /// Whether we have a stored size expression. |
1565 | unsigned HasStoredSizeExpr : 1; |
1566 | }; |
1567 | |
1568 | class BuiltinTypeBitfields { |
1569 | friend class BuiltinType; |
1570 | |
1571 | unsigned : NumTypeBits; |
1572 | |
1573 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1574 | unsigned Kind : 8; |
1575 | }; |
1576 | |
1577 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1578 | /// Only common bits are stored here. Additional uncommon bits are stored |
1579 | /// in a trailing object after FunctionProtoType. |
1580 | class FunctionTypeBitfields { |
1581 | friend class FunctionProtoType; |
1582 | friend class FunctionType; |
1583 | |
1584 | unsigned : NumTypeBits; |
1585 | |
1586 | /// Extra information which affects how the function is called, like |
1587 | /// regparm and the calling convention. |
1588 | unsigned ExtInfo : 13; |
1589 | |
1590 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1591 | /// |
1592 | /// This is a value of type \c RefQualifierKind. |
1593 | unsigned RefQualifier : 2; |
1594 | |
1595 | /// Used only by FunctionProtoType, put here to pack with the |
1596 | /// other bitfields. |
1597 | /// The qualifiers are part of FunctionProtoType because... |
1598 | /// |
1599 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1600 | /// cv-qualifier-seq, [...], are part of the function type. |
1601 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1602 | /// Whether this function has extended Qualifiers. |
1603 | unsigned HasExtQuals : 1; |
1604 | |
1605 | /// The number of parameters this function has, not counting '...'. |
1606 | /// According to [implimits] 8 bits should be enough here but this is |
1607 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1608 | /// keep NumParams as wide as reasonably possible. |
1609 | unsigned NumParams : 16; |
1610 | |
1611 | /// The type of exception specification this function has. |
1612 | unsigned ExceptionSpecType : 4; |
1613 | |
1614 | /// Whether this function has extended parameter information. |
1615 | unsigned HasExtParameterInfos : 1; |
1616 | |
1617 | /// Whether the function is variadic. |
1618 | unsigned Variadic : 1; |
1619 | |
1620 | /// Whether this function has a trailing return type. |
1621 | unsigned HasTrailingReturn : 1; |
1622 | }; |
1623 | |
1624 | class ObjCObjectTypeBitfields { |
1625 | friend class ObjCObjectType; |
1626 | |
1627 | unsigned : NumTypeBits; |
1628 | |
1629 | /// The number of type arguments stored directly on this object type. |
1630 | unsigned NumTypeArgs : 7; |
1631 | |
1632 | /// The number of protocols stored directly on this object type. |
1633 | unsigned NumProtocols : 6; |
1634 | |
1635 | /// Whether this is a "kindof" type. |
1636 | unsigned IsKindOf : 1; |
1637 | }; |
1638 | |
1639 | class ReferenceTypeBitfields { |
1640 | friend class ReferenceType; |
1641 | |
1642 | unsigned : NumTypeBits; |
1643 | |
1644 | /// True if the type was originally spelled with an lvalue sigil. |
1645 | /// This is never true of rvalue references but can also be false |
1646 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1647 | /// as follows: |
1648 | /// |
1649 | /// typedef int &ref; // lvalue, spelled lvalue |
1650 | /// typedef int &&rvref; // rvalue |
1651 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1652 | /// ref &&a; // lvalue, inner ref |
1653 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1654 | /// rvref &&a; // rvalue, inner ref |
1655 | unsigned SpelledAsLValue : 1; |
1656 | |
1657 | /// True if the inner type is a reference type. This only happens |
1658 | /// in non-canonical forms. |
1659 | unsigned InnerRef : 1; |
1660 | }; |
1661 | |
1662 | class TypeWithKeywordBitfields { |
1663 | friend class TypeWithKeyword; |
1664 | |
1665 | unsigned : NumTypeBits; |
1666 | |
1667 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1668 | unsigned Keyword : 8; |
1669 | }; |
1670 | |
1671 | enum { NumTypeWithKeywordBits = 8 }; |
1672 | |
1673 | class ElaboratedTypeBitfields { |
1674 | friend class ElaboratedType; |
1675 | |
1676 | unsigned : NumTypeBits; |
1677 | unsigned : NumTypeWithKeywordBits; |
1678 | |
1679 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1680 | unsigned HasOwnedTagDecl : 1; |
1681 | }; |
1682 | |
1683 | class VectorTypeBitfields { |
1684 | friend class VectorType; |
1685 | friend class DependentVectorType; |
1686 | |
1687 | unsigned : NumTypeBits; |
1688 | |
1689 | /// The kind of vector, either a generic vector type or some |
1690 | /// target-specific vector type such as for AltiVec or Neon. |
1691 | unsigned VecKind : 3; |
1692 | /// The number of elements in the vector. |
1693 | uint32_t NumElements; |
1694 | }; |
1695 | |
1696 | class AttributedTypeBitfields { |
1697 | friend class AttributedType; |
1698 | |
1699 | unsigned : NumTypeBits; |
1700 | |
1701 | /// An AttributedType::Kind |
1702 | unsigned AttrKind : 32 - NumTypeBits; |
1703 | }; |
1704 | |
1705 | class AutoTypeBitfields { |
1706 | friend class AutoType; |
1707 | |
1708 | unsigned : NumTypeBits; |
1709 | |
1710 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1711 | /// or '__auto_type'? AutoTypeKeyword value. |
1712 | unsigned Keyword : 2; |
1713 | |
1714 | /// The number of template arguments in the type-constraints, which is |
1715 | /// expected to be able to hold at least 1024 according to [implimits]. |
1716 | /// However as this limit is somewhat easy to hit with template |
1717 | /// metaprogramming we'd prefer to keep it as large as possible. |
1718 | /// At the moment it has been left as a non-bitfield since this type |
1719 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1720 | /// introduce the performance impact of a bitfield. |
1721 | unsigned NumArgs; |
1722 | }; |
1723 | |
1724 | class SubstTemplateTypeParmPackTypeBitfields { |
1725 | friend class SubstTemplateTypeParmPackType; |
1726 | |
1727 | unsigned : NumTypeBits; |
1728 | |
1729 | /// The number of template arguments in \c Arguments, which is |
1730 | /// expected to be able to hold at least 1024 according to [implimits]. |
1731 | /// However as this limit is somewhat easy to hit with template |
1732 | /// metaprogramming we'd prefer to keep it as large as possible. |
1733 | /// At the moment it has been left as a non-bitfield since this type |
1734 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1735 | /// introduce the performance impact of a bitfield. |
1736 | unsigned NumArgs; |
1737 | }; |
1738 | |
1739 | class TemplateSpecializationTypeBitfields { |
1740 | friend class TemplateSpecializationType; |
1741 | |
1742 | unsigned : NumTypeBits; |
1743 | |
1744 | /// Whether this template specialization type is a substituted type alias. |
1745 | unsigned TypeAlias : 1; |
1746 | |
1747 | /// The number of template arguments named in this class template |
1748 | /// specialization, which is expected to be able to hold at least 1024 |
1749 | /// according to [implimits]. However, as this limit is somewhat easy to |
1750 | /// hit with template metaprogramming we'd prefer to keep it as large |
1751 | /// as possible. At the moment it has been left as a non-bitfield since |
1752 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1753 | /// to introduce the performance impact of a bitfield. |
1754 | unsigned NumArgs; |
1755 | }; |
1756 | |
1757 | class DependentTemplateSpecializationTypeBitfields { |
1758 | friend class DependentTemplateSpecializationType; |
1759 | |
1760 | unsigned : NumTypeBits; |
1761 | unsigned : NumTypeWithKeywordBits; |
1762 | |
1763 | /// The number of template arguments named in this class template |
1764 | /// specialization, which is expected to be able to hold at least 1024 |
1765 | /// according to [implimits]. However, as this limit is somewhat easy to |
1766 | /// hit with template metaprogramming we'd prefer to keep it as large |
1767 | /// as possible. At the moment it has been left as a non-bitfield since |
1768 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1769 | /// to introduce the performance impact of a bitfield. |
1770 | unsigned NumArgs; |
1771 | }; |
1772 | |
1773 | class PackExpansionTypeBitfields { |
1774 | friend class PackExpansionType; |
1775 | |
1776 | unsigned : NumTypeBits; |
1777 | |
1778 | /// The number of expansions that this pack expansion will |
1779 | /// generate when substituted (+1), which is expected to be able to |
1780 | /// hold at least 1024 according to [implimits]. However, as this limit |
1781 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1782 | /// keep it as large as possible. At the moment it has been left as a |
1783 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1784 | /// there is no reason to introduce the performance impact of a bitfield. |
1785 | /// |
1786 | /// This field will only have a non-zero value when some of the parameter |
1787 | /// packs that occur within the pattern have been substituted but others |
1788 | /// have not. |
1789 | unsigned NumExpansions; |
1790 | }; |
1791 | |
1792 | union { |
1793 | TypeBitfields TypeBits; |
1794 | ArrayTypeBitfields ArrayTypeBits; |
1795 | ConstantArrayTypeBitfields ConstantArrayTypeBits; |
1796 | AttributedTypeBitfields AttributedTypeBits; |
1797 | AutoTypeBitfields AutoTypeBits; |
1798 | BuiltinTypeBitfields BuiltinTypeBits; |
1799 | FunctionTypeBitfields FunctionTypeBits; |
1800 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1801 | ReferenceTypeBitfields ReferenceTypeBits; |
1802 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1803 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1804 | VectorTypeBitfields VectorTypeBits; |
1805 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1806 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1807 | DependentTemplateSpecializationTypeBitfields |
1808 | DependentTemplateSpecializationTypeBits; |
1809 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1810 | }; |
1811 | |
1812 | private: |
1813 | template <class T> friend class TypePropertyCache; |
1814 | |
1815 | /// Set whether this type comes from an AST file. |
1816 | void setFromAST(bool V = true) const { |
1817 | TypeBits.FromAST = V; |
1818 | } |
1819 | |
1820 | protected: |
1821 | friend class ASTContext; |
1822 | |
1823 | Type(TypeClass tc, QualType canon, TypeDependence Dependence) |
1824 | : ExtQualsTypeCommonBase(this, |
1825 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1826 | static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase), |
1827 | "changing bitfields changed sizeof(Type)!"); |
1828 | static_assert(alignof(decltype(*this)) % sizeof(void *) == 0, |
1829 | "Insufficient alignment!"); |
1830 | TypeBits.TC = tc; |
1831 | TypeBits.Dependence = static_cast<unsigned>(Dependence); |
1832 | TypeBits.CacheValid = false; |
1833 | TypeBits.CachedLocalOrUnnamed = false; |
1834 | TypeBits.CachedLinkage = NoLinkage; |
1835 | TypeBits.FromAST = false; |
1836 | } |
1837 | |
1838 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1839 | Type *this_() { return this; } |
1840 | |
1841 | void setDependence(TypeDependence D) { |
1842 | TypeBits.Dependence = static_cast<unsigned>(D); |
1843 | } |
1844 | |
1845 | void addDependence(TypeDependence D) { setDependence(getDependence() | D); } |
1846 | |
1847 | public: |
1848 | friend class ASTReader; |
1849 | friend class ASTWriter; |
1850 | template <class T> friend class serialization::AbstractTypeReader; |
1851 | template <class T> friend class serialization::AbstractTypeWriter; |
1852 | |
1853 | Type(const Type &) = delete; |
1854 | Type(Type &&) = delete; |
1855 | Type &operator=(const Type &) = delete; |
1856 | Type &operator=(Type &&) = delete; |
1857 | |
1858 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1859 | |
1860 | /// Whether this type comes from an AST file. |
1861 | bool isFromAST() const { return TypeBits.FromAST; } |
1862 | |
1863 | /// Whether this type is or contains an unexpanded parameter |
1864 | /// pack, used to support C++0x variadic templates. |
1865 | /// |
1866 | /// A type that contains a parameter pack shall be expanded by the |
1867 | /// ellipsis operator at some point. For example, the typedef in the |
1868 | /// following example contains an unexpanded parameter pack 'T': |
1869 | /// |
1870 | /// \code |
1871 | /// template<typename ...T> |
1872 | /// struct X { |
1873 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1874 | /// }; |
1875 | /// \endcode |
1876 | /// |
1877 | /// Note that this routine does not specify which |
1878 | bool containsUnexpandedParameterPack() const { |
1879 | return getDependence() & TypeDependence::UnexpandedPack; |
1880 | } |
1881 | |
1882 | /// Determines if this type would be canonical if it had no further |
1883 | /// qualification. |
1884 | bool isCanonicalUnqualified() const { |
1885 | return CanonicalType == QualType(this, 0); |
1886 | } |
1887 | |
1888 | /// Pull a single level of sugar off of this locally-unqualified type. |
1889 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1890 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1891 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1892 | |
1893 | /// As an extension, we classify types as one of "sized" or "sizeless"; |
1894 | /// every type is one or the other. Standard types are all sized; |
1895 | /// sizeless types are purely an extension. |
1896 | /// |
1897 | /// Sizeless types contain data with no specified size, alignment, |
1898 | /// or layout. |
1899 | bool isSizelessType() const; |
1900 | bool isSizelessBuiltinType() const; |
1901 | |
1902 | /// Determines if this is a sizeless type supported by the |
1903 | /// 'arm_sve_vector_bits' type attribute, which can be applied to a single |
1904 | /// SVE vector or predicate, excluding tuple types such as svint32x4_t. |
1905 | bool isVLSTBuiltinType() const; |
1906 | |
1907 | /// Returns the representative type for the element of an SVE builtin type. |
1908 | /// This is used to represent fixed-length SVE vectors created with the |
1909 | /// 'arm_sve_vector_bits' type attribute as VectorType. |
1910 | QualType getSveEltType(const ASTContext &Ctx) const; |
1911 | |
1912 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1913 | /// object types, function types, and incomplete types. |
1914 | |
1915 | /// Return true if this is an incomplete type. |
1916 | /// A type that can describe objects, but which lacks information needed to |
1917 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1918 | /// routine will need to determine if the size is actually required. |
1919 | /// |
1920 | /// Def If non-null, and the type refers to some kind of declaration |
1921 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1922 | /// class), will be set to the declaration. |
1923 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1924 | |
1925 | /// Return true if this is an incomplete or object |
1926 | /// type, in other words, not a function type. |
1927 | bool isIncompleteOrObjectType() const { |
1928 | return !isFunctionType(); |
1929 | } |
1930 | |
1931 | /// Determine whether this type is an object type. |
1932 | bool isObjectType() const { |
1933 | // C++ [basic.types]p8: |
1934 | // An object type is a (possibly cv-qualified) type that is not a |
1935 | // function type, not a reference type, and not a void type. |
1936 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1937 | } |
1938 | |
1939 | /// Return true if this is a literal type |
1940 | /// (C++11 [basic.types]p10) |
1941 | bool isLiteralType(const ASTContext &Ctx) const; |
1942 | |
1943 | /// Determine if this type is a structural type, per C++20 [temp.param]p7. |
1944 | bool isStructuralType() const; |
1945 | |
1946 | /// Test if this type is a standard-layout type. |
1947 | /// (C++0x [basic.type]p9) |
1948 | bool isStandardLayoutType() const; |
1949 | |
1950 | /// Helper methods to distinguish type categories. All type predicates |
1951 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1952 | |
1953 | /// Returns true if the type is a builtin type. |
1954 | bool isBuiltinType() const; |
1955 | |
1956 | /// Test for a particular builtin type. |
1957 | bool isSpecificBuiltinType(unsigned K) const; |
1958 | |
1959 | /// Test for a type which does not represent an actual type-system type but |
1960 | /// is instead used as a placeholder for various convenient purposes within |
1961 | /// Clang. All such types are BuiltinTypes. |
1962 | bool isPlaceholderType() const; |
1963 | const BuiltinType *getAsPlaceholderType() const; |
1964 | |
1965 | /// Test for a specific placeholder type. |
1966 | bool isSpecificPlaceholderType(unsigned K) const; |
1967 | |
1968 | /// Test for a placeholder type other than Overload; see |
1969 | /// BuiltinType::isNonOverloadPlaceholderType. |
1970 | bool isNonOverloadPlaceholderType() const; |
1971 | |
1972 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1973 | /// isComplexIntegerType() can be used to test for complex integers. |
1974 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1975 | bool isEnumeralType() const; |
1976 | |
1977 | /// Determine whether this type is a scoped enumeration type. |
1978 | bool isScopedEnumeralType() const; |
1979 | bool isBooleanType() const; |
1980 | bool isCharType() const; |
1981 | bool isWideCharType() const; |
1982 | bool isChar8Type() const; |
1983 | bool isChar16Type() const; |
1984 | bool isChar32Type() const; |
1985 | bool isAnyCharacterType() const; |
1986 | bool isIntegralType(const ASTContext &Ctx) const; |
1987 | |
1988 | /// Determine whether this type is an integral or enumeration type. |
1989 | bool isIntegralOrEnumerationType() const; |
1990 | |
1991 | /// Determine whether this type is an integral or unscoped enumeration type. |
1992 | bool isIntegralOrUnscopedEnumerationType() const; |
1993 | bool isUnscopedEnumerationType() const; |
1994 | |
1995 | /// Floating point categories. |
1996 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1997 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1998 | /// isComplexIntegerType() can be used to test for complex integers. |
1999 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
2000 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
2001 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
2002 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
2003 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
2004 | bool isBFloat16Type() const; |
2005 | bool isFloat128Type() const; |
2006 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
2007 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
2008 | bool isVoidType() const; // C99 6.2.5p19 |
2009 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
2010 | bool isAggregateType() const; |
2011 | bool isFundamentalType() const; |
2012 | bool isCompoundType() const; |
2013 | |
2014 | // Type Predicates: Check to see if this type is structurally the specified |
2015 | // type, ignoring typedefs and qualifiers. |
2016 | bool isFunctionType() const; |
2017 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
2018 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
2019 | bool isPointerType() const; |
2020 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
2021 | bool isBlockPointerType() const; |
2022 | bool isVoidPointerType() const; |
2023 | bool isReferenceType() const; |
2024 | bool isLValueReferenceType() const; |
2025 | bool isRValueReferenceType() const; |
2026 | bool isObjectPointerType() const; |
2027 | bool isFunctionPointerType() const; |
2028 | bool isFunctionReferenceType() const; |
2029 | bool isMemberPointerType() const; |
2030 | bool isMemberFunctionPointerType() const; |
2031 | bool isMemberDataPointerType() const; |
2032 | bool isArrayType() const; |
2033 | bool isConstantArrayType() const; |
2034 | bool isIncompleteArrayType() const; |
2035 | bool isVariableArrayType() const; |
2036 | bool isDependentSizedArrayType() const; |
2037 | bool isRecordType() const; |
2038 | bool isClassType() const; |
2039 | bool isStructureType() const; |
2040 | bool isObjCBoxableRecordType() const; |
2041 | bool isInterfaceType() const; |
2042 | bool isStructureOrClassType() const; |
2043 | bool isUnionType() const; |
2044 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2045 | bool isVectorType() const; // GCC vector type. |
2046 | bool isExtVectorType() const; // Extended vector type. |
2047 | bool isMatrixType() const; // Matrix type. |
2048 | bool isConstantMatrixType() const; // Constant matrix type. |
2049 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2050 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2051 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2052 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2053 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2054 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2055 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2056 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2057 | // for the common case. |
2058 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2059 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2060 | bool isObjCQualifiedIdType() const; // id<foo> |
2061 | bool isObjCQualifiedClassType() const; // Class<foo> |
2062 | bool isObjCObjectOrInterfaceType() const; |
2063 | bool isObjCIdType() const; // id |
2064 | bool isDecltypeType() const; |
2065 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2066 | /// qualifier? |
2067 | /// |
2068 | /// This approximates the answer to the following question: if this |
2069 | /// translation unit were compiled in ARC, would this type be qualified |
2070 | /// with __unsafe_unretained? |
2071 | bool isObjCInertUnsafeUnretainedType() const { |
2072 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2073 | } |
2074 | |
2075 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2076 | /// object type, e.g., __kindof NSView * or __kindof id |
2077 | /// <NSCopying>. |
2078 | /// |
2079 | /// \param bound Will be set to the bound on non-id subtype types, |
2080 | /// which will be (possibly specialized) Objective-C class type, or |
2081 | /// null for 'id. |
2082 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2083 | const ObjCObjectType *&bound) const; |
2084 | |
2085 | bool isObjCClassType() const; // Class |
2086 | |
2087 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2088 | /// Class type, e.g., __kindof Class <NSCopying>. |
2089 | /// |
2090 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2091 | /// here because Objective-C's type system cannot express "a class |
2092 | /// object for a subclass of NSFoo". |
2093 | bool isObjCClassOrClassKindOfType() const; |
2094 | |
2095 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2096 | bool isObjCSelType() const; // Class |
2097 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2098 | bool isObjCARCBridgableType() const; |
2099 | bool isCARCBridgableType() const; |
2100 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2101 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2102 | bool isNothrowT() const; // C++ std::nothrow_t |
2103 | bool isAlignValT() const; // C++17 std::align_val_t |
2104 | bool isStdByteType() const; // C++17 std::byte |
2105 | bool isAtomicType() const; // C11 _Atomic() |
2106 | bool isUndeducedAutoType() const; // C++11 auto or |
2107 | // C++14 decltype(auto) |
2108 | bool isTypedefNameType() const; // typedef or alias template |
2109 | |
2110 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2111 | bool is##Id##Type() const; |
2112 | #include "clang/Basic/OpenCLImageTypes.def" |
2113 | |
2114 | bool isImageType() const; // Any OpenCL image type |
2115 | |
2116 | bool isSamplerT() const; // OpenCL sampler_t |
2117 | bool isEventT() const; // OpenCL event_t |
2118 | bool isClkEventT() const; // OpenCL clk_event_t |
2119 | bool isQueueT() const; // OpenCL queue_t |
2120 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2121 | |
2122 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2123 | bool is##Id##Type() const; |
2124 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2125 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2126 | bool isOCLIntelSubgroupAVCType() const; |
2127 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2128 | |
2129 | bool isPipeType() const; // OpenCL pipe type |
2130 | bool isExtIntType() const; // Extended Int Type |
2131 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2132 | |
2133 | /// Determines if this type, which must satisfy |
2134 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2135 | /// than implicitly __strong. |
2136 | bool isObjCARCImplicitlyUnretainedType() const; |
2137 | |
2138 | /// Check if the type is the CUDA device builtin surface type. |
2139 | bool isCUDADeviceBuiltinSurfaceType() const; |
2140 | /// Check if the type is the CUDA device builtin texture type. |
2141 | bool isCUDADeviceBuiltinTextureType() const; |
2142 | |
2143 | /// Return the implicit lifetime for this type, which must not be dependent. |
2144 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2145 | |
2146 | enum ScalarTypeKind { |
2147 | STK_CPointer, |
2148 | STK_BlockPointer, |
2149 | STK_ObjCObjectPointer, |
2150 | STK_MemberPointer, |
2151 | STK_Bool, |
2152 | STK_Integral, |
2153 | STK_Floating, |
2154 | STK_IntegralComplex, |
2155 | STK_FloatingComplex, |
2156 | STK_FixedPoint |
2157 | }; |
2158 | |
2159 | /// Given that this is a scalar type, classify it. |
2160 | ScalarTypeKind getScalarTypeKind() const; |
2161 | |
2162 | TypeDependence getDependence() const { |
2163 | return static_cast<TypeDependence>(TypeBits.Dependence); |
2164 | } |
2165 | |
2166 | /// Whether this type is an error type. |
2167 | bool containsErrors() const { |
2168 | return getDependence() & TypeDependence::Error; |
2169 | } |
2170 | |
2171 | /// Whether this type is a dependent type, meaning that its definition |
2172 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2173 | bool isDependentType() const { |
2174 | return getDependence() & TypeDependence::Dependent; |
2175 | } |
2176 | |
2177 | /// Determine whether this type is an instantiation-dependent type, |
2178 | /// meaning that the type involves a template parameter (even if the |
2179 | /// definition does not actually depend on the type substituted for that |
2180 | /// template parameter). |
2181 | bool isInstantiationDependentType() const { |
2182 | return getDependence() & TypeDependence::Instantiation; |
2183 | } |
2184 | |
2185 | /// Determine whether this type is an undeduced type, meaning that |
2186 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2187 | /// deduced. |
2188 | bool isUndeducedType() const; |
2189 | |
2190 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2191 | bool isVariablyModifiedType() const { |
2192 | return getDependence() & TypeDependence::VariablyModified; |
2193 | } |
2194 | |
2195 | /// Whether this type involves a variable-length array type |
2196 | /// with a definite size. |
2197 | bool hasSizedVLAType() const; |
2198 | |
2199 | /// Whether this type is or contains a local or unnamed type. |
2200 | bool hasUnnamedOrLocalType() const; |
2201 | |
2202 | bool isOverloadableType() const; |
2203 | |
2204 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2205 | bool isElaboratedTypeSpecifier() const; |
2206 | |
2207 | bool canDecayToPointerType() const; |
2208 | |
2209 | /// Whether this type is represented natively as a pointer. This includes |
2210 | /// pointers, references, block pointers, and Objective-C interface, |
2211 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2212 | bool hasPointerRepresentation() const; |
2213 | |
2214 | /// Whether this type can represent an objective pointer type for the |
2215 | /// purpose of GC'ability |
2216 | bool hasObjCPointerRepresentation() const; |
2217 | |
2218 | /// Determine whether this type has an integer representation |
2219 | /// of some sort, e.g., it is an integer type or a vector. |
2220 | bool hasIntegerRepresentation() const; |
2221 | |
2222 | /// Determine whether this type has an signed integer representation |
2223 | /// of some sort, e.g., it is an signed integer type or a vector. |
2224 | bool hasSignedIntegerRepresentation() const; |
2225 | |
2226 | /// Determine whether this type has an unsigned integer representation |
2227 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2228 | bool hasUnsignedIntegerRepresentation() const; |
2229 | |
2230 | /// Determine whether this type has a floating-point representation |
2231 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2232 | bool hasFloatingRepresentation() const; |
2233 | |
2234 | // Type Checking Functions: Check to see if this type is structurally the |
2235 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2236 | // the best type we can. |
2237 | const RecordType *getAsStructureType() const; |
2238 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2239 | const RecordType *getAsUnionType() const; |
2240 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2241 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2242 | |
2243 | // The following is a convenience method that returns an ObjCObjectPointerType |
2244 | // for object declared using an interface. |
2245 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2246 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2247 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2248 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2249 | |
2250 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2251 | /// because the type is a RecordType or because it is the injected-class-name |
2252 | /// type of a class template or class template partial specialization. |
2253 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2254 | |
2255 | /// Retrieves the RecordDecl this type refers to. |
2256 | RecordDecl *getAsRecordDecl() const; |
2257 | |
2258 | /// Retrieves the TagDecl that this type refers to, either |
2259 | /// because the type is a TagType or because it is the injected-class-name |
2260 | /// type of a class template or class template partial specialization. |
2261 | TagDecl *getAsTagDecl() const; |
2262 | |
2263 | /// If this is a pointer or reference to a RecordType, return the |
2264 | /// CXXRecordDecl that the type refers to. |
2265 | /// |
2266 | /// If this is not a pointer or reference, or the type being pointed to does |
2267 | /// not refer to a CXXRecordDecl, returns NULL. |
2268 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2269 | |
2270 | /// Get the DeducedType whose type will be deduced for a variable with |
2271 | /// an initializer of this type. This looks through declarators like pointer |
2272 | /// types, but not through decltype or typedefs. |
2273 | DeducedType *getContainedDeducedType() const; |
2274 | |
2275 | /// Get the AutoType whose type will be deduced for a variable with |
2276 | /// an initializer of this type. This looks through declarators like pointer |
2277 | /// types, but not through decltype or typedefs. |
2278 | AutoType *getContainedAutoType() const { |
2279 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2280 | } |
2281 | |
2282 | /// Determine whether this type was written with a leading 'auto' |
2283 | /// corresponding to a trailing return type (possibly for a nested |
2284 | /// function type within a pointer to function type or similar). |
2285 | bool hasAutoForTrailingReturnType() const; |
2286 | |
2287 | /// Member-template getAs<specific type>'. Look through sugar for |
2288 | /// an instance of \<specific type>. This scheme will eventually |
2289 | /// replace the specific getAsXXXX methods above. |
2290 | /// |
2291 | /// There are some specializations of this member template listed |
2292 | /// immediately following this class. |
2293 | template <typename T> const T *getAs() const; |
2294 | |
2295 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2296 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2297 | /// This is used when you need to walk over sugar nodes that represent some |
2298 | /// kind of type adjustment from a type that was written as a \<specific type> |
2299 | /// to another type that is still canonically a \<specific type>. |
2300 | template <typename T> const T *getAsAdjusted() const; |
2301 | |
2302 | /// A variant of getAs<> for array types which silently discards |
2303 | /// qualifiers from the outermost type. |
2304 | const ArrayType *getAsArrayTypeUnsafe() const; |
2305 | |
2306 | /// Member-template castAs<specific type>. Look through sugar for |
2307 | /// the underlying instance of \<specific type>. |
2308 | /// |
2309 | /// This method has the same relationship to getAs<T> as cast<T> has |
2310 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2311 | /// have the intended type, and this method will never return null. |
2312 | template <typename T> const T *castAs() const; |
2313 | |
2314 | /// A variant of castAs<> for array type which silently discards |
2315 | /// qualifiers from the outermost type. |
2316 | const ArrayType *castAsArrayTypeUnsafe() const; |
2317 | |
2318 | /// Determine whether this type had the specified attribute applied to it |
2319 | /// (looking through top-level type sugar). |
2320 | bool hasAttr(attr::Kind AK) const; |
2321 | |
2322 | /// Get the base element type of this type, potentially discarding type |
2323 | /// qualifiers. This should never be used when type qualifiers |
2324 | /// are meaningful. |
2325 | const Type *getBaseElementTypeUnsafe() const; |
2326 | |
2327 | /// If this is an array type, return the element type of the array, |
2328 | /// potentially with type qualifiers missing. |
2329 | /// This should never be used when type qualifiers are meaningful. |
2330 | const Type *getArrayElementTypeNoTypeQual() const; |
2331 | |
2332 | /// If this is a pointer type, return the pointee type. |
2333 | /// If this is an array type, return the array element type. |
2334 | /// This should never be used when type qualifiers are meaningful. |
2335 | const Type *getPointeeOrArrayElementType() const; |
2336 | |
2337 | /// If this is a pointer, ObjC object pointer, or block |
2338 | /// pointer, this returns the respective pointee. |
2339 | QualType getPointeeType() const; |
2340 | |
2341 | /// Return the specified type with any "sugar" removed from the type, |
2342 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2343 | const Type *getUnqualifiedDesugaredType() const; |
2344 | |
2345 | /// More type predicates useful for type checking/promotion |
2346 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2347 | |
2348 | /// Return true if this is an integer type that is |
2349 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2350 | /// or an enum decl which has a signed representation. |
2351 | bool isSignedIntegerType() const; |
2352 | |
2353 | /// Return true if this is an integer type that is |
2354 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2355 | /// or an enum decl which has an unsigned representation. |
2356 | bool isUnsignedIntegerType() const; |
2357 | |
2358 | /// Determines whether this is an integer type that is signed or an |
2359 | /// enumeration types whose underlying type is a signed integer type. |
2360 | bool isSignedIntegerOrEnumerationType() const; |
2361 | |
2362 | /// Determines whether this is an integer type that is unsigned or an |
2363 | /// enumeration types whose underlying type is a unsigned integer type. |
2364 | bool isUnsignedIntegerOrEnumerationType() const; |
2365 | |
2366 | /// Return true if this is a fixed point type according to |
2367 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2368 | bool isFixedPointType() const; |
2369 | |
2370 | /// Return true if this is a fixed point or integer type. |
2371 | bool isFixedPointOrIntegerType() const; |
2372 | |
2373 | /// Return true if this is a saturated fixed point type according to |
2374 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2375 | bool isSaturatedFixedPointType() const; |
2376 | |
2377 | /// Return true if this is a saturated fixed point type according to |
2378 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2379 | bool isUnsaturatedFixedPointType() const; |
2380 | |
2381 | /// Return true if this is a fixed point type that is signed according |
2382 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2383 | bool isSignedFixedPointType() const; |
2384 | |
2385 | /// Return true if this is a fixed point type that is unsigned according |
2386 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2387 | bool isUnsignedFixedPointType() const; |
2388 | |
2389 | /// Return true if this is not a variable sized type, |
2390 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2391 | /// incomplete types. |
2392 | bool isConstantSizeType() const; |
2393 | |
2394 | /// Returns true if this type can be represented by some |
2395 | /// set of type specifiers. |
2396 | bool isSpecifierType() const; |
2397 | |
2398 | /// Determine the linkage of this type. |
2399 | Linkage getLinkage() const; |
2400 | |
2401 | /// Determine the visibility of this type. |
2402 | Visibility getVisibility() const { |
2403 | return getLinkageAndVisibility().getVisibility(); |
2404 | } |
2405 | |
2406 | /// Return true if the visibility was explicitly set is the code. |
2407 | bool isVisibilityExplicit() const { |
2408 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2409 | } |
2410 | |
2411 | /// Determine the linkage and visibility of this type. |
2412 | LinkageInfo getLinkageAndVisibility() const; |
2413 | |
2414 | /// True if the computed linkage is valid. Used for consistency |
2415 | /// checking. Should always return true. |
2416 | bool isLinkageValid() const; |
2417 | |
2418 | /// Determine the nullability of the given type. |
2419 | /// |
2420 | /// Note that nullability is only captured as sugar within the type |
2421 | /// system, not as part of the canonical type, so nullability will |
2422 | /// be lost by canonicalization and desugaring. |
2423 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2424 | |
2425 | /// Determine whether the given type can have a nullability |
2426 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2427 | /// |
2428 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2429 | /// this type can have nullability because it is dependent. |
2430 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2431 | |
2432 | /// Retrieve the set of substitutions required when accessing a member |
2433 | /// of the Objective-C receiver type that is declared in the given context. |
2434 | /// |
2435 | /// \c *this is the type of the object we're operating on, e.g., the |
2436 | /// receiver for a message send or the base of a property access, and is |
2437 | /// expected to be of some object or object pointer type. |
2438 | /// |
2439 | /// \param dc The declaration context for which we are building up a |
2440 | /// substitution mapping, which should be an Objective-C class, extension, |
2441 | /// category, or method within. |
2442 | /// |
2443 | /// \returns an array of type arguments that can be substituted for |
2444 | /// the type parameters of the given declaration context in any type described |
2445 | /// within that context, or an empty optional to indicate that no |
2446 | /// substitution is required. |
2447 | Optional<ArrayRef<QualType>> |
2448 | getObjCSubstitutions(const DeclContext *dc) const; |
2449 | |
2450 | /// Determines if this is an ObjC interface type that may accept type |
2451 | /// parameters. |
2452 | bool acceptsObjCTypeParams() const; |
2453 | |
2454 | const char *getTypeClassName() const; |
2455 | |
2456 | QualType getCanonicalTypeInternal() const { |
2457 | return CanonicalType; |
2458 | } |
2459 | |
2460 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2461 | void dump() const; |
2462 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
2463 | }; |
2464 | |
2465 | /// This will check for a TypedefType by removing any existing sugar |
2466 | /// until it reaches a TypedefType or a non-sugared type. |
2467 | template <> const TypedefType *Type::getAs() const; |
2468 | |
2469 | /// This will check for a TemplateSpecializationType by removing any |
2470 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2471 | /// non-sugared type. |
2472 | template <> const TemplateSpecializationType *Type::getAs() const; |
2473 | |
2474 | /// This will check for an AttributedType by removing any existing sugar |
2475 | /// until it reaches an AttributedType or a non-sugared type. |
2476 | template <> const AttributedType *Type::getAs() const; |
2477 | |
2478 | // We can do canonical leaf types faster, because we don't have to |
2479 | // worry about preserving child type decoration. |
2480 | #define TYPE(Class, Base) |
2481 | #define LEAF_TYPE(Class) \ |
2482 | template <> inline const Class##Type *Type::getAs() const { \ |
2483 | return dyn_cast<Class##Type>(CanonicalType); \ |
2484 | } \ |
2485 | template <> inline const Class##Type *Type::castAs() const { \ |
2486 | return cast<Class##Type>(CanonicalType); \ |
2487 | } |
2488 | #include "clang/AST/TypeNodes.inc" |
2489 | |
2490 | /// This class is used for builtin types like 'int'. Builtin |
2491 | /// types are always canonical and have a literal name field. |
2492 | class BuiltinType : public Type { |
2493 | public: |
2494 | enum Kind { |
2495 | // OpenCL image types |
2496 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2497 | #include "clang/Basic/OpenCLImageTypes.def" |
2498 | // OpenCL extension types |
2499 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2500 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2501 | // SVE Types |
2502 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2503 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2504 | // PPC MMA Types |
2505 | #define PPC_VECTOR_TYPE(Name, Id, Size) Id, |
2506 | #include "clang/Basic/PPCTypes.def" |
2507 | // RVV Types |
2508 | #define RVV_TYPE(Name, Id, SingletonId) Id, |
2509 | #include "clang/Basic/RISCVVTypes.def" |
2510 | // All other builtin types |
2511 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2512 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2513 | #include "clang/AST/BuiltinTypes.def" |
2514 | }; |
2515 | |
2516 | private: |
2517 | friend class ASTContext; // ASTContext creates these. |
2518 | |
2519 | BuiltinType(Kind K) |
2520 | : Type(Builtin, QualType(), |
2521 | K == Dependent ? TypeDependence::DependentInstantiation |
2522 | : TypeDependence::None) { |
2523 | BuiltinTypeBits.Kind = K; |
2524 | } |
2525 | |
2526 | public: |
2527 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2528 | StringRef getName(const PrintingPolicy &Policy) const; |
2529 | |
2530 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2531 | // The StringRef is null-terminated. |
2532 | StringRef str = getName(Policy); |
2533 | assert(!str.empty() && str.data()[str.size()] == '\0')(static_cast <bool> (!str.empty() && str.data() [str.size()] == '\0') ? void (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 2533, __extension__ __PRETTY_FUNCTION__)); |
2534 | return str.data(); |
2535 | } |
2536 | |
2537 | bool isSugared() const { return false; } |
2538 | QualType desugar() const { return QualType(this, 0); } |
2539 | |
2540 | bool isInteger() const { |
2541 | return getKind() >= Bool && getKind() <= Int128; |
2542 | } |
2543 | |
2544 | bool isSignedInteger() const { |
2545 | return getKind() >= Char_S && getKind() <= Int128; |
2546 | } |
2547 | |
2548 | bool isUnsignedInteger() const { |
2549 | return getKind() >= Bool && getKind() <= UInt128; |
2550 | } |
2551 | |
2552 | bool isFloatingPoint() const { |
2553 | return getKind() >= Half && getKind() <= Float128; |
2554 | } |
2555 | |
2556 | /// Determines whether the given kind corresponds to a placeholder type. |
2557 | static bool isPlaceholderTypeKind(Kind K) { |
2558 | return K >= Overload; |
2559 | } |
2560 | |
2561 | /// Determines whether this type is a placeholder type, i.e. a type |
2562 | /// which cannot appear in arbitrary positions in a fully-formed |
2563 | /// expression. |
2564 | bool isPlaceholderType() const { |
2565 | return isPlaceholderTypeKind(getKind()); |
2566 | } |
2567 | |
2568 | /// Determines whether this type is a placeholder type other than |
2569 | /// Overload. Most placeholder types require only syntactic |
2570 | /// information about their context in order to be resolved (e.g. |
2571 | /// whether it is a call expression), which means they can (and |
2572 | /// should) be resolved in an earlier "phase" of analysis. |
2573 | /// Overload expressions sometimes pick up further information |
2574 | /// from their context, like whether the context expects a |
2575 | /// specific function-pointer type, and so frequently need |
2576 | /// special treatment. |
2577 | bool isNonOverloadPlaceholderType() const { |
2578 | return getKind() > Overload; |
2579 | } |
2580 | |
2581 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2582 | }; |
2583 | |
2584 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2585 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2586 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2587 | friend class ASTContext; // ASTContext creates these. |
2588 | |
2589 | QualType ElementType; |
2590 | |
2591 | ComplexType(QualType Element, QualType CanonicalPtr) |
2592 | : Type(Complex, CanonicalPtr, Element->getDependence()), |
2593 | ElementType(Element) {} |
2594 | |
2595 | public: |
2596 | QualType getElementType() const { return ElementType; } |
2597 | |
2598 | bool isSugared() const { return false; } |
2599 | QualType desugar() const { return QualType(this, 0); } |
2600 | |
2601 | void Profile(llvm::FoldingSetNodeID &ID) { |
2602 | Profile(ID, getElementType()); |
2603 | } |
2604 | |
2605 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2606 | ID.AddPointer(Element.getAsOpaquePtr()); |
2607 | } |
2608 | |
2609 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2610 | }; |
2611 | |
2612 | /// Sugar for parentheses used when specifying types. |
2613 | class ParenType : public Type, public llvm::FoldingSetNode { |
2614 | friend class ASTContext; // ASTContext creates these. |
2615 | |
2616 | QualType Inner; |
2617 | |
2618 | ParenType(QualType InnerType, QualType CanonType) |
2619 | : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {} |
2620 | |
2621 | public: |
2622 | QualType getInnerType() const { return Inner; } |
2623 | |
2624 | bool isSugared() const { return true; } |
2625 | QualType desugar() const { return getInnerType(); } |
2626 | |
2627 | void Profile(llvm::FoldingSetNodeID &ID) { |
2628 | Profile(ID, getInnerType()); |
2629 | } |
2630 | |
2631 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2632 | Inner.Profile(ID); |
2633 | } |
2634 | |
2635 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2636 | }; |
2637 | |
2638 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2639 | class PointerType : public Type, public llvm::FoldingSetNode { |
2640 | friend class ASTContext; // ASTContext creates these. |
2641 | |
2642 | QualType PointeeType; |
2643 | |
2644 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2645 | : Type(Pointer, CanonicalPtr, Pointee->getDependence()), |
2646 | PointeeType(Pointee) {} |
2647 | |
2648 | public: |
2649 | QualType getPointeeType() const { return PointeeType; } |
2650 | |
2651 | bool isSugared() const { return false; } |
2652 | QualType desugar() const { return QualType(this, 0); } |
2653 | |
2654 | void Profile(llvm::FoldingSetNodeID &ID) { |
2655 | Profile(ID, getPointeeType()); |
2656 | } |
2657 | |
2658 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2659 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2660 | } |
2661 | |
2662 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2663 | }; |
2664 | |
2665 | /// Represents a type which was implicitly adjusted by the semantic |
2666 | /// engine for arbitrary reasons. For example, array and function types can |
2667 | /// decay, and function types can have their calling conventions adjusted. |
2668 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2669 | QualType OriginalTy; |
2670 | QualType AdjustedTy; |
2671 | |
2672 | protected: |
2673 | friend class ASTContext; // ASTContext creates these. |
2674 | |
2675 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2676 | QualType CanonicalPtr) |
2677 | : Type(TC, CanonicalPtr, OriginalTy->getDependence()), |
2678 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2679 | |
2680 | public: |
2681 | QualType getOriginalType() const { return OriginalTy; } |
2682 | QualType getAdjustedType() const { return AdjustedTy; } |
2683 | |
2684 | bool isSugared() const { return true; } |
2685 | QualType desugar() const { return AdjustedTy; } |
2686 | |
2687 | void Profile(llvm::FoldingSetNodeID &ID) { |
2688 | Profile(ID, OriginalTy, AdjustedTy); |
2689 | } |
2690 | |
2691 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2692 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2693 | ID.AddPointer(New.getAsOpaquePtr()); |
2694 | } |
2695 | |
2696 | static bool classof(const Type *T) { |
2697 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2698 | } |
2699 | }; |
2700 | |
2701 | /// Represents a pointer type decayed from an array or function type. |
2702 | class DecayedType : public AdjustedType { |
2703 | friend class ASTContext; // ASTContext creates these. |
2704 | |
2705 | inline |
2706 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2707 | |
2708 | public: |
2709 | QualType getDecayedType() const { return getAdjustedType(); } |
2710 | |
2711 | inline QualType getPointeeType() const; |
2712 | |
2713 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2714 | }; |
2715 | |
2716 | /// Pointer to a block type. |
2717 | /// This type is to represent types syntactically represented as |
2718 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2719 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2720 | friend class ASTContext; // ASTContext creates these. |
2721 | |
2722 | // Block is some kind of pointer type |
2723 | QualType PointeeType; |
2724 | |
2725 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2726 | : Type(BlockPointer, CanonicalCls, Pointee->getDependence()), |
2727 | PointeeType(Pointee) {} |
2728 | |
2729 | public: |
2730 | // Get the pointee type. Pointee is required to always be a function type. |
2731 | QualType getPointeeType() const { return PointeeType; } |
2732 | |
2733 | bool isSugared() const { return false; } |
2734 | QualType desugar() const { return QualType(this, 0); } |
2735 | |
2736 | void Profile(llvm::FoldingSetNodeID &ID) { |
2737 | Profile(ID, getPointeeType()); |
2738 | } |
2739 | |
2740 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2741 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2742 | } |
2743 | |
2744 | static bool classof(const Type *T) { |
2745 | return T->getTypeClass() == BlockPointer; |
2746 | } |
2747 | }; |
2748 | |
2749 | /// Base for LValueReferenceType and RValueReferenceType |
2750 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2751 | QualType PointeeType; |
2752 | |
2753 | protected: |
2754 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2755 | bool SpelledAsLValue) |
2756 | : Type(tc, CanonicalRef, Referencee->getDependence()), |
2757 | PointeeType(Referencee) { |
2758 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2759 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2760 | } |
2761 | |
2762 | public: |
2763 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2764 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2765 | |
2766 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2767 | |
2768 | QualType getPointeeType() const { |
2769 | // FIXME: this might strip inner qualifiers; okay? |
2770 | const ReferenceType *T = this; |
2771 | while (T->isInnerRef()) |
2772 | T = T->PointeeType->castAs<ReferenceType>(); |
2773 | return T->PointeeType; |
2774 | } |
2775 | |
2776 | void Profile(llvm::FoldingSetNodeID &ID) { |
2777 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2778 | } |
2779 | |
2780 | static void Profile(llvm::FoldingSetNodeID &ID, |
2781 | QualType Referencee, |
2782 | bool SpelledAsLValue) { |
2783 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2784 | ID.AddBoolean(SpelledAsLValue); |
2785 | } |
2786 | |
2787 | static bool classof(const Type *T) { |
2788 | return T->getTypeClass() == LValueReference || |
2789 | T->getTypeClass() == RValueReference; |
2790 | } |
2791 | }; |
2792 | |
2793 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2794 | class LValueReferenceType : public ReferenceType { |
2795 | friend class ASTContext; // ASTContext creates these |
2796 | |
2797 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2798 | bool SpelledAsLValue) |
2799 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2800 | SpelledAsLValue) {} |
2801 | |
2802 | public: |
2803 | bool isSugared() const { return false; } |
2804 | QualType desugar() const { return QualType(this, 0); } |
2805 | |
2806 | static bool classof(const Type *T) { |
2807 | return T->getTypeClass() == LValueReference; |
2808 | } |
2809 | }; |
2810 | |
2811 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2812 | class RValueReferenceType : public ReferenceType { |
2813 | friend class ASTContext; // ASTContext creates these |
2814 | |
2815 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2816 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2817 | |
2818 | public: |
2819 | bool isSugared() const { return false; } |
2820 | QualType desugar() const { return QualType(this, 0); } |
2821 | |
2822 | static bool classof(const Type *T) { |
2823 | return T->getTypeClass() == RValueReference; |
2824 | } |
2825 | }; |
2826 | |
2827 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2828 | /// |
2829 | /// This includes both pointers to data members and pointer to member functions. |
2830 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2831 | friend class ASTContext; // ASTContext creates these. |
2832 | |
2833 | QualType PointeeType; |
2834 | |
2835 | /// The class of which the pointee is a member. Must ultimately be a |
2836 | /// RecordType, but could be a typedef or a template parameter too. |
2837 | const Type *Class; |
2838 | |
2839 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2840 | : Type(MemberPointer, CanonicalPtr, |
2841 | (Cls->getDependence() & ~TypeDependence::VariablyModified) | |
2842 | Pointee->getDependence()), |
2843 | PointeeType(Pointee), Class(Cls) {} |
2844 | |
2845 | public: |
2846 | QualType getPointeeType() const { return PointeeType; } |
2847 | |
2848 | /// Returns true if the member type (i.e. the pointee type) is a |
2849 | /// function type rather than a data-member type. |
2850 | bool isMemberFunctionPointer() const { |
2851 | return PointeeType->isFunctionProtoType(); |
2852 | } |
2853 | |
2854 | /// Returns true if the member type (i.e. the pointee type) is a |
2855 | /// data type rather than a function type. |
2856 | bool isMemberDataPointer() const { |
2857 | return !PointeeType->isFunctionProtoType(); |
2858 | } |
2859 | |
2860 | const Type *getClass() const { return Class; } |
2861 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2862 | |
2863 | bool isSugared() const { return false; } |
2864 | QualType desugar() const { return QualType(this, 0); } |
2865 | |
2866 | void Profile(llvm::FoldingSetNodeID &ID) { |
2867 | Profile(ID, getPointeeType(), getClass()); |
2868 | } |
2869 | |
2870 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2871 | const Type *Class) { |
2872 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2873 | ID.AddPointer(Class); |
2874 | } |
2875 | |
2876 | static bool classof(const Type *T) { |
2877 | return T->getTypeClass() == MemberPointer; |
2878 | } |
2879 | }; |
2880 | |
2881 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2882 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2883 | public: |
2884 | /// Capture whether this is a normal array (e.g. int X[4]) |
2885 | /// an array with a static size (e.g. int X[static 4]), or an array |
2886 | /// with a star size (e.g. int X[*]). |
2887 | /// 'static' is only allowed on function parameters. |
2888 | enum ArraySizeModifier { |
2889 | Normal, Static, Star |
2890 | }; |
2891 | |
2892 | private: |
2893 | /// The element type of the array. |
2894 | QualType ElementType; |
2895 | |
2896 | protected: |
2897 | friend class ASTContext; // ASTContext creates these. |
2898 | |
2899 | ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, |
2900 | unsigned tq, const Expr *sz = nullptr); |
2901 | |
2902 | public: |
2903 | QualType getElementType() const { return ElementType; } |
2904 | |
2905 | ArraySizeModifier getSizeModifier() const { |
2906 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2907 | } |
2908 | |
2909 | Qualifiers getIndexTypeQualifiers() const { |
2910 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2911 | } |
2912 | |
2913 | unsigned getIndexTypeCVRQualifiers() const { |
2914 | return ArrayTypeBits.IndexTypeQuals; |
2915 | } |
2916 | |
2917 | static bool classof(const Type *T) { |
2918 | return T->getTypeClass() == ConstantArray || |
2919 | T->getTypeClass() == VariableArray || |
2920 | T->getTypeClass() == IncompleteArray || |
2921 | T->getTypeClass() == DependentSizedArray; |
2922 | } |
2923 | }; |
2924 | |
2925 | /// Represents the canonical version of C arrays with a specified constant size. |
2926 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2927 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2928 | class ConstantArrayType final |
2929 | : public ArrayType, |
2930 | private llvm::TrailingObjects<ConstantArrayType, const Expr *> { |
2931 | friend class ASTContext; // ASTContext creates these. |
2932 | friend TrailingObjects; |
2933 | |
2934 | llvm::APInt Size; // Allows us to unique the type. |
2935 | |
2936 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2937 | const Expr *sz, ArraySizeModifier sm, unsigned tq) |
2938 | : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { |
2939 | ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; |
2940 | if (ConstantArrayTypeBits.HasStoredSizeExpr) { |
2941 | assert(!can.isNull() && "canonical constant array should not have size")(static_cast <bool> (!can.isNull() && "canonical constant array should not have size" ) ? void (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 2941, __extension__ __PRETTY_FUNCTION__)); |
2942 | *getTrailingObjects<const Expr*>() = sz; |
2943 | } |
2944 | } |
2945 | |
2946 | unsigned numTrailingObjects(OverloadToken<const Expr*>) const { |
2947 | return ConstantArrayTypeBits.HasStoredSizeExpr; |
2948 | } |
2949 | |
2950 | public: |
2951 | const llvm::APInt &getSize() const { return Size; } |
2952 | const Expr *getSizeExpr() const { |
2953 | return ConstantArrayTypeBits.HasStoredSizeExpr |
2954 | ? *getTrailingObjects<const Expr *>() |
2955 | : nullptr; |
2956 | } |
2957 | bool isSugared() const { return false; } |
2958 | QualType desugar() const { return QualType(this, 0); } |
2959 | |
2960 | /// Determine the number of bits required to address a member of |
2961 | // an array with the given element type and number of elements. |
2962 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2963 | QualType ElementType, |
2964 | const llvm::APInt &NumElements); |
2965 | |
2966 | /// Determine the maximum number of active bits that an array's size |
2967 | /// can require, which limits the maximum size of the array. |
2968 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2969 | |
2970 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
2971 | Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), |
2972 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2973 | } |
2974 | |
2975 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, |
2976 | QualType ET, const llvm::APInt &ArraySize, |
2977 | const Expr *SizeExpr, ArraySizeModifier SizeMod, |
2978 | unsigned TypeQuals); |
2979 | |
2980 | static bool classof(const Type *T) { |
2981 | return T->getTypeClass() == ConstantArray; |
2982 | } |
2983 | }; |
2984 | |
2985 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2986 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2987 | /// unspecified. |
2988 | class IncompleteArrayType : public ArrayType { |
2989 | friend class ASTContext; // ASTContext creates these. |
2990 | |
2991 | IncompleteArrayType(QualType et, QualType can, |
2992 | ArraySizeModifier sm, unsigned tq) |
2993 | : ArrayType(IncompleteArray, et, can, sm, tq) {} |
2994 | |
2995 | public: |
2996 | friend class StmtIteratorBase; |
2997 | |
2998 | bool isSugared() const { return false; } |
2999 | QualType desugar() const { return QualType(this, 0); } |
3000 | |
3001 | static bool classof(const Type *T) { |
3002 | return T->getTypeClass() == IncompleteArray; |
3003 | } |
3004 | |
3005 | void Profile(llvm::FoldingSetNodeID &ID) { |
3006 | Profile(ID, getElementType(), getSizeModifier(), |
3007 | getIndexTypeCVRQualifiers()); |
3008 | } |
3009 | |
3010 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
3011 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
3012 | ID.AddPointer(ET.getAsOpaquePtr()); |
3013 | ID.AddInteger(SizeMod); |
3014 | ID.AddInteger(TypeQuals); |
3015 | } |
3016 | }; |
3017 | |
3018 | /// Represents a C array with a specified size that is not an |
3019 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
3020 | /// Since the size expression is an arbitrary expression, we store it as such. |
3021 | /// |
3022 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3023 | /// should not be: two lexically equivalent variable array types could mean |
3024 | /// different things, for example, these variables do not have the same type |
3025 | /// dynamically: |
3026 | /// |
3027 | /// void foo(int x) { |
3028 | /// int Y[x]; |
3029 | /// ++x; |
3030 | /// int Z[x]; |
3031 | /// } |
3032 | class VariableArrayType : public ArrayType { |
3033 | friend class ASTContext; // ASTContext creates these. |
3034 | |
3035 | /// An assignment-expression. VLA's are only permitted within |
3036 | /// a function block. |
3037 | Stmt *SizeExpr; |
3038 | |
3039 | /// The range spanned by the left and right array brackets. |
3040 | SourceRange Brackets; |
3041 | |
3042 | VariableArrayType(QualType et, QualType can, Expr *e, |
3043 | ArraySizeModifier sm, unsigned tq, |
3044 | SourceRange brackets) |
3045 | : ArrayType(VariableArray, et, can, sm, tq, e), |
3046 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3047 | |
3048 | public: |
3049 | friend class StmtIteratorBase; |
3050 | |
3051 | Expr *getSizeExpr() const { |
3052 | // We use C-style casts instead of cast<> here because we do not wish |
3053 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3054 | return (Expr*) SizeExpr; |
3055 | } |
3056 | |
3057 | SourceRange getBracketsRange() const { return Brackets; } |
3058 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3059 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3060 | |
3061 | bool isSugared() const { return false; } |
3062 | QualType desugar() const { return QualType(this, 0); } |
3063 | |
3064 | static bool classof(const Type *T) { |
3065 | return T->getTypeClass() == VariableArray; |
3066 | } |
3067 | |
3068 | void Profile(llvm::FoldingSetNodeID &ID) { |
3069 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 3069); |
3070 | } |
3071 | }; |
3072 | |
3073 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3074 | /// |
3075 | /// For example: |
3076 | /// \code |
3077 | /// template<typename T, int Size> |
3078 | /// class array { |
3079 | /// T data[Size]; |
3080 | /// }; |
3081 | /// \endcode |
3082 | /// |
3083 | /// For these types, we won't actually know what the array bound is |
3084 | /// until template instantiation occurs, at which point this will |
3085 | /// become either a ConstantArrayType or a VariableArrayType. |
3086 | class DependentSizedArrayType : public ArrayType { |
3087 | friend class ASTContext; // ASTContext creates these. |
3088 | |
3089 | const ASTContext &Context; |
3090 | |
3091 | /// An assignment expression that will instantiate to the |
3092 | /// size of the array. |
3093 | /// |
3094 | /// The expression itself might be null, in which case the array |
3095 | /// type will have its size deduced from an initializer. |
3096 | Stmt *SizeExpr; |
3097 | |
3098 | /// The range spanned by the left and right array brackets. |
3099 | SourceRange Brackets; |
3100 | |
3101 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3102 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3103 | SourceRange brackets); |
3104 | |
3105 | public: |
3106 | friend class StmtIteratorBase; |
3107 | |
3108 | Expr *getSizeExpr() const { |
3109 | // We use C-style casts instead of cast<> here because we do not wish |
3110 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3111 | return (Expr*) SizeExpr; |
3112 | } |
3113 | |
3114 | SourceRange getBracketsRange() const { return Brackets; } |
3115 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3116 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3117 | |
3118 | bool isSugared() const { return false; } |
3119 | QualType desugar() const { return QualType(this, 0); } |
3120 | |
3121 | static bool classof(const Type *T) { |
3122 | return T->getTypeClass() == DependentSizedArray; |
3123 | } |
3124 | |
3125 | void Profile(llvm::FoldingSetNodeID &ID) { |
3126 | Profile(ID, Context, getElementType(), |
3127 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3128 | } |
3129 | |
3130 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3131 | QualType ET, ArraySizeModifier SizeMod, |
3132 | unsigned TypeQuals, Expr *E); |
3133 | }; |
3134 | |
3135 | /// Represents an extended address space qualifier where the input address space |
3136 | /// value is dependent. Non-dependent address spaces are not represented with a |
3137 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3138 | /// |
3139 | /// For example: |
3140 | /// \code |
3141 | /// template<typename T, int AddrSpace> |
3142 | /// class AddressSpace { |
3143 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3144 | /// } |
3145 | /// \endcode |
3146 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3147 | friend class ASTContext; |
3148 | |
3149 | const ASTContext &Context; |
3150 | Expr *AddrSpaceExpr; |
3151 | QualType PointeeType; |
3152 | SourceLocation loc; |
3153 | |
3154 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3155 | QualType can, Expr *AddrSpaceExpr, |
3156 | SourceLocation loc); |
3157 | |
3158 | public: |
3159 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3160 | QualType getPointeeType() const { return PointeeType; } |
3161 | SourceLocation getAttributeLoc() const { return loc; } |
3162 | |
3163 | bool isSugared() const { return false; } |
3164 | QualType desugar() const { return QualType(this, 0); } |
3165 | |
3166 | static bool classof(const Type *T) { |
3167 | return T->getTypeClass() == DependentAddressSpace; |
3168 | } |
3169 | |
3170 | void Profile(llvm::FoldingSetNodeID &ID) { |
3171 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3172 | } |
3173 | |
3174 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3175 | QualType PointeeType, Expr *AddrSpaceExpr); |
3176 | }; |
3177 | |
3178 | /// Represents an extended vector type where either the type or size is |
3179 | /// dependent. |
3180 | /// |
3181 | /// For example: |
3182 | /// \code |
3183 | /// template<typename T, int Size> |
3184 | /// class vector { |
3185 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3186 | /// } |
3187 | /// \endcode |
3188 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3189 | friend class ASTContext; |
3190 | |
3191 | const ASTContext &Context; |
3192 | Expr *SizeExpr; |
3193 | |
3194 | /// The element type of the array. |
3195 | QualType ElementType; |
3196 | |
3197 | SourceLocation loc; |
3198 | |
3199 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3200 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3201 | |
3202 | public: |
3203 | Expr *getSizeExpr() const { return SizeExpr; } |
3204 | QualType getElementType() const { return ElementType; } |
3205 | SourceLocation getAttributeLoc() const { return loc; } |
3206 | |
3207 | bool isSugared() const { return false; } |
3208 | QualType desugar() const { return QualType(this, 0); } |
3209 | |
3210 | static bool classof(const Type *T) { |
3211 | return T->getTypeClass() == DependentSizedExtVector; |
3212 | } |
3213 | |
3214 | void Profile(llvm::FoldingSetNodeID &ID) { |
3215 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3216 | } |
3217 | |
3218 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3219 | QualType ElementType, Expr *SizeExpr); |
3220 | }; |
3221 | |
3222 | |
3223 | /// Represents a GCC generic vector type. This type is created using |
3224 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3225 | /// bytes; or from an Altivec __vector or vector declaration. |
3226 | /// Since the constructor takes the number of vector elements, the |
3227 | /// client is responsible for converting the size into the number of elements. |
3228 | class VectorType : public Type, public llvm::FoldingSetNode { |
3229 | public: |
3230 | enum VectorKind { |
3231 | /// not a target-specific vector type |
3232 | GenericVector, |
3233 | |
3234 | /// is AltiVec vector |
3235 | AltiVecVector, |
3236 | |
3237 | /// is AltiVec 'vector Pixel' |
3238 | AltiVecPixel, |
3239 | |
3240 | /// is AltiVec 'vector bool ...' |
3241 | AltiVecBool, |
3242 | |
3243 | /// is ARM Neon vector |
3244 | NeonVector, |
3245 | |
3246 | /// is ARM Neon polynomial vector |
3247 | NeonPolyVector, |
3248 | |
3249 | /// is AArch64 SVE fixed-length data vector |
3250 | SveFixedLengthDataVector, |
3251 | |
3252 | /// is AArch64 SVE fixed-length predicate vector |
3253 | SveFixedLengthPredicateVector |
3254 | }; |
3255 | |
3256 | protected: |
3257 | friend class ASTContext; // ASTContext creates these. |
3258 | |
3259 | /// The element type of the vector. |
3260 | QualType ElementType; |
3261 | |
3262 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3263 | VectorKind vecKind); |
3264 | |
3265 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3266 | QualType canonType, VectorKind vecKind); |
3267 | |
3268 | public: |
3269 | QualType getElementType() const { return ElementType; } |
3270 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3271 | |
3272 | bool isSugared() const { return false; } |
3273 | QualType desugar() const { return QualType(this, 0); } |
3274 | |
3275 | VectorKind getVectorKind() const { |
3276 | return VectorKind(VectorTypeBits.VecKind); |
3277 | } |
3278 | |
3279 | void Profile(llvm::FoldingSetNodeID &ID) { |
3280 | Profile(ID, getElementType(), getNumElements(), |
3281 | getTypeClass(), getVectorKind()); |
3282 | } |
3283 | |
3284 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3285 | unsigned NumElements, TypeClass TypeClass, |
3286 | VectorKind VecKind) { |
3287 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3288 | ID.AddInteger(NumElements); |
3289 | ID.AddInteger(TypeClass); |
3290 | ID.AddInteger(VecKind); |
3291 | } |
3292 | |
3293 | static bool classof(const Type *T) { |
3294 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3295 | } |
3296 | }; |
3297 | |
3298 | /// Represents a vector type where either the type or size is dependent. |
3299 | //// |
3300 | /// For example: |
3301 | /// \code |
3302 | /// template<typename T, int Size> |
3303 | /// class vector { |
3304 | /// typedef T __attribute__((vector_size(Size))) type; |
3305 | /// } |
3306 | /// \endcode |
3307 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3308 | friend class ASTContext; |
3309 | |
3310 | const ASTContext &Context; |
3311 | QualType ElementType; |
3312 | Expr *SizeExpr; |
3313 | SourceLocation Loc; |
3314 | |
3315 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3316 | QualType CanonType, Expr *SizeExpr, |
3317 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3318 | |
3319 | public: |
3320 | Expr *getSizeExpr() const { return SizeExpr; } |
3321 | QualType getElementType() const { return ElementType; } |
3322 | SourceLocation getAttributeLoc() const { return Loc; } |
3323 | VectorType::VectorKind getVectorKind() const { |
3324 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3325 | } |
3326 | |
3327 | bool isSugared() const { return false; } |
3328 | QualType desugar() const { return QualType(this, 0); } |
3329 | |
3330 | static bool classof(const Type *T) { |
3331 | return T->getTypeClass() == DependentVector; |
3332 | } |
3333 | |
3334 | void Profile(llvm::FoldingSetNodeID &ID) { |
3335 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3336 | } |
3337 | |
3338 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3339 | QualType ElementType, const Expr *SizeExpr, |
3340 | VectorType::VectorKind VecKind); |
3341 | }; |
3342 | |
3343 | /// ExtVectorType - Extended vector type. This type is created using |
3344 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3345 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3346 | /// class enables syntactic extensions, like Vector Components for accessing |
3347 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3348 | /// Shading Language). |
3349 | class ExtVectorType : public VectorType { |
3350 | friend class ASTContext; // ASTContext creates these. |
3351 | |
3352 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3353 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3354 | |
3355 | public: |
3356 | static int getPointAccessorIdx(char c) { |
3357 | switch (c) { |
3358 | default: return -1; |
3359 | case 'x': case 'r': return 0; |
3360 | case 'y': case 'g': return 1; |
3361 | case 'z': case 'b': return 2; |
3362 | case 'w': case 'a': return 3; |
3363 | } |
3364 | } |
3365 | |
3366 | static int getNumericAccessorIdx(char c) { |
3367 | switch (c) { |
3368 | default: return -1; |
3369 | case '0': return 0; |
3370 | case '1': return 1; |
3371 | case '2': return 2; |
3372 | case '3': return 3; |
3373 | case '4': return 4; |
3374 | case '5': return 5; |
3375 | case '6': return 6; |
3376 | case '7': return 7; |
3377 | case '8': return 8; |
3378 | case '9': return 9; |
3379 | case 'A': |
3380 | case 'a': return 10; |
3381 | case 'B': |
3382 | case 'b': return 11; |
3383 | case 'C': |
3384 | case 'c': return 12; |
3385 | case 'D': |
3386 | case 'd': return 13; |
3387 | case 'E': |
3388 | case 'e': return 14; |
3389 | case 'F': |
3390 | case 'f': return 15; |
3391 | } |
3392 | } |
3393 | |
3394 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3395 | if (isNumericAccessor) |
3396 | return getNumericAccessorIdx(c); |
3397 | else |
3398 | return getPointAccessorIdx(c); |
3399 | } |
3400 | |
3401 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3402 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3403 | return unsigned(idx-1) < getNumElements(); |
3404 | return false; |
3405 | } |
3406 | |
3407 | bool isSugared() const { return false; } |
3408 | QualType desugar() const { return QualType(this, 0); } |
3409 | |
3410 | static bool classof(const Type *T) { |
3411 | return T->getTypeClass() == ExtVector; |
3412 | } |
3413 | }; |
3414 | |
3415 | /// Represents a matrix type, as defined in the Matrix Types clang extensions. |
3416 | /// __attribute__((matrix_type(rows, columns))), where "rows" specifies |
3417 | /// number of rows and "columns" specifies the number of columns. |
3418 | class MatrixType : public Type, public llvm::FoldingSetNode { |
3419 | protected: |
3420 | friend class ASTContext; |
3421 | |
3422 | /// The element type of the matrix. |
3423 | QualType ElementType; |
3424 | |
3425 | MatrixType(QualType ElementTy, QualType CanonElementTy); |
3426 | |
3427 | MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy, |
3428 | const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr); |
3429 | |
3430 | public: |
3431 | /// Returns type of the elements being stored in the matrix |
3432 | QualType getElementType() const { return ElementType; } |
3433 | |
3434 | /// Valid elements types are the following: |
3435 | /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types |
3436 | /// and _Bool |
3437 | /// * the standard floating types float or double |
3438 | /// * a half-precision floating point type, if one is supported on the target |
3439 | static bool isValidElementType(QualType T) { |
3440 | return T->isDependentType() || |
3441 | (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType()); |
3442 | } |
3443 | |
3444 | bool isSugared() const { return false; } |
3445 | QualType desugar() const { return QualType(this, 0); } |
3446 | |
3447 | static bool classof(const Type *T) { |
3448 | return T->getTypeClass() == ConstantMatrix || |
3449 | T->getTypeClass() == DependentSizedMatrix; |
3450 | } |
3451 | }; |
3452 | |
3453 | /// Represents a concrete matrix type with constant number of rows and columns |
3454 | class ConstantMatrixType final : public MatrixType { |
3455 | protected: |
3456 | friend class ASTContext; |
3457 | |
3458 | /// Number of rows and columns. |
3459 | unsigned NumRows; |
3460 | unsigned NumColumns; |
3461 | |
3462 | static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1; |
3463 | |
3464 | ConstantMatrixType(QualType MatrixElementType, unsigned NRows, |
3465 | unsigned NColumns, QualType CanonElementType); |
3466 | |
3467 | ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows, |
3468 | unsigned NColumns, QualType CanonElementType); |
3469 | |
3470 | public: |
3471 | /// Returns the number of rows in the matrix. |
3472 | unsigned getNumRows() const { return NumRows; } |
3473 | |
3474 | /// Returns the number of columns in the matrix. |
3475 | unsigned getNumColumns() const { return NumColumns; } |
3476 | |
3477 | /// Returns the number of elements required to embed the matrix into a vector. |
3478 | unsigned getNumElementsFlattened() const { |
3479 | return getNumRows() * getNumColumns(); |
3480 | } |
3481 | |
3482 | /// Returns true if \p NumElements is a valid matrix dimension. |
3483 | static constexpr bool isDimensionValid(size_t NumElements) { |
3484 | return NumElements > 0 && NumElements <= MaxElementsPerDimension; |
3485 | } |
3486 | |
3487 | /// Returns the maximum number of elements per dimension. |
3488 | static constexpr unsigned getMaxElementsPerDimension() { |
3489 | return MaxElementsPerDimension; |
3490 | } |
3491 | |
3492 | void Profile(llvm::FoldingSetNodeID &ID) { |
3493 | Profile(ID, getElementType(), getNumRows(), getNumColumns(), |
3494 | getTypeClass()); |
3495 | } |
3496 | |
3497 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3498 | unsigned NumRows, unsigned NumColumns, |
3499 | TypeClass TypeClass) { |
3500 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3501 | ID.AddInteger(NumRows); |
3502 | ID.AddInteger(NumColumns); |
3503 | ID.AddInteger(TypeClass); |
3504 | } |
3505 | |
3506 | static bool classof(const Type *T) { |
3507 | return T->getTypeClass() == ConstantMatrix; |
3508 | } |
3509 | }; |
3510 | |
3511 | /// Represents a matrix type where the type and the number of rows and columns |
3512 | /// is dependent on a template. |
3513 | class DependentSizedMatrixType final : public MatrixType { |
3514 | friend class ASTContext; |
3515 | |
3516 | const ASTContext &Context; |
3517 | Expr *RowExpr; |
3518 | Expr *ColumnExpr; |
3519 | |
3520 | SourceLocation loc; |
3521 | |
3522 | DependentSizedMatrixType(const ASTContext &Context, QualType ElementType, |
3523 | QualType CanonicalType, Expr *RowExpr, |
3524 | Expr *ColumnExpr, SourceLocation loc); |
3525 | |
3526 | public: |
3527 | QualType getElementType() const { return ElementType; } |
3528 | Expr *getRowExpr() const { return RowExpr; } |
3529 | Expr *getColumnExpr() const { return ColumnExpr; } |
3530 | SourceLocation getAttributeLoc() const { return loc; } |
3531 | |
3532 | bool isSugared() const { return false; } |
3533 | QualType desugar() const { return QualType(this, 0); } |
3534 | |
3535 | static bool classof(const Type *T) { |
3536 | return T->getTypeClass() == DependentSizedMatrix; |
3537 | } |
3538 | |
3539 | void Profile(llvm::FoldingSetNodeID &ID) { |
3540 | Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr()); |
3541 | } |
3542 | |
3543 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3544 | QualType ElementType, Expr *RowExpr, Expr *ColumnExpr); |
3545 | }; |
3546 | |
3547 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3548 | /// class of FunctionNoProtoType and FunctionProtoType. |
3549 | class FunctionType : public Type { |
3550 | // The type returned by the function. |
3551 | QualType ResultType; |
3552 | |
3553 | public: |
3554 | /// Interesting information about a specific parameter that can't simply |
3555 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3556 | /// but is in FunctionType to make this class available during the |
3557 | /// specification of the bases of FunctionProtoType. |
3558 | /// |
3559 | /// It makes sense to model language features this way when there's some |
3560 | /// sort of parameter-specific override (such as an attribute) that |
3561 | /// affects how the function is called. For example, the ARC ns_consumed |
3562 | /// attribute changes whether a parameter is passed at +0 (the default) |
3563 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3564 | /// but isn't really a change to the parameter type. |
3565 | /// |
3566 | /// One serious disadvantage of modelling language features this way is |
3567 | /// that they generally do not work with language features that attempt |
3568 | /// to destructure types. For example, template argument deduction will |
3569 | /// not be able to match a parameter declared as |
3570 | /// T (*)(U) |
3571 | /// against an argument of type |
3572 | /// void (*)(__attribute__((ns_consumed)) id) |
3573 | /// because the substitution of T=void, U=id into the former will |
3574 | /// not produce the latter. |
3575 | class ExtParameterInfo { |
3576 | enum { |
3577 | ABIMask = 0x0F, |
3578 | IsConsumed = 0x10, |
3579 | HasPassObjSize = 0x20, |
3580 | IsNoEscape = 0x40, |
3581 | }; |
3582 | unsigned char Data = 0; |
3583 | |
3584 | public: |
3585 | ExtParameterInfo() = default; |
3586 | |
3587 | /// Return the ABI treatment of this parameter. |
3588 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3589 | ExtParameterInfo withABI(ParameterABI kind) const { |
3590 | ExtParameterInfo copy = *this; |
3591 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3592 | return copy; |
3593 | } |
3594 | |
3595 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3596 | /// Consumed parameters must have retainable object type. |
3597 | bool isConsumed() const { return (Data & IsConsumed); } |
3598 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3599 | ExtParameterInfo copy = *this; |
3600 | if (consumed) |
3601 | copy.Data |= IsConsumed; |
3602 | else |
3603 | copy.Data &= ~IsConsumed; |
3604 | return copy; |
3605 | } |
3606 | |
3607 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3608 | ExtParameterInfo withHasPassObjectSize() const { |
3609 | ExtParameterInfo Copy = *this; |
3610 | Copy.Data |= HasPassObjSize; |
3611 | return Copy; |
3612 | } |
3613 | |
3614 | bool isNoEscape() const { return Data & IsNoEscape; } |
3615 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3616 | ExtParameterInfo Copy = *this; |
3617 | if (NoEscape) |
3618 | Copy.Data |= IsNoEscape; |
3619 | else |
3620 | Copy.Data &= ~IsNoEscape; |
3621 | return Copy; |
3622 | } |
3623 | |
3624 | unsigned char getOpaqueValue() const { return Data; } |
3625 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3626 | ExtParameterInfo result; |
3627 | result.Data = data; |
3628 | return result; |
3629 | } |
3630 | |
3631 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3632 | return lhs.Data == rhs.Data; |
3633 | } |
3634 | |
3635 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3636 | return lhs.Data != rhs.Data; |
3637 | } |
3638 | }; |
3639 | |
3640 | /// A class which abstracts out some details necessary for |
3641 | /// making a call. |
3642 | /// |
3643 | /// It is not actually used directly for storing this information in |
3644 | /// a FunctionType, although FunctionType does currently use the |
3645 | /// same bit-pattern. |
3646 | /// |
3647 | // If you add a field (say Foo), other than the obvious places (both, |
3648 | // constructors, compile failures), what you need to update is |
3649 | // * Operator== |
3650 | // * getFoo |
3651 | // * withFoo |
3652 | // * functionType. Add Foo, getFoo. |
3653 | // * ASTContext::getFooType |
3654 | // * ASTContext::mergeFunctionTypes |
3655 | // * FunctionNoProtoType::Profile |
3656 | // * FunctionProtoType::Profile |
3657 | // * TypePrinter::PrintFunctionProto |
3658 | // * AST read and write |
3659 | // * Codegen |
3660 | class ExtInfo { |
3661 | friend class FunctionType; |
3662 | |
3663 | // Feel free to rearrange or add bits, but if you go over 16, you'll need to |
3664 | // adjust the Bits field below, and if you add bits, you'll need to adjust |
3665 | // Type::FunctionTypeBitfields::ExtInfo as well. |
3666 | |
3667 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall| |
3668 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 | |
3669 | // |
3670 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3671 | enum { CallConvMask = 0x1F }; |
3672 | enum { NoReturnMask = 0x20 }; |
3673 | enum { ProducesResultMask = 0x40 }; |
3674 | enum { NoCallerSavedRegsMask = 0x80 }; |
3675 | enum { |
3676 | RegParmMask = 0x700, |
3677 | RegParmOffset = 8 |
3678 | }; |
3679 | enum { NoCfCheckMask = 0x800 }; |
3680 | enum { CmseNSCallMask = 0x1000 }; |
3681 | uint16_t Bits = CC_C; |
3682 | |
3683 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3684 | |
3685 | public: |
3686 | // Constructor with no defaults. Use this when you know that you |
3687 | // have all the elements (when reading an AST file for example). |
3688 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3689 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck, |
3690 | bool cmseNSCall) { |
3691 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(static_cast <bool> ((!hasRegParm || regParm < 7) && "Invalid regparm value") ? void (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 3691, __extension__ __PRETTY_FUNCTION__)); |
3692 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3693 | (producesResult ? ProducesResultMask : 0) | |
3694 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3695 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3696 | (NoCfCheck ? NoCfCheckMask : 0) | |
3697 | (cmseNSCall ? CmseNSCallMask : 0); |
3698 | } |
3699 | |
3700 | // Constructor with all defaults. Use when for example creating a |
3701 | // function known to use defaults. |
3702 | ExtInfo() = default; |
3703 | |
3704 | // Constructor with just the calling convention, which is an important part |
3705 | // of the canonical type. |
3706 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3707 | |
3708 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3709 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3710 | bool getCmseNSCall() const { return Bits & CmseNSCallMask; } |
3711 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3712 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3713 | bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; } |
3714 | |
3715 | unsigned getRegParm() const { |
3716 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3717 | if (RegParm > 0) |
3718 | --RegParm; |
3719 | return RegParm; |
3720 | } |
3721 | |
3722 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3723 | |
3724 | bool operator==(ExtInfo Other) const { |
3725 | return Bits == Other.Bits; |
3726 | } |
3727 | bool operator!=(ExtInfo Other) const { |
3728 | return Bits != Other.Bits; |
3729 | } |
3730 | |
3731 | // Note that we don't have setters. That is by design, use |
3732 | // the following with methods instead of mutating these objects. |
3733 | |
3734 | ExtInfo withNoReturn(bool noReturn) const { |
3735 | if (noReturn) |
3736 | return ExtInfo(Bits | NoReturnMask); |
3737 | else |
3738 | return ExtInfo(Bits & ~NoReturnMask); |
3739 | } |
3740 | |
3741 | ExtInfo withProducesResult(bool producesResult) const { |
3742 | if (producesResult) |
3743 | return ExtInfo(Bits | ProducesResultMask); |
3744 | else |
3745 | return ExtInfo(Bits & ~ProducesResultMask); |
3746 | } |
3747 | |
3748 | ExtInfo withCmseNSCall(bool cmseNSCall) const { |
3749 | if (cmseNSCall) |
3750 | return ExtInfo(Bits | CmseNSCallMask); |
3751 | else |
3752 | return ExtInfo(Bits & ~CmseNSCallMask); |
3753 | } |
3754 | |
3755 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3756 | if (noCallerSavedRegs) |
3757 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3758 | else |
3759 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3760 | } |
3761 | |
3762 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3763 | if (noCfCheck) |
3764 | return ExtInfo(Bits | NoCfCheckMask); |
3765 | else |
3766 | return ExtInfo(Bits & ~NoCfCheckMask); |
3767 | } |
3768 | |
3769 | ExtInfo withRegParm(unsigned RegParm) const { |
3770 | assert(RegParm < 7 && "Invalid regparm value")(static_cast <bool> (RegParm < 7 && "Invalid regparm value" ) ? void (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 3770, __extension__ __PRETTY_FUNCTION__)); |
3771 | return ExtInfo((Bits & ~RegParmMask) | |
3772 | ((RegParm + 1) << RegParmOffset)); |
3773 | } |
3774 | |
3775 | ExtInfo withCallingConv(CallingConv cc) const { |
3776 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3777 | } |
3778 | |
3779 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3780 | ID.AddInteger(Bits); |
3781 | } |
3782 | }; |
3783 | |
3784 | /// A simple holder for a QualType representing a type in an |
3785 | /// exception specification. Unfortunately needed by FunctionProtoType |
3786 | /// because TrailingObjects cannot handle repeated types. |
3787 | struct ExceptionType { QualType Type; }; |
3788 | |
3789 | /// A simple holder for various uncommon bits which do not fit in |
3790 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3791 | /// alignment of subsequent objects in TrailingObjects. You must update |
3792 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3793 | struct alignas(void *) FunctionTypeExtraBitfields { |
3794 | /// The number of types in the exception specification. |
3795 | /// A whole unsigned is not needed here and according to |
3796 | /// [implimits] 8 bits would be enough here. |
3797 | unsigned NumExceptionType; |
3798 | }; |
3799 | |
3800 | protected: |
3801 | FunctionType(TypeClass tc, QualType res, QualType Canonical, |
3802 | TypeDependence Dependence, ExtInfo Info) |
3803 | : Type(tc, Canonical, Dependence), ResultType(res) { |
3804 | FunctionTypeBits.ExtInfo = Info.Bits; |
3805 | } |
3806 | |
3807 | Qualifiers getFastTypeQuals() const { |
3808 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3809 | } |
3810 | |
3811 | public: |
3812 | QualType getReturnType() const { return ResultType; } |
3813 | |
3814 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3815 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3816 | |
3817 | /// Determine whether this function type includes the GNU noreturn |
3818 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3819 | /// type. |
3820 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3821 | |
3822 | bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); } |
3823 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3824 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3825 | |
3826 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3827 | "Const, volatile and restrict are assumed to be a subset of " |
3828 | "the fast qualifiers."); |
3829 | |
3830 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3831 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3832 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3833 | |
3834 | /// Determine the type of an expression that calls a function of |
3835 | /// this type. |
3836 | QualType getCallResultType(const ASTContext &Context) const { |
3837 | return getReturnType().getNonLValueExprType(Context); |
3838 | } |
3839 | |
3840 | static StringRef getNameForCallConv(CallingConv CC); |
3841 | |
3842 | static bool classof(const Type *T) { |
3843 | return T->getTypeClass() == FunctionNoProto || |
3844 | T->getTypeClass() == FunctionProto; |
3845 | } |
3846 | }; |
3847 | |
3848 | /// Represents a K&R-style 'int foo()' function, which has |
3849 | /// no information available about its arguments. |
3850 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3851 | friend class ASTContext; // ASTContext creates these. |
3852 | |
3853 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3854 | : FunctionType(FunctionNoProto, Result, Canonical, |
3855 | Result->getDependence() & |
3856 | ~(TypeDependence::DependentInstantiation | |
3857 | TypeDependence::UnexpandedPack), |
3858 | Info) {} |
3859 | |
3860 | public: |
3861 | // No additional state past what FunctionType provides. |
3862 | |
3863 | bool isSugared() const { return false; } |
3864 | QualType desugar() const { return QualType(this, 0); } |
3865 | |
3866 | void Profile(llvm::FoldingSetNodeID &ID) { |
3867 | Profile(ID, getReturnType(), getExtInfo()); |
3868 | } |
3869 | |
3870 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3871 | ExtInfo Info) { |
3872 | Info.Profile(ID); |
3873 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3874 | } |
3875 | |
3876 | static bool classof(const Type *T) { |
3877 | return T->getTypeClass() == FunctionNoProto; |
3878 | } |
3879 | }; |
3880 | |
3881 | /// Represents a prototype with parameter type info, e.g. |
3882 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3883 | /// parameters, not as having a single void parameter. Such a type can have |
3884 | /// an exception specification, but this specification is not part of the |
3885 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3886 | /// which optional. For more information about the trailing objects see |
3887 | /// the first comment inside FunctionProtoType. |
3888 | class FunctionProtoType final |
3889 | : public FunctionType, |
3890 | public llvm::FoldingSetNode, |
3891 | private llvm::TrailingObjects< |
3892 | FunctionProtoType, QualType, SourceLocation, |
3893 | FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, |
3894 | Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> { |
3895 | friend class ASTContext; // ASTContext creates these. |
3896 | friend TrailingObjects; |
3897 | |
3898 | // FunctionProtoType is followed by several trailing objects, some of |
3899 | // which optional. They are in order: |
3900 | // |
3901 | // * An array of getNumParams() QualType holding the parameter types. |
3902 | // Always present. Note that for the vast majority of FunctionProtoType, |
3903 | // these will be the only trailing objects. |
3904 | // |
3905 | // * Optionally if the function is variadic, the SourceLocation of the |
3906 | // ellipsis. |
3907 | // |
3908 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3909 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3910 | // a single FunctionTypeExtraBitfields. Present if and only if |
3911 | // hasExtraBitfields() is true. |
3912 | // |
3913 | // * Optionally exactly one of: |
3914 | // * an array of getNumExceptions() ExceptionType, |
3915 | // * a single Expr *, |
3916 | // * a pair of FunctionDecl *, |
3917 | // * a single FunctionDecl * |
3918 | // used to store information about the various types of exception |
3919 | // specification. See getExceptionSpecSize for the details. |
3920 | // |
3921 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3922 | // an ExtParameterInfo for each of the parameters. Present if and |
3923 | // only if hasExtParameterInfos() is true. |
3924 | // |
3925 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3926 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3927 | // if hasExtQualifiers() is true. |
3928 | // |
3929 | // The optional FunctionTypeExtraBitfields has to be before the data |
3930 | // related to the exception specification since it contains the number |
3931 | // of exception types. |
3932 | // |
3933 | // We put the ExtParameterInfos last. If all were equal, it would make |
3934 | // more sense to put these before the exception specification, because |
3935 | // it's much easier to skip past them compared to the elaborate switch |
3936 | // required to skip the exception specification. However, all is not |
3937 | // equal; ExtParameterInfos are used to model very uncommon features, |
3938 | // and it's better not to burden the more common paths. |
3939 | |
3940 | public: |
3941 | /// Holds information about the various types of exception specification. |
3942 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3943 | /// used to group together the various bits of information about the |
3944 | /// exception specification. |
3945 | struct ExceptionSpecInfo { |
3946 | /// The kind of exception specification this is. |
3947 | ExceptionSpecificationType Type = EST_None; |
3948 | |
3949 | /// Explicitly-specified list of exception types. |
3950 | ArrayRef<QualType> Exceptions; |
3951 | |
3952 | /// Noexcept expression, if this is a computed noexcept specification. |
3953 | Expr *NoexceptExpr = nullptr; |
3954 | |
3955 | /// The function whose exception specification this is, for |
3956 | /// EST_Unevaluated and EST_Uninstantiated. |
3957 | FunctionDecl *SourceDecl = nullptr; |
3958 | |
3959 | /// The function template whose exception specification this is instantiated |
3960 | /// from, for EST_Uninstantiated. |
3961 | FunctionDecl *SourceTemplate = nullptr; |
3962 | |
3963 | ExceptionSpecInfo() = default; |
3964 | |
3965 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3966 | }; |
3967 | |
3968 | /// Extra information about a function prototype. ExtProtoInfo is not |
3969 | /// stored as such in FunctionProtoType but is used to group together |
3970 | /// the various bits of extra information about a function prototype. |
3971 | struct ExtProtoInfo { |
3972 | FunctionType::ExtInfo ExtInfo; |
3973 | bool Variadic : 1; |
3974 | bool HasTrailingReturn : 1; |
3975 | Qualifiers TypeQuals; |
3976 | RefQualifierKind RefQualifier = RQ_None; |
3977 | ExceptionSpecInfo ExceptionSpec; |
3978 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3979 | SourceLocation EllipsisLoc; |
3980 | |
3981 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3982 | |
3983 | ExtProtoInfo(CallingConv CC) |
3984 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3985 | |
3986 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3987 | ExtProtoInfo Result(*this); |
3988 | Result.ExceptionSpec = ESI; |
3989 | return Result; |
3990 | } |
3991 | }; |
3992 | |
3993 | private: |
3994 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3995 | return getNumParams(); |
3996 | } |
3997 | |
3998 | unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { |
3999 | return isVariadic(); |
4000 | } |
4001 | |
4002 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
4003 | return hasExtraBitfields(); |
4004 | } |
4005 | |
4006 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
4007 | return getExceptionSpecSize().NumExceptionType; |
4008 | } |
4009 | |
4010 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
4011 | return getExceptionSpecSize().NumExprPtr; |
4012 | } |
4013 | |
4014 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
4015 | return getExceptionSpecSize().NumFunctionDeclPtr; |
4016 | } |
4017 | |
4018 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
4019 | return hasExtParameterInfos() ? getNumParams() : 0; |
4020 | } |
4021 | |
4022 | /// Determine whether there are any argument types that |
4023 | /// contain an unexpanded parameter pack. |
4024 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
4025 | unsigned numArgs) { |
4026 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
4027 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
4028 | return true; |
4029 | |
4030 | return false; |
4031 | } |
4032 | |
4033 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
4034 | QualType canonical, const ExtProtoInfo &epi); |
4035 | |
4036 | /// This struct is returned by getExceptionSpecSize and is used to |
4037 | /// translate an ExceptionSpecificationType to the number and kind |
4038 | /// of trailing objects related to the exception specification. |
4039 | struct ExceptionSpecSizeHolder { |
4040 | unsigned NumExceptionType; |
4041 | unsigned NumExprPtr; |
4042 | unsigned NumFunctionDeclPtr; |
4043 | }; |
4044 | |
4045 | /// Return the number and kind of trailing objects |
4046 | /// related to the exception specification. |
4047 | static ExceptionSpecSizeHolder |
4048 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
4049 | switch (EST) { |
4050 | case EST_None: |
4051 | case EST_DynamicNone: |
4052 | case EST_MSAny: |
4053 | case EST_BasicNoexcept: |
4054 | case EST_Unparsed: |
4055 | case EST_NoThrow: |
4056 | return {0, 0, 0}; |
4057 | |
4058 | case EST_Dynamic: |
4059 | return {NumExceptions, 0, 0}; |
4060 | |
4061 | case EST_DependentNoexcept: |
4062 | case EST_NoexceptFalse: |
4063 | case EST_NoexceptTrue: |
4064 | return {0, 1, 0}; |
4065 | |
4066 | case EST_Uninstantiated: |
4067 | return {0, 0, 2}; |
4068 | |
4069 | case EST_Unevaluated: |
4070 | return {0, 0, 1}; |
4071 | } |
4072 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4072); |
4073 | } |
4074 | |
4075 | /// Return the number and kind of trailing objects |
4076 | /// related to the exception specification. |
4077 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
4078 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
4079 | } |
4080 | |
4081 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4082 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
4083 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
4084 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
4085 | return EST == EST_Dynamic; |
4086 | } |
4087 | |
4088 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
4089 | bool hasExtraBitfields() const { |
4090 | return hasExtraBitfields(getExceptionSpecType()); |
4091 | } |
4092 | |
4093 | bool hasExtQualifiers() const { |
4094 | return FunctionTypeBits.HasExtQuals; |
4095 | } |
4096 | |
4097 | public: |
4098 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
4099 | |
4100 | QualType getParamType(unsigned i) const { |
4101 | assert(i < getNumParams() && "invalid parameter index")(static_cast <bool> (i < getNumParams() && "invalid parameter index" ) ? void (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4101, __extension__ __PRETTY_FUNCTION__)); |
4102 | return param_type_begin()[i]; |
4103 | } |
4104 | |
4105 | ArrayRef<QualType> getParamTypes() const { |
4106 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
4107 | } |
4108 | |
4109 | ExtProtoInfo getExtProtoInfo() const { |
4110 | ExtProtoInfo EPI; |
4111 | EPI.ExtInfo = getExtInfo(); |
4112 | EPI.Variadic = isVariadic(); |
4113 | EPI.EllipsisLoc = getEllipsisLoc(); |
4114 | EPI.HasTrailingReturn = hasTrailingReturn(); |
4115 | EPI.ExceptionSpec = getExceptionSpecInfo(); |
4116 | EPI.TypeQuals = getMethodQuals(); |
4117 | EPI.RefQualifier = getRefQualifier(); |
4118 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
4119 | return EPI; |
4120 | } |
4121 | |
4122 | /// Get the kind of exception specification on this function. |
4123 | ExceptionSpecificationType getExceptionSpecType() const { |
4124 | return static_cast<ExceptionSpecificationType>( |
4125 | FunctionTypeBits.ExceptionSpecType); |
4126 | } |
4127 | |
4128 | /// Return whether this function has any kind of exception spec. |
4129 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
4130 | |
4131 | /// Return whether this function has a dynamic (throw) exception spec. |
4132 | bool hasDynamicExceptionSpec() const { |
4133 | return isDynamicExceptionSpec(getExceptionSpecType()); |
4134 | } |
4135 | |
4136 | /// Return whether this function has a noexcept exception spec. |
4137 | bool hasNoexceptExceptionSpec() const { |
4138 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
4139 | } |
4140 | |
4141 | /// Return whether this function has a dependent exception spec. |
4142 | bool hasDependentExceptionSpec() const; |
4143 | |
4144 | /// Return whether this function has an instantiation-dependent exception |
4145 | /// spec. |
4146 | bool hasInstantiationDependentExceptionSpec() const; |
4147 | |
4148 | /// Return all the available information about this type's exception spec. |
4149 | ExceptionSpecInfo getExceptionSpecInfo() const { |
4150 | ExceptionSpecInfo Result; |
4151 | Result.Type = getExceptionSpecType(); |
4152 | if (Result.Type == EST_Dynamic) { |
4153 | Result.Exceptions = exceptions(); |
4154 | } else if (isComputedNoexcept(Result.Type)) { |
4155 | Result.NoexceptExpr = getNoexceptExpr(); |
4156 | } else if (Result.Type == EST_Uninstantiated) { |
4157 | Result.SourceDecl = getExceptionSpecDecl(); |
4158 | Result.SourceTemplate = getExceptionSpecTemplate(); |
4159 | } else if (Result.Type == EST_Unevaluated) { |
4160 | Result.SourceDecl = getExceptionSpecDecl(); |
4161 | } |
4162 | return Result; |
4163 | } |
4164 | |
4165 | /// Return the number of types in the exception specification. |
4166 | unsigned getNumExceptions() const { |
4167 | return getExceptionSpecType() == EST_Dynamic |
4168 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
4169 | ->NumExceptionType |
4170 | : 0; |
4171 | } |
4172 | |
4173 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
4174 | QualType getExceptionType(unsigned i) const { |
4175 | assert(i < getNumExceptions() && "Invalid exception number!")(static_cast <bool> (i < getNumExceptions() && "Invalid exception number!") ? void (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4175, __extension__ __PRETTY_FUNCTION__)); |
4176 | return exception_begin()[i]; |
4177 | } |
4178 | |
4179 | /// Return the expression inside noexcept(expression), or a null pointer |
4180 | /// if there is none (because the exception spec is not of this form). |
4181 | Expr *getNoexceptExpr() const { |
4182 | if (!isComputedNoexcept(getExceptionSpecType())) |
4183 | return nullptr; |
4184 | return *getTrailingObjects<Expr *>(); |
4185 | } |
4186 | |
4187 | /// If this function type has an exception specification which hasn't |
4188 | /// been determined yet (either because it has not been evaluated or because |
4189 | /// it has not been instantiated), this is the function whose exception |
4190 | /// specification is represented by this type. |
4191 | FunctionDecl *getExceptionSpecDecl() const { |
4192 | if (getExceptionSpecType() != EST_Uninstantiated && |
4193 | getExceptionSpecType() != EST_Unevaluated) |
4194 | return nullptr; |
4195 | return getTrailingObjects<FunctionDecl *>()[0]; |
4196 | } |
4197 | |
4198 | /// If this function type has an uninstantiated exception |
4199 | /// specification, this is the function whose exception specification |
4200 | /// should be instantiated to find the exception specification for |
4201 | /// this type. |
4202 | FunctionDecl *getExceptionSpecTemplate() const { |
4203 | if (getExceptionSpecType() != EST_Uninstantiated) |
4204 | return nullptr; |
4205 | return getTrailingObjects<FunctionDecl *>()[1]; |
4206 | } |
4207 | |
4208 | /// Determine whether this function type has a non-throwing exception |
4209 | /// specification. |
4210 | CanThrowResult canThrow() const; |
4211 | |
4212 | /// Determine whether this function type has a non-throwing exception |
4213 | /// specification. If this depends on template arguments, returns |
4214 | /// \c ResultIfDependent. |
4215 | bool isNothrow(bool ResultIfDependent = false) const { |
4216 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4217 | } |
4218 | |
4219 | /// Whether this function prototype is variadic. |
4220 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4221 | |
4222 | SourceLocation getEllipsisLoc() const { |
4223 | return isVariadic() ? *getTrailingObjects<SourceLocation>() |
4224 | : SourceLocation(); |
4225 | } |
4226 | |
4227 | /// Determines whether this function prototype contains a |
4228 | /// parameter pack at the end. |
4229 | /// |
4230 | /// A function template whose last parameter is a parameter pack can be |
4231 | /// called with an arbitrary number of arguments, much like a variadic |
4232 | /// function. |
4233 | bool isTemplateVariadic() const; |
4234 | |
4235 | /// Whether this function prototype has a trailing return type. |
4236 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4237 | |
4238 | Qualifiers getMethodQuals() const { |
4239 | if (hasExtQualifiers()) |
4240 | return *getTrailingObjects<Qualifiers>(); |
4241 | else |
4242 | return getFastTypeQuals(); |
4243 | } |
4244 | |
4245 | /// Retrieve the ref-qualifier associated with this function type. |
4246 | RefQualifierKind getRefQualifier() const { |
4247 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4248 | } |
4249 | |
4250 | using param_type_iterator = const QualType *; |
4251 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4252 | |
4253 | param_type_range param_types() const { |
4254 | return param_type_range(param_type_begin(), param_type_end()); |
4255 | } |
4256 | |
4257 | param_type_iterator param_type_begin() const { |
4258 | return getTrailingObjects<QualType>(); |
4259 | } |
4260 | |
4261 | param_type_iterator param_type_end() const { |
4262 | return param_type_begin() + getNumParams(); |
4263 | } |
4264 | |
4265 | using exception_iterator = const QualType *; |
4266 | |
4267 | ArrayRef<QualType> exceptions() const { |
4268 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4269 | } |
4270 | |
4271 | exception_iterator exception_begin() const { |
4272 | return reinterpret_cast<exception_iterator>( |
4273 | getTrailingObjects<ExceptionType>()); |
4274 | } |
4275 | |
4276 | exception_iterator exception_end() const { |
4277 | return exception_begin() + getNumExceptions(); |
4278 | } |
4279 | |
4280 | /// Is there any interesting extra information for any of the parameters |
4281 | /// of this function type? |
4282 | bool hasExtParameterInfos() const { |
4283 | return FunctionTypeBits.HasExtParameterInfos; |
4284 | } |
4285 | |
4286 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4287 | assert(hasExtParameterInfos())(static_cast <bool> (hasExtParameterInfos()) ? void (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4287, __extension__ __PRETTY_FUNCTION__)); |
4288 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4289 | getNumParams()); |
4290 | } |
4291 | |
4292 | /// Return a pointer to the beginning of the array of extra parameter |
4293 | /// information, if present, or else null if none of the parameters |
4294 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4295 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4296 | if (!hasExtParameterInfos()) |
4297 | return nullptr; |
4298 | return getTrailingObjects<ExtParameterInfo>(); |
4299 | } |
4300 | |
4301 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4302 | assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range" ) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4302, __extension__ __PRETTY_FUNCTION__)); |
4303 | if (hasExtParameterInfos()) |
4304 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4305 | return ExtParameterInfo(); |
4306 | } |
4307 | |
4308 | ParameterABI getParameterABI(unsigned I) const { |
4309 | assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range" ) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4309, __extension__ __PRETTY_FUNCTION__)); |
4310 | if (hasExtParameterInfos()) |
4311 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4312 | return ParameterABI::Ordinary; |
4313 | } |
4314 | |
4315 | bool isParamConsumed(unsigned I) const { |
4316 | assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range" ) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4316, __extension__ __PRETTY_FUNCTION__)); |
4317 | if (hasExtParameterInfos()) |
4318 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4319 | return false; |
4320 | } |
4321 | |
4322 | bool isSugared() const { return false; } |
4323 | QualType desugar() const { return QualType(this, 0); } |
4324 | |
4325 | void printExceptionSpecification(raw_ostream &OS, |
4326 | const PrintingPolicy &Policy) const; |
4327 | |
4328 | static bool classof(const Type *T) { |
4329 | return T->getTypeClass() == FunctionProto; |
4330 | } |
4331 | |
4332 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
4333 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
4334 | param_type_iterator ArgTys, unsigned NumArgs, |
4335 | const ExtProtoInfo &EPI, const ASTContext &Context, |
4336 | bool Canonical); |
4337 | }; |
4338 | |
4339 | /// Represents the dependent type named by a dependently-scoped |
4340 | /// typename using declaration, e.g. |
4341 | /// using typename Base<T>::foo; |
4342 | /// |
4343 | /// Template instantiation turns these into the underlying type. |
4344 | class UnresolvedUsingType : public Type { |
4345 | friend class ASTContext; // ASTContext creates these. |
4346 | |
4347 | UnresolvedUsingTypenameDecl *Decl; |
4348 | |
4349 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
4350 | : Type(UnresolvedUsing, QualType(), |
4351 | TypeDependence::DependentInstantiation), |
4352 | Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {} |
4353 | |
4354 | public: |
4355 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
4356 | |
4357 | bool isSugared() const { return false; } |
4358 | QualType desugar() const { return QualType(this, 0); } |
4359 | |
4360 | static bool classof(const Type *T) { |
4361 | return T->getTypeClass() == UnresolvedUsing; |
4362 | } |
4363 | |
4364 | void Profile(llvm::FoldingSetNodeID &ID) { |
4365 | return Profile(ID, Decl); |
4366 | } |
4367 | |
4368 | static void Profile(llvm::FoldingSetNodeID &ID, |
4369 | UnresolvedUsingTypenameDecl *D) { |
4370 | ID.AddPointer(D); |
4371 | } |
4372 | }; |
4373 | |
4374 | class TypedefType : public Type { |
4375 | TypedefNameDecl *Decl; |
4376 | |
4377 | private: |
4378 | friend class ASTContext; // ASTContext creates these. |
4379 | |
4380 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying, |
4381 | QualType can); |
4382 | |
4383 | public: |
4384 | TypedefNameDecl *getDecl() const { return Decl; } |
4385 | |
4386 | bool isSugared() const { return true; } |
4387 | QualType desugar() const; |
4388 | |
4389 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
4390 | }; |
4391 | |
4392 | /// Sugar type that represents a type that was qualified by a qualifier written |
4393 | /// as a macro invocation. |
4394 | class MacroQualifiedType : public Type { |
4395 | friend class ASTContext; // ASTContext creates these. |
4396 | |
4397 | QualType UnderlyingTy; |
4398 | const IdentifierInfo *MacroII; |
4399 | |
4400 | MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, |
4401 | const IdentifierInfo *MacroII) |
4402 | : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()), |
4403 | UnderlyingTy(UnderlyingTy), MacroII(MacroII) { |
4404 | assert(isa<AttributedType>(UnderlyingTy) &&(static_cast <bool> (isa<AttributedType>(UnderlyingTy ) && "Expected a macro qualified type to only wrap attributed types." ) ? void (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4405, __extension__ __PRETTY_FUNCTION__)) |
4405 | "Expected a macro qualified type to only wrap attributed types.")(static_cast <bool> (isa<AttributedType>(UnderlyingTy ) && "Expected a macro qualified type to only wrap attributed types." ) ? void (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4405, __extension__ __PRETTY_FUNCTION__)); |
4406 | } |
4407 | |
4408 | public: |
4409 | const IdentifierInfo *getMacroIdentifier() const { return MacroII; } |
4410 | QualType getUnderlyingType() const { return UnderlyingTy; } |
4411 | |
4412 | /// Return this attributed type's modified type with no qualifiers attached to |
4413 | /// it. |
4414 | QualType getModifiedType() const; |
4415 | |
4416 | bool isSugared() const { return true; } |
4417 | QualType desugar() const; |
4418 | |
4419 | static bool classof(const Type *T) { |
4420 | return T->getTypeClass() == MacroQualified; |
4421 | } |
4422 | }; |
4423 | |
4424 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
4425 | class TypeOfExprType : public Type { |
4426 | Expr *TOExpr; |
4427 | |
4428 | protected: |
4429 | friend class ASTContext; // ASTContext creates these. |
4430 | |
4431 | TypeOfExprType(Expr *E, QualType can = QualType()); |
4432 | |
4433 | public: |
4434 | Expr *getUnderlyingExpr() const { return TOExpr; } |
4435 | |
4436 | /// Remove a single level of sugar. |
4437 | QualType desugar() const; |
4438 | |
4439 | /// Returns whether this type directly provides sugar. |
4440 | bool isSugared() const; |
4441 | |
4442 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
4443 | }; |
4444 | |
4445 | /// Internal representation of canonical, dependent |
4446 | /// `typeof(expr)` types. |
4447 | /// |
4448 | /// This class is used internally by the ASTContext to manage |
4449 | /// canonical, dependent types, only. Clients will only see instances |
4450 | /// of this class via TypeOfExprType nodes. |
4451 | class DependentTypeOfExprType |
4452 | : public TypeOfExprType, public llvm::FoldingSetNode { |
4453 | const ASTContext &Context; |
4454 | |
4455 | public: |
4456 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
4457 | : TypeOfExprType(E), Context(Context) {} |
4458 | |
4459 | void Profile(llvm::FoldingSetNodeID &ID) { |
4460 | Profile(ID, Context, getUnderlyingExpr()); |
4461 | } |
4462 | |
4463 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4464 | Expr *E); |
4465 | }; |
4466 | |
4467 | /// Represents `typeof(type)`, a GCC extension. |
4468 | class TypeOfType : public Type { |
4469 | friend class ASTContext; // ASTContext creates these. |
4470 | |
4471 | QualType TOType; |
4472 | |
4473 | TypeOfType(QualType T, QualType can) |
4474 | : Type(TypeOf, can, T->getDependence()), TOType(T) { |
4475 | assert(!isa<TypedefType>(can) && "Invalid canonical type")(static_cast <bool> (!isa<TypedefType>(can) && "Invalid canonical type") ? void (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4475, __extension__ __PRETTY_FUNCTION__)); |
4476 | } |
4477 | |
4478 | public: |
4479 | QualType getUnderlyingType() const { return TOType; } |
4480 | |
4481 | /// Remove a single level of sugar. |
4482 | QualType desugar() const { return getUnderlyingType(); } |
4483 | |
4484 | /// Returns whether this type directly provides sugar. |
4485 | bool isSugared() const { return true; } |
4486 | |
4487 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
4488 | }; |
4489 | |
4490 | /// Represents the type `decltype(expr)` (C++11). |
4491 | class DecltypeType : public Type { |
4492 | Expr *E; |
4493 | QualType UnderlyingType; |
4494 | |
4495 | protected: |
4496 | friend class ASTContext; // ASTContext creates these. |
4497 | |
4498 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
4499 | |
4500 | public: |
4501 | Expr *getUnderlyingExpr() const { return E; } |
4502 | QualType getUnderlyingType() const { return UnderlyingType; } |
4503 | |
4504 | /// Remove a single level of sugar. |
4505 | QualType desugar() const; |
4506 | |
4507 | /// Returns whether this type directly provides sugar. |
4508 | bool isSugared() const; |
4509 | |
4510 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
4511 | }; |
4512 | |
4513 | /// Internal representation of canonical, dependent |
4514 | /// decltype(expr) types. |
4515 | /// |
4516 | /// This class is used internally by the ASTContext to manage |
4517 | /// canonical, dependent types, only. Clients will only see instances |
4518 | /// of this class via DecltypeType nodes. |
4519 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
4520 | const ASTContext &Context; |
4521 | |
4522 | public: |
4523 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
4524 | |
4525 | void Profile(llvm::FoldingSetNodeID &ID) { |
4526 | Profile(ID, Context, getUnderlyingExpr()); |
4527 | } |
4528 | |
4529 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4530 | Expr *E); |
4531 | }; |
4532 | |
4533 | /// A unary type transform, which is a type constructed from another. |
4534 | class UnaryTransformType : public Type { |
4535 | public: |
4536 | enum UTTKind { |
4537 | EnumUnderlyingType |
4538 | }; |
4539 | |
4540 | private: |
4541 | /// The untransformed type. |
4542 | QualType BaseType; |
4543 | |
4544 | /// The transformed type if not dependent, otherwise the same as BaseType. |
4545 | QualType UnderlyingType; |
4546 | |
4547 | UTTKind UKind; |
4548 | |
4549 | protected: |
4550 | friend class ASTContext; |
4551 | |
4552 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
4553 | QualType CanonicalTy); |
4554 | |
4555 | public: |
4556 | bool isSugared() const { return !isDependentType(); } |
4557 | QualType desugar() const { return UnderlyingType; } |
4558 | |
4559 | QualType getUnderlyingType() const { return UnderlyingType; } |
4560 | QualType getBaseType() const { return BaseType; } |
4561 | |
4562 | UTTKind getUTTKind() const { return UKind; } |
4563 | |
4564 | static bool classof(const Type *T) { |
4565 | return T->getTypeClass() == UnaryTransform; |
4566 | } |
4567 | }; |
4568 | |
4569 | /// Internal representation of canonical, dependent |
4570 | /// __underlying_type(type) types. |
4571 | /// |
4572 | /// This class is used internally by the ASTContext to manage |
4573 | /// canonical, dependent types, only. Clients will only see instances |
4574 | /// of this class via UnaryTransformType nodes. |
4575 | class DependentUnaryTransformType : public UnaryTransformType, |
4576 | public llvm::FoldingSetNode { |
4577 | public: |
4578 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
4579 | UTTKind UKind); |
4580 | |
4581 | void Profile(llvm::FoldingSetNodeID &ID) { |
4582 | Profile(ID, getBaseType(), getUTTKind()); |
4583 | } |
4584 | |
4585 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
4586 | UTTKind UKind) { |
4587 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
4588 | ID.AddInteger((unsigned)UKind); |
4589 | } |
4590 | }; |
4591 | |
4592 | class TagType : public Type { |
4593 | friend class ASTReader; |
4594 | template <class T> friend class serialization::AbstractTypeReader; |
4595 | |
4596 | /// Stores the TagDecl associated with this type. The decl may point to any |
4597 | /// TagDecl that declares the entity. |
4598 | TagDecl *decl; |
4599 | |
4600 | protected: |
4601 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
4602 | |
4603 | public: |
4604 | TagDecl *getDecl() const; |
4605 | |
4606 | /// Determines whether this type is in the process of being defined. |
4607 | bool isBeingDefined() const; |
4608 | |
4609 | static bool classof(const Type *T) { |
4610 | return T->getTypeClass() == Enum || T->getTypeClass() == Record; |
4611 | } |
4612 | }; |
4613 | |
4614 | /// A helper class that allows the use of isa/cast/dyncast |
4615 | /// to detect TagType objects of structs/unions/classes. |
4616 | class RecordType : public TagType { |
4617 | protected: |
4618 | friend class ASTContext; // ASTContext creates these. |
4619 | |
4620 | explicit RecordType(const RecordDecl *D) |
4621 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4622 | explicit RecordType(TypeClass TC, RecordDecl *D) |
4623 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4624 | |
4625 | public: |
4626 | RecordDecl *getDecl() const { |
4627 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
4628 | } |
4629 | |
4630 | /// Recursively check all fields in the record for const-ness. If any field |
4631 | /// is declared const, return true. Otherwise, return false. |
4632 | bool hasConstFields() const; |
4633 | |
4634 | bool isSugared() const { return false; } |
4635 | QualType desugar() const { return QualType(this, 0); } |
4636 | |
4637 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4638 | }; |
4639 | |
4640 | /// A helper class that allows the use of isa/cast/dyncast |
4641 | /// to detect TagType objects of enums. |
4642 | class EnumType : public TagType { |
4643 | friend class ASTContext; // ASTContext creates these. |
4644 | |
4645 | explicit EnumType(const EnumDecl *D) |
4646 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4647 | |
4648 | public: |
4649 | EnumDecl *getDecl() const { |
4650 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4651 | } |
4652 | |
4653 | bool isSugared() const { return false; } |
4654 | QualType desugar() const { return QualType(this, 0); } |
4655 | |
4656 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4657 | }; |
4658 | |
4659 | /// An attributed type is a type to which a type attribute has been applied. |
4660 | /// |
4661 | /// The "modified type" is the fully-sugared type to which the attributed |
4662 | /// type was applied; generally it is not canonically equivalent to the |
4663 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4664 | /// which the type is canonically equivalent to. |
4665 | /// |
4666 | /// For example, in the following attributed type: |
4667 | /// int32_t __attribute__((vector_size(16))) |
4668 | /// - the modified type is the TypedefType for int32_t |
4669 | /// - the equivalent type is VectorType(16, int32_t) |
4670 | /// - the canonical type is VectorType(16, int) |
4671 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4672 | public: |
4673 | using Kind = attr::Kind; |
4674 | |
4675 | private: |
4676 | friend class ASTContext; // ASTContext creates these |
4677 | |
4678 | QualType ModifiedType; |
4679 | QualType EquivalentType; |
4680 | |
4681 | AttributedType(QualType canon, attr::Kind attrKind, QualType modified, |
4682 | QualType equivalent) |
4683 | : Type(Attributed, canon, equivalent->getDependence()), |
4684 | ModifiedType(modified), EquivalentType(equivalent) { |
4685 | AttributedTypeBits.AttrKind = attrKind; |
4686 | } |
4687 | |
4688 | public: |
4689 | Kind getAttrKind() const { |
4690 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4691 | } |
4692 | |
4693 | QualType getModifiedType() const { return ModifiedType; } |
4694 | QualType getEquivalentType() const { return EquivalentType; } |
4695 | |
4696 | bool isSugared() const { return true; } |
4697 | QualType desugar() const { return getEquivalentType(); } |
4698 | |
4699 | /// Does this attribute behave like a type qualifier? |
4700 | /// |
4701 | /// A type qualifier adjusts a type to provide specialized rules for |
4702 | /// a specific object, like the standard const and volatile qualifiers. |
4703 | /// This includes attributes controlling things like nullability, |
4704 | /// address spaces, and ARC ownership. The value of the object is still |
4705 | /// largely described by the modified type. |
4706 | /// |
4707 | /// In contrast, many type attributes "rewrite" their modified type to |
4708 | /// produce a fundamentally different type, not necessarily related in any |
4709 | /// formalizable way to the original type. For example, calling convention |
4710 | /// and vector attributes are not simple type qualifiers. |
4711 | /// |
4712 | /// Type qualifiers are often, but not always, reflected in the canonical |
4713 | /// type. |
4714 | bool isQualifier() const; |
4715 | |
4716 | bool isMSTypeSpec() const; |
4717 | |
4718 | bool isCallingConv() const; |
4719 | |
4720 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4721 | |
4722 | /// Retrieve the attribute kind corresponding to the given |
4723 | /// nullability kind. |
4724 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4725 | switch (kind) { |
4726 | case NullabilityKind::NonNull: |
4727 | return attr::TypeNonNull; |
4728 | |
4729 | case NullabilityKind::Nullable: |
4730 | return attr::TypeNullable; |
4731 | |
4732 | case NullabilityKind::NullableResult: |
4733 | return attr::TypeNullableResult; |
4734 | |
4735 | case NullabilityKind::Unspecified: |
4736 | return attr::TypeNullUnspecified; |
4737 | } |
4738 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 4738); |
4739 | } |
4740 | |
4741 | /// Strip off the top-level nullability annotation on the given |
4742 | /// type, if it's there. |
4743 | /// |
4744 | /// \param T The type to strip. If the type is exactly an |
4745 | /// AttributedType specifying nullability (without looking through |
4746 | /// type sugar), the nullability is returned and this type changed |
4747 | /// to the underlying modified type. |
4748 | /// |
4749 | /// \returns the top-level nullability, if present. |
4750 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4751 | |
4752 | void Profile(llvm::FoldingSetNodeID &ID) { |
4753 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4754 | } |
4755 | |
4756 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4757 | QualType modified, QualType equivalent) { |
4758 | ID.AddInteger(attrKind); |
4759 | ID.AddPointer(modified.getAsOpaquePtr()); |
4760 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4761 | } |
4762 | |
4763 | static bool classof(const Type *T) { |
4764 | return T->getTypeClass() == Attributed; |
4765 | } |
4766 | }; |
4767 | |
4768 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4769 | friend class ASTContext; // ASTContext creates these |
4770 | |
4771 | // Helper data collector for canonical types. |
4772 | struct CanonicalTTPTInfo { |
4773 | unsigned Depth : 15; |
4774 | unsigned ParameterPack : 1; |
4775 | unsigned Index : 16; |
4776 | }; |
4777 | |
4778 | union { |
4779 | // Info for the canonical type. |
4780 | CanonicalTTPTInfo CanTTPTInfo; |
4781 | |
4782 | // Info for the non-canonical type. |
4783 | TemplateTypeParmDecl *TTPDecl; |
4784 | }; |
4785 | |
4786 | /// Build a non-canonical type. |
4787 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4788 | : Type(TemplateTypeParm, Canon, |
4789 | TypeDependence::DependentInstantiation | |
4790 | (Canon->getDependence() & TypeDependence::UnexpandedPack)), |
4791 | TTPDecl(TTPDecl) {} |
4792 | |
4793 | /// Build the canonical type. |
4794 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4795 | : Type(TemplateTypeParm, QualType(this, 0), |
4796 | TypeDependence::DependentInstantiation | |
4797 | (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) { |
4798 | CanTTPTInfo.Depth = D; |
4799 | CanTTPTInfo.Index = I; |
4800 | CanTTPTInfo.ParameterPack = PP; |
4801 | } |
4802 | |
4803 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4804 | QualType Can = getCanonicalTypeInternal(); |
4805 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4806 | } |
4807 | |
4808 | public: |
4809 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4810 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4811 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4812 | |
4813 | TemplateTypeParmDecl *getDecl() const { |
4814 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4815 | } |
4816 | |
4817 | IdentifierInfo *getIdentifier() const; |
4818 | |
4819 | bool isSugared() const { return false; } |
4820 | QualType desugar() const { return QualType(this, 0); } |
4821 | |
4822 | void Profile(llvm::FoldingSetNodeID &ID) { |
4823 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4824 | } |
4825 | |
4826 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4827 | unsigned Index, bool ParameterPack, |
4828 | TemplateTypeParmDecl *TTPDecl) { |
4829 | ID.AddInteger(Depth); |
4830 | ID.AddInteger(Index); |
4831 | ID.AddBoolean(ParameterPack); |
4832 | ID.AddPointer(TTPDecl); |
4833 | } |
4834 | |
4835 | static bool classof(const Type *T) { |
4836 | return T->getTypeClass() == TemplateTypeParm; |
4837 | } |
4838 | }; |
4839 | |
4840 | /// Represents the result of substituting a type for a template |
4841 | /// type parameter. |
4842 | /// |
4843 | /// Within an instantiated template, all template type parameters have |
4844 | /// been replaced with these. They are used solely to record that a |
4845 | /// type was originally written as a template type parameter; |
4846 | /// therefore they are never canonical. |
4847 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4848 | friend class ASTContext; |
4849 | |
4850 | // The original type parameter. |
4851 | const TemplateTypeParmType *Replaced; |
4852 | |
4853 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4854 | : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()), |
4855 | Replaced(Param) {} |
4856 | |
4857 | public: |
4858 | /// Gets the template parameter that was substituted for. |
4859 | const TemplateTypeParmType *getReplacedParameter() const { |
4860 | return Replaced; |
4861 | } |
4862 | |
4863 | /// Gets the type that was substituted for the template |
4864 | /// parameter. |
4865 | QualType getReplacementType() const { |
4866 | return getCanonicalTypeInternal(); |
4867 | } |
4868 | |
4869 | bool isSugared() const { return true; } |
4870 | QualType desugar() const { return getReplacementType(); } |
4871 | |
4872 | void Profile(llvm::FoldingSetNodeID &ID) { |
4873 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4874 | } |
4875 | |
4876 | static void Profile(llvm::FoldingSetNodeID &ID, |
4877 | const TemplateTypeParmType *Replaced, |
4878 | QualType Replacement) { |
4879 | ID.AddPointer(Replaced); |
4880 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4881 | } |
4882 | |
4883 | static bool classof(const Type *T) { |
4884 | return T->getTypeClass() == SubstTemplateTypeParm; |
4885 | } |
4886 | }; |
4887 | |
4888 | /// Represents the result of substituting a set of types for a template |
4889 | /// type parameter pack. |
4890 | /// |
4891 | /// When a pack expansion in the source code contains multiple parameter packs |
4892 | /// and those parameter packs correspond to different levels of template |
4893 | /// parameter lists, this type node is used to represent a template type |
4894 | /// parameter pack from an outer level, which has already had its argument pack |
4895 | /// substituted but that still lives within a pack expansion that itself |
4896 | /// could not be instantiated. When actually performing a substitution into |
4897 | /// that pack expansion (e.g., when all template parameters have corresponding |
4898 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4899 | /// at the current pack substitution index. |
4900 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4901 | friend class ASTContext; |
4902 | |
4903 | /// The original type parameter. |
4904 | const TemplateTypeParmType *Replaced; |
4905 | |
4906 | /// A pointer to the set of template arguments that this |
4907 | /// parameter pack is instantiated with. |
4908 | const TemplateArgument *Arguments; |
4909 | |
4910 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4911 | QualType Canon, |
4912 | const TemplateArgument &ArgPack); |
4913 | |
4914 | public: |
4915 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4916 | |
4917 | /// Gets the template parameter that was substituted for. |
4918 | const TemplateTypeParmType *getReplacedParameter() const { |
4919 | return Replaced; |
4920 | } |
4921 | |
4922 | unsigned getNumArgs() const { |
4923 | return SubstTemplateTypeParmPackTypeBits.NumArgs; |
4924 | } |
4925 | |
4926 | bool isSugared() const { return false; } |
4927 | QualType desugar() const { return QualType(this, 0); } |
4928 | |
4929 | TemplateArgument getArgumentPack() const; |
4930 | |
4931 | void Profile(llvm::FoldingSetNodeID &ID); |
4932 | static void Profile(llvm::FoldingSetNodeID &ID, |
4933 | const TemplateTypeParmType *Replaced, |
4934 | const TemplateArgument &ArgPack); |
4935 | |
4936 | static bool classof(const Type *T) { |
4937 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4938 | } |
4939 | }; |
4940 | |
4941 | /// Common base class for placeholders for types that get replaced by |
4942 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4943 | /// class template types, and constrained type names. |
4944 | /// |
4945 | /// These types are usually a placeholder for a deduced type. However, before |
4946 | /// the initializer is attached, or (usually) if the initializer is |
4947 | /// type-dependent, there is no deduced type and the type is canonical. In |
4948 | /// the latter case, it is also a dependent type. |
4949 | class DeducedType : public Type { |
4950 | protected: |
4951 | DeducedType(TypeClass TC, QualType DeducedAsType, |
4952 | TypeDependence ExtraDependence) |
4953 | : Type(TC, |
4954 | // FIXME: Retain the sugared deduced type? |
4955 | DeducedAsType.isNull() ? QualType(this, 0) |
4956 | : DeducedAsType.getCanonicalType(), |
4957 | ExtraDependence | (DeducedAsType.isNull() |
4958 | ? TypeDependence::None |
4959 | : DeducedAsType->getDependence() & |
4960 | ~TypeDependence::VariablyModified)) {} |
4961 | |
4962 | public: |
4963 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4964 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4965 | |
4966 | /// Get the type deduced for this placeholder type, or null if it's |
4967 | /// either not been deduced or was deduced to a dependent type. |
4968 | QualType getDeducedType() const { |
4969 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4970 | } |
4971 | bool isDeduced() const { |
4972 | return !isCanonicalUnqualified() || isDependentType(); |
4973 | } |
4974 | |
4975 | static bool classof(const Type *T) { |
4976 | return T->getTypeClass() == Auto || |
4977 | T->getTypeClass() == DeducedTemplateSpecialization; |
4978 | } |
4979 | }; |
4980 | |
4981 | /// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained |
4982 | /// by a type-constraint. |
4983 | class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode { |
4984 | friend class ASTContext; // ASTContext creates these |
4985 | |
4986 | ConceptDecl *TypeConstraintConcept; |
4987 | |
4988 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4989 | TypeDependence ExtraDependence, ConceptDecl *CD, |
4990 | ArrayRef<TemplateArgument> TypeConstraintArgs); |
4991 | |
4992 | const TemplateArgument *getArgBuffer() const { |
4993 | return reinterpret_cast<const TemplateArgument*>(this+1); |
4994 | } |
4995 | |
4996 | TemplateArgument *getArgBuffer() { |
4997 | return reinterpret_cast<TemplateArgument*>(this+1); |
4998 | } |
4999 | |
5000 | public: |
5001 | /// Retrieve the template arguments. |
5002 | const TemplateArgument *getArgs() const { |
5003 | return getArgBuffer(); |
5004 | } |
5005 | |
5006 | /// Retrieve the number of template arguments. |
5007 | unsigned getNumArgs() const { |
5008 | return AutoTypeBits.NumArgs; |
5009 | } |
5010 | |
5011 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5012 | |
5013 | ArrayRef<TemplateArgument> getTypeConstraintArguments() const { |
5014 | return {getArgs(), getNumArgs()}; |
5015 | } |
5016 | |
5017 | ConceptDecl *getTypeConstraintConcept() const { |
5018 | return TypeConstraintConcept; |
5019 | } |
5020 | |
5021 | bool isConstrained() const { |
5022 | return TypeConstraintConcept != nullptr; |
5023 | } |
5024 | |
5025 | bool isDecltypeAuto() const { |
5026 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
5027 | } |
5028 | |
5029 | AutoTypeKeyword getKeyword() const { |
5030 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
5031 | } |
5032 | |
5033 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5034 | Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(), |
5035 | getTypeConstraintConcept(), getTypeConstraintArguments()); |
5036 | } |
5037 | |
5038 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
5039 | QualType Deduced, AutoTypeKeyword Keyword, |
5040 | bool IsDependent, ConceptDecl *CD, |
5041 | ArrayRef<TemplateArgument> Arguments); |
5042 | |
5043 | static bool classof(const Type *T) { |
5044 | return T->getTypeClass() == Auto; |
5045 | } |
5046 | }; |
5047 | |
5048 | /// Represents a C++17 deduced template specialization type. |
5049 | class DeducedTemplateSpecializationType : public DeducedType, |
5050 | public llvm::FoldingSetNode { |
5051 | friend class ASTContext; // ASTContext creates these |
5052 | |
5053 | /// The name of the template whose arguments will be deduced. |
5054 | TemplateName Template; |
5055 | |
5056 | DeducedTemplateSpecializationType(TemplateName Template, |
5057 | QualType DeducedAsType, |
5058 | bool IsDeducedAsDependent) |
5059 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
5060 | toTypeDependence(Template.getDependence()) | |
5061 | (IsDeducedAsDependent |
5062 | ? TypeDependence::DependentInstantiation |
5063 | : TypeDependence::None)), |
5064 | Template(Template) {} |
5065 | |
5066 | public: |
5067 | /// Retrieve the name of the template that we are deducing. |
5068 | TemplateName getTemplateName() const { return Template;} |
5069 | |
5070 | void Profile(llvm::FoldingSetNodeID &ID) { |
5071 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
5072 | } |
5073 | |
5074 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
5075 | QualType Deduced, bool IsDependent) { |
5076 | Template.Profile(ID); |
5077 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
5078 | ID.AddBoolean(IsDependent); |
5079 | } |
5080 | |
5081 | static bool classof(const Type *T) { |
5082 | return T->getTypeClass() == DeducedTemplateSpecialization; |
5083 | } |
5084 | }; |
5085 | |
5086 | /// Represents a type template specialization; the template |
5087 | /// must be a class template, a type alias template, or a template |
5088 | /// template parameter. A template which cannot be resolved to one of |
5089 | /// these, e.g. because it is written with a dependent scope |
5090 | /// specifier, is instead represented as a |
5091 | /// @c DependentTemplateSpecializationType. |
5092 | /// |
5093 | /// A non-dependent template specialization type is always "sugar", |
5094 | /// typically for a \c RecordType. For example, a class template |
5095 | /// specialization type of \c vector<int> will refer to a tag type for |
5096 | /// the instantiation \c std::vector<int, std::allocator<int>> |
5097 | /// |
5098 | /// Template specializations are dependent if either the template or |
5099 | /// any of the template arguments are dependent, in which case the |
5100 | /// type may also be canonical. |
5101 | /// |
5102 | /// Instances of this type are allocated with a trailing array of |
5103 | /// TemplateArguments, followed by a QualType representing the |
5104 | /// non-canonical aliased type when the template is a type alias |
5105 | /// template. |
5106 | class alignas(8) TemplateSpecializationType |
5107 | : public Type, |
5108 | public llvm::FoldingSetNode { |
5109 | friend class ASTContext; // ASTContext creates these |
5110 | |
5111 | /// The name of the template being specialized. This is |
5112 | /// either a TemplateName::Template (in which case it is a |
5113 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
5114 | /// TypeAliasTemplateDecl*), a |
5115 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
5116 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
5117 | /// replacement must, recursively, be one of these). |
5118 | TemplateName Template; |
5119 | |
5120 | TemplateSpecializationType(TemplateName T, |
5121 | ArrayRef<TemplateArgument> Args, |
5122 | QualType Canon, |
5123 | QualType Aliased); |
5124 | |
5125 | public: |
5126 | /// Determine whether any of the given template arguments are dependent. |
5127 | /// |
5128 | /// The converted arguments should be supplied when known; whether an |
5129 | /// argument is dependent can depend on the conversions performed on it |
5130 | /// (for example, a 'const int' passed as a template argument might be |
5131 | /// dependent if the parameter is a reference but non-dependent if the |
5132 | /// parameter is an int). |
5133 | /// |
5134 | /// Note that the \p Args parameter is unused: this is intentional, to remind |
5135 | /// the caller that they need to pass in the converted arguments, not the |
5136 | /// specified arguments. |
5137 | static bool |
5138 | anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
5139 | ArrayRef<TemplateArgument> Converted); |
5140 | static bool |
5141 | anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
5142 | ArrayRef<TemplateArgument> Converted); |
5143 | static bool anyInstantiationDependentTemplateArguments( |
5144 | ArrayRef<TemplateArgumentLoc> Args); |
5145 | |
5146 | /// True if this template specialization type matches a current |
5147 | /// instantiation in the context in which it is found. |
5148 | bool isCurrentInstantiation() const { |
5149 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
5150 | } |
5151 | |
5152 | /// Determine if this template specialization type is for a type alias |
5153 | /// template that has been substituted. |
5154 | /// |
5155 | /// Nearly every template specialization type whose template is an alias |
5156 | /// template will be substituted. However, this is not the case when |
5157 | /// the specialization contains a pack expansion but the template alias |
5158 | /// does not have a corresponding parameter pack, e.g., |
5159 | /// |
5160 | /// \code |
5161 | /// template<typename T, typename U, typename V> struct S; |
5162 | /// template<typename T, typename U> using A = S<T, int, U>; |
5163 | /// template<typename... Ts> struct X { |
5164 | /// typedef A<Ts...> type; // not a type alias |
5165 | /// }; |
5166 | /// \endcode |
5167 | bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } |
5168 | |
5169 | /// Get the aliased type, if this is a specialization of a type alias |
5170 | /// template. |
5171 | QualType getAliasedType() const { |
5172 | assert(isTypeAlias() && "not a type alias template specialization")(static_cast <bool> (isTypeAlias() && "not a type alias template specialization" ) ? void (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5172, __extension__ __PRETTY_FUNCTION__)); |
5173 | return *reinterpret_cast<const QualType*>(end()); |
5174 | } |
5175 | |
5176 | using iterator = const TemplateArgument *; |
5177 | |
5178 | iterator begin() const { return getArgs(); } |
5179 | iterator end() const; // defined inline in TemplateBase.h |
5180 | |
5181 | /// Retrieve the name of the template that we are specializing. |
5182 | TemplateName getTemplateName() const { return Template; } |
5183 | |
5184 | /// Retrieve the template arguments. |
5185 | const TemplateArgument *getArgs() const { |
5186 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
5187 | } |
5188 | |
5189 | /// Retrieve the number of template arguments. |
5190 | unsigned getNumArgs() const { |
5191 | return TemplateSpecializationTypeBits.NumArgs; |
5192 | } |
5193 | |
5194 | /// Retrieve a specific template argument as a type. |
5195 | /// \pre \c isArgType(Arg) |
5196 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5197 | |
5198 | ArrayRef<TemplateArgument> template_arguments() const { |
5199 | return {getArgs(), getNumArgs()}; |
5200 | } |
5201 | |
5202 | bool isSugared() const { |
5203 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
5204 | } |
5205 | |
5206 | QualType desugar() const { |
5207 | return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); |
5208 | } |
5209 | |
5210 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
5211 | Profile(ID, Template, template_arguments(), Ctx); |
5212 | if (isTypeAlias()) |
5213 | getAliasedType().Profile(ID); |
5214 | } |
5215 | |
5216 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
5217 | ArrayRef<TemplateArgument> Args, |
5218 | const ASTContext &Context); |
5219 | |
5220 | static bool classof(const Type *T) { |
5221 | return T->getTypeClass() == TemplateSpecialization; |
5222 | } |
5223 | }; |
5224 | |
5225 | /// Print a template argument list, including the '<' and '>' |
5226 | /// enclosing the template arguments. |
5227 | void printTemplateArgumentList(raw_ostream &OS, |
5228 | ArrayRef<TemplateArgument> Args, |
5229 | const PrintingPolicy &Policy, |
5230 | const TemplateParameterList *TPL = nullptr); |
5231 | |
5232 | void printTemplateArgumentList(raw_ostream &OS, |
5233 | ArrayRef<TemplateArgumentLoc> Args, |
5234 | const PrintingPolicy &Policy, |
5235 | const TemplateParameterList *TPL = nullptr); |
5236 | |
5237 | void printTemplateArgumentList(raw_ostream &OS, |
5238 | const TemplateArgumentListInfo &Args, |
5239 | const PrintingPolicy &Policy, |
5240 | const TemplateParameterList *TPL = nullptr); |
5241 | |
5242 | /// The injected class name of a C++ class template or class |
5243 | /// template partial specialization. Used to record that a type was |
5244 | /// spelled with a bare identifier rather than as a template-id; the |
5245 | /// equivalent for non-templated classes is just RecordType. |
5246 | /// |
5247 | /// Injected class name types are always dependent. Template |
5248 | /// instantiation turns these into RecordTypes. |
5249 | /// |
5250 | /// Injected class name types are always canonical. This works |
5251 | /// because it is impossible to compare an injected class name type |
5252 | /// with the corresponding non-injected template type, for the same |
5253 | /// reason that it is impossible to directly compare template |
5254 | /// parameters from different dependent contexts: injected class name |
5255 | /// types can only occur within the scope of a particular templated |
5256 | /// declaration, and within that scope every template specialization |
5257 | /// will canonicalize to the injected class name (when appropriate |
5258 | /// according to the rules of the language). |
5259 | class InjectedClassNameType : public Type { |
5260 | friend class ASTContext; // ASTContext creates these. |
5261 | friend class ASTNodeImporter; |
5262 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
5263 | // currently suitable for AST reading, too much |
5264 | // interdependencies. |
5265 | template <class T> friend class serialization::AbstractTypeReader; |
5266 | |
5267 | CXXRecordDecl *Decl; |
5268 | |
5269 | /// The template specialization which this type represents. |
5270 | /// For example, in |
5271 | /// template <class T> class A { ... }; |
5272 | /// this is A<T>, whereas in |
5273 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
5274 | /// this is A<B<X,Y> >. |
5275 | /// |
5276 | /// It is always unqualified, always a template specialization type, |
5277 | /// and always dependent. |
5278 | QualType InjectedType; |
5279 | |
5280 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
5281 | : Type(InjectedClassName, QualType(), |
5282 | TypeDependence::DependentInstantiation), |
5283 | Decl(D), InjectedType(TST) { |
5284 | assert(isa<TemplateSpecializationType>(TST))(static_cast <bool> (isa<TemplateSpecializationType> (TST)) ? void (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5284, __extension__ __PRETTY_FUNCTION__)); |
5285 | assert(!TST.hasQualifiers())(static_cast <bool> (!TST.hasQualifiers()) ? void (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5285, __extension__ __PRETTY_FUNCTION__)); |
5286 | assert(TST->isDependentType())(static_cast <bool> (TST->isDependentType()) ? void ( 0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5286, __extension__ __PRETTY_FUNCTION__)); |
5287 | } |
5288 | |
5289 | public: |
5290 | QualType getInjectedSpecializationType() const { return InjectedType; } |
5291 | |
5292 | const TemplateSpecializationType *getInjectedTST() const { |
5293 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
5294 | } |
5295 | |
5296 | TemplateName getTemplateName() const { |
5297 | return getInjectedTST()->getTemplateName(); |
5298 | } |
5299 | |
5300 | CXXRecordDecl *getDecl() const; |
5301 | |
5302 | bool isSugared() const { return false; } |
5303 | QualType desugar() const { return QualType(this, 0); } |
5304 | |
5305 | static bool classof(const Type *T) { |
5306 | return T->getTypeClass() == InjectedClassName; |
5307 | } |
5308 | }; |
5309 | |
5310 | /// The kind of a tag type. |
5311 | enum TagTypeKind { |
5312 | /// The "struct" keyword. |
5313 | TTK_Struct, |
5314 | |
5315 | /// The "__interface" keyword. |
5316 | TTK_Interface, |
5317 | |
5318 | /// The "union" keyword. |
5319 | TTK_Union, |
5320 | |
5321 | /// The "class" keyword. |
5322 | TTK_Class, |
5323 | |
5324 | /// The "enum" keyword. |
5325 | TTK_Enum |
5326 | }; |
5327 | |
5328 | /// The elaboration keyword that precedes a qualified type name or |
5329 | /// introduces an elaborated-type-specifier. |
5330 | enum ElaboratedTypeKeyword { |
5331 | /// The "struct" keyword introduces the elaborated-type-specifier. |
5332 | ETK_Struct, |
5333 | |
5334 | /// The "__interface" keyword introduces the elaborated-type-specifier. |
5335 | ETK_Interface, |
5336 | |
5337 | /// The "union" keyword introduces the elaborated-type-specifier. |
5338 | ETK_Union, |
5339 | |
5340 | /// The "class" keyword introduces the elaborated-type-specifier. |
5341 | ETK_Class, |
5342 | |
5343 | /// The "enum" keyword introduces the elaborated-type-specifier. |
5344 | ETK_Enum, |
5345 | |
5346 | /// The "typename" keyword precedes the qualified type name, e.g., |
5347 | /// \c typename T::type. |
5348 | ETK_Typename, |
5349 | |
5350 | /// No keyword precedes the qualified type name. |
5351 | ETK_None |
5352 | }; |
5353 | |
5354 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
5355 | /// The keyword in stored in the free bits of the base class. |
5356 | /// Also provides a few static helpers for converting and printing |
5357 | /// elaborated type keyword and tag type kind enumerations. |
5358 | class TypeWithKeyword : public Type { |
5359 | protected: |
5360 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
5361 | QualType Canonical, TypeDependence Dependence) |
5362 | : Type(tc, Canonical, Dependence) { |
5363 | TypeWithKeywordBits.Keyword = Keyword; |
5364 | } |
5365 | |
5366 | public: |
5367 | ElaboratedTypeKeyword getKeyword() const { |
5368 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
5369 | } |
5370 | |
5371 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
5372 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
5373 | |
5374 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
5375 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
5376 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
5377 | |
5378 | /// Converts a TagTypeKind into an elaborated type keyword. |
5379 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
5380 | |
5381 | /// Converts an elaborated type keyword into a TagTypeKind. |
5382 | /// It is an error to provide an elaborated type keyword |
5383 | /// which *isn't* a tag kind here. |
5384 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
5385 | |
5386 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
5387 | |
5388 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
5389 | |
5390 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
5391 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
5392 | } |
5393 | |
5394 | class CannotCastToThisType {}; |
5395 | static CannotCastToThisType classof(const Type *); |
5396 | }; |
5397 | |
5398 | /// Represents a type that was referred to using an elaborated type |
5399 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
5400 | /// or both. |
5401 | /// |
5402 | /// This type is used to keep track of a type name as written in the |
5403 | /// source code, including tag keywords and any nested-name-specifiers. |
5404 | /// The type itself is always "sugar", used to express what was written |
5405 | /// in the source code but containing no additional semantic information. |
5406 | class ElaboratedType final |
5407 | : public TypeWithKeyword, |
5408 | public llvm::FoldingSetNode, |
5409 | private llvm::TrailingObjects<ElaboratedType, TagDecl *> { |
5410 | friend class ASTContext; // ASTContext creates these |
5411 | friend TrailingObjects; |
5412 | |
5413 | /// The nested name specifier containing the qualifier. |
5414 | NestedNameSpecifier *NNS; |
5415 | |
5416 | /// The type that this qualified name refers to. |
5417 | QualType NamedType; |
5418 | |
5419 | /// The (re)declaration of this tag type owned by this occurrence is stored |
5420 | /// as a trailing object if there is one. Use getOwnedTagDecl to obtain |
5421 | /// it, or obtain a null pointer if there is none. |
5422 | |
5423 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5424 | QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) |
5425 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
5426 | // Any semantic dependence on the qualifier will have |
5427 | // been incorporated into NamedType. We still need to |
5428 | // track syntactic (instantiation / error / pack) |
5429 | // dependence on the qualifier. |
5430 | NamedType->getDependence() | |
5431 | (NNS ? toSyntacticDependence( |
5432 | toTypeDependence(NNS->getDependence())) |
5433 | : TypeDependence::None)), |
5434 | NNS(NNS), NamedType(NamedType) { |
5435 | ElaboratedTypeBits.HasOwnedTagDecl = false; |
5436 | if (OwnedTagDecl) { |
5437 | ElaboratedTypeBits.HasOwnedTagDecl = true; |
5438 | *getTrailingObjects<TagDecl *>() = OwnedTagDecl; |
5439 | } |
5440 | assert(!(Keyword == ETK_None && NNS == nullptr) &&(static_cast <bool> (!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null.") ? void (0) : __assert_fail ( "!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5442, __extension__ __PRETTY_FUNCTION__)) |
5441 | "ElaboratedType cannot have elaborated type keyword "(static_cast <bool> (!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null.") ? void (0) : __assert_fail ( "!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5442, __extension__ __PRETTY_FUNCTION__)) |
5442 | "and name qualifier both null.")(static_cast <bool> (!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null.") ? void (0) : __assert_fail ( "!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5442, __extension__ __PRETTY_FUNCTION__)); |
5443 | } |
5444 | |
5445 | public: |
5446 | /// Retrieve the qualification on this type. |
5447 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5448 | |
5449 | /// Retrieve the type named by the qualified-id. |
5450 | QualType getNamedType() const { return NamedType; } |
5451 | |
5452 | /// Remove a single level of sugar. |
5453 | QualType desugar() const { return getNamedType(); } |
5454 | |
5455 | /// Returns whether this type directly provides sugar. |
5456 | bool isSugared() const { return true; } |
5457 | |
5458 | /// Return the (re)declaration of this type owned by this occurrence of this |
5459 | /// type, or nullptr if there is none. |
5460 | TagDecl *getOwnedTagDecl() const { |
5461 | return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() |
5462 | : nullptr; |
5463 | } |
5464 | |
5465 | void Profile(llvm::FoldingSetNodeID &ID) { |
5466 | Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); |
5467 | } |
5468 | |
5469 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5470 | NestedNameSpecifier *NNS, QualType NamedType, |
5471 | TagDecl *OwnedTagDecl) { |
5472 | ID.AddInteger(Keyword); |
5473 | ID.AddPointer(NNS); |
5474 | NamedType.Profile(ID); |
5475 | ID.AddPointer(OwnedTagDecl); |
5476 | } |
5477 | |
5478 | static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } |
5479 | }; |
5480 | |
5481 | /// Represents a qualified type name for which the type name is |
5482 | /// dependent. |
5483 | /// |
5484 | /// DependentNameType represents a class of dependent types that involve a |
5485 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
5486 | /// name of a type. The DependentNameType may start with a "typename" (for a |
5487 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
5488 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
5489 | /// know that we must be referring to a type, e.g., in a base class specifier). |
5490 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
5491 | /// mode, this type is used with non-dependent names to delay name lookup until |
5492 | /// instantiation. |
5493 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
5494 | friend class ASTContext; // ASTContext creates these |
5495 | |
5496 | /// The nested name specifier containing the qualifier. |
5497 | NestedNameSpecifier *NNS; |
5498 | |
5499 | /// The type that this typename specifier refers to. |
5500 | const IdentifierInfo *Name; |
5501 | |
5502 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5503 | const IdentifierInfo *Name, QualType CanonType) |
5504 | : TypeWithKeyword(Keyword, DependentName, CanonType, |
5505 | TypeDependence::DependentInstantiation | |
5506 | toTypeDependence(NNS->getDependence())), |
5507 | NNS(NNS), Name(Name) {} |
5508 | |
5509 | public: |
5510 | /// Retrieve the qualification on this type. |
5511 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5512 | |
5513 | /// Retrieve the type named by the typename specifier as an identifier. |
5514 | /// |
5515 | /// This routine will return a non-NULL identifier pointer when the |
5516 | /// form of the original typename was terminated by an identifier, |
5517 | /// e.g., "typename T::type". |
5518 | const IdentifierInfo *getIdentifier() const { |
5519 | return Name; |
5520 | } |
5521 | |
5522 | bool isSugared() const { return false; } |
5523 | QualType desugar() const { return QualType(this, 0); } |
5524 | |
5525 | void Profile(llvm::FoldingSetNodeID &ID) { |
5526 | Profile(ID, getKeyword(), NNS, Name); |
5527 | } |
5528 | |
5529 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5530 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
5531 | ID.AddInteger(Keyword); |
5532 | ID.AddPointer(NNS); |
5533 | ID.AddPointer(Name); |
5534 | } |
5535 | |
5536 | static bool classof(const Type *T) { |
5537 | return T->getTypeClass() == DependentName; |
5538 | } |
5539 | }; |
5540 | |
5541 | /// Represents a template specialization type whose template cannot be |
5542 | /// resolved, e.g. |
5543 | /// A<T>::template B<T> |
5544 | class alignas(8) DependentTemplateSpecializationType |
5545 | : public TypeWithKeyword, |
5546 | public llvm::FoldingSetNode { |
5547 | friend class ASTContext; // ASTContext creates these |
5548 | |
5549 | /// The nested name specifier containing the qualifier. |
5550 | NestedNameSpecifier *NNS; |
5551 | |
5552 | /// The identifier of the template. |
5553 | const IdentifierInfo *Name; |
5554 | |
5555 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
5556 | NestedNameSpecifier *NNS, |
5557 | const IdentifierInfo *Name, |
5558 | ArrayRef<TemplateArgument> Args, |
5559 | QualType Canon); |
5560 | |
5561 | const TemplateArgument *getArgBuffer() const { |
5562 | return reinterpret_cast<const TemplateArgument*>(this+1); |
5563 | } |
5564 | |
5565 | TemplateArgument *getArgBuffer() { |
5566 | return reinterpret_cast<TemplateArgument*>(this+1); |
5567 | } |
5568 | |
5569 | public: |
5570 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5571 | const IdentifierInfo *getIdentifier() const { return Name; } |
5572 | |
5573 | /// Retrieve the template arguments. |
5574 | const TemplateArgument *getArgs() const { |
5575 | return getArgBuffer(); |
5576 | } |
5577 | |
5578 | /// Retrieve the number of template arguments. |
5579 | unsigned getNumArgs() const { |
5580 | return DependentTemplateSpecializationTypeBits.NumArgs; |
5581 | } |
5582 | |
5583 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5584 | |
5585 | ArrayRef<TemplateArgument> template_arguments() const { |
5586 | return {getArgs(), getNumArgs()}; |
5587 | } |
5588 | |
5589 | using iterator = const TemplateArgument *; |
5590 | |
5591 | iterator begin() const { return getArgs(); } |
5592 | iterator end() const; // inline in TemplateBase.h |
5593 | |
5594 | bool isSugared() const { return false; } |
5595 | QualType desugar() const { return QualType(this, 0); } |
5596 | |
5597 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5598 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); |
5599 | } |
5600 | |
5601 | static void Profile(llvm::FoldingSetNodeID &ID, |
5602 | const ASTContext &Context, |
5603 | ElaboratedTypeKeyword Keyword, |
5604 | NestedNameSpecifier *Qualifier, |
5605 | const IdentifierInfo *Name, |
5606 | ArrayRef<TemplateArgument> Args); |
5607 | |
5608 | static bool classof(const Type *T) { |
5609 | return T->getTypeClass() == DependentTemplateSpecialization; |
5610 | } |
5611 | }; |
5612 | |
5613 | /// Represents a pack expansion of types. |
5614 | /// |
5615 | /// Pack expansions are part of C++11 variadic templates. A pack |
5616 | /// expansion contains a pattern, which itself contains one or more |
5617 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
5618 | /// produces a series of types, each instantiated from the pattern of |
5619 | /// the expansion, where the Ith instantiation of the pattern uses the |
5620 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
5621 | /// pack expansion is considered to "expand" these unexpanded |
5622 | /// parameter packs. |
5623 | /// |
5624 | /// \code |
5625 | /// template<typename ...Types> struct tuple; |
5626 | /// |
5627 | /// template<typename ...Types> |
5628 | /// struct tuple_of_references { |
5629 | /// typedef tuple<Types&...> type; |
5630 | /// }; |
5631 | /// \endcode |
5632 | /// |
5633 | /// Here, the pack expansion \c Types&... is represented via a |
5634 | /// PackExpansionType whose pattern is Types&. |
5635 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5636 | friend class ASTContext; // ASTContext creates these |
5637 | |
5638 | /// The pattern of the pack expansion. |
5639 | QualType Pattern; |
5640 | |
5641 | PackExpansionType(QualType Pattern, QualType Canon, |
5642 | Optional<unsigned> NumExpansions) |
5643 | : Type(PackExpansion, Canon, |
5644 | (Pattern->getDependence() | TypeDependence::Dependent | |
5645 | TypeDependence::Instantiation) & |
5646 | ~TypeDependence::UnexpandedPack), |
5647 | Pattern(Pattern) { |
5648 | PackExpansionTypeBits.NumExpansions = |
5649 | NumExpansions ? *NumExpansions + 1 : 0; |
5650 | } |
5651 | |
5652 | public: |
5653 | /// Retrieve the pattern of this pack expansion, which is the |
5654 | /// type that will be repeatedly instantiated when instantiating the |
5655 | /// pack expansion itself. |
5656 | QualType getPattern() const { return Pattern; } |
5657 | |
5658 | /// Retrieve the number of expansions that this pack expansion will |
5659 | /// generate, if known. |
5660 | Optional<unsigned> getNumExpansions() const { |
5661 | if (PackExpansionTypeBits.NumExpansions) |
5662 | return PackExpansionTypeBits.NumExpansions - 1; |
5663 | return None; |
5664 | } |
5665 | |
5666 | bool isSugared() const { return false; } |
5667 | QualType desugar() const { return QualType(this, 0); } |
5668 | |
5669 | void Profile(llvm::FoldingSetNodeID &ID) { |
5670 | Profile(ID, getPattern(), getNumExpansions()); |
5671 | } |
5672 | |
5673 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5674 | Optional<unsigned> NumExpansions) { |
5675 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5676 | ID.AddBoolean(NumExpansions.hasValue()); |
5677 | if (NumExpansions) |
5678 | ID.AddInteger(*NumExpansions); |
5679 | } |
5680 | |
5681 | static bool classof(const Type *T) { |
5682 | return T->getTypeClass() == PackExpansion; |
5683 | } |
5684 | }; |
5685 | |
5686 | /// This class wraps the list of protocol qualifiers. For types that can |
5687 | /// take ObjC protocol qualifers, they can subclass this class. |
5688 | template <class T> |
5689 | class ObjCProtocolQualifiers { |
5690 | protected: |
5691 | ObjCProtocolQualifiers() = default; |
5692 | |
5693 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5694 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5695 | } |
5696 | |
5697 | ObjCProtocolDecl **getProtocolStorage() { |
5698 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5699 | } |
5700 | |
5701 | void setNumProtocols(unsigned N) { |
5702 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5703 | } |
5704 | |
5705 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5706 | setNumProtocols(protocols.size()); |
5707 | assert(getNumProtocols() == protocols.size() &&(static_cast <bool> (getNumProtocols() == protocols.size () && "bitfield overflow in protocol count") ? void ( 0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5708, __extension__ __PRETTY_FUNCTION__)) |
5708 | "bitfield overflow in protocol count")(static_cast <bool> (getNumProtocols() == protocols.size () && "bitfield overflow in protocol count") ? void ( 0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5708, __extension__ __PRETTY_FUNCTION__)); |
5709 | if (!protocols.empty()) |
5710 | memcpy(getProtocolStorage(), protocols.data(), |
5711 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5712 | } |
5713 | |
5714 | public: |
5715 | using qual_iterator = ObjCProtocolDecl * const *; |
5716 | using qual_range = llvm::iterator_range<qual_iterator>; |
5717 | |
5718 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5719 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5720 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5721 | |
5722 | bool qual_empty() const { return getNumProtocols() == 0; } |
5723 | |
5724 | /// Return the number of qualifying protocols in this type, or 0 if |
5725 | /// there are none. |
5726 | unsigned getNumProtocols() const { |
5727 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5728 | } |
5729 | |
5730 | /// Fetch a protocol by index. |
5731 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5732 | assert(I < getNumProtocols() && "Out-of-range protocol access")(static_cast <bool> (I < getNumProtocols() && "Out-of-range protocol access") ? void (0) : __assert_fail ( "I < getNumProtocols() && \"Out-of-range protocol access\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5732, __extension__ __PRETTY_FUNCTION__)); |
5733 | return qual_begin()[I]; |
5734 | } |
5735 | |
5736 | /// Retrieve all of the protocol qualifiers. |
5737 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5738 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5739 | } |
5740 | }; |
5741 | |
5742 | /// Represents a type parameter type in Objective C. It can take |
5743 | /// a list of protocols. |
5744 | class ObjCTypeParamType : public Type, |
5745 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5746 | public llvm::FoldingSetNode { |
5747 | friend class ASTContext; |
5748 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5749 | |
5750 | /// The number of protocols stored on this type. |
5751 | unsigned NumProtocols : 6; |
5752 | |
5753 | ObjCTypeParamDecl *OTPDecl; |
5754 | |
5755 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5756 | /// canonical type, the list of protocols are sorted alphabetically |
5757 | /// and uniqued. |
5758 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5759 | |
5760 | /// Return the number of qualifying protocols in this interface type, |
5761 | /// or 0 if there are none. |
5762 | unsigned getNumProtocolsImpl() const { |
5763 | return NumProtocols; |
5764 | } |
5765 | |
5766 | void setNumProtocolsImpl(unsigned N) { |
5767 | NumProtocols = N; |
5768 | } |
5769 | |
5770 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5771 | QualType can, |
5772 | ArrayRef<ObjCProtocolDecl *> protocols); |
5773 | |
5774 | public: |
5775 | bool isSugared() const { return true; } |
5776 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5777 | |
5778 | static bool classof(const Type *T) { |
5779 | return T->getTypeClass() == ObjCTypeParam; |
5780 | } |
5781 | |
5782 | void Profile(llvm::FoldingSetNodeID &ID); |
5783 | static void Profile(llvm::FoldingSetNodeID &ID, |
5784 | const ObjCTypeParamDecl *OTPDecl, |
5785 | QualType CanonicalType, |
5786 | ArrayRef<ObjCProtocolDecl *> protocols); |
5787 | |
5788 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5789 | }; |
5790 | |
5791 | /// Represents a class type in Objective C. |
5792 | /// |
5793 | /// Every Objective C type is a combination of a base type, a set of |
5794 | /// type arguments (optional, for parameterized classes) and a list of |
5795 | /// protocols. |
5796 | /// |
5797 | /// Given the following declarations: |
5798 | /// \code |
5799 | /// \@class C<T>; |
5800 | /// \@protocol P; |
5801 | /// \endcode |
5802 | /// |
5803 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5804 | /// with base C and no protocols. |
5805 | /// |
5806 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5807 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5808 | /// protocol list. |
5809 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5810 | /// and protocol list [P]. |
5811 | /// |
5812 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5813 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5814 | /// and no protocols. |
5815 | /// |
5816 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5817 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5818 | /// this should get its own sugar class to better represent the source. |
5819 | class ObjCObjectType : public Type, |
5820 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5821 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5822 | |
5823 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5824 | // after the ObjCObjectPointerType node. |
5825 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5826 | // after the type arguments of ObjCObjectPointerType node. |
5827 | // |
5828 | // These protocols are those written directly on the type. If |
5829 | // protocol qualifiers ever become additive, the iterators will need |
5830 | // to get kindof complicated. |
5831 | // |
5832 | // In the canonical object type, these are sorted alphabetically |
5833 | // and uniqued. |
5834 | |
5835 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5836 | QualType BaseType; |
5837 | |
5838 | /// Cached superclass type. |
5839 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5840 | CachedSuperClassType; |
5841 | |
5842 | QualType *getTypeArgStorage(); |
5843 | const QualType *getTypeArgStorage() const { |
5844 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5845 | } |
5846 | |
5847 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5848 | /// Return the number of qualifying protocols in this interface type, |
5849 | /// or 0 if there are none. |
5850 | unsigned getNumProtocolsImpl() const { |
5851 | return ObjCObjectTypeBits.NumProtocols; |
5852 | } |
5853 | void setNumProtocolsImpl(unsigned N) { |
5854 | ObjCObjectTypeBits.NumProtocols = N; |
5855 | } |
5856 | |
5857 | protected: |
5858 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5859 | |
5860 | ObjCObjectType(QualType Canonical, QualType Base, |
5861 | ArrayRef<QualType> typeArgs, |
5862 | ArrayRef<ObjCProtocolDecl *> protocols, |
5863 | bool isKindOf); |
5864 | |
5865 | ObjCObjectType(enum Nonce_ObjCInterface) |
5866 | : Type(ObjCInterface, QualType(), TypeDependence::None), |
5867 | BaseType(QualType(this_(), 0)) { |
5868 | ObjCObjectTypeBits.NumProtocols = 0; |
5869 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5870 | ObjCObjectTypeBits.IsKindOf = 0; |
5871 | } |
5872 | |
5873 | void computeSuperClassTypeSlow() const; |
5874 | |
5875 | public: |
5876 | /// Gets the base type of this object type. This is always (possibly |
5877 | /// sugar for) one of: |
5878 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5879 | /// user, which is a typedef for an ObjCObjectPointerType) |
5880 | /// - the 'Class' builtin type (same caveat) |
5881 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5882 | QualType getBaseType() const { return BaseType; } |
5883 | |
5884 | bool isObjCId() const { |
5885 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5886 | } |
5887 | |
5888 | bool isObjCClass() const { |
5889 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5890 | } |
5891 | |
5892 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5893 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5894 | bool isObjCUnqualifiedIdOrClass() const { |
5895 | if (!qual_empty()) return false; |
5896 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5897 | return T->getKind() == BuiltinType::ObjCId || |
5898 | T->getKind() == BuiltinType::ObjCClass; |
5899 | return false; |
5900 | } |
5901 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5902 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5903 | |
5904 | /// Gets the interface declaration for this object type, if the base type |
5905 | /// really is an interface. |
5906 | ObjCInterfaceDecl *getInterface() const; |
5907 | |
5908 | /// Determine whether this object type is "specialized", meaning |
5909 | /// that it has type arguments. |
5910 | bool isSpecialized() const; |
5911 | |
5912 | /// Determine whether this object type was written with type arguments. |
5913 | bool isSpecializedAsWritten() const { |
5914 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5915 | } |
5916 | |
5917 | /// Determine whether this object type is "unspecialized", meaning |
5918 | /// that it has no type arguments. |
5919 | bool isUnspecialized() const { return !isSpecialized(); } |
5920 | |
5921 | /// Determine whether this object type is "unspecialized" as |
5922 | /// written, meaning that it has no type arguments. |
5923 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5924 | |
5925 | /// Retrieve the type arguments of this object type (semantically). |
5926 | ArrayRef<QualType> getTypeArgs() const; |
5927 | |
5928 | /// Retrieve the type arguments of this object type as they were |
5929 | /// written. |
5930 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5931 | return llvm::makeArrayRef(getTypeArgStorage(), |
5932 | ObjCObjectTypeBits.NumTypeArgs); |
5933 | } |
5934 | |
5935 | /// Whether this is a "__kindof" type as written. |
5936 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5937 | |
5938 | /// Whether this ia a "__kindof" type (semantically). |
5939 | bool isKindOfType() const; |
5940 | |
5941 | /// Retrieve the type of the superclass of this object type. |
5942 | /// |
5943 | /// This operation substitutes any type arguments into the |
5944 | /// superclass of the current class type, potentially producing a |
5945 | /// specialization of the superclass type. Produces a null type if |
5946 | /// there is no superclass. |
5947 | QualType getSuperClassType() const { |
5948 | if (!CachedSuperClassType.getInt()) |
5949 | computeSuperClassTypeSlow(); |
5950 | |
5951 | assert(CachedSuperClassType.getInt() && "Superclass not set?")(static_cast <bool> (CachedSuperClassType.getInt() && "Superclass not set?") ? void (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 5951, __extension__ __PRETTY_FUNCTION__)); |
5952 | return QualType(CachedSuperClassType.getPointer(), 0); |
5953 | } |
5954 | |
5955 | /// Strip off the Objective-C "kindof" type and (with it) any |
5956 | /// protocol qualifiers. |
5957 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5958 | |
5959 | bool isSugared() const { return false; } |
5960 | QualType desugar() const { return QualType(this, 0); } |
5961 | |
5962 | static bool classof(const Type *T) { |
5963 | return T->getTypeClass() == ObjCObject || |
5964 | T->getTypeClass() == ObjCInterface; |
5965 | } |
5966 | }; |
5967 | |
5968 | /// A class providing a concrete implementation |
5969 | /// of ObjCObjectType, so as to not increase the footprint of |
5970 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5971 | /// system should not reference this type. |
5972 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5973 | friend class ASTContext; |
5974 | |
5975 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5976 | // will need to be modified. |
5977 | |
5978 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5979 | ArrayRef<QualType> typeArgs, |
5980 | ArrayRef<ObjCProtocolDecl *> protocols, |
5981 | bool isKindOf) |
5982 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5983 | |
5984 | public: |
5985 | void Profile(llvm::FoldingSetNodeID &ID); |
5986 | static void Profile(llvm::FoldingSetNodeID &ID, |
5987 | QualType Base, |
5988 | ArrayRef<QualType> typeArgs, |
5989 | ArrayRef<ObjCProtocolDecl *> protocols, |
5990 | bool isKindOf); |
5991 | }; |
5992 | |
5993 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5994 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5995 | } |
5996 | |
5997 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5998 | return reinterpret_cast<ObjCProtocolDecl**>( |
5999 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
6000 | } |
6001 | |
6002 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
6003 | return reinterpret_cast<ObjCProtocolDecl**>( |
6004 | static_cast<ObjCTypeParamType*>(this)+1); |
6005 | } |
6006 | |
6007 | /// Interfaces are the core concept in Objective-C for object oriented design. |
6008 | /// They basically correspond to C++ classes. There are two kinds of interface |
6009 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
6010 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
6011 | /// |
6012 | /// ObjCInterfaceType guarantees the following properties when considered |
6013 | /// as a subtype of its superclass, ObjCObjectType: |
6014 | /// - There are no protocol qualifiers. To reinforce this, code which |
6015 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
6016 | /// fail to compile. |
6017 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
6018 | /// T->getBaseType() == QualType(T, 0). |
6019 | class ObjCInterfaceType : public ObjCObjectType { |
6020 | friend class ASTContext; // ASTContext creates these. |
6021 | friend class ASTReader; |
6022 | friend class ObjCInterfaceDecl; |
6023 | template <class T> friend class serialization::AbstractTypeReader; |
6024 | |
6025 | mutable ObjCInterfaceDecl *Decl; |
6026 | |
6027 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
6028 | : ObjCObjectType(Nonce_ObjCInterface), |
6029 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
6030 | |
6031 | public: |
6032 | /// Get the declaration of this interface. |
6033 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
6034 | |
6035 | bool isSugared() const { return false; } |
6036 | QualType desugar() const { return QualType(this, 0); } |
6037 | |
6038 | static bool classof(const Type *T) { |
6039 | return T->getTypeClass() == ObjCInterface; |
6040 | } |
6041 | |
6042 | // Nonsense to "hide" certain members of ObjCObjectType within this |
6043 | // class. People asking for protocols on an ObjCInterfaceType are |
6044 | // not going to get what they want: ObjCInterfaceTypes are |
6045 | // guaranteed to have no protocols. |
6046 | enum { |
6047 | qual_iterator, |
6048 | qual_begin, |
6049 | qual_end, |
6050 | getNumProtocols, |
6051 | getProtocol |
6052 | }; |
6053 | }; |
6054 | |
6055 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
6056 | QualType baseType = getBaseType(); |
6057 | while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { |
6058 | if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
6059 | return T->getDecl(); |
6060 | |
6061 | baseType = ObjT->getBaseType(); |
6062 | } |
6063 | |
6064 | return nullptr; |
6065 | } |
6066 | |
6067 | /// Represents a pointer to an Objective C object. |
6068 | /// |
6069 | /// These are constructed from pointer declarators when the pointee type is |
6070 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
6071 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
6072 | /// and 'Class<P>' are translated into these. |
6073 | /// |
6074 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
6075 | /// only the first level of pointer gets it own type implementation. |
6076 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
6077 | friend class ASTContext; // ASTContext creates these. |
6078 | |
6079 | QualType PointeeType; |
6080 | |
6081 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
6082 | : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()), |
6083 | PointeeType(Pointee) {} |
6084 | |
6085 | public: |
6086 | /// Gets the type pointed to by this ObjC pointer. |
6087 | /// The result will always be an ObjCObjectType or sugar thereof. |
6088 | QualType getPointeeType() const { return PointeeType; } |
6089 | |
6090 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
6091 | /// |
6092 | /// This method is equivalent to getPointeeType() except that |
6093 | /// it discards any typedefs (or other sugar) between this |
6094 | /// type and the "outermost" object type. So for: |
6095 | /// \code |
6096 | /// \@class A; \@protocol P; \@protocol Q; |
6097 | /// typedef A<P> AP; |
6098 | /// typedef A A1; |
6099 | /// typedef A1<P> A1P; |
6100 | /// typedef A1P<Q> A1PQ; |
6101 | /// \endcode |
6102 | /// For 'A*', getObjectType() will return 'A'. |
6103 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
6104 | /// For 'AP*', getObjectType() will return 'A<P>'. |
6105 | /// For 'A1*', getObjectType() will return 'A'. |
6106 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
6107 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
6108 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
6109 | /// adding protocols to a protocol-qualified base discards the |
6110 | /// old qualifiers (for now). But if it didn't, getObjectType() |
6111 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
6112 | /// qualifiers more complicated). |
6113 | const ObjCObjectType *getObjectType() const { |
6114 | return PointeeType->castAs<ObjCObjectType>(); |
6115 | } |
6116 | |
6117 | /// If this pointer points to an Objective C |
6118 | /// \@interface type, gets the type for that interface. Any protocol |
6119 | /// qualifiers on the interface are ignored. |
6120 | /// |
6121 | /// \return null if the base type for this pointer is 'id' or 'Class' |
6122 | const ObjCInterfaceType *getInterfaceType() const; |
6123 | |
6124 | /// If this pointer points to an Objective \@interface |
6125 | /// type, gets the declaration for that interface. |
6126 | /// |
6127 | /// \return null if the base type for this pointer is 'id' or 'Class' |
6128 | ObjCInterfaceDecl *getInterfaceDecl() const { |
6129 | return getObjectType()->getInterface(); |
6130 | } |
6131 | |
6132 | /// True if this is equivalent to the 'id' type, i.e. if |
6133 | /// its object type is the primitive 'id' type with no protocols. |
6134 | bool isObjCIdType() const { |
6135 | return getObjectType()->isObjCUnqualifiedId(); |
6136 | } |
6137 | |
6138 | /// True if this is equivalent to the 'Class' type, |
6139 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
6140 | bool isObjCClassType() const { |
6141 | return getObjectType()->isObjCUnqualifiedClass(); |
6142 | } |
6143 | |
6144 | /// True if this is equivalent to the 'id' or 'Class' type, |
6145 | bool isObjCIdOrClassType() const { |
6146 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
6147 | } |
6148 | |
6149 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
6150 | /// protocols. |
6151 | bool isObjCQualifiedIdType() const { |
6152 | return getObjectType()->isObjCQualifiedId(); |
6153 | } |
6154 | |
6155 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
6156 | /// protocols. |
6157 | bool isObjCQualifiedClassType() const { |
6158 | return getObjectType()->isObjCQualifiedClass(); |
6159 | } |
6160 | |
6161 | /// Whether this is a "__kindof" type. |
6162 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
6163 | |
6164 | /// Whether this type is specialized, meaning that it has type arguments. |
6165 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
6166 | |
6167 | /// Whether this type is specialized, meaning that it has type arguments. |
6168 | bool isSpecializedAsWritten() const { |
6169 | return getObjectType()->isSpecializedAsWritten(); |
6170 | } |
6171 | |
6172 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
6173 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
6174 | |
6175 | /// Determine whether this object type is "unspecialized" as |
6176 | /// written, meaning that it has no type arguments. |
6177 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
6178 | |
6179 | /// Retrieve the type arguments for this type. |
6180 | ArrayRef<QualType> getTypeArgs() const { |
6181 | return getObjectType()->getTypeArgs(); |
6182 | } |
6183 | |
6184 | /// Retrieve the type arguments for this type. |
6185 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
6186 | return getObjectType()->getTypeArgsAsWritten(); |
6187 | } |
6188 | |
6189 | /// An iterator over the qualifiers on the object type. Provided |
6190 | /// for convenience. This will always iterate over the full set of |
6191 | /// protocols on a type, not just those provided directly. |
6192 | using qual_iterator = ObjCObjectType::qual_iterator; |
6193 | using qual_range = llvm::iterator_range<qual_iterator>; |
6194 | |
6195 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
6196 | |
6197 | qual_iterator qual_begin() const { |
6198 | return getObjectType()->qual_begin(); |
6199 | } |
6200 | |
6201 | qual_iterator qual_end() const { |
6202 | return getObjectType()->qual_end(); |
6203 | } |
6204 | |
6205 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
6206 | |
6207 | /// Return the number of qualifying protocols on the object type. |
6208 | unsigned getNumProtocols() const { |
6209 | return getObjectType()->getNumProtocols(); |
6210 | } |
6211 | |
6212 | /// Retrieve a qualifying protocol by index on the object type. |
6213 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
6214 | return getObjectType()->getProtocol(I); |
6215 | } |
6216 | |
6217 | bool isSugared() const { return false; } |
6218 | QualType desugar() const { return QualType(this, 0); } |
6219 | |
6220 | /// Retrieve the type of the superclass of this object pointer type. |
6221 | /// |
6222 | /// This operation substitutes any type arguments into the |
6223 | /// superclass of the current class type, potentially producing a |
6224 | /// pointer to a specialization of the superclass type. Produces a |
6225 | /// null type if there is no superclass. |
6226 | QualType getSuperClassType() const; |
6227 | |
6228 | /// Strip off the Objective-C "kindof" type and (with it) any |
6229 | /// protocol qualifiers. |
6230 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
6231 | const ASTContext &ctx) const; |
6232 | |
6233 | void Profile(llvm::FoldingSetNodeID &ID) { |
6234 | Profile(ID, getPointeeType()); |
6235 | } |
6236 | |
6237 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6238 | ID.AddPointer(T.getAsOpaquePtr()); |
6239 | } |
6240 | |
6241 | static bool classof(const Type *T) { |
6242 | return T->getTypeClass() == ObjCObjectPointer; |
6243 | } |
6244 | }; |
6245 | |
6246 | class AtomicType : public Type, public llvm::FoldingSetNode { |
6247 | friend class ASTContext; // ASTContext creates these. |
6248 | |
6249 | QualType ValueType; |
6250 | |
6251 | AtomicType(QualType ValTy, QualType Canonical) |
6252 | : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {} |
6253 | |
6254 | public: |
6255 | /// Gets the type contained by this atomic type, i.e. |
6256 | /// the type returned by performing an atomic load of this atomic type. |
6257 | QualType getValueType() const { return ValueType; } |
6258 | |
6259 | bool isSugared() const { return false; } |
6260 | QualType desugar() const { return QualType(this, 0); } |
6261 | |
6262 | void Profile(llvm::FoldingSetNodeID &ID) { |
6263 | Profile(ID, getValueType()); |
6264 | } |
6265 | |
6266 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6267 | ID.AddPointer(T.getAsOpaquePtr()); |
6268 | } |
6269 | |
6270 | static bool classof(const Type *T) { |
6271 | return T->getTypeClass() == Atomic; |
6272 | } |
6273 | }; |
6274 | |
6275 | /// PipeType - OpenCL20. |
6276 | class PipeType : public Type, public llvm::FoldingSetNode { |
6277 | friend class ASTContext; // ASTContext creates these. |
6278 | |
6279 | QualType ElementType; |
6280 | bool isRead; |
6281 | |
6282 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
6283 | : Type(Pipe, CanonicalPtr, elemType->getDependence()), |
6284 | ElementType(elemType), isRead(isRead) {} |
6285 | |
6286 | public: |
6287 | QualType getElementType() const { return ElementType; } |
6288 | |
6289 | bool isSugared() const { return false; } |
6290 | |
6291 | QualType desugar() const { return QualType(this, 0); } |
6292 | |
6293 | void Profile(llvm::FoldingSetNodeID &ID) { |
6294 | Profile(ID, getElementType(), isReadOnly()); |
6295 | } |
6296 | |
6297 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
6298 | ID.AddPointer(T.getAsOpaquePtr()); |
6299 | ID.AddBoolean(isRead); |
6300 | } |
6301 | |
6302 | static bool classof(const Type *T) { |
6303 | return T->getTypeClass() == Pipe; |
6304 | } |
6305 | |
6306 | bool isReadOnly() const { return isRead; } |
6307 | }; |
6308 | |
6309 | /// A fixed int type of a specified bitwidth. |
6310 | class ExtIntType final : public Type, public llvm::FoldingSetNode { |
6311 | friend class ASTContext; |
6312 | unsigned IsUnsigned : 1; |
6313 | unsigned NumBits : 24; |
6314 | |
6315 | protected: |
6316 | ExtIntType(bool isUnsigned, unsigned NumBits); |
6317 | |
6318 | public: |
6319 | bool isUnsigned() const { return IsUnsigned; } |
6320 | bool isSigned() const { return !IsUnsigned; } |
6321 | unsigned getNumBits() const { return NumBits; } |
6322 | |
6323 | bool isSugared() const { return false; } |
6324 | QualType desugar() const { return QualType(this, 0); } |
6325 | |
6326 | void Profile(llvm::FoldingSetNodeID &ID) { |
6327 | Profile(ID, isUnsigned(), getNumBits()); |
6328 | } |
6329 | |
6330 | static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned, |
6331 | unsigned NumBits) { |
6332 | ID.AddBoolean(IsUnsigned); |
6333 | ID.AddInteger(NumBits); |
6334 | } |
6335 | |
6336 | static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; } |
6337 | }; |
6338 | |
6339 | class DependentExtIntType final : public Type, public llvm::FoldingSetNode { |
6340 | friend class ASTContext; |
6341 | const ASTContext &Context; |
6342 | llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned; |
6343 | |
6344 | protected: |
6345 | DependentExtIntType(const ASTContext &Context, bool IsUnsigned, |
6346 | Expr *NumBits); |
6347 | |
6348 | public: |
6349 | bool isUnsigned() const; |
6350 | bool isSigned() const { return !isUnsigned(); } |
6351 | Expr *getNumBitsExpr() const; |
6352 | |
6353 | bool isSugared() const { return false; } |
6354 | QualType desugar() const { return QualType(this, 0); } |
6355 | |
6356 | void Profile(llvm::FoldingSetNodeID &ID) { |
6357 | Profile(ID, Context, isUnsigned(), getNumBitsExpr()); |
6358 | } |
6359 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
6360 | bool IsUnsigned, Expr *NumBitsExpr); |
6361 | |
6362 | static bool classof(const Type *T) { |
6363 | return T->getTypeClass() == DependentExtInt; |
6364 | } |
6365 | }; |
6366 | |
6367 | /// A qualifier set is used to build a set of qualifiers. |
6368 | class QualifierCollector : public Qualifiers { |
6369 | public: |
6370 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
6371 | |
6372 | /// Collect any qualifiers on the given type and return an |
6373 | /// unqualified type. The qualifiers are assumed to be consistent |
6374 | /// with those already in the type. |
6375 | const Type *strip(QualType type) { |
6376 | addFastQualifiers(type.getLocalFastQualifiers()); |
6377 | if (!type.hasLocalNonFastQualifiers()) |
6378 | return type.getTypePtrUnsafe(); |
6379 | |
6380 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
6381 | addConsistentQualifiers(extQuals->getQualifiers()); |
6382 | return extQuals->getBaseType(); |
6383 | } |
6384 | |
6385 | /// Apply the collected qualifiers to the given type. |
6386 | QualType apply(const ASTContext &Context, QualType QT) const; |
6387 | |
6388 | /// Apply the collected qualifiers to the given type. |
6389 | QualType apply(const ASTContext &Context, const Type* T) const; |
6390 | }; |
6391 | |
6392 | /// A container of type source information. |
6393 | /// |
6394 | /// A client can read the relevant info using TypeLoc wrappers, e.g: |
6395 | /// @code |
6396 | /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); |
6397 | /// TL.getBeginLoc().print(OS, SrcMgr); |
6398 | /// @endcode |
6399 | class alignas(8) TypeSourceInfo { |
6400 | // Contains a memory block after the class, used for type source information, |
6401 | // allocated by ASTContext. |
6402 | friend class ASTContext; |
6403 | |
6404 | QualType Ty; |
6405 | |
6406 | TypeSourceInfo(QualType ty) : Ty(ty) {} |
6407 | |
6408 | public: |
6409 | /// Return the type wrapped by this type source info. |
6410 | QualType getType() const { return Ty; } |
6411 | |
6412 | /// Return the TypeLoc wrapper for the type source info. |
6413 | TypeLoc getTypeLoc() const; // implemented in TypeLoc.h |
6414 | |
6415 | /// Override the type stored in this TypeSourceInfo. Use with caution! |
6416 | void overrideType(QualType T) { Ty = T; } |
6417 | }; |
6418 | |
6419 | // Inline function definitions. |
6420 | |
6421 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
6422 | SplitQualType desugar = |
6423 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
6424 | desugar.Quals.addConsistentQualifiers(Quals); |
6425 | return desugar; |
6426 | } |
6427 | |
6428 | inline const Type *QualType::getTypePtr() const { |
6429 | return getCommonPtr()->BaseType; |
6430 | } |
6431 | |
6432 | inline const Type *QualType::getTypePtrOrNull() const { |
6433 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
6434 | } |
6435 | |
6436 | inline SplitQualType QualType::split() const { |
6437 | if (!hasLocalNonFastQualifiers()) |
6438 | return SplitQualType(getTypePtrUnsafe(), |
6439 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
6440 | |
6441 | const ExtQuals *eq = getExtQualsUnsafe(); |
6442 | Qualifiers qs = eq->getQualifiers(); |
6443 | qs.addFastQualifiers(getLocalFastQualifiers()); |
6444 | return SplitQualType(eq->getBaseType(), qs); |
6445 | } |
6446 | |
6447 | inline Qualifiers QualType::getLocalQualifiers() const { |
6448 | Qualifiers Quals; |
6449 | if (hasLocalNonFastQualifiers()) |
6450 | Quals = getExtQualsUnsafe()->getQualifiers(); |
6451 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
6452 | return Quals; |
6453 | } |
6454 | |
6455 | inline Qualifiers QualType::getQualifiers() const { |
6456 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
6457 | quals.addFastQualifiers(getLocalFastQualifiers()); |
6458 | return quals; |
6459 | } |
6460 | |
6461 | inline unsigned QualType::getCVRQualifiers() const { |
6462 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
6463 | cvr |= getLocalCVRQualifiers(); |
6464 | return cvr; |
6465 | } |
6466 | |
6467 | inline QualType QualType::getCanonicalType() const { |
6468 | QualType canon = getCommonPtr()->CanonicalType; |
6469 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
6470 | } |
6471 | |
6472 | inline bool QualType::isCanonical() const { |
6473 | return getTypePtr()->isCanonicalUnqualified(); |
6474 | } |
6475 | |
6476 | inline bool QualType::isCanonicalAsParam() const { |
6477 | if (!isCanonical()) return false; |
6478 | if (hasLocalQualifiers()) return false; |
6479 | |
6480 | const Type *T = getTypePtr(); |
6481 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
6482 | return false; |
6483 | |
6484 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
6485 | } |
6486 | |
6487 | inline bool QualType::isConstQualified() const { |
6488 | return isLocalConstQualified() || |
6489 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
6490 | } |
6491 | |
6492 | inline bool QualType::isRestrictQualified() const { |
6493 | return isLocalRestrictQualified() || |
6494 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
6495 | } |
6496 | |
6497 | |
6498 | inline bool QualType::isVolatileQualified() const { |
6499 | return isLocalVolatileQualified() || |
6500 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
6501 | } |
6502 | |
6503 | inline bool QualType::hasQualifiers() const { |
6504 | return hasLocalQualifiers() || |
6505 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
6506 | } |
6507 | |
6508 | inline QualType QualType::getUnqualifiedType() const { |
6509 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6510 | return QualType(getTypePtr(), 0); |
6511 | |
6512 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
6513 | } |
6514 | |
6515 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
6516 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6517 | return split(); |
6518 | |
6519 | return getSplitUnqualifiedTypeImpl(*this); |
6520 | } |
6521 | |
6522 | inline void QualType::removeLocalConst() { |
6523 | removeLocalFastQualifiers(Qualifiers::Const); |
6524 | } |
6525 | |
6526 | inline void QualType::removeLocalRestrict() { |
6527 | removeLocalFastQualifiers(Qualifiers::Restrict); |
6528 | } |
6529 | |
6530 | inline void QualType::removeLocalVolatile() { |
6531 | removeLocalFastQualifiers(Qualifiers::Volatile); |
6532 | } |
6533 | |
6534 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
6535 | assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")(static_cast <bool> (!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits") ? void (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 6535, __extension__ __PRETTY_FUNCTION__)); |
6536 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
6537 | "Fast bits differ from CVR bits!"); |
6538 | |
6539 | // Fast path: we don't need to touch the slow qualifiers. |
6540 | removeLocalFastQualifiers(Mask); |
6541 | } |
6542 | |
6543 | /// Check if this type has any address space qualifier. |
6544 | inline bool QualType::hasAddressSpace() const { |
6545 | return getQualifiers().hasAddressSpace(); |
6546 | } |
6547 | |
6548 | /// Return the address space of this type. |
6549 | inline LangAS QualType::getAddressSpace() const { |
6550 | return getQualifiers().getAddressSpace(); |
6551 | } |
6552 | |
6553 | /// Return the gc attribute of this type. |
6554 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
6555 | return getQualifiers().getObjCGCAttr(); |
6556 | } |
6557 | |
6558 | inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
6559 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6560 | return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); |
6561 | return false; |
6562 | } |
6563 | |
6564 | inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { |
6565 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6566 | return hasNonTrivialToPrimitiveDestructCUnion(RD); |
6567 | return false; |
6568 | } |
6569 | |
6570 | inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { |
6571 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6572 | return hasNonTrivialToPrimitiveCopyCUnion(RD); |
6573 | return false; |
6574 | } |
6575 | |
6576 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
6577 | if (const auto *PT = t.getAs<PointerType>()) { |
6578 | if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) |
6579 | return FT->getExtInfo(); |
6580 | } else if (const auto *FT = t.getAs<FunctionType>()) |
6581 | return FT->getExtInfo(); |
6582 | |
6583 | return FunctionType::ExtInfo(); |
6584 | } |
6585 | |
6586 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
6587 | return getFunctionExtInfo(*t); |
6588 | } |
6589 | |
6590 | /// Determine whether this type is more |
6591 | /// qualified than the Other type. For example, "const volatile int" |
6592 | /// is more qualified than "const int", "volatile int", and |
6593 | /// "int". However, it is not more qualified than "const volatile |
6594 | /// int". |
6595 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
6596 | Qualifiers MyQuals = getQualifiers(); |
6597 | Qualifiers OtherQuals = other.getQualifiers(); |
6598 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
6599 | } |
6600 | |
6601 | /// Determine whether this type is at last |
6602 | /// as qualified as the Other type. For example, "const volatile |
6603 | /// int" is at least as qualified as "const int", "volatile int", |
6604 | /// "int", and "const volatile int". |
6605 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
6606 | Qualifiers OtherQuals = other.getQualifiers(); |
6607 | |
6608 | // Ignore __unaligned qualifier if this type is a void. |
6609 | if (getUnqualifiedType()->isVoidType()) |
6610 | OtherQuals.removeUnaligned(); |
6611 | |
6612 | return getQualifiers().compatiblyIncludes(OtherQuals); |
6613 | } |
6614 | |
6615 | /// If Type is a reference type (e.g., const |
6616 | /// int&), returns the type that the reference refers to ("const |
6617 | /// int"). Otherwise, returns the type itself. This routine is used |
6618 | /// throughout Sema to implement C++ 5p6: |
6619 | /// |
6620 | /// If an expression initially has the type "reference to T" (8.3.2, |
6621 | /// 8.5.3), the type is adjusted to "T" prior to any further |
6622 | /// analysis, the expression designates the object or function |
6623 | /// denoted by the reference, and the expression is an lvalue. |
6624 | inline QualType QualType::getNonReferenceType() const { |
6625 | if (const auto *RefType = (*this)->getAs<ReferenceType>()) |
6626 | return RefType->getPointeeType(); |
6627 | else |
6628 | return *this; |
6629 | } |
6630 | |
6631 | inline bool QualType::isCForbiddenLValueType() const { |
6632 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
6633 | getTypePtr()->isFunctionType()); |
6634 | } |
6635 | |
6636 | /// Tests whether the type is categorized as a fundamental type. |
6637 | /// |
6638 | /// \returns True for types specified in C++0x [basic.fundamental]. |
6639 | inline bool Type::isFundamentalType() const { |
6640 | return isVoidType() || |
6641 | isNullPtrType() || |
6642 | // FIXME: It's really annoying that we don't have an |
6643 | // 'isArithmeticType()' which agrees with the standard definition. |
6644 | (isArithmeticType() && !isEnumeralType()); |
6645 | } |
6646 | |
6647 | /// Tests whether the type is categorized as a compound type. |
6648 | /// |
6649 | /// \returns True for types specified in C++0x [basic.compound]. |
6650 | inline bool Type::isCompoundType() const { |
6651 | // C++0x [basic.compound]p1: |
6652 | // Compound types can be constructed in the following ways: |
6653 | // -- arrays of objects of a given type [...]; |
6654 | return isArrayType() || |
6655 | // -- functions, which have parameters of given types [...]; |
6656 | isFunctionType() || |
6657 | // -- pointers to void or objects or functions [...]; |
6658 | isPointerType() || |
6659 | // -- references to objects or functions of a given type. [...] |
6660 | isReferenceType() || |
6661 | // -- classes containing a sequence of objects of various types, [...]; |
6662 | isRecordType() || |
6663 | // -- unions, which are classes capable of containing objects of different |
6664 | // types at different times; |
6665 | isUnionType() || |
6666 | // -- enumerations, which comprise a set of named constant values. [...]; |
6667 | isEnumeralType() || |
6668 | // -- pointers to non-static class members, [...]. |
6669 | isMemberPointerType(); |
6670 | } |
6671 | |
6672 | inline bool Type::isFunctionType() const { |
6673 | return isa<FunctionType>(CanonicalType); |
6674 | } |
6675 | |
6676 | inline bool Type::isPointerType() const { |
6677 | return isa<PointerType>(CanonicalType); |
6678 | } |
6679 | |
6680 | inline bool Type::isAnyPointerType() const { |
6681 | return isPointerType() || isObjCObjectPointerType(); |
6682 | } |
6683 | |
6684 | inline bool Type::isBlockPointerType() const { |
6685 | return isa<BlockPointerType>(CanonicalType); |
6686 | } |
6687 | |
6688 | inline bool Type::isReferenceType() const { |
6689 | return isa<ReferenceType>(CanonicalType); |
6690 | } |
6691 | |
6692 | inline bool Type::isLValueReferenceType() const { |
6693 | return isa<LValueReferenceType>(CanonicalType); |
6694 | } |
6695 | |
6696 | inline bool Type::isRValueReferenceType() const { |
6697 | return isa<RValueReferenceType>(CanonicalType); |
6698 | } |
6699 | |
6700 | inline bool Type::isObjectPointerType() const { |
6701 | // Note: an "object pointer type" is not the same thing as a pointer to an |
6702 | // object type; rather, it is a pointer to an object type or a pointer to cv |
6703 | // void. |
6704 | if (const auto *T = getAs<PointerType>()) |
6705 | return !T->getPointeeType()->isFunctionType(); |
6706 | else |
6707 | return false; |
6708 | } |
6709 | |
6710 | inline bool Type::isFunctionPointerType() const { |
6711 | if (const auto *T = getAs<PointerType>()) |
6712 | return T->getPointeeType()->isFunctionType(); |
6713 | else |
6714 | return false; |
6715 | } |
6716 | |
6717 | inline bool Type::isFunctionReferenceType() const { |
6718 | if (const auto *T = getAs<ReferenceType>()) |
6719 | return T->getPointeeType()->isFunctionType(); |
6720 | else |
6721 | return false; |
6722 | } |
6723 | |
6724 | inline bool Type::isMemberPointerType() const { |
6725 | return isa<MemberPointerType>(CanonicalType); |
6726 | } |
6727 | |
6728 | inline bool Type::isMemberFunctionPointerType() const { |
6729 | if (const auto *T = getAs<MemberPointerType>()) |
6730 | return T->isMemberFunctionPointer(); |
6731 | else |
6732 | return false; |
6733 | } |
6734 | |
6735 | inline bool Type::isMemberDataPointerType() const { |
6736 | if (const auto *T = getAs<MemberPointerType>()) |
6737 | return T->isMemberDataPointer(); |
6738 | else |
6739 | return false; |
6740 | } |
6741 | |
6742 | inline bool Type::isArrayType() const { |
6743 | return isa<ArrayType>(CanonicalType); |
6744 | } |
6745 | |
6746 | inline bool Type::isConstantArrayType() const { |
6747 | return isa<ConstantArrayType>(CanonicalType); |
6748 | } |
6749 | |
6750 | inline bool Type::isIncompleteArrayType() const { |
6751 | return isa<IncompleteArrayType>(CanonicalType); |
6752 | } |
6753 | |
6754 | inline bool Type::isVariableArrayType() const { |
6755 | return isa<VariableArrayType>(CanonicalType); |
6756 | } |
6757 | |
6758 | inline bool Type::isDependentSizedArrayType() const { |
6759 | return isa<DependentSizedArrayType>(CanonicalType); |
6760 | } |
6761 | |
6762 | inline bool Type::isBuiltinType() const { |
6763 | return isa<BuiltinType>(CanonicalType); |
6764 | } |
6765 | |
6766 | inline bool Type::isRecordType() const { |
6767 | return isa<RecordType>(CanonicalType); |
6768 | } |
6769 | |
6770 | inline bool Type::isEnumeralType() const { |
6771 | return isa<EnumType>(CanonicalType); |
6772 | } |
6773 | |
6774 | inline bool Type::isAnyComplexType() const { |
6775 | return isa<ComplexType>(CanonicalType); |
6776 | } |
6777 | |
6778 | inline bool Type::isVectorType() const { |
6779 | return isa<VectorType>(CanonicalType); |
6780 | } |
6781 | |
6782 | inline bool Type::isExtVectorType() const { |
6783 | return isa<ExtVectorType>(CanonicalType); |
6784 | } |
6785 | |
6786 | inline bool Type::isMatrixType() const { |
6787 | return isa<MatrixType>(CanonicalType); |
6788 | } |
6789 | |
6790 | inline bool Type::isConstantMatrixType() const { |
6791 | return isa<ConstantMatrixType>(CanonicalType); |
6792 | } |
6793 | |
6794 | inline bool Type::isDependentAddressSpaceType() const { |
6795 | return isa<DependentAddressSpaceType>(CanonicalType); |
6796 | } |
6797 | |
6798 | inline bool Type::isObjCObjectPointerType() const { |
6799 | return isa<ObjCObjectPointerType>(CanonicalType); |
6800 | } |
6801 | |
6802 | inline bool Type::isObjCObjectType() const { |
6803 | return isa<ObjCObjectType>(CanonicalType); |
6804 | } |
6805 | |
6806 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6807 | return isa<ObjCInterfaceType>(CanonicalType) || |
6808 | isa<ObjCObjectType>(CanonicalType); |
6809 | } |
6810 | |
6811 | inline bool Type::isAtomicType() const { |
6812 | return isa<AtomicType>(CanonicalType); |
6813 | } |
6814 | |
6815 | inline bool Type::isUndeducedAutoType() const { |
6816 | return isa<AutoType>(CanonicalType); |
6817 | } |
6818 | |
6819 | inline bool Type::isObjCQualifiedIdType() const { |
6820 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6821 | return OPT->isObjCQualifiedIdType(); |
6822 | return false; |
6823 | } |
6824 | |
6825 | inline bool Type::isObjCQualifiedClassType() const { |
6826 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6827 | return OPT->isObjCQualifiedClassType(); |
6828 | return false; |
6829 | } |
6830 | |
6831 | inline bool Type::isObjCIdType() const { |
6832 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6833 | return OPT->isObjCIdType(); |
6834 | return false; |
6835 | } |
6836 | |
6837 | inline bool Type::isObjCClassType() const { |
6838 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6839 | return OPT->isObjCClassType(); |
6840 | return false; |
6841 | } |
6842 | |
6843 | inline bool Type::isObjCSelType() const { |
6844 | if (const auto *OPT = getAs<PointerType>()) |
6845 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6846 | return false; |
6847 | } |
6848 | |
6849 | inline bool Type::isObjCBuiltinType() const { |
6850 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6851 | } |
6852 | |
6853 | inline bool Type::isDecltypeType() const { |
6854 | return isa<DecltypeType>(this); |
6855 | } |
6856 | |
6857 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6858 | inline bool Type::is##Id##Type() const { \ |
6859 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6860 | } |
6861 | #include "clang/Basic/OpenCLImageTypes.def" |
6862 | |
6863 | inline bool Type::isSamplerT() const { |
6864 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6865 | } |
6866 | |
6867 | inline bool Type::isEventT() const { |
6868 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6869 | } |
6870 | |
6871 | inline bool Type::isClkEventT() const { |
6872 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6873 | } |
6874 | |
6875 | inline bool Type::isQueueT() const { |
6876 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6877 | } |
6878 | |
6879 | inline bool Type::isReserveIDT() const { |
6880 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6881 | } |
6882 | |
6883 | inline bool Type::isImageType() const { |
6884 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6885 | return |
6886 | #include "clang/Basic/OpenCLImageTypes.def" |
6887 | false; // end boolean or operation |
6888 | } |
6889 | |
6890 | inline bool Type::isPipeType() const { |
6891 | return isa<PipeType>(CanonicalType); |
6892 | } |
6893 | |
6894 | inline bool Type::isExtIntType() const { |
6895 | return isa<ExtIntType>(CanonicalType); |
6896 | } |
6897 | |
6898 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6899 | inline bool Type::is##Id##Type() const { \ |
6900 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6901 | } |
6902 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6903 | |
6904 | inline bool Type::isOCLIntelSubgroupAVCType() const { |
6905 | #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ |
6906 | isOCLIntelSubgroupAVC##Id##Type() || |
6907 | return |
6908 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6909 | false; // end of boolean or operation |
6910 | } |
6911 | |
6912 | inline bool Type::isOCLExtOpaqueType() const { |
6913 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || |
6914 | return |
6915 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6916 | false; // end of boolean or operation |
6917 | } |
6918 | |
6919 | inline bool Type::isOpenCLSpecificType() const { |
6920 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6921 | isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); |
6922 | } |
6923 | |
6924 | inline bool Type::isTemplateTypeParmType() const { |
6925 | return isa<TemplateTypeParmType>(CanonicalType); |
6926 | } |
6927 | |
6928 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6929 | if (const BuiltinType *BT = getAs<BuiltinType>()) { |
6930 | return BT->getKind() == static_cast<BuiltinType::Kind>(K); |
6931 | } |
6932 | return false; |
6933 | } |
6934 | |
6935 | inline bool Type::isPlaceholderType() const { |
6936 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6937 | return BT->isPlaceholderType(); |
6938 | return false; |
6939 | } |
6940 | |
6941 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6942 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6943 | if (BT->isPlaceholderType()) |
6944 | return BT; |
6945 | return nullptr; |
6946 | } |
6947 | |
6948 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6949 | assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))(static_cast <bool> (BuiltinType::isPlaceholderTypeKind ((BuiltinType::Kind) K)) ? void (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 6949, __extension__ __PRETTY_FUNCTION__)); |
6950 | return isSpecificBuiltinType(K); |
6951 | } |
6952 | |
6953 | inline bool Type::isNonOverloadPlaceholderType() const { |
6954 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6955 | return BT->isNonOverloadPlaceholderType(); |
6956 | return false; |
6957 | } |
6958 | |
6959 | inline bool Type::isVoidType() const { |
6960 | return isSpecificBuiltinType(BuiltinType::Void); |
6961 | } |
6962 | |
6963 | inline bool Type::isHalfType() const { |
6964 | // FIXME: Should we allow complex __fp16? Probably not. |
6965 | return isSpecificBuiltinType(BuiltinType::Half); |
6966 | } |
6967 | |
6968 | inline bool Type::isFloat16Type() const { |
6969 | return isSpecificBuiltinType(BuiltinType::Float16); |
6970 | } |
6971 | |
6972 | inline bool Type::isBFloat16Type() const { |
6973 | return isSpecificBuiltinType(BuiltinType::BFloat16); |
6974 | } |
6975 | |
6976 | inline bool Type::isFloat128Type() const { |
6977 | return isSpecificBuiltinType(BuiltinType::Float128); |
6978 | } |
6979 | |
6980 | inline bool Type::isNullPtrType() const { |
6981 | return isSpecificBuiltinType(BuiltinType::NullPtr); |
6982 | } |
6983 | |
6984 | bool IsEnumDeclComplete(EnumDecl *); |
6985 | bool IsEnumDeclScoped(EnumDecl *); |
6986 | |
6987 | inline bool Type::isIntegerType() const { |
6988 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6989 | return BT->getKind() >= BuiltinType::Bool && |
6990 | BT->getKind() <= BuiltinType::Int128; |
6991 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6992 | // Incomplete enum types are not treated as integer types. |
6993 | // FIXME: In C++, enum types are never integer types. |
6994 | return IsEnumDeclComplete(ET->getDecl()) && |
6995 | !IsEnumDeclScoped(ET->getDecl()); |
6996 | } |
6997 | return isExtIntType(); |
6998 | } |
6999 | |
7000 | inline bool Type::isFixedPointType() const { |
7001 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
7002 | return BT->getKind() >= BuiltinType::ShortAccum && |
7003 | BT->getKind() <= BuiltinType::SatULongFract; |
7004 | } |
7005 | return false; |
7006 | } |
7007 | |
7008 | inline bool Type::isFixedPointOrIntegerType() const { |
7009 | return isFixedPointType() || isIntegerType(); |
7010 | } |
7011 | |
7012 | inline bool Type::isSaturatedFixedPointType() const { |
7013 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
7014 | return BT->getKind() >= BuiltinType::SatShortAccum && |
7015 | BT->getKind() <= BuiltinType::SatULongFract; |
7016 | } |
7017 | return false; |
7018 | } |
7019 | |
7020 | inline bool Type::isUnsaturatedFixedPointType() const { |
7021 | return isFixedPointType() && !isSaturatedFixedPointType(); |
7022 | } |
7023 | |
7024 | inline bool Type::isSignedFixedPointType() const { |
7025 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
7026 | return ((BT->getKind() >= BuiltinType::ShortAccum && |
7027 | BT->getKind() <= BuiltinType::LongAccum) || |
7028 | (BT->getKind() >= BuiltinType::ShortFract && |
7029 | BT->getKind() <= BuiltinType::LongFract) || |
7030 | (BT->getKind() >= BuiltinType::SatShortAccum && |
7031 | BT->getKind() <= BuiltinType::SatLongAccum) || |
7032 | (BT->getKind() >= BuiltinType::SatShortFract && |
7033 | BT->getKind() <= BuiltinType::SatLongFract)); |
7034 | } |
7035 | return false; |
7036 | } |
7037 | |
7038 | inline bool Type::isUnsignedFixedPointType() const { |
7039 | return isFixedPointType() && !isSignedFixedPointType(); |
7040 | } |
7041 | |
7042 | inline bool Type::isScalarType() const { |
7043 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7044 | return BT->getKind() > BuiltinType::Void && |
7045 | BT->getKind() <= BuiltinType::NullPtr; |
7046 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
7047 | // Enums are scalar types, but only if they are defined. Incomplete enums |
7048 | // are not treated as scalar types. |
7049 | return IsEnumDeclComplete(ET->getDecl()); |
7050 | return isa<PointerType>(CanonicalType) || |
7051 | isa<BlockPointerType>(CanonicalType) || |
7052 | isa<MemberPointerType>(CanonicalType) || |
7053 | isa<ComplexType>(CanonicalType) || |
7054 | isa<ObjCObjectPointerType>(CanonicalType) || |
7055 | isExtIntType(); |
7056 | } |
7057 | |
7058 | inline bool Type::isIntegralOrEnumerationType() const { |
7059 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7060 | return BT->getKind() >= BuiltinType::Bool && |
7061 | BT->getKind() <= BuiltinType::Int128; |
7062 | |
7063 | // Check for a complete enum type; incomplete enum types are not properly an |
7064 | // enumeration type in the sense required here. |
7065 | if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) |
7066 | return IsEnumDeclComplete(ET->getDecl()); |
7067 | |
7068 | return isExtIntType(); |
7069 | } |
7070 | |
7071 | inline bool Type::isBooleanType() const { |
7072 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
7073 | return BT->getKind() == BuiltinType::Bool; |
7074 | return false; |
7075 | } |
7076 | |
7077 | inline bool Type::isUndeducedType() const { |
7078 | auto *DT = getContainedDeducedType(); |
7079 | return DT && !DT->isDeduced(); |
7080 | } |
7081 | |
7082 | /// Determines whether this is a type for which one can define |
7083 | /// an overloaded operator. |
7084 | inline bool Type::isOverloadableType() const { |
7085 | return isDependentType() || isRecordType() || isEnumeralType(); |
7086 | } |
7087 | |
7088 | /// Determines whether this type is written as a typedef-name. |
7089 | inline bool Type::isTypedefNameType() const { |
7090 | if (getAs<TypedefType>()) |
7091 | return true; |
7092 | if (auto *TST = getAs<TemplateSpecializationType>()) |
7093 | return TST->isTypeAlias(); |
7094 | return false; |
7095 | } |
7096 | |
7097 | /// Determines whether this type can decay to a pointer type. |
7098 | inline bool Type::canDecayToPointerType() const { |
7099 | return isFunctionType() || isArrayType(); |
7100 | } |
7101 | |
7102 | inline bool Type::hasPointerRepresentation() const { |
7103 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
7104 | isObjCObjectPointerType() || isNullPtrType()); |
7105 | } |
7106 | |
7107 | inline bool Type::hasObjCPointerRepresentation() const { |
7108 | return isObjCObjectPointerType(); |
7109 | } |
7110 | |
7111 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
7112 | const Type *type = this; |
7113 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
7114 | type = arrayType->getElementType().getTypePtr(); |
7115 | return type; |
7116 | } |
7117 | |
7118 | inline const Type *Type::getPointeeOrArrayElementType() const { |
7119 | const Type *type = this; |
7120 | if (type->isAnyPointerType()) |
7121 | return type->getPointeeType().getTypePtr(); |
7122 | else if (type->isArrayType()) |
7123 | return type->getBaseElementTypeUnsafe(); |
7124 | return type; |
7125 | } |
7126 | /// Insertion operator for partial diagnostics. This allows sending adress |
7127 | /// spaces into a diagnostic with <<. |
7128 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7129 | LangAS AS) { |
7130 | PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), |
7131 | DiagnosticsEngine::ArgumentKind::ak_addrspace); |
7132 | return PD; |
7133 | } |
7134 | |
7135 | /// Insertion operator for partial diagnostics. This allows sending Qualifiers |
7136 | /// into a diagnostic with <<. |
7137 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7138 | Qualifiers Q) { |
7139 | PD.AddTaggedVal(Q.getAsOpaqueValue(), |
7140 | DiagnosticsEngine::ArgumentKind::ak_qual); |
7141 | return PD; |
7142 | } |
7143 | |
7144 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
7145 | /// into a diagnostic with <<. |
7146 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
7147 | QualType T) { |
7148 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
7149 | DiagnosticsEngine::ak_qualtype); |
7150 | return PD; |
7151 | } |
7152 | |
7153 | // Helper class template that is used by Type::getAs to ensure that one does |
7154 | // not try to look through a qualified type to get to an array type. |
7155 | template <typename T> |
7156 | using TypeIsArrayType = |
7157 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
7158 | std::is_base_of<ArrayType, T>::value>; |
7159 | |
7160 | // Member-template getAs<specific type>'. |
7161 | template <typename T> const T *Type::getAs() const { |
7162 | static_assert(!TypeIsArrayType<T>::value, |
7163 | "ArrayType cannot be used with getAs!"); |
7164 | |
7165 | // If this is directly a T type, return it. |
7166 | if (const auto *Ty = dyn_cast<T>(this)) |
7167 | return Ty; |
7168 | |
7169 | // If the canonical form of this type isn't the right kind, reject it. |
7170 | if (!isa<T>(CanonicalType)) |
7171 | return nullptr; |
7172 | |
7173 | // If this is a typedef for the type, strip the typedef off without |
7174 | // losing all typedef information. |
7175 | return cast<T>(getUnqualifiedDesugaredType()); |
7176 | } |
7177 | |
7178 | template <typename T> const T *Type::getAsAdjusted() const { |
7179 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
7180 | |
7181 | // If this is directly a T type, return it. |
7182 | if (const auto *Ty = dyn_cast<T>(this)) |
7183 | return Ty; |
7184 | |
7185 | // If the canonical form of this type isn't the right kind, reject it. |
7186 | if (!isa<T>(CanonicalType)) |
7187 | return nullptr; |
7188 | |
7189 | // Strip off type adjustments that do not modify the underlying nature of the |
7190 | // type. |
7191 | const Type *Ty = this; |
7192 | while (Ty) { |
7193 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
7194 | Ty = A->getModifiedType().getTypePtr(); |
7195 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
7196 | Ty = E->desugar().getTypePtr(); |
7197 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
7198 | Ty = P->desugar().getTypePtr(); |
7199 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
7200 | Ty = A->desugar().getTypePtr(); |
7201 | else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) |
7202 | Ty = M->desugar().getTypePtr(); |
7203 | else |
7204 | break; |
7205 | } |
7206 | |
7207 | // Just because the canonical type is correct does not mean we can use cast<>, |
7208 | // since we may not have stripped off all the sugar down to the base type. |
7209 | return dyn_cast<T>(Ty); |
7210 | } |
7211 | |
7212 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
7213 | // If this is directly an array type, return it. |
7214 | if (const auto *arr = dyn_cast<ArrayType>(this)) |
7215 | return arr; |
7216 | |
7217 | // If the canonical form of this type isn't the right kind, reject it. |
7218 | if (!isa<ArrayType>(CanonicalType)) |
7219 | return nullptr; |
7220 | |
7221 | // If this is a typedef for the type, strip the typedef off without |
7222 | // losing all typedef information. |
7223 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7224 | } |
7225 | |
7226 | template <typename T> const T *Type::castAs() const { |
7227 | static_assert(!TypeIsArrayType<T>::value, |
7228 | "ArrayType cannot be used with castAs!"); |
7229 | |
7230 | if (const auto *ty = dyn_cast<T>(this)) return ty; |
7231 | assert(isa<T>(CanonicalType))(static_cast <bool> (isa<T>(CanonicalType)) ? void (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 7231, __extension__ __PRETTY_FUNCTION__)); |
7232 | return cast<T>(getUnqualifiedDesugaredType()); |
7233 | } |
7234 | |
7235 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
7236 | assert(isa<ArrayType>(CanonicalType))(static_cast <bool> (isa<ArrayType>(CanonicalType )) ? void (0) : __assert_fail ("isa<ArrayType>(CanonicalType)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 7236, __extension__ __PRETTY_FUNCTION__)); |
7237 | if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; |
7238 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7239 | } |
7240 | |
7241 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
7242 | QualType CanonicalPtr) |
7243 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
7244 | #ifndef NDEBUG |
7245 | QualType Adjusted = getAdjustedType(); |
7246 | (void)AttributedType::stripOuterNullability(Adjusted); |
7247 | assert(isa<PointerType>(Adjusted))(static_cast <bool> (isa<PointerType>(Adjusted)) ? void (0) : __assert_fail ("isa<PointerType>(Adjusted)" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Type.h" , 7247, __extension__ __PRETTY_FUNCTION__)); |
7248 | #endif |
7249 | } |
7250 | |
7251 | QualType DecayedType::getPointeeType() const { |
7252 | QualType Decayed = getDecayedType(); |
7253 | (void)AttributedType::stripOuterNullability(Decayed); |
7254 | return cast<PointerType>(Decayed)->getPointeeType(); |
7255 | } |
7256 | |
7257 | // Get the decimal string representation of a fixed point type, represented |
7258 | // as a scaled integer. |
7259 | // TODO: At some point, we should change the arguments to instead just accept an |
7260 | // APFixedPoint instead of APSInt and scale. |
7261 | void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, |
7262 | unsigned Scale); |
7263 | |
7264 | } // namespace clang |
7265 | |
7266 | #endif // LLVM_CLANG_AST_TYPE_H |