File: | clang/lib/AST/ExprConstant.cpp |
Warning: | line 5968, column 57 Called C++ object pointer is null |
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 ? Frame->Index : 0, Version); | ||||||
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
| ||||||
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
| ||||||
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
| ||||||
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
| ||||||
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
| ||||||
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 = dyn_cast<VarDecl>(E->getMemberDecl())) { | ||||||
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 | //===- Decl.h - Classes for representing declarations -----------*- 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 | // This file defines the Decl subclasses. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_AST_DECL_H |
14 | #define LLVM_CLANG_AST_DECL_H |
15 | |
16 | #include "clang/AST/APValue.h" |
17 | #include "clang/AST/ASTContextAllocate.h" |
18 | #include "clang/AST/DeclAccessPair.h" |
19 | #include "clang/AST/DeclBase.h" |
20 | #include "clang/AST/DeclarationName.h" |
21 | #include "clang/AST/ExternalASTSource.h" |
22 | #include "clang/AST/NestedNameSpecifier.h" |
23 | #include "clang/AST/Redeclarable.h" |
24 | #include "clang/AST/Type.h" |
25 | #include "clang/Basic/AddressSpaces.h" |
26 | #include "clang/Basic/Diagnostic.h" |
27 | #include "clang/Basic/IdentifierTable.h" |
28 | #include "clang/Basic/LLVM.h" |
29 | #include "clang/Basic/Linkage.h" |
30 | #include "clang/Basic/OperatorKinds.h" |
31 | #include "clang/Basic/PartialDiagnostic.h" |
32 | #include "clang/Basic/PragmaKinds.h" |
33 | #include "clang/Basic/SourceLocation.h" |
34 | #include "clang/Basic/Specifiers.h" |
35 | #include "clang/Basic/Visibility.h" |
36 | #include "llvm/ADT/APSInt.h" |
37 | #include "llvm/ADT/ArrayRef.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/iterator_range.h" |
43 | #include "llvm/Support/Casting.h" |
44 | #include "llvm/Support/Compiler.h" |
45 | #include "llvm/Support/TrailingObjects.h" |
46 | #include <cassert> |
47 | #include <cstddef> |
48 | #include <cstdint> |
49 | #include <string> |
50 | #include <utility> |
51 | |
52 | namespace clang { |
53 | |
54 | class ASTContext; |
55 | struct ASTTemplateArgumentListInfo; |
56 | class Attr; |
57 | class CompoundStmt; |
58 | class DependentFunctionTemplateSpecializationInfo; |
59 | class EnumDecl; |
60 | class Expr; |
61 | class FunctionTemplateDecl; |
62 | class FunctionTemplateSpecializationInfo; |
63 | class FunctionTypeLoc; |
64 | class LabelStmt; |
65 | class MemberSpecializationInfo; |
66 | class Module; |
67 | class NamespaceDecl; |
68 | class ParmVarDecl; |
69 | class RecordDecl; |
70 | class Stmt; |
71 | class StringLiteral; |
72 | class TagDecl; |
73 | class TemplateArgumentList; |
74 | class TemplateArgumentListInfo; |
75 | class TemplateParameterList; |
76 | class TypeAliasTemplateDecl; |
77 | class TypeLoc; |
78 | class UnresolvedSetImpl; |
79 | class VarTemplateDecl; |
80 | |
81 | /// The top declaration context. |
82 | class TranslationUnitDecl : public Decl, |
83 | public DeclContext, |
84 | public Redeclarable<TranslationUnitDecl> { |
85 | using redeclarable_base = Redeclarable<TranslationUnitDecl>; |
86 | |
87 | TranslationUnitDecl *getNextRedeclarationImpl() override { |
88 | return getNextRedeclaration(); |
89 | } |
90 | |
91 | TranslationUnitDecl *getPreviousDeclImpl() override { |
92 | return getPreviousDecl(); |
93 | } |
94 | |
95 | TranslationUnitDecl *getMostRecentDeclImpl() override { |
96 | return getMostRecentDecl(); |
97 | } |
98 | |
99 | ASTContext &Ctx; |
100 | |
101 | /// The (most recently entered) anonymous namespace for this |
102 | /// translation unit, if one has been created. |
103 | NamespaceDecl *AnonymousNamespace = nullptr; |
104 | |
105 | explicit TranslationUnitDecl(ASTContext &ctx); |
106 | |
107 | virtual void anchor(); |
108 | |
109 | public: |
110 | using redecl_range = redeclarable_base::redecl_range; |
111 | using redecl_iterator = redeclarable_base::redecl_iterator; |
112 | |
113 | using redeclarable_base::getMostRecentDecl; |
114 | using redeclarable_base::getPreviousDecl; |
115 | using redeclarable_base::isFirstDecl; |
116 | using redeclarable_base::redecls; |
117 | using redeclarable_base::redecls_begin; |
118 | using redeclarable_base::redecls_end; |
119 | |
120 | ASTContext &getASTContext() const { return Ctx; } |
121 | |
122 | NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } |
123 | void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } |
124 | |
125 | static TranslationUnitDecl *Create(ASTContext &C); |
126 | |
127 | // Implement isa/cast/dyncast/etc. |
128 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
129 | static bool classofKind(Kind K) { return K == TranslationUnit; } |
130 | static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { |
131 | return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D)); |
132 | } |
133 | static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { |
134 | return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC)); |
135 | } |
136 | }; |
137 | |
138 | /// Represents a `#pragma comment` line. Always a child of |
139 | /// TranslationUnitDecl. |
140 | class PragmaCommentDecl final |
141 | : public Decl, |
142 | private llvm::TrailingObjects<PragmaCommentDecl, char> { |
143 | friend class ASTDeclReader; |
144 | friend class ASTDeclWriter; |
145 | friend TrailingObjects; |
146 | |
147 | PragmaMSCommentKind CommentKind; |
148 | |
149 | PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc, |
150 | PragmaMSCommentKind CommentKind) |
151 | : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {} |
152 | |
153 | virtual void anchor(); |
154 | |
155 | public: |
156 | static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC, |
157 | SourceLocation CommentLoc, |
158 | PragmaMSCommentKind CommentKind, |
159 | StringRef Arg); |
160 | static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
161 | unsigned ArgSize); |
162 | |
163 | PragmaMSCommentKind getCommentKind() const { return CommentKind; } |
164 | |
165 | StringRef getArg() const { return getTrailingObjects<char>(); } |
166 | |
167 | // Implement isa/cast/dyncast/etc. |
168 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
169 | static bool classofKind(Kind K) { return K == PragmaComment; } |
170 | }; |
171 | |
172 | /// Represents a `#pragma detect_mismatch` line. Always a child of |
173 | /// TranslationUnitDecl. |
174 | class PragmaDetectMismatchDecl final |
175 | : public Decl, |
176 | private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> { |
177 | friend class ASTDeclReader; |
178 | friend class ASTDeclWriter; |
179 | friend TrailingObjects; |
180 | |
181 | size_t ValueStart; |
182 | |
183 | PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc, |
184 | size_t ValueStart) |
185 | : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {} |
186 | |
187 | virtual void anchor(); |
188 | |
189 | public: |
190 | static PragmaDetectMismatchDecl *Create(const ASTContext &C, |
191 | TranslationUnitDecl *DC, |
192 | SourceLocation Loc, StringRef Name, |
193 | StringRef Value); |
194 | static PragmaDetectMismatchDecl * |
195 | CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize); |
196 | |
197 | StringRef getName() const { return getTrailingObjects<char>(); } |
198 | StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; } |
199 | |
200 | // Implement isa/cast/dyncast/etc. |
201 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
202 | static bool classofKind(Kind K) { return K == PragmaDetectMismatch; } |
203 | }; |
204 | |
205 | /// Declaration context for names declared as extern "C" in C++. This |
206 | /// is neither the semantic nor lexical context for such declarations, but is |
207 | /// used to check for conflicts with other extern "C" declarations. Example: |
208 | /// |
209 | /// \code |
210 | /// namespace N { extern "C" void f(); } // #1 |
211 | /// void N::f() {} // #2 |
212 | /// namespace M { extern "C" void f(); } // #3 |
213 | /// \endcode |
214 | /// |
215 | /// The semantic context of #1 is namespace N and its lexical context is the |
216 | /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical |
217 | /// context is the TU. However, both declarations are also visible in the |
218 | /// extern "C" context. |
219 | /// |
220 | /// The declaration at #3 finds it is a redeclaration of \c N::f through |
221 | /// lookup in the extern "C" context. |
222 | class ExternCContextDecl : public Decl, public DeclContext { |
223 | explicit ExternCContextDecl(TranslationUnitDecl *TU) |
224 | : Decl(ExternCContext, TU, SourceLocation()), |
225 | DeclContext(ExternCContext) {} |
226 | |
227 | virtual void anchor(); |
228 | |
229 | public: |
230 | static ExternCContextDecl *Create(const ASTContext &C, |
231 | TranslationUnitDecl *TU); |
232 | |
233 | // Implement isa/cast/dyncast/etc. |
234 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
235 | static bool classofKind(Kind K) { return K == ExternCContext; } |
236 | static DeclContext *castToDeclContext(const ExternCContextDecl *D) { |
237 | return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D)); |
238 | } |
239 | static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) { |
240 | return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC)); |
241 | } |
242 | }; |
243 | |
244 | /// This represents a decl that may have a name. Many decls have names such |
245 | /// as ObjCMethodDecl, but not \@class, etc. |
246 | /// |
247 | /// Note that not every NamedDecl is actually named (e.g., a struct might |
248 | /// be anonymous), and not every name is an identifier. |
249 | class NamedDecl : public Decl { |
250 | /// The name of this declaration, which is typically a normal |
251 | /// identifier but may also be a special kind of name (C++ |
252 | /// constructor, Objective-C selector, etc.) |
253 | DeclarationName Name; |
254 | |
255 | virtual void anchor(); |
256 | |
257 | private: |
258 | NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__)); |
259 | |
260 | protected: |
261 | NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) |
262 | : Decl(DK, DC, L), Name(N) {} |
263 | |
264 | public: |
265 | /// Get the identifier that names this declaration, if there is one. |
266 | /// |
267 | /// This will return NULL if this declaration has no name (e.g., for |
268 | /// an unnamed class) or if the name is a special name (C++ constructor, |
269 | /// Objective-C selector, etc.). |
270 | IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } |
271 | |
272 | /// Get the name of identifier for this declaration as a StringRef. |
273 | /// |
274 | /// This requires that the declaration have a name and that it be a simple |
275 | /// identifier. |
276 | StringRef getName() const { |
277 | assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier" ) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 277, __extension__ __PRETTY_FUNCTION__)); |
278 | return getIdentifier() ? getIdentifier()->getName() : ""; |
279 | } |
280 | |
281 | /// Get a human-readable name for the declaration, even if it is one of the |
282 | /// special kinds of names (C++ constructor, Objective-C selector, etc). |
283 | /// |
284 | /// Creating this name requires expensive string manipulation, so it should |
285 | /// be called only when performance doesn't matter. For simple declarations, |
286 | /// getNameAsCString() should suffice. |
287 | // |
288 | // FIXME: This function should be renamed to indicate that it is not just an |
289 | // alternate form of getName(), and clients should move as appropriate. |
290 | // |
291 | // FIXME: Deprecated, move clients to getName(). |
292 | std::string getNameAsString() const { return Name.getAsString(); } |
293 | |
294 | /// Pretty-print the unqualified name of this declaration. Can be overloaded |
295 | /// by derived classes to provide a more user-friendly name when appropriate. |
296 | virtual void printName(raw_ostream &os) const; |
297 | |
298 | /// Get the actual, stored name of the declaration, which may be a special |
299 | /// name. |
300 | /// |
301 | /// Note that generally in diagnostics, the non-null \p NamedDecl* itself |
302 | /// should be sent into the diagnostic instead of using the result of |
303 | /// \p getDeclName(). |
304 | /// |
305 | /// A \p DeclarationName in a diagnostic will just be streamed to the output, |
306 | /// which will directly result in a call to \p DeclarationName::print. |
307 | /// |
308 | /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to |
309 | /// \p DeclarationName::print, but with two customisation points along the |
310 | /// way (\p getNameForDiagnostic and \p printName). These are used to print |
311 | /// the template arguments if any, and to provide a user-friendly name for |
312 | /// some entities (such as unnamed variables and anonymous records). |
313 | DeclarationName getDeclName() const { return Name; } |
314 | |
315 | /// Set the name of this declaration. |
316 | void setDeclName(DeclarationName N) { Name = N; } |
317 | |
318 | /// Returns a human-readable qualified name for this declaration, like |
319 | /// A::B::i, for i being member of namespace A::B. |
320 | /// |
321 | /// If the declaration is not a member of context which can be named (record, |
322 | /// namespace), it will return the same result as printName(). |
323 | /// |
324 | /// Creating this name is expensive, so it should be called only when |
325 | /// performance doesn't matter. |
326 | void printQualifiedName(raw_ostream &OS) const; |
327 | void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const; |
328 | |
329 | /// Print only the nested name specifier part of a fully-qualified name, |
330 | /// including the '::' at the end. E.g. |
331 | /// when `printQualifiedName(D)` prints "A::B::i", |
332 | /// this function prints "A::B::". |
333 | void printNestedNameSpecifier(raw_ostream &OS) const; |
334 | void printNestedNameSpecifier(raw_ostream &OS, |
335 | const PrintingPolicy &Policy) const; |
336 | |
337 | // FIXME: Remove string version. |
338 | std::string getQualifiedNameAsString() const; |
339 | |
340 | /// Appends a human-readable name for this declaration into the given stream. |
341 | /// |
342 | /// This is the method invoked by Sema when displaying a NamedDecl |
343 | /// in a diagnostic. It does not necessarily produce the same |
344 | /// result as printName(); for example, class template |
345 | /// specializations are printed with their template arguments. |
346 | virtual void getNameForDiagnostic(raw_ostream &OS, |
347 | const PrintingPolicy &Policy, |
348 | bool Qualified) const; |
349 | |
350 | /// Determine whether this declaration, if known to be well-formed within |
351 | /// its context, will replace the declaration OldD if introduced into scope. |
352 | /// |
353 | /// A declaration will replace another declaration if, for example, it is |
354 | /// a redeclaration of the same variable or function, but not if it is a |
355 | /// declaration of a different kind (function vs. class) or an overloaded |
356 | /// function. |
357 | /// |
358 | /// \param IsKnownNewer \c true if this declaration is known to be newer |
359 | /// than \p OldD (for instance, if this declaration is newly-created). |
360 | bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const; |
361 | |
362 | /// Determine whether this declaration has linkage. |
363 | bool hasLinkage() const; |
364 | |
365 | using Decl::isModulePrivate; |
366 | using Decl::setModulePrivate; |
367 | |
368 | /// Determine whether this declaration is a C++ class member. |
369 | bool isCXXClassMember() const { |
370 | const DeclContext *DC = getDeclContext(); |
371 | |
372 | // C++0x [class.mem]p1: |
373 | // The enumerators of an unscoped enumeration defined in |
374 | // the class are members of the class. |
375 | if (isa<EnumDecl>(DC)) |
376 | DC = DC->getRedeclContext(); |
377 | |
378 | return DC->isRecord(); |
379 | } |
380 | |
381 | /// Determine whether the given declaration is an instance member of |
382 | /// a C++ class. |
383 | bool isCXXInstanceMember() const; |
384 | |
385 | /// Determine if the declaration obeys the reserved identifier rules of the |
386 | /// given language. |
387 | ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const; |
388 | |
389 | /// Determine what kind of linkage this entity has. |
390 | /// |
391 | /// This is not the linkage as defined by the standard or the codegen notion |
392 | /// of linkage. It is just an implementation detail that is used to compute |
393 | /// those. |
394 | Linkage getLinkageInternal() const; |
395 | |
396 | /// Get the linkage from a semantic point of view. Entities in |
397 | /// anonymous namespaces are external (in c++98). |
398 | Linkage getFormalLinkage() const { |
399 | return clang::getFormalLinkage(getLinkageInternal()); |
400 | } |
401 | |
402 | /// True if this decl has external linkage. |
403 | bool hasExternalFormalLinkage() const { |
404 | return isExternalFormalLinkage(getLinkageInternal()); |
405 | } |
406 | |
407 | bool isExternallyVisible() const { |
408 | return clang::isExternallyVisible(getLinkageInternal()); |
409 | } |
410 | |
411 | /// Determine whether this declaration can be redeclared in a |
412 | /// different translation unit. |
413 | bool isExternallyDeclarable() const { |
414 | return isExternallyVisible() && !getOwningModuleForLinkage(); |
415 | } |
416 | |
417 | /// Determines the visibility of this entity. |
418 | Visibility getVisibility() const { |
419 | return getLinkageAndVisibility().getVisibility(); |
420 | } |
421 | |
422 | /// Determines the linkage and visibility of this entity. |
423 | LinkageInfo getLinkageAndVisibility() const; |
424 | |
425 | /// Kinds of explicit visibility. |
426 | enum ExplicitVisibilityKind { |
427 | /// Do an LV computation for, ultimately, a type. |
428 | /// Visibility may be restricted by type visibility settings and |
429 | /// the visibility of template arguments. |
430 | VisibilityForType, |
431 | |
432 | /// Do an LV computation for, ultimately, a non-type declaration. |
433 | /// Visibility may be restricted by value visibility settings and |
434 | /// the visibility of template arguments. |
435 | VisibilityForValue |
436 | }; |
437 | |
438 | /// If visibility was explicitly specified for this |
439 | /// declaration, return that visibility. |
440 | Optional<Visibility> |
441 | getExplicitVisibility(ExplicitVisibilityKind kind) const; |
442 | |
443 | /// True if the computed linkage is valid. Used for consistency |
444 | /// checking. Should always return true. |
445 | bool isLinkageValid() const; |
446 | |
447 | /// True if something has required us to compute the linkage |
448 | /// of this declaration. |
449 | /// |
450 | /// Language features which can retroactively change linkage (like a |
451 | /// typedef name for linkage purposes) may need to consider this, |
452 | /// but hopefully only in transitory ways during parsing. |
453 | bool hasLinkageBeenComputed() const { |
454 | return hasCachedLinkage(); |
455 | } |
456 | |
457 | /// Looks through UsingDecls and ObjCCompatibleAliasDecls for |
458 | /// the underlying named decl. |
459 | NamedDecl *getUnderlyingDecl() { |
460 | // Fast-path the common case. |
461 | if (this->getKind() != UsingShadow && |
462 | this->getKind() != ConstructorUsingShadow && |
463 | this->getKind() != ObjCCompatibleAlias && |
464 | this->getKind() != NamespaceAlias) |
465 | return this; |
466 | |
467 | return getUnderlyingDeclImpl(); |
468 | } |
469 | const NamedDecl *getUnderlyingDecl() const { |
470 | return const_cast<NamedDecl*>(this)->getUnderlyingDecl(); |
471 | } |
472 | |
473 | NamedDecl *getMostRecentDecl() { |
474 | return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl()); |
475 | } |
476 | const NamedDecl *getMostRecentDecl() const { |
477 | return const_cast<NamedDecl*>(this)->getMostRecentDecl(); |
478 | } |
479 | |
480 | ObjCStringFormatFamily getObjCFStringFormattingFamily() const; |
481 | |
482 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
483 | static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } |
484 | }; |
485 | |
486 | inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) { |
487 | ND.printName(OS); |
488 | return OS; |
489 | } |
490 | |
491 | /// Represents the declaration of a label. Labels also have a |
492 | /// corresponding LabelStmt, which indicates the position that the label was |
493 | /// defined at. For normal labels, the location of the decl is the same as the |
494 | /// location of the statement. For GNU local labels (__label__), the decl |
495 | /// location is where the __label__ is. |
496 | class LabelDecl : public NamedDecl { |
497 | LabelStmt *TheStmt; |
498 | StringRef MSAsmName; |
499 | bool MSAsmNameResolved = false; |
500 | |
501 | /// For normal labels, this is the same as the main declaration |
502 | /// label, i.e., the location of the identifier; for GNU local labels, |
503 | /// this is the location of the __label__ keyword. |
504 | SourceLocation LocStart; |
505 | |
506 | LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, |
507 | LabelStmt *S, SourceLocation StartL) |
508 | : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} |
509 | |
510 | void anchor() override; |
511 | |
512 | public: |
513 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
514 | SourceLocation IdentL, IdentifierInfo *II); |
515 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
516 | SourceLocation IdentL, IdentifierInfo *II, |
517 | SourceLocation GnuLabelL); |
518 | static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
519 | |
520 | LabelStmt *getStmt() const { return TheStmt; } |
521 | void setStmt(LabelStmt *T) { TheStmt = T; } |
522 | |
523 | bool isGnuLocal() const { return LocStart != getLocation(); } |
524 | void setLocStart(SourceLocation L) { LocStart = L; } |
525 | |
526 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
527 | return SourceRange(LocStart, getLocation()); |
528 | } |
529 | |
530 | bool isMSAsmLabel() const { return !MSAsmName.empty(); } |
531 | bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; } |
532 | void setMSAsmLabel(StringRef Name); |
533 | StringRef getMSAsmLabel() const { return MSAsmName; } |
534 | void setMSAsmLabelResolved() { MSAsmNameResolved = true; } |
535 | |
536 | // Implement isa/cast/dyncast/etc. |
537 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
538 | static bool classofKind(Kind K) { return K == Label; } |
539 | }; |
540 | |
541 | /// Represent a C++ namespace. |
542 | class NamespaceDecl : public NamedDecl, public DeclContext, |
543 | public Redeclarable<NamespaceDecl> |
544 | { |
545 | /// The starting location of the source range, pointing |
546 | /// to either the namespace or the inline keyword. |
547 | SourceLocation LocStart; |
548 | |
549 | /// The ending location of the source range. |
550 | SourceLocation RBraceLoc; |
551 | |
552 | /// A pointer to either the anonymous namespace that lives just inside |
553 | /// this namespace or to the first namespace in the chain (the latter case |
554 | /// only when this is not the first in the chain), along with a |
555 | /// boolean value indicating whether this is an inline namespace. |
556 | llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline; |
557 | |
558 | NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, |
559 | SourceLocation StartLoc, SourceLocation IdLoc, |
560 | IdentifierInfo *Id, NamespaceDecl *PrevDecl); |
561 | |
562 | using redeclarable_base = Redeclarable<NamespaceDecl>; |
563 | |
564 | NamespaceDecl *getNextRedeclarationImpl() override; |
565 | NamespaceDecl *getPreviousDeclImpl() override; |
566 | NamespaceDecl *getMostRecentDeclImpl() override; |
567 | |
568 | public: |
569 | friend class ASTDeclReader; |
570 | friend class ASTDeclWriter; |
571 | |
572 | static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, |
573 | bool Inline, SourceLocation StartLoc, |
574 | SourceLocation IdLoc, IdentifierInfo *Id, |
575 | NamespaceDecl *PrevDecl); |
576 | |
577 | static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
578 | |
579 | using redecl_range = redeclarable_base::redecl_range; |
580 | using redecl_iterator = redeclarable_base::redecl_iterator; |
581 | |
582 | using redeclarable_base::redecls_begin; |
583 | using redeclarable_base::redecls_end; |
584 | using redeclarable_base::redecls; |
585 | using redeclarable_base::getPreviousDecl; |
586 | using redeclarable_base::getMostRecentDecl; |
587 | using redeclarable_base::isFirstDecl; |
588 | |
589 | /// Returns true if this is an anonymous namespace declaration. |
590 | /// |
591 | /// For example: |
592 | /// \code |
593 | /// namespace { |
594 | /// ... |
595 | /// }; |
596 | /// \endcode |
597 | /// q.v. C++ [namespace.unnamed] |
598 | bool isAnonymousNamespace() const { |
599 | return !getIdentifier(); |
600 | } |
601 | |
602 | /// Returns true if this is an inline namespace declaration. |
603 | bool isInline() const { |
604 | return AnonOrFirstNamespaceAndInline.getInt(); |
605 | } |
606 | |
607 | /// Set whether this is an inline namespace declaration. |
608 | void setInline(bool Inline) { |
609 | AnonOrFirstNamespaceAndInline.setInt(Inline); |
610 | } |
611 | |
612 | /// Returns true if the inline qualifier for \c Name is redundant. |
613 | bool isRedundantInlineQualifierFor(DeclarationName Name) const { |
614 | if (!isInline()) |
615 | return false; |
616 | auto X = lookup(Name); |
617 | // We should not perform a lookup within a transparent context, so find a |
618 | // non-transparent parent context. |
619 | auto Y = getParent()->getNonTransparentContext()->lookup(Name); |
620 | return std::distance(X.begin(), X.end()) == |
621 | std::distance(Y.begin(), Y.end()); |
622 | } |
623 | |
624 | /// Get the original (first) namespace declaration. |
625 | NamespaceDecl *getOriginalNamespace(); |
626 | |
627 | /// Get the original (first) namespace declaration. |
628 | const NamespaceDecl *getOriginalNamespace() const; |
629 | |
630 | /// Return true if this declaration is an original (first) declaration |
631 | /// of the namespace. This is false for non-original (subsequent) namespace |
632 | /// declarations and anonymous namespaces. |
633 | bool isOriginalNamespace() const; |
634 | |
635 | /// Retrieve the anonymous namespace nested inside this namespace, |
636 | /// if any. |
637 | NamespaceDecl *getAnonymousNamespace() const { |
638 | return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer(); |
639 | } |
640 | |
641 | void setAnonymousNamespace(NamespaceDecl *D) { |
642 | getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D); |
643 | } |
644 | |
645 | /// Retrieves the canonical declaration of this namespace. |
646 | NamespaceDecl *getCanonicalDecl() override { |
647 | return getOriginalNamespace(); |
648 | } |
649 | const NamespaceDecl *getCanonicalDecl() const { |
650 | return getOriginalNamespace(); |
651 | } |
652 | |
653 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
654 | return SourceRange(LocStart, RBraceLoc); |
655 | } |
656 | |
657 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
658 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
659 | void setLocStart(SourceLocation L) { LocStart = L; } |
660 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
661 | |
662 | // Implement isa/cast/dyncast/etc. |
663 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
664 | static bool classofKind(Kind K) { return K == Namespace; } |
665 | static DeclContext *castToDeclContext(const NamespaceDecl *D) { |
666 | return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D)); |
667 | } |
668 | static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { |
669 | return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC)); |
670 | } |
671 | }; |
672 | |
673 | /// Represent the declaration of a variable (in which case it is |
674 | /// an lvalue) a function (in which case it is a function designator) or |
675 | /// an enum constant. |
676 | class ValueDecl : public NamedDecl { |
677 | QualType DeclType; |
678 | |
679 | void anchor() override; |
680 | |
681 | protected: |
682 | ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, |
683 | DeclarationName N, QualType T) |
684 | : NamedDecl(DK, DC, L, N), DeclType(T) {} |
685 | |
686 | public: |
687 | QualType getType() const { return DeclType; } |
688 | void setType(QualType newType) { DeclType = newType; } |
689 | |
690 | /// Determine whether this symbol is weakly-imported, |
691 | /// or declared with the weak or weak-ref attr. |
692 | bool isWeak() const; |
693 | |
694 | // Implement isa/cast/dyncast/etc. |
695 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
696 | static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } |
697 | }; |
698 | |
699 | /// A struct with extended info about a syntactic |
700 | /// name qualifier, to be used for the case of out-of-line declarations. |
701 | struct QualifierInfo { |
702 | NestedNameSpecifierLoc QualifierLoc; |
703 | |
704 | /// The number of "outer" template parameter lists. |
705 | /// The count includes all of the template parameter lists that were matched |
706 | /// against the template-ids occurring into the NNS and possibly (in the |
707 | /// case of an explicit specialization) a final "template <>". |
708 | unsigned NumTemplParamLists = 0; |
709 | |
710 | /// A new-allocated array of size NumTemplParamLists, |
711 | /// containing pointers to the "outer" template parameter lists. |
712 | /// It includes all of the template parameter lists that were matched |
713 | /// against the template-ids occurring into the NNS and possibly (in the |
714 | /// case of an explicit specialization) a final "template <>". |
715 | TemplateParameterList** TemplParamLists = nullptr; |
716 | |
717 | QualifierInfo() = default; |
718 | QualifierInfo(const QualifierInfo &) = delete; |
719 | QualifierInfo& operator=(const QualifierInfo &) = delete; |
720 | |
721 | /// Sets info about "outer" template parameter lists. |
722 | void setTemplateParameterListsInfo(ASTContext &Context, |
723 | ArrayRef<TemplateParameterList *> TPLists); |
724 | }; |
725 | |
726 | /// Represents a ValueDecl that came out of a declarator. |
727 | /// Contains type source information through TypeSourceInfo. |
728 | class DeclaratorDecl : public ValueDecl { |
729 | // A struct representing a TInfo, a trailing requires-clause and a syntactic |
730 | // qualifier, to be used for the (uncommon) case of out-of-line declarations |
731 | // and constrained function decls. |
732 | struct ExtInfo : public QualifierInfo { |
733 | TypeSourceInfo *TInfo; |
734 | Expr *TrailingRequiresClause = nullptr; |
735 | }; |
736 | |
737 | llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo; |
738 | |
739 | /// The start of the source range for this declaration, |
740 | /// ignoring outer template declarations. |
741 | SourceLocation InnerLocStart; |
742 | |
743 | bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); } |
744 | ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); } |
745 | const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); } |
746 | |
747 | protected: |
748 | DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, |
749 | DeclarationName N, QualType T, TypeSourceInfo *TInfo, |
750 | SourceLocation StartL) |
751 | : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {} |
752 | |
753 | public: |
754 | friend class ASTDeclReader; |
755 | friend class ASTDeclWriter; |
756 | |
757 | TypeSourceInfo *getTypeSourceInfo() const { |
758 | return hasExtInfo() |
759 | ? getExtInfo()->TInfo |
760 | : DeclInfo.get<TypeSourceInfo*>(); |
761 | } |
762 | |
763 | void setTypeSourceInfo(TypeSourceInfo *TI) { |
764 | if (hasExtInfo()) |
765 | getExtInfo()->TInfo = TI; |
766 | else |
767 | DeclInfo = TI; |
768 | } |
769 | |
770 | /// Return start of source range ignoring outer template declarations. |
771 | SourceLocation getInnerLocStart() const { return InnerLocStart; } |
772 | void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } |
773 | |
774 | /// Return start of source range taking into account any outer template |
775 | /// declarations. |
776 | SourceLocation getOuterLocStart() const; |
777 | |
778 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
779 | |
780 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
781 | return getOuterLocStart(); |
782 | } |
783 | |
784 | /// Retrieve the nested-name-specifier that qualifies the name of this |
785 | /// declaration, if it was present in the source. |
786 | NestedNameSpecifier *getQualifier() const { |
787 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
788 | : nullptr; |
789 | } |
790 | |
791 | /// Retrieve the nested-name-specifier (with source-location |
792 | /// information) that qualifies the name of this declaration, if it was |
793 | /// present in the source. |
794 | NestedNameSpecifierLoc getQualifierLoc() const { |
795 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
796 | : NestedNameSpecifierLoc(); |
797 | } |
798 | |
799 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
800 | |
801 | /// \brief Get the constraint-expression introduced by the trailing |
802 | /// requires-clause in the function/member declaration, or null if no |
803 | /// requires-clause was provided. |
804 | Expr *getTrailingRequiresClause() { |
805 | return hasExtInfo() ? getExtInfo()->TrailingRequiresClause |
806 | : nullptr; |
807 | } |
808 | |
809 | const Expr *getTrailingRequiresClause() const { |
810 | return hasExtInfo() ? getExtInfo()->TrailingRequiresClause |
811 | : nullptr; |
812 | } |
813 | |
814 | void setTrailingRequiresClause(Expr *TrailingRequiresClause); |
815 | |
816 | unsigned getNumTemplateParameterLists() const { |
817 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
818 | } |
819 | |
820 | TemplateParameterList *getTemplateParameterList(unsigned index) const { |
821 | assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists ()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 821, __extension__ __PRETTY_FUNCTION__)); |
822 | return getExtInfo()->TemplParamLists[index]; |
823 | } |
824 | |
825 | void setTemplateParameterListsInfo(ASTContext &Context, |
826 | ArrayRef<TemplateParameterList *> TPLists); |
827 | |
828 | SourceLocation getTypeSpecStartLoc() const; |
829 | SourceLocation getTypeSpecEndLoc() const; |
830 | |
831 | // Implement isa/cast/dyncast/etc. |
832 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
833 | static bool classofKind(Kind K) { |
834 | return K >= firstDeclarator && K <= lastDeclarator; |
835 | } |
836 | }; |
837 | |
838 | /// Structure used to store a statement, the constant value to |
839 | /// which it was evaluated (if any), and whether or not the statement |
840 | /// is an integral constant expression (if known). |
841 | struct EvaluatedStmt { |
842 | /// Whether this statement was already evaluated. |
843 | bool WasEvaluated : 1; |
844 | |
845 | /// Whether this statement is being evaluated. |
846 | bool IsEvaluating : 1; |
847 | |
848 | /// Whether this variable is known to have constant initialization. This is |
849 | /// currently only computed in C++, for static / thread storage duration |
850 | /// variables that might have constant initialization and for variables that |
851 | /// are usable in constant expressions. |
852 | bool HasConstantInitialization : 1; |
853 | |
854 | /// Whether this variable is known to have constant destruction. That is, |
855 | /// whether running the destructor on the initial value is a side-effect |
856 | /// (and doesn't inspect any state that might have changed during program |
857 | /// execution). This is currently only computed if the destructor is |
858 | /// non-trivial. |
859 | bool HasConstantDestruction : 1; |
860 | |
861 | /// In C++98, whether the initializer is an ICE. This affects whether the |
862 | /// variable is usable in constant expressions. |
863 | bool HasICEInit : 1; |
864 | bool CheckedForICEInit : 1; |
865 | |
866 | Stmt *Value; |
867 | APValue Evaluated; |
868 | |
869 | EvaluatedStmt() |
870 | : WasEvaluated(false), IsEvaluating(false), |
871 | HasConstantInitialization(false), HasConstantDestruction(false), |
872 | HasICEInit(false), CheckedForICEInit(false) {} |
873 | }; |
874 | |
875 | /// Represents a variable declaration or definition. |
876 | class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> { |
877 | public: |
878 | /// Initialization styles. |
879 | enum InitializationStyle { |
880 | /// C-style initialization with assignment |
881 | CInit, |
882 | |
883 | /// Call-style initialization (C++98) |
884 | CallInit, |
885 | |
886 | /// Direct list-initialization (C++11) |
887 | ListInit |
888 | }; |
889 | |
890 | /// Kinds of thread-local storage. |
891 | enum TLSKind { |
892 | /// Not a TLS variable. |
893 | TLS_None, |
894 | |
895 | /// TLS with a known-constant initializer. |
896 | TLS_Static, |
897 | |
898 | /// TLS with a dynamic initializer. |
899 | TLS_Dynamic |
900 | }; |
901 | |
902 | /// Return the string used to specify the storage class \p SC. |
903 | /// |
904 | /// It is illegal to call this function with SC == None. |
905 | static const char *getStorageClassSpecifierString(StorageClass SC); |
906 | |
907 | protected: |
908 | // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we |
909 | // have allocated the auxiliary struct of information there. |
910 | // |
911 | // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for |
912 | // this as *many* VarDecls are ParmVarDecls that don't have default |
913 | // arguments. We could save some space by moving this pointer union to be |
914 | // allocated in trailing space when necessary. |
915 | using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>; |
916 | |
917 | /// The initializer for this variable or, for a ParmVarDecl, the |
918 | /// C++ default argument. |
919 | mutable InitType Init; |
920 | |
921 | private: |
922 | friend class ASTDeclReader; |
923 | friend class ASTNodeImporter; |
924 | friend class StmtIteratorBase; |
925 | |
926 | class VarDeclBitfields { |
927 | friend class ASTDeclReader; |
928 | friend class VarDecl; |
929 | |
930 | unsigned SClass : 3; |
931 | unsigned TSCSpec : 2; |
932 | unsigned InitStyle : 2; |
933 | |
934 | /// Whether this variable is an ARC pseudo-__strong variable; see |
935 | /// isARCPseudoStrong() for details. |
936 | unsigned ARCPseudoStrong : 1; |
937 | }; |
938 | enum { NumVarDeclBits = 8 }; |
939 | |
940 | protected: |
941 | enum { NumParameterIndexBits = 8 }; |
942 | |
943 | enum DefaultArgKind { |
944 | DAK_None, |
945 | DAK_Unparsed, |
946 | DAK_Uninstantiated, |
947 | DAK_Normal |
948 | }; |
949 | |
950 | enum { NumScopeDepthOrObjCQualsBits = 7 }; |
951 | |
952 | class ParmVarDeclBitfields { |
953 | friend class ASTDeclReader; |
954 | friend class ParmVarDecl; |
955 | |
956 | unsigned : NumVarDeclBits; |
957 | |
958 | /// Whether this parameter inherits a default argument from a |
959 | /// prior declaration. |
960 | unsigned HasInheritedDefaultArg : 1; |
961 | |
962 | /// Describes the kind of default argument for this parameter. By default |
963 | /// this is none. If this is normal, then the default argument is stored in |
964 | /// the \c VarDecl initializer expression unless we were unable to parse |
965 | /// (even an invalid) expression for the default argument. |
966 | unsigned DefaultArgKind : 2; |
967 | |
968 | /// Whether this parameter undergoes K&R argument promotion. |
969 | unsigned IsKNRPromoted : 1; |
970 | |
971 | /// Whether this parameter is an ObjC method parameter or not. |
972 | unsigned IsObjCMethodParam : 1; |
973 | |
974 | /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier. |
975 | /// Otherwise, the number of function parameter scopes enclosing |
976 | /// the function parameter scope in which this parameter was |
977 | /// declared. |
978 | unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits; |
979 | |
980 | /// The number of parameters preceding this parameter in the |
981 | /// function parameter scope in which it was declared. |
982 | unsigned ParameterIndex : NumParameterIndexBits; |
983 | }; |
984 | |
985 | class NonParmVarDeclBitfields { |
986 | friend class ASTDeclReader; |
987 | friend class ImplicitParamDecl; |
988 | friend class VarDecl; |
989 | |
990 | unsigned : NumVarDeclBits; |
991 | |
992 | // FIXME: We need something similar to CXXRecordDecl::DefinitionData. |
993 | /// Whether this variable is a definition which was demoted due to |
994 | /// module merge. |
995 | unsigned IsThisDeclarationADemotedDefinition : 1; |
996 | |
997 | /// Whether this variable is the exception variable in a C++ catch |
998 | /// or an Objective-C @catch statement. |
999 | unsigned ExceptionVar : 1; |
1000 | |
1001 | /// Whether this local variable could be allocated in the return |
1002 | /// slot of its function, enabling the named return value optimization |
1003 | /// (NRVO). |
1004 | unsigned NRVOVariable : 1; |
1005 | |
1006 | /// Whether this variable is the for-range-declaration in a C++0x |
1007 | /// for-range statement. |
1008 | unsigned CXXForRangeDecl : 1; |
1009 | |
1010 | /// Whether this variable is the for-in loop declaration in Objective-C. |
1011 | unsigned ObjCForDecl : 1; |
1012 | |
1013 | /// Whether this variable is (C++1z) inline. |
1014 | unsigned IsInline : 1; |
1015 | |
1016 | /// Whether this variable has (C++1z) inline explicitly specified. |
1017 | unsigned IsInlineSpecified : 1; |
1018 | |
1019 | /// Whether this variable is (C++0x) constexpr. |
1020 | unsigned IsConstexpr : 1; |
1021 | |
1022 | /// Whether this variable is the implicit variable for a lambda |
1023 | /// init-capture. |
1024 | unsigned IsInitCapture : 1; |
1025 | |
1026 | /// Whether this local extern variable's previous declaration was |
1027 | /// declared in the same block scope. This controls whether we should merge |
1028 | /// the type of this declaration with its previous declaration. |
1029 | unsigned PreviousDeclInSameBlockScope : 1; |
1030 | |
1031 | /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or |
1032 | /// something else. |
1033 | unsigned ImplicitParamKind : 3; |
1034 | |
1035 | unsigned EscapingByref : 1; |
1036 | }; |
1037 | |
1038 | union { |
1039 | unsigned AllBits; |
1040 | VarDeclBitfields VarDeclBits; |
1041 | ParmVarDeclBitfields ParmVarDeclBits; |
1042 | NonParmVarDeclBitfields NonParmVarDeclBits; |
1043 | }; |
1044 | |
1045 | VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1046 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
1047 | TypeSourceInfo *TInfo, StorageClass SC); |
1048 | |
1049 | using redeclarable_base = Redeclarable<VarDecl>; |
1050 | |
1051 | VarDecl *getNextRedeclarationImpl() override { |
1052 | return getNextRedeclaration(); |
1053 | } |
1054 | |
1055 | VarDecl *getPreviousDeclImpl() override { |
1056 | return getPreviousDecl(); |
1057 | } |
1058 | |
1059 | VarDecl *getMostRecentDeclImpl() override { |
1060 | return getMostRecentDecl(); |
1061 | } |
1062 | |
1063 | public: |
1064 | using redecl_range = redeclarable_base::redecl_range; |
1065 | using redecl_iterator = redeclarable_base::redecl_iterator; |
1066 | |
1067 | using redeclarable_base::redecls_begin; |
1068 | using redeclarable_base::redecls_end; |
1069 | using redeclarable_base::redecls; |
1070 | using redeclarable_base::getPreviousDecl; |
1071 | using redeclarable_base::getMostRecentDecl; |
1072 | using redeclarable_base::isFirstDecl; |
1073 | |
1074 | static VarDecl *Create(ASTContext &C, DeclContext *DC, |
1075 | SourceLocation StartLoc, SourceLocation IdLoc, |
1076 | IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, |
1077 | StorageClass S); |
1078 | |
1079 | static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1080 | |
1081 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1082 | |
1083 | /// Returns the storage class as written in the source. For the |
1084 | /// computed linkage of symbol, see getLinkage. |
1085 | StorageClass getStorageClass() const { |
1086 | return (StorageClass) VarDeclBits.SClass; |
1087 | } |
1088 | void setStorageClass(StorageClass SC); |
1089 | |
1090 | void setTSCSpec(ThreadStorageClassSpecifier TSC) { |
1091 | VarDeclBits.TSCSpec = TSC; |
1092 | assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC && "truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1092, __extension__ __PRETTY_FUNCTION__)); |
1093 | } |
1094 | ThreadStorageClassSpecifier getTSCSpec() const { |
1095 | return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec); |
1096 | } |
1097 | TLSKind getTLSKind() const; |
1098 | |
1099 | /// Returns true if a variable with function scope is a non-static local |
1100 | /// variable. |
1101 | bool hasLocalStorage() const { |
1102 | if (getStorageClass() == SC_None) { |
1103 | // OpenCL v1.2 s6.5.3: The __constant or constant address space name is |
1104 | // used to describe variables allocated in global memory and which are |
1105 | // accessed inside a kernel(s) as read-only variables. As such, variables |
1106 | // in constant address space cannot have local storage. |
1107 | if (getType().getAddressSpace() == LangAS::opencl_constant) |
1108 | return false; |
1109 | // Second check is for C++11 [dcl.stc]p4. |
1110 | return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified; |
1111 | } |
1112 | |
1113 | // Global Named Register (GNU extension) |
1114 | if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm()) |
1115 | return false; |
1116 | |
1117 | // Return true for: Auto, Register. |
1118 | // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal. |
1119 | |
1120 | return getStorageClass() >= SC_Auto; |
1121 | } |
1122 | |
1123 | /// Returns true if a variable with function scope is a static local |
1124 | /// variable. |
1125 | bool isStaticLocal() const { |
1126 | return (getStorageClass() == SC_Static || |
1127 | // C++11 [dcl.stc]p4 |
1128 | (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local)) |
1129 | && !isFileVarDecl(); |
1130 | } |
1131 | |
1132 | /// Returns true if a variable has extern or __private_extern__ |
1133 | /// storage. |
1134 | bool hasExternalStorage() const { |
1135 | return getStorageClass() == SC_Extern || |
1136 | getStorageClass() == SC_PrivateExtern; |
1137 | } |
1138 | |
1139 | /// Returns true for all variables that do not have local storage. |
1140 | /// |
1141 | /// This includes all global variables as well as static variables declared |
1142 | /// within a function. |
1143 | bool hasGlobalStorage() const { return !hasLocalStorage(); } |
1144 | |
1145 | /// Get the storage duration of this variable, per C++ [basic.stc]. |
1146 | StorageDuration getStorageDuration() const { |
1147 | return hasLocalStorage() ? SD_Automatic : |
1148 | getTSCSpec() ? SD_Thread : SD_Static; |
1149 | } |
1150 | |
1151 | /// Compute the language linkage. |
1152 | LanguageLinkage getLanguageLinkage() const; |
1153 | |
1154 | /// Determines whether this variable is a variable with external, C linkage. |
1155 | bool isExternC() const; |
1156 | |
1157 | /// Determines whether this variable's context is, or is nested within, |
1158 | /// a C++ extern "C" linkage spec. |
1159 | bool isInExternCContext() const; |
1160 | |
1161 | /// Determines whether this variable's context is, or is nested within, |
1162 | /// a C++ extern "C++" linkage spec. |
1163 | bool isInExternCXXContext() const; |
1164 | |
1165 | /// Returns true for local variable declarations other than parameters. |
1166 | /// Note that this includes static variables inside of functions. It also |
1167 | /// includes variables inside blocks. |
1168 | /// |
1169 | /// void foo() { int x; static int y; extern int z; } |
1170 | bool isLocalVarDecl() const { |
1171 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1172 | return false; |
1173 | if (const DeclContext *DC = getLexicalDeclContext()) |
1174 | return DC->getRedeclContext()->isFunctionOrMethod(); |
1175 | return false; |
1176 | } |
1177 | |
1178 | /// Similar to isLocalVarDecl but also includes parameters. |
1179 | bool isLocalVarDeclOrParm() const { |
1180 | return isLocalVarDecl() || getKind() == Decl::ParmVar; |
1181 | } |
1182 | |
1183 | /// Similar to isLocalVarDecl, but excludes variables declared in blocks. |
1184 | bool isFunctionOrMethodVarDecl() const { |
1185 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1186 | return false; |
1187 | const DeclContext *DC = getLexicalDeclContext()->getRedeclContext(); |
1188 | return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; |
1189 | } |
1190 | |
1191 | /// Determines whether this is a static data member. |
1192 | /// |
1193 | /// This will only be true in C++, and applies to, e.g., the |
1194 | /// variable 'x' in: |
1195 | /// \code |
1196 | /// struct S { |
1197 | /// static int x; |
1198 | /// }; |
1199 | /// \endcode |
1200 | bool isStaticDataMember() const { |
1201 | // If it wasn't static, it would be a FieldDecl. |
1202 | return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); |
1203 | } |
1204 | |
1205 | VarDecl *getCanonicalDecl() override; |
1206 | const VarDecl *getCanonicalDecl() const { |
1207 | return const_cast<VarDecl*>(this)->getCanonicalDecl(); |
1208 | } |
1209 | |
1210 | enum DefinitionKind { |
1211 | /// This declaration is only a declaration. |
1212 | DeclarationOnly, |
1213 | |
1214 | /// This declaration is a tentative definition. |
1215 | TentativeDefinition, |
1216 | |
1217 | /// This declaration is definitely a definition. |
1218 | Definition |
1219 | }; |
1220 | |
1221 | /// Check whether this declaration is a definition. If this could be |
1222 | /// a tentative definition (in C), don't check whether there's an overriding |
1223 | /// definition. |
1224 | DefinitionKind isThisDeclarationADefinition(ASTContext &) const; |
1225 | DefinitionKind isThisDeclarationADefinition() const { |
1226 | return isThisDeclarationADefinition(getASTContext()); |
1227 | } |
1228 | |
1229 | /// Check whether this variable is defined in this translation unit. |
1230 | DefinitionKind hasDefinition(ASTContext &) const; |
1231 | DefinitionKind hasDefinition() const { |
1232 | return hasDefinition(getASTContext()); |
1233 | } |
1234 | |
1235 | /// Get the tentative definition that acts as the real definition in a TU. |
1236 | /// Returns null if there is a proper definition available. |
1237 | VarDecl *getActingDefinition(); |
1238 | const VarDecl *getActingDefinition() const { |
1239 | return const_cast<VarDecl*>(this)->getActingDefinition(); |
1240 | } |
1241 | |
1242 | /// Get the real (not just tentative) definition for this declaration. |
1243 | VarDecl *getDefinition(ASTContext &); |
1244 | const VarDecl *getDefinition(ASTContext &C) const { |
1245 | return const_cast<VarDecl*>(this)->getDefinition(C); |
1246 | } |
1247 | VarDecl *getDefinition() { |
1248 | return getDefinition(getASTContext()); |
1249 | } |
1250 | const VarDecl *getDefinition() const { |
1251 | return const_cast<VarDecl*>(this)->getDefinition(); |
1252 | } |
1253 | |
1254 | /// Determine whether this is or was instantiated from an out-of-line |
1255 | /// definition of a static data member. |
1256 | bool isOutOfLine() const override; |
1257 | |
1258 | /// Returns true for file scoped variable declaration. |
1259 | bool isFileVarDecl() const { |
1260 | Kind K = getKind(); |
1261 | if (K == ParmVar || K == ImplicitParam) |
1262 | return false; |
1263 | |
1264 | if (getLexicalDeclContext()->getRedeclContext()->isFileContext()) |
1265 | return true; |
1266 | |
1267 | if (isStaticDataMember()) |
1268 | return true; |
1269 | |
1270 | return false; |
1271 | } |
1272 | |
1273 | /// Get the initializer for this variable, no matter which |
1274 | /// declaration it is attached to. |
1275 | const Expr *getAnyInitializer() const { |
1276 | const VarDecl *D; |
1277 | return getAnyInitializer(D); |
1278 | } |
1279 | |
1280 | /// Get the initializer for this variable, no matter which |
1281 | /// declaration it is attached to. Also get that declaration. |
1282 | const Expr *getAnyInitializer(const VarDecl *&D) const; |
1283 | |
1284 | bool hasInit() const; |
1285 | const Expr *getInit() const { |
1286 | return const_cast<VarDecl *>(this)->getInit(); |
1287 | } |
1288 | Expr *getInit(); |
1289 | |
1290 | /// Retrieve the address of the initializer expression. |
1291 | Stmt **getInitAddress(); |
1292 | |
1293 | void setInit(Expr *I); |
1294 | |
1295 | /// Get the initializing declaration of this variable, if any. This is |
1296 | /// usually the definition, except that for a static data member it can be |
1297 | /// the in-class declaration. |
1298 | VarDecl *getInitializingDeclaration(); |
1299 | const VarDecl *getInitializingDeclaration() const { |
1300 | return const_cast<VarDecl *>(this)->getInitializingDeclaration(); |
1301 | } |
1302 | |
1303 | /// Determine whether this variable's value might be usable in a |
1304 | /// constant expression, according to the relevant language standard. |
1305 | /// This only checks properties of the declaration, and does not check |
1306 | /// whether the initializer is in fact a constant expression. |
1307 | /// |
1308 | /// This corresponds to C++20 [expr.const]p3's notion of a |
1309 | /// "potentially-constant" variable. |
1310 | bool mightBeUsableInConstantExpressions(const ASTContext &C) const; |
1311 | |
1312 | /// Determine whether this variable's value can be used in a |
1313 | /// constant expression, according to the relevant language standard, |
1314 | /// including checking whether it was initialized by a constant expression. |
1315 | bool isUsableInConstantExpressions(const ASTContext &C) const; |
1316 | |
1317 | EvaluatedStmt *ensureEvaluatedStmt() const; |
1318 | EvaluatedStmt *getEvaluatedStmt() const; |
1319 | |
1320 | /// Attempt to evaluate the value of the initializer attached to this |
1321 | /// declaration, and produce notes explaining why it cannot be evaluated. |
1322 | /// Returns a pointer to the value if evaluation succeeded, 0 otherwise. |
1323 | APValue *evaluateValue() const; |
1324 | |
1325 | private: |
1326 | APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes, |
1327 | bool IsConstantInitialization) const; |
1328 | |
1329 | public: |
1330 | /// Return the already-evaluated value of this variable's |
1331 | /// initializer, or NULL if the value is not yet known. Returns pointer |
1332 | /// to untyped APValue if the value could not be evaluated. |
1333 | APValue *getEvaluatedValue() const; |
1334 | |
1335 | /// Evaluate the destruction of this variable to determine if it constitutes |
1336 | /// constant destruction. |
1337 | /// |
1338 | /// \pre hasConstantInitialization() |
1339 | /// \return \c true if this variable has constant destruction, \c false if |
1340 | /// not. |
1341 | bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
1342 | |
1343 | /// Determine whether this variable has constant initialization. |
1344 | /// |
1345 | /// This is only set in two cases: when the language semantics require |
1346 | /// constant initialization (globals in C and some globals in C++), and when |
1347 | /// the variable is usable in constant expressions (constexpr, const int, and |
1348 | /// reference variables in C++). |
1349 | bool hasConstantInitialization() const; |
1350 | |
1351 | /// Determine whether the initializer of this variable is an integer constant |
1352 | /// expression. For use in C++98, where this affects whether the variable is |
1353 | /// usable in constant expressions. |
1354 | bool hasICEInitializer(const ASTContext &Context) const; |
1355 | |
1356 | /// Evaluate the initializer of this variable to determine whether it's a |
1357 | /// constant initializer. Should only be called once, after completing the |
1358 | /// definition of the variable. |
1359 | bool checkForConstantInitialization( |
1360 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
1361 | |
1362 | void setInitStyle(InitializationStyle Style) { |
1363 | VarDeclBits.InitStyle = Style; |
1364 | } |
1365 | |
1366 | /// The style of initialization for this declaration. |
1367 | /// |
1368 | /// C-style initialization is "int x = 1;". Call-style initialization is |
1369 | /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be |
1370 | /// the expression inside the parens or a "ClassType(a,b,c)" class constructor |
1371 | /// expression for class types. List-style initialization is C++11 syntax, |
1372 | /// e.g. "int x{1};". Clients can distinguish between different forms of |
1373 | /// initialization by checking this value. In particular, "int x = {1};" is |
1374 | /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the |
1375 | /// Init expression in all three cases is an InitListExpr. |
1376 | InitializationStyle getInitStyle() const { |
1377 | return static_cast<InitializationStyle>(VarDeclBits.InitStyle); |
1378 | } |
1379 | |
1380 | /// Whether the initializer is a direct-initializer (list or call). |
1381 | bool isDirectInit() const { |
1382 | return getInitStyle() != CInit; |
1383 | } |
1384 | |
1385 | /// If this definition should pretend to be a declaration. |
1386 | bool isThisDeclarationADemotedDefinition() const { |
1387 | return isa<ParmVarDecl>(this) ? false : |
1388 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition; |
1389 | } |
1390 | |
1391 | /// This is a definition which should be demoted to a declaration. |
1392 | /// |
1393 | /// In some cases (mostly module merging) we can end up with two visible |
1394 | /// definitions one of which needs to be demoted to a declaration to keep |
1395 | /// the AST invariants. |
1396 | void demoteThisDefinitionToDeclaration() { |
1397 | assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() && "Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1397, __extension__ __PRETTY_FUNCTION__)); |
1398 | assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1398, __extension__ __PRETTY_FUNCTION__)); |
1399 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1; |
1400 | } |
1401 | |
1402 | /// Determine whether this variable is the exception variable in a |
1403 | /// C++ catch statememt or an Objective-C \@catch statement. |
1404 | bool isExceptionVariable() const { |
1405 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar; |
1406 | } |
1407 | void setExceptionVariable(bool EV) { |
1408 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1408, __extension__ __PRETTY_FUNCTION__)); |
1409 | NonParmVarDeclBits.ExceptionVar = EV; |
1410 | } |
1411 | |
1412 | /// Determine whether this local variable can be used with the named |
1413 | /// return value optimization (NRVO). |
1414 | /// |
1415 | /// The named return value optimization (NRVO) works by marking certain |
1416 | /// non-volatile local variables of class type as NRVO objects. These |
1417 | /// locals can be allocated within the return slot of their containing |
1418 | /// function, in which case there is no need to copy the object to the |
1419 | /// return slot when returning from the function. Within the function body, |
1420 | /// each return that returns the NRVO object will have this variable as its |
1421 | /// NRVO candidate. |
1422 | bool isNRVOVariable() const { |
1423 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable; |
1424 | } |
1425 | void setNRVOVariable(bool NRVO) { |
1426 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1426, __extension__ __PRETTY_FUNCTION__)); |
1427 | NonParmVarDeclBits.NRVOVariable = NRVO; |
1428 | } |
1429 | |
1430 | /// Determine whether this variable is the for-range-declaration in |
1431 | /// a C++0x for-range statement. |
1432 | bool isCXXForRangeDecl() const { |
1433 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl; |
1434 | } |
1435 | void setCXXForRangeDecl(bool FRD) { |
1436 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1436, __extension__ __PRETTY_FUNCTION__)); |
1437 | NonParmVarDeclBits.CXXForRangeDecl = FRD; |
1438 | } |
1439 | |
1440 | /// Determine whether this variable is a for-loop declaration for a |
1441 | /// for-in statement in Objective-C. |
1442 | bool isObjCForDecl() const { |
1443 | return NonParmVarDeclBits.ObjCForDecl; |
1444 | } |
1445 | |
1446 | void setObjCForDecl(bool FRD) { |
1447 | NonParmVarDeclBits.ObjCForDecl = FRD; |
1448 | } |
1449 | |
1450 | /// Determine whether this variable is an ARC pseudo-__strong variable. A |
1451 | /// pseudo-__strong variable has a __strong-qualified type but does not |
1452 | /// actually retain the object written into it. Generally such variables are |
1453 | /// also 'const' for safety. There are 3 cases where this will be set, 1) if |
1454 | /// the variable is annotated with the objc_externally_retained attribute, 2) |
1455 | /// if its 'self' in a non-init method, or 3) if its the variable in an for-in |
1456 | /// loop. |
1457 | bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; } |
1458 | void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; } |
1459 | |
1460 | /// Whether this variable is (C++1z) inline. |
1461 | bool isInline() const { |
1462 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline; |
1463 | } |
1464 | bool isInlineSpecified() const { |
1465 | return isa<ParmVarDecl>(this) ? false |
1466 | : NonParmVarDeclBits.IsInlineSpecified; |
1467 | } |
1468 | void setInlineSpecified() { |
1469 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1469, __extension__ __PRETTY_FUNCTION__)); |
1470 | NonParmVarDeclBits.IsInline = true; |
1471 | NonParmVarDeclBits.IsInlineSpecified = true; |
1472 | } |
1473 | void setImplicitlyInline() { |
1474 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1474, __extension__ __PRETTY_FUNCTION__)); |
1475 | NonParmVarDeclBits.IsInline = true; |
1476 | } |
1477 | |
1478 | /// Whether this variable is (C++11) constexpr. |
1479 | bool isConstexpr() const { |
1480 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr; |
1481 | } |
1482 | void setConstexpr(bool IC) { |
1483 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1483, __extension__ __PRETTY_FUNCTION__)); |
1484 | NonParmVarDeclBits.IsConstexpr = IC; |
1485 | } |
1486 | |
1487 | /// Whether this variable is the implicit variable for a lambda init-capture. |
1488 | bool isInitCapture() const { |
1489 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture; |
1490 | } |
1491 | void setInitCapture(bool IC) { |
1492 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1492, __extension__ __PRETTY_FUNCTION__)); |
1493 | NonParmVarDeclBits.IsInitCapture = IC; |
1494 | } |
1495 | |
1496 | /// Determine whether this variable is actually a function parameter pack or |
1497 | /// init-capture pack. |
1498 | bool isParameterPack() const; |
1499 | |
1500 | /// Whether this local extern variable declaration's previous declaration |
1501 | /// was declared in the same block scope. Only correct in C++. |
1502 | bool isPreviousDeclInSameBlockScope() const { |
1503 | return isa<ParmVarDecl>(this) |
1504 | ? false |
1505 | : NonParmVarDeclBits.PreviousDeclInSameBlockScope; |
1506 | } |
1507 | void setPreviousDeclInSameBlockScope(bool Same) { |
1508 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1508, __extension__ __PRETTY_FUNCTION__)); |
1509 | NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same; |
1510 | } |
1511 | |
1512 | /// Indicates the capture is a __block variable that is captured by a block |
1513 | /// that can potentially escape (a block for which BlockDecl::doesNotEscape |
1514 | /// returns false). |
1515 | bool isEscapingByref() const; |
1516 | |
1517 | /// Indicates the capture is a __block variable that is never captured by an |
1518 | /// escaping block. |
1519 | bool isNonEscapingByref() const; |
1520 | |
1521 | void setEscapingByref() { |
1522 | NonParmVarDeclBits.EscapingByref = true; |
1523 | } |
1524 | |
1525 | /// Determines if this variable's alignment is dependent. |
1526 | bool hasDependentAlignment() const; |
1527 | |
1528 | /// Retrieve the variable declaration from which this variable could |
1529 | /// be instantiated, if it is an instantiation (rather than a non-template). |
1530 | VarDecl *getTemplateInstantiationPattern() const; |
1531 | |
1532 | /// If this variable is an instantiated static data member of a |
1533 | /// class template specialization, returns the templated static data member |
1534 | /// from which it was instantiated. |
1535 | VarDecl *getInstantiatedFromStaticDataMember() const; |
1536 | |
1537 | /// If this variable is an instantiation of a variable template or a |
1538 | /// static data member of a class template, determine what kind of |
1539 | /// template specialization or instantiation this is. |
1540 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
1541 | |
1542 | /// Get the template specialization kind of this variable for the purposes of |
1543 | /// template instantiation. This differs from getTemplateSpecializationKind() |
1544 | /// for an instantiation of a class-scope explicit specialization. |
1545 | TemplateSpecializationKind |
1546 | getTemplateSpecializationKindForInstantiation() const; |
1547 | |
1548 | /// If this variable is an instantiation of a variable template or a |
1549 | /// static data member of a class template, determine its point of |
1550 | /// instantiation. |
1551 | SourceLocation getPointOfInstantiation() const; |
1552 | |
1553 | /// If this variable is an instantiation of a static data member of a |
1554 | /// class template specialization, retrieves the member specialization |
1555 | /// information. |
1556 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
1557 | |
1558 | /// For a static data member that was instantiated from a static |
1559 | /// data member of a class template, set the template specialiation kind. |
1560 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
1561 | SourceLocation PointOfInstantiation = SourceLocation()); |
1562 | |
1563 | /// Specify that this variable is an instantiation of the |
1564 | /// static data member VD. |
1565 | void setInstantiationOfStaticDataMember(VarDecl *VD, |
1566 | TemplateSpecializationKind TSK); |
1567 | |
1568 | /// Retrieves the variable template that is described by this |
1569 | /// variable declaration. |
1570 | /// |
1571 | /// Every variable template is represented as a VarTemplateDecl and a |
1572 | /// VarDecl. The former contains template properties (such as |
1573 | /// the template parameter lists) while the latter contains the |
1574 | /// actual description of the template's |
1575 | /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the |
1576 | /// VarDecl that from a VarTemplateDecl, while |
1577 | /// getDescribedVarTemplate() retrieves the VarTemplateDecl from |
1578 | /// a VarDecl. |
1579 | VarTemplateDecl *getDescribedVarTemplate() const; |
1580 | |
1581 | void setDescribedVarTemplate(VarTemplateDecl *Template); |
1582 | |
1583 | // Is this variable known to have a definition somewhere in the complete |
1584 | // program? This may be true even if the declaration has internal linkage and |
1585 | // has no definition within this source file. |
1586 | bool isKnownToBeDefined() const; |
1587 | |
1588 | /// Is destruction of this variable entirely suppressed? If so, the variable |
1589 | /// need not have a usable destructor at all. |
1590 | bool isNoDestroy(const ASTContext &) const; |
1591 | |
1592 | /// Would the destruction of this variable have any effect, and if so, what |
1593 | /// kind? |
1594 | QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const; |
1595 | |
1596 | // Implement isa/cast/dyncast/etc. |
1597 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1598 | static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } |
1599 | }; |
1600 | |
1601 | class ImplicitParamDecl : public VarDecl { |
1602 | void anchor() override; |
1603 | |
1604 | public: |
1605 | /// Defines the kind of the implicit parameter: is this an implicit parameter |
1606 | /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured |
1607 | /// context or something else. |
1608 | enum ImplicitParamKind : unsigned { |
1609 | /// Parameter for Objective-C 'self' argument |
1610 | ObjCSelf, |
1611 | |
1612 | /// Parameter for Objective-C '_cmd' argument |
1613 | ObjCCmd, |
1614 | |
1615 | /// Parameter for C++ 'this' argument |
1616 | CXXThis, |
1617 | |
1618 | /// Parameter for C++ virtual table pointers |
1619 | CXXVTT, |
1620 | |
1621 | /// Parameter for captured context |
1622 | CapturedContext, |
1623 | |
1624 | /// Other implicit parameter |
1625 | Other, |
1626 | }; |
1627 | |
1628 | /// Create implicit parameter. |
1629 | static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, |
1630 | SourceLocation IdLoc, IdentifierInfo *Id, |
1631 | QualType T, ImplicitParamKind ParamKind); |
1632 | static ImplicitParamDecl *Create(ASTContext &C, QualType T, |
1633 | ImplicitParamKind ParamKind); |
1634 | |
1635 | static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1636 | |
1637 | ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, |
1638 | IdentifierInfo *Id, QualType Type, |
1639 | ImplicitParamKind ParamKind) |
1640 | : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type, |
1641 | /*TInfo=*/nullptr, SC_None) { |
1642 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1643 | setImplicit(); |
1644 | } |
1645 | |
1646 | ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind) |
1647 | : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(), |
1648 | SourceLocation(), /*Id=*/nullptr, Type, |
1649 | /*TInfo=*/nullptr, SC_None) { |
1650 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1651 | setImplicit(); |
1652 | } |
1653 | |
1654 | /// Returns the implicit parameter kind. |
1655 | ImplicitParamKind getParameterKind() const { |
1656 | return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind); |
1657 | } |
1658 | |
1659 | // Implement isa/cast/dyncast/etc. |
1660 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1661 | static bool classofKind(Kind K) { return K == ImplicitParam; } |
1662 | }; |
1663 | |
1664 | /// Represents a parameter to a function. |
1665 | class ParmVarDecl : public VarDecl { |
1666 | public: |
1667 | enum { MaxFunctionScopeDepth = 255 }; |
1668 | enum { MaxFunctionScopeIndex = 255 }; |
1669 | |
1670 | protected: |
1671 | ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1672 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
1673 | TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg) |
1674 | : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) { |
1675 | assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg == false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1675, __extension__ __PRETTY_FUNCTION__)); |
1676 | assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None ) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1676, __extension__ __PRETTY_FUNCTION__)); |
1677 | assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false ) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1677, __extension__ __PRETTY_FUNCTION__)); |
1678 | assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam == false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1678, __extension__ __PRETTY_FUNCTION__)); |
1679 | setDefaultArg(DefArg); |
1680 | } |
1681 | |
1682 | public: |
1683 | static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, |
1684 | SourceLocation StartLoc, |
1685 | SourceLocation IdLoc, IdentifierInfo *Id, |
1686 | QualType T, TypeSourceInfo *TInfo, |
1687 | StorageClass S, Expr *DefArg); |
1688 | |
1689 | static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1690 | |
1691 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1692 | |
1693 | void setObjCMethodScopeInfo(unsigned parameterIndex) { |
1694 | ParmVarDeclBits.IsObjCMethodParam = true; |
1695 | setParameterIndex(parameterIndex); |
1696 | } |
1697 | |
1698 | void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) { |
1699 | assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam ) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1699, __extension__ __PRETTY_FUNCTION__)); |
1700 | |
1701 | ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth; |
1702 | assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1703, __extension__ __PRETTY_FUNCTION__)) |
1703 | && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1703, __extension__ __PRETTY_FUNCTION__)); |
1704 | |
1705 | setParameterIndex(parameterIndex); |
1706 | } |
1707 | |
1708 | bool isObjCMethodParameter() const { |
1709 | return ParmVarDeclBits.IsObjCMethodParam; |
1710 | } |
1711 | |
1712 | /// Determines whether this parameter is destroyed in the callee function. |
1713 | bool isDestroyedInCallee() const; |
1714 | |
1715 | unsigned getFunctionScopeDepth() const { |
1716 | if (ParmVarDeclBits.IsObjCMethodParam) return 0; |
1717 | return ParmVarDeclBits.ScopeDepthOrObjCQuals; |
1718 | } |
1719 | |
1720 | static constexpr unsigned getMaxFunctionScopeDepth() { |
1721 | return (1u << NumScopeDepthOrObjCQualsBits) - 1; |
1722 | } |
1723 | |
1724 | /// Returns the index of this parameter in its prototype or method scope. |
1725 | unsigned getFunctionScopeIndex() const { |
1726 | return getParameterIndex(); |
1727 | } |
1728 | |
1729 | ObjCDeclQualifier getObjCDeclQualifier() const { |
1730 | if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None; |
1731 | return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals); |
1732 | } |
1733 | void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { |
1734 | assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1734, __extension__ __PRETTY_FUNCTION__)); |
1735 | ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal; |
1736 | } |
1737 | |
1738 | /// True if the value passed to this parameter must undergo |
1739 | /// K&R-style default argument promotion: |
1740 | /// |
1741 | /// C99 6.5.2.2. |
1742 | /// If the expression that denotes the called function has a type |
1743 | /// that does not include a prototype, the integer promotions are |
1744 | /// performed on each argument, and arguments that have type float |
1745 | /// are promoted to double. |
1746 | bool isKNRPromoted() const { |
1747 | return ParmVarDeclBits.IsKNRPromoted; |
1748 | } |
1749 | void setKNRPromoted(bool promoted) { |
1750 | ParmVarDeclBits.IsKNRPromoted = promoted; |
1751 | } |
1752 | |
1753 | Expr *getDefaultArg(); |
1754 | const Expr *getDefaultArg() const { |
1755 | return const_cast<ParmVarDecl *>(this)->getDefaultArg(); |
1756 | } |
1757 | |
1758 | void setDefaultArg(Expr *defarg); |
1759 | |
1760 | /// Retrieve the source range that covers the entire default |
1761 | /// argument. |
1762 | SourceRange getDefaultArgRange() const; |
1763 | void setUninstantiatedDefaultArg(Expr *arg); |
1764 | Expr *getUninstantiatedDefaultArg(); |
1765 | const Expr *getUninstantiatedDefaultArg() const { |
1766 | return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg(); |
1767 | } |
1768 | |
1769 | /// Determines whether this parameter has a default argument, |
1770 | /// either parsed or not. |
1771 | bool hasDefaultArg() const; |
1772 | |
1773 | /// Determines whether this parameter has a default argument that has not |
1774 | /// yet been parsed. This will occur during the processing of a C++ class |
1775 | /// whose member functions have default arguments, e.g., |
1776 | /// @code |
1777 | /// class X { |
1778 | /// public: |
1779 | /// void f(int x = 17); // x has an unparsed default argument now |
1780 | /// }; // x has a regular default argument now |
1781 | /// @endcode |
1782 | bool hasUnparsedDefaultArg() const { |
1783 | return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed; |
1784 | } |
1785 | |
1786 | bool hasUninstantiatedDefaultArg() const { |
1787 | return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated; |
1788 | } |
1789 | |
1790 | /// Specify that this parameter has an unparsed default argument. |
1791 | /// The argument will be replaced with a real default argument via |
1792 | /// setDefaultArg when the class definition enclosing the function |
1793 | /// declaration that owns this default argument is completed. |
1794 | void setUnparsedDefaultArg() { |
1795 | ParmVarDeclBits.DefaultArgKind = DAK_Unparsed; |
1796 | } |
1797 | |
1798 | bool hasInheritedDefaultArg() const { |
1799 | return ParmVarDeclBits.HasInheritedDefaultArg; |
1800 | } |
1801 | |
1802 | void setHasInheritedDefaultArg(bool I = true) { |
1803 | ParmVarDeclBits.HasInheritedDefaultArg = I; |
1804 | } |
1805 | |
1806 | QualType getOriginalType() const; |
1807 | |
1808 | /// Sets the function declaration that owns this |
1809 | /// ParmVarDecl. Since ParmVarDecls are often created before the |
1810 | /// FunctionDecls that own them, this routine is required to update |
1811 | /// the DeclContext appropriately. |
1812 | void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } |
1813 | |
1814 | // Implement isa/cast/dyncast/etc. |
1815 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1816 | static bool classofKind(Kind K) { return K == ParmVar; } |
1817 | |
1818 | private: |
1819 | enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 }; |
1820 | |
1821 | void setParameterIndex(unsigned parameterIndex) { |
1822 | if (parameterIndex >= ParameterIndexSentinel) { |
1823 | setParameterIndexLarge(parameterIndex); |
1824 | return; |
1825 | } |
1826 | |
1827 | ParmVarDeclBits.ParameterIndex = parameterIndex; |
1828 | assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 1828, __extension__ __PRETTY_FUNCTION__)); |
1829 | } |
1830 | unsigned getParameterIndex() const { |
1831 | unsigned d = ParmVarDeclBits.ParameterIndex; |
1832 | return d == ParameterIndexSentinel ? getParameterIndexLarge() : d; |
1833 | } |
1834 | |
1835 | void setParameterIndexLarge(unsigned parameterIndex); |
1836 | unsigned getParameterIndexLarge() const; |
1837 | }; |
1838 | |
1839 | enum class MultiVersionKind { |
1840 | None, |
1841 | Target, |
1842 | CPUSpecific, |
1843 | CPUDispatch |
1844 | }; |
1845 | |
1846 | /// Represents a function declaration or definition. |
1847 | /// |
1848 | /// Since a given function can be declared several times in a program, |
1849 | /// there may be several FunctionDecls that correspond to that |
1850 | /// function. Only one of those FunctionDecls will be found when |
1851 | /// traversing the list of declarations in the context of the |
1852 | /// FunctionDecl (e.g., the translation unit); this FunctionDecl |
1853 | /// contains all of the information known about the function. Other, |
1854 | /// previous declarations of the function are available via the |
1855 | /// getPreviousDecl() chain. |
1856 | class FunctionDecl : public DeclaratorDecl, |
1857 | public DeclContext, |
1858 | public Redeclarable<FunctionDecl> { |
1859 | // This class stores some data in DeclContext::FunctionDeclBits |
1860 | // to save some space. Use the provided accessors to access it. |
1861 | public: |
1862 | /// The kind of templated function a FunctionDecl can be. |
1863 | enum TemplatedKind { |
1864 | // Not templated. |
1865 | TK_NonTemplate, |
1866 | // The pattern in a function template declaration. |
1867 | TK_FunctionTemplate, |
1868 | // A non-template function that is an instantiation or explicit |
1869 | // specialization of a member of a templated class. |
1870 | TK_MemberSpecialization, |
1871 | // An instantiation or explicit specialization of a function template. |
1872 | // Note: this might have been instantiated from a templated class if it |
1873 | // is a class-scope explicit specialization. |
1874 | TK_FunctionTemplateSpecialization, |
1875 | // A function template specialization that hasn't yet been resolved to a |
1876 | // particular specialized function template. |
1877 | TK_DependentFunctionTemplateSpecialization |
1878 | }; |
1879 | |
1880 | /// Stashed information about a defaulted function definition whose body has |
1881 | /// not yet been lazily generated. |
1882 | class DefaultedFunctionInfo final |
1883 | : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> { |
1884 | friend TrailingObjects; |
1885 | unsigned NumLookups; |
1886 | |
1887 | public: |
1888 | static DefaultedFunctionInfo *Create(ASTContext &Context, |
1889 | ArrayRef<DeclAccessPair> Lookups); |
1890 | /// Get the unqualified lookup results that should be used in this |
1891 | /// defaulted function definition. |
1892 | ArrayRef<DeclAccessPair> getUnqualifiedLookups() const { |
1893 | return {getTrailingObjects<DeclAccessPair>(), NumLookups}; |
1894 | } |
1895 | }; |
1896 | |
1897 | private: |
1898 | /// A new[]'d array of pointers to VarDecls for the formal |
1899 | /// parameters of this function. This is null if a prototype or if there are |
1900 | /// no formals. |
1901 | ParmVarDecl **ParamInfo = nullptr; |
1902 | |
1903 | /// The active member of this union is determined by |
1904 | /// FunctionDeclBits.HasDefaultedFunctionInfo. |
1905 | union { |
1906 | /// The body of the function. |
1907 | LazyDeclStmtPtr Body; |
1908 | /// Information about a future defaulted function definition. |
1909 | DefaultedFunctionInfo *DefaultedInfo; |
1910 | }; |
1911 | |
1912 | unsigned ODRHash; |
1913 | |
1914 | /// End part of this FunctionDecl's source range. |
1915 | /// |
1916 | /// We could compute the full range in getSourceRange(). However, when we're |
1917 | /// dealing with a function definition deserialized from a PCH/AST file, |
1918 | /// we can only compute the full range once the function body has been |
1919 | /// de-serialized, so it's far better to have the (sometimes-redundant) |
1920 | /// EndRangeLoc. |
1921 | SourceLocation EndRangeLoc; |
1922 | |
1923 | /// The template or declaration that this declaration |
1924 | /// describes or was instantiated from, respectively. |
1925 | /// |
1926 | /// For non-templates, this value will be NULL. For function |
1927 | /// declarations that describe a function template, this will be a |
1928 | /// pointer to a FunctionTemplateDecl. For member functions |
1929 | /// of class template specializations, this will be a MemberSpecializationInfo |
1930 | /// pointer containing information about the specialization. |
1931 | /// For function template specializations, this will be a |
1932 | /// FunctionTemplateSpecializationInfo, which contains information about |
1933 | /// the template being specialized and the template arguments involved in |
1934 | /// that specialization. |
1935 | llvm::PointerUnion<FunctionTemplateDecl *, |
1936 | MemberSpecializationInfo *, |
1937 | FunctionTemplateSpecializationInfo *, |
1938 | DependentFunctionTemplateSpecializationInfo *> |
1939 | TemplateOrSpecialization; |
1940 | |
1941 | /// Provides source/type location info for the declaration name embedded in |
1942 | /// the DeclaratorDecl base class. |
1943 | DeclarationNameLoc DNLoc; |
1944 | |
1945 | /// Specify that this function declaration is actually a function |
1946 | /// template specialization. |
1947 | /// |
1948 | /// \param C the ASTContext. |
1949 | /// |
1950 | /// \param Template the function template that this function template |
1951 | /// specialization specializes. |
1952 | /// |
1953 | /// \param TemplateArgs the template arguments that produced this |
1954 | /// function template specialization from the template. |
1955 | /// |
1956 | /// \param InsertPos If non-NULL, the position in the function template |
1957 | /// specialization set where the function template specialization data will |
1958 | /// be inserted. |
1959 | /// |
1960 | /// \param TSK the kind of template specialization this is. |
1961 | /// |
1962 | /// \param TemplateArgsAsWritten location info of template arguments. |
1963 | /// |
1964 | /// \param PointOfInstantiation point at which the function template |
1965 | /// specialization was first instantiated. |
1966 | void setFunctionTemplateSpecialization(ASTContext &C, |
1967 | FunctionTemplateDecl *Template, |
1968 | const TemplateArgumentList *TemplateArgs, |
1969 | void *InsertPos, |
1970 | TemplateSpecializationKind TSK, |
1971 | const TemplateArgumentListInfo *TemplateArgsAsWritten, |
1972 | SourceLocation PointOfInstantiation); |
1973 | |
1974 | /// Specify that this record is an instantiation of the |
1975 | /// member function FD. |
1976 | void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, |
1977 | TemplateSpecializationKind TSK); |
1978 | |
1979 | void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo); |
1980 | |
1981 | // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl |
1982 | // need to access this bit but we want to avoid making ASTDeclWriter |
1983 | // a friend of FunctionDeclBitfields just for this. |
1984 | bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; } |
1985 | |
1986 | /// Whether an ODRHash has been stored. |
1987 | bool hasODRHash() const { return FunctionDeclBits.HasODRHash; } |
1988 | |
1989 | /// State that an ODRHash has been stored. |
1990 | void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; } |
1991 | |
1992 | protected: |
1993 | FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1994 | const DeclarationNameInfo &NameInfo, QualType T, |
1995 | TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin, |
1996 | bool isInlineSpecified, ConstexprSpecKind ConstexprKind, |
1997 | Expr *TrailingRequiresClause = nullptr); |
1998 | |
1999 | using redeclarable_base = Redeclarable<FunctionDecl>; |
2000 | |
2001 | FunctionDecl *getNextRedeclarationImpl() override { |
2002 | return getNextRedeclaration(); |
2003 | } |
2004 | |
2005 | FunctionDecl *getPreviousDeclImpl() override { |
2006 | return getPreviousDecl(); |
2007 | } |
2008 | |
2009 | FunctionDecl *getMostRecentDeclImpl() override { |
2010 | return getMostRecentDecl(); |
2011 | } |
2012 | |
2013 | public: |
2014 | friend class ASTDeclReader; |
2015 | friend class ASTDeclWriter; |
2016 | |
2017 | using redecl_range = redeclarable_base::redecl_range; |
2018 | using redecl_iterator = redeclarable_base::redecl_iterator; |
2019 | |
2020 | using redeclarable_base::redecls_begin; |
2021 | using redeclarable_base::redecls_end; |
2022 | using redeclarable_base::redecls; |
2023 | using redeclarable_base::getPreviousDecl; |
2024 | using redeclarable_base::getMostRecentDecl; |
2025 | using redeclarable_base::isFirstDecl; |
2026 | |
2027 | static FunctionDecl * |
2028 | Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
2029 | SourceLocation NLoc, DeclarationName N, QualType T, |
2030 | TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin = false, |
2031 | bool isInlineSpecified = false, bool hasWrittenPrototype = true, |
2032 | ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified, |
2033 | Expr *TrailingRequiresClause = nullptr) { |
2034 | DeclarationNameInfo NameInfo(N, NLoc); |
2035 | return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC, |
2036 | UsesFPIntrin, isInlineSpecified, |
2037 | hasWrittenPrototype, ConstexprKind, |
2038 | TrailingRequiresClause); |
2039 | } |
2040 | |
2041 | static FunctionDecl * |
2042 | Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
2043 | const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, |
2044 | StorageClass SC, bool UsesFPIntrin, bool isInlineSpecified, |
2045 | bool hasWrittenPrototype, ConstexprSpecKind ConstexprKind, |
2046 | Expr *TrailingRequiresClause); |
2047 | |
2048 | static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2049 | |
2050 | DeclarationNameInfo getNameInfo() const { |
2051 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
2052 | } |
2053 | |
2054 | void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, |
2055 | bool Qualified) const override; |
2056 | |
2057 | void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } |
2058 | |
2059 | /// Returns the location of the ellipsis of a variadic function. |
2060 | SourceLocation getEllipsisLoc() const { |
2061 | const auto *FPT = getType()->getAs<FunctionProtoType>(); |
2062 | if (FPT && FPT->isVariadic()) |
2063 | return FPT->getEllipsisLoc(); |
2064 | return SourceLocation(); |
2065 | } |
2066 | |
2067 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2068 | |
2069 | // Function definitions. |
2070 | // |
2071 | // A function declaration may be: |
2072 | // - a non defining declaration, |
2073 | // - a definition. A function may be defined because: |
2074 | // - it has a body, or will have it in the case of late parsing. |
2075 | // - it has an uninstantiated body. The body does not exist because the |
2076 | // function is not used yet, but the declaration is considered a |
2077 | // definition and does not allow other definition of this function. |
2078 | // - it does not have a user specified body, but it does not allow |
2079 | // redefinition, because it is deleted/defaulted or is defined through |
2080 | // some other mechanism (alias, ifunc). |
2081 | |
2082 | /// Returns true if the function has a body. |
2083 | /// |
2084 | /// The function body might be in any of the (re-)declarations of this |
2085 | /// function. The variant that accepts a FunctionDecl pointer will set that |
2086 | /// function declaration to the actual declaration containing the body (if |
2087 | /// there is one). |
2088 | bool hasBody(const FunctionDecl *&Definition) const; |
2089 | |
2090 | bool hasBody() const override { |
2091 | const FunctionDecl* Definition; |
2092 | return hasBody(Definition); |
2093 | } |
2094 | |
2095 | /// Returns whether the function has a trivial body that does not require any |
2096 | /// specific codegen. |
2097 | bool hasTrivialBody() const; |
2098 | |
2099 | /// Returns true if the function has a definition that does not need to be |
2100 | /// instantiated. |
2101 | /// |
2102 | /// The variant that accepts a FunctionDecl pointer will set that function |
2103 | /// declaration to the declaration that is a definition (if there is one). |
2104 | /// |
2105 | /// \param CheckForPendingFriendDefinition If \c true, also check for friend |
2106 | /// declarations that were instantiataed from function definitions. |
2107 | /// Such a declaration behaves as if it is a definition for the |
2108 | /// purpose of redefinition checking, but isn't actually a "real" |
2109 | /// definition until its body is instantiated. |
2110 | bool isDefined(const FunctionDecl *&Definition, |
2111 | bool CheckForPendingFriendDefinition = false) const; |
2112 | |
2113 | bool isDefined() const { |
2114 | const FunctionDecl* Definition; |
2115 | return isDefined(Definition); |
2116 | } |
2117 | |
2118 | /// Get the definition for this declaration. |
2119 | FunctionDecl *getDefinition() { |
2120 | const FunctionDecl *Definition; |
2121 | if (isDefined(Definition)) |
2122 | return const_cast<FunctionDecl *>(Definition); |
2123 | return nullptr; |
2124 | } |
2125 | const FunctionDecl *getDefinition() const { |
2126 | return const_cast<FunctionDecl *>(this)->getDefinition(); |
2127 | } |
2128 | |
2129 | /// Retrieve the body (definition) of the function. The function body might be |
2130 | /// in any of the (re-)declarations of this function. The variant that accepts |
2131 | /// a FunctionDecl pointer will set that function declaration to the actual |
2132 | /// declaration containing the body (if there is one). |
2133 | /// NOTE: For checking if there is a body, use hasBody() instead, to avoid |
2134 | /// unnecessary AST de-serialization of the body. |
2135 | Stmt *getBody(const FunctionDecl *&Definition) const; |
2136 | |
2137 | Stmt *getBody() const override { |
2138 | const FunctionDecl* Definition; |
2139 | return getBody(Definition); |
2140 | } |
2141 | |
2142 | /// Returns whether this specific declaration of the function is also a |
2143 | /// definition that does not contain uninstantiated body. |
2144 | /// |
2145 | /// This does not determine whether the function has been defined (e.g., in a |
2146 | /// previous definition); for that information, use isDefined. |
2147 | /// |
2148 | /// Note: the function declaration does not become a definition until the |
2149 | /// parser reaches the definition, if called before, this function will return |
2150 | /// `false`. |
2151 | bool isThisDeclarationADefinition() const { |
2152 | return isDeletedAsWritten() || isDefaulted() || |
2153 | doesThisDeclarationHaveABody() || hasSkippedBody() || |
2154 | willHaveBody() || hasDefiningAttr(); |
2155 | } |
2156 | |
2157 | /// Determine whether this specific declaration of the function is a friend |
2158 | /// declaration that was instantiated from a function definition. Such |
2159 | /// declarations behave like definitions in some contexts. |
2160 | bool isThisDeclarationInstantiatedFromAFriendDefinition() const; |
2161 | |
2162 | /// Returns whether this specific declaration of the function has a body. |
2163 | bool doesThisDeclarationHaveABody() const { |
2164 | return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) || |
2165 | isLateTemplateParsed(); |
2166 | } |
2167 | |
2168 | void setBody(Stmt *B); |
2169 | void setLazyBody(uint64_t Offset) { |
2170 | FunctionDeclBits.HasDefaultedFunctionInfo = false; |
2171 | Body = LazyDeclStmtPtr(Offset); |
2172 | } |
2173 | |
2174 | void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info); |
2175 | DefaultedFunctionInfo *getDefaultedFunctionInfo() const; |
2176 | |
2177 | /// Whether this function is variadic. |
2178 | bool isVariadic() const; |
2179 | |
2180 | /// Whether this function is marked as virtual explicitly. |
2181 | bool isVirtualAsWritten() const { |
2182 | return FunctionDeclBits.IsVirtualAsWritten; |
2183 | } |
2184 | |
2185 | /// State that this function is marked as virtual explicitly. |
2186 | void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; } |
2187 | |
2188 | /// Whether this virtual function is pure, i.e. makes the containing class |
2189 | /// abstract. |
2190 | bool isPure() const { return FunctionDeclBits.IsPure; } |
2191 | void setPure(bool P = true); |
2192 | |
2193 | /// Whether this templated function will be late parsed. |
2194 | bool isLateTemplateParsed() const { |
2195 | return FunctionDeclBits.IsLateTemplateParsed; |
2196 | } |
2197 | |
2198 | /// State that this templated function will be late parsed. |
2199 | void setLateTemplateParsed(bool ILT = true) { |
2200 | FunctionDeclBits.IsLateTemplateParsed = ILT; |
2201 | } |
2202 | |
2203 | /// Whether this function is "trivial" in some specialized C++ senses. |
2204 | /// Can only be true for default constructors, copy constructors, |
2205 | /// copy assignment operators, and destructors. Not meaningful until |
2206 | /// the class has been fully built by Sema. |
2207 | bool isTrivial() const { return FunctionDeclBits.IsTrivial; } |
2208 | void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; } |
2209 | |
2210 | bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; } |
2211 | void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; } |
2212 | |
2213 | /// Whether this function is defaulted. Valid for e.g. |
2214 | /// special member functions, defaulted comparisions (not methods!). |
2215 | bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; } |
2216 | void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; } |
2217 | |
2218 | /// Whether this function is explicitly defaulted. |
2219 | bool isExplicitlyDefaulted() const { |
2220 | return FunctionDeclBits.IsExplicitlyDefaulted; |
2221 | } |
2222 | |
2223 | /// State that this function is explicitly defaulted. |
2224 | void setExplicitlyDefaulted(bool ED = true) { |
2225 | FunctionDeclBits.IsExplicitlyDefaulted = ED; |
2226 | } |
2227 | |
2228 | /// True if this method is user-declared and was not |
2229 | /// deleted or defaulted on its first declaration. |
2230 | bool isUserProvided() const { |
2231 | auto *DeclAsWritten = this; |
2232 | if (FunctionDecl *Pattern = getTemplateInstantiationPattern()) |
2233 | DeclAsWritten = Pattern; |
2234 | return !(DeclAsWritten->isDeleted() || |
2235 | DeclAsWritten->getCanonicalDecl()->isDefaulted()); |
2236 | } |
2237 | |
2238 | /// Whether falling off this function implicitly returns null/zero. |
2239 | /// If a more specific implicit return value is required, front-ends |
2240 | /// should synthesize the appropriate return statements. |
2241 | bool hasImplicitReturnZero() const { |
2242 | return FunctionDeclBits.HasImplicitReturnZero; |
2243 | } |
2244 | |
2245 | /// State that falling off this function implicitly returns null/zero. |
2246 | /// If a more specific implicit return value is required, front-ends |
2247 | /// should synthesize the appropriate return statements. |
2248 | void setHasImplicitReturnZero(bool IRZ) { |
2249 | FunctionDeclBits.HasImplicitReturnZero = IRZ; |
2250 | } |
2251 | |
2252 | /// Whether this function has a prototype, either because one |
2253 | /// was explicitly written or because it was "inherited" by merging |
2254 | /// a declaration without a prototype with a declaration that has a |
2255 | /// prototype. |
2256 | bool hasPrototype() const { |
2257 | return hasWrittenPrototype() || hasInheritedPrototype(); |
2258 | } |
2259 | |
2260 | /// Whether this function has a written prototype. |
2261 | bool hasWrittenPrototype() const { |
2262 | return FunctionDeclBits.HasWrittenPrototype; |
2263 | } |
2264 | |
2265 | /// State that this function has a written prototype. |
2266 | void setHasWrittenPrototype(bool P = true) { |
2267 | FunctionDeclBits.HasWrittenPrototype = P; |
2268 | } |
2269 | |
2270 | /// Whether this function inherited its prototype from a |
2271 | /// previous declaration. |
2272 | bool hasInheritedPrototype() const { |
2273 | return FunctionDeclBits.HasInheritedPrototype; |
2274 | } |
2275 | |
2276 | /// State that this function inherited its prototype from a |
2277 | /// previous declaration. |
2278 | void setHasInheritedPrototype(bool P = true) { |
2279 | FunctionDeclBits.HasInheritedPrototype = P; |
2280 | } |
2281 | |
2282 | /// Whether this is a (C++11) constexpr function or constexpr constructor. |
2283 | bool isConstexpr() const { |
2284 | return getConstexprKind() != ConstexprSpecKind::Unspecified; |
2285 | } |
2286 | void setConstexprKind(ConstexprSpecKind CSK) { |
2287 | FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK); |
2288 | } |
2289 | ConstexprSpecKind getConstexprKind() const { |
2290 | return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind); |
2291 | } |
2292 | bool isConstexprSpecified() const { |
2293 | return getConstexprKind() == ConstexprSpecKind::Constexpr; |
2294 | } |
2295 | bool isConsteval() const { |
2296 | return getConstexprKind() == ConstexprSpecKind::Consteval; |
2297 | } |
2298 | |
2299 | /// Whether the instantiation of this function is pending. |
2300 | /// This bit is set when the decision to instantiate this function is made |
2301 | /// and unset if and when the function body is created. That leaves out |
2302 | /// cases where instantiation did not happen because the template definition |
2303 | /// was not seen in this TU. This bit remains set in those cases, under the |
2304 | /// assumption that the instantiation will happen in some other TU. |
2305 | bool instantiationIsPending() const { |
2306 | return FunctionDeclBits.InstantiationIsPending; |
2307 | } |
2308 | |
2309 | /// State that the instantiation of this function is pending. |
2310 | /// (see instantiationIsPending) |
2311 | void setInstantiationIsPending(bool IC) { |
2312 | FunctionDeclBits.InstantiationIsPending = IC; |
2313 | } |
2314 | |
2315 | /// Indicates the function uses __try. |
2316 | bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; } |
2317 | void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; } |
2318 | |
2319 | /// Whether this function has been deleted. |
2320 | /// |
2321 | /// A function that is "deleted" (via the C++0x "= delete" syntax) |
2322 | /// acts like a normal function, except that it cannot actually be |
2323 | /// called or have its address taken. Deleted functions are |
2324 | /// typically used in C++ overload resolution to attract arguments |
2325 | /// whose type or lvalue/rvalue-ness would permit the use of a |
2326 | /// different overload that would behave incorrectly. For example, |
2327 | /// one might use deleted functions to ban implicit conversion from |
2328 | /// a floating-point number to an Integer type: |
2329 | /// |
2330 | /// @code |
2331 | /// struct Integer { |
2332 | /// Integer(long); // construct from a long |
2333 | /// Integer(double) = delete; // no construction from float or double |
2334 | /// Integer(long double) = delete; // no construction from long double |
2335 | /// }; |
2336 | /// @endcode |
2337 | // If a function is deleted, its first declaration must be. |
2338 | bool isDeleted() const { |
2339 | return getCanonicalDecl()->FunctionDeclBits.IsDeleted; |
2340 | } |
2341 | |
2342 | bool isDeletedAsWritten() const { |
2343 | return FunctionDeclBits.IsDeleted && !isDefaulted(); |
2344 | } |
2345 | |
2346 | void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; } |
2347 | |
2348 | /// Determines whether this function is "main", which is the |
2349 | /// entry point into an executable program. |
2350 | bool isMain() const; |
2351 | |
2352 | /// Determines whether this function is a MSVCRT user defined entry |
2353 | /// point. |
2354 | bool isMSVCRTEntryPoint() const; |
2355 | |
2356 | /// Determines whether this operator new or delete is one |
2357 | /// of the reserved global placement operators: |
2358 | /// void *operator new(size_t, void *); |
2359 | /// void *operator new[](size_t, void *); |
2360 | /// void operator delete(void *, void *); |
2361 | /// void operator delete[](void *, void *); |
2362 | /// These functions have special behavior under [new.delete.placement]: |
2363 | /// These functions are reserved, a C++ program may not define |
2364 | /// functions that displace the versions in the Standard C++ library. |
2365 | /// The provisions of [basic.stc.dynamic] do not apply to these |
2366 | /// reserved placement forms of operator new and operator delete. |
2367 | /// |
2368 | /// This function must be an allocation or deallocation function. |
2369 | bool isReservedGlobalPlacementOperator() const; |
2370 | |
2371 | /// Determines whether this function is one of the replaceable |
2372 | /// global allocation functions: |
2373 | /// void *operator new(size_t); |
2374 | /// void *operator new(size_t, const std::nothrow_t &) noexcept; |
2375 | /// void *operator new[](size_t); |
2376 | /// void *operator new[](size_t, const std::nothrow_t &) noexcept; |
2377 | /// void operator delete(void *) noexcept; |
2378 | /// void operator delete(void *, std::size_t) noexcept; [C++1y] |
2379 | /// void operator delete(void *, const std::nothrow_t &) noexcept; |
2380 | /// void operator delete[](void *) noexcept; |
2381 | /// void operator delete[](void *, std::size_t) noexcept; [C++1y] |
2382 | /// void operator delete[](void *, const std::nothrow_t &) noexcept; |
2383 | /// These functions have special behavior under C++1y [expr.new]: |
2384 | /// An implementation is allowed to omit a call to a replaceable global |
2385 | /// allocation function. [...] |
2386 | /// |
2387 | /// If this function is an aligned allocation/deallocation function, return |
2388 | /// the parameter number of the requested alignment through AlignmentParam. |
2389 | /// |
2390 | /// If this function is an allocation/deallocation function that takes |
2391 | /// the `std::nothrow_t` tag, return true through IsNothrow, |
2392 | bool isReplaceableGlobalAllocationFunction( |
2393 | Optional<unsigned> *AlignmentParam = nullptr, |
2394 | bool *IsNothrow = nullptr) const; |
2395 | |
2396 | /// Determine if this function provides an inline implementation of a builtin. |
2397 | bool isInlineBuiltinDeclaration() const; |
2398 | |
2399 | /// Determine whether this is a destroying operator delete. |
2400 | bool isDestroyingOperatorDelete() const; |
2401 | |
2402 | /// Compute the language linkage. |
2403 | LanguageLinkage getLanguageLinkage() const; |
2404 | |
2405 | /// Determines whether this function is a function with |
2406 | /// external, C linkage. |
2407 | bool isExternC() const; |
2408 | |
2409 | /// Determines whether this function's context is, or is nested within, |
2410 | /// a C++ extern "C" linkage spec. |
2411 | bool isInExternCContext() const; |
2412 | |
2413 | /// Determines whether this function's context is, or is nested within, |
2414 | /// a C++ extern "C++" linkage spec. |
2415 | bool isInExternCXXContext() const; |
2416 | |
2417 | /// Determines whether this is a global function. |
2418 | bool isGlobal() const; |
2419 | |
2420 | /// Determines whether this function is known to be 'noreturn', through |
2421 | /// an attribute on its declaration or its type. |
2422 | bool isNoReturn() const; |
2423 | |
2424 | /// True if the function was a definition but its body was skipped. |
2425 | bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; } |
2426 | void setHasSkippedBody(bool Skipped = true) { |
2427 | FunctionDeclBits.HasSkippedBody = Skipped; |
2428 | } |
2429 | |
2430 | /// True if this function will eventually have a body, once it's fully parsed. |
2431 | bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; } |
2432 | void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; } |
2433 | |
2434 | /// True if this function is considered a multiversioned function. |
2435 | bool isMultiVersion() const { |
2436 | return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion; |
2437 | } |
2438 | |
2439 | /// Sets the multiversion state for this declaration and all of its |
2440 | /// redeclarations. |
2441 | void setIsMultiVersion(bool V = true) { |
2442 | getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V; |
2443 | } |
2444 | |
2445 | /// Gets the kind of multiversioning attribute this declaration has. Note that |
2446 | /// this can return a value even if the function is not multiversion, such as |
2447 | /// the case of 'target'. |
2448 | MultiVersionKind getMultiVersionKind() const; |
2449 | |
2450 | |
2451 | /// True if this function is a multiversioned dispatch function as a part of |
2452 | /// the cpu_specific/cpu_dispatch functionality. |
2453 | bool isCPUDispatchMultiVersion() const; |
2454 | /// True if this function is a multiversioned processor specific function as a |
2455 | /// part of the cpu_specific/cpu_dispatch functionality. |
2456 | bool isCPUSpecificMultiVersion() const; |
2457 | |
2458 | /// True if this function is a multiversioned dispatch function as a part of |
2459 | /// the target functionality. |
2460 | bool isTargetMultiVersion() const; |
2461 | |
2462 | /// \brief Get the associated-constraints of this function declaration. |
2463 | /// Currently, this will either be a vector of size 1 containing the |
2464 | /// trailing-requires-clause or an empty vector. |
2465 | /// |
2466 | /// Use this instead of getTrailingRequiresClause for concepts APIs that |
2467 | /// accept an ArrayRef of constraint expressions. |
2468 | void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const { |
2469 | if (auto *TRC = getTrailingRequiresClause()) |
2470 | AC.push_back(TRC); |
2471 | } |
2472 | |
2473 | void setPreviousDeclaration(FunctionDecl * PrevDecl); |
2474 | |
2475 | FunctionDecl *getCanonicalDecl() override; |
2476 | const FunctionDecl *getCanonicalDecl() const { |
2477 | return const_cast<FunctionDecl*>(this)->getCanonicalDecl(); |
2478 | } |
2479 | |
2480 | unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const; |
2481 | |
2482 | // ArrayRef interface to parameters. |
2483 | ArrayRef<ParmVarDecl *> parameters() const { |
2484 | return {ParamInfo, getNumParams()}; |
2485 | } |
2486 | MutableArrayRef<ParmVarDecl *> parameters() { |
2487 | return {ParamInfo, getNumParams()}; |
2488 | } |
2489 | |
2490 | // Iterator access to formal parameters. |
2491 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
2492 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
2493 | |
2494 | bool param_empty() const { return parameters().empty(); } |
2495 | param_iterator param_begin() { return parameters().begin(); } |
2496 | param_iterator param_end() { return parameters().end(); } |
2497 | param_const_iterator param_begin() const { return parameters().begin(); } |
2498 | param_const_iterator param_end() const { return parameters().end(); } |
2499 | size_t param_size() const { return parameters().size(); } |
2500 | |
2501 | /// Return the number of parameters this function must have based on its |
2502 | /// FunctionType. This is the length of the ParamInfo array after it has been |
2503 | /// created. |
2504 | unsigned getNumParams() const; |
2505 | |
2506 | const ParmVarDecl *getParamDecl(unsigned i) const { |
2507 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 2507, __extension__ __PRETTY_FUNCTION__)); |
2508 | return ParamInfo[i]; |
2509 | } |
2510 | ParmVarDecl *getParamDecl(unsigned i) { |
2511 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 2511, __extension__ __PRETTY_FUNCTION__)); |
2512 | return ParamInfo[i]; |
2513 | } |
2514 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { |
2515 | setParams(getASTContext(), NewParamInfo); |
2516 | } |
2517 | |
2518 | /// Returns the minimum number of arguments needed to call this function. This |
2519 | /// may be fewer than the number of function parameters, if some of the |
2520 | /// parameters have default arguments (in C++). |
2521 | unsigned getMinRequiredArguments() const; |
2522 | |
2523 | /// Determine whether this function has a single parameter, or multiple |
2524 | /// parameters where all but the first have default arguments. |
2525 | /// |
2526 | /// This notion is used in the definition of copy/move constructors and |
2527 | /// initializer list constructors. Note that, unlike getMinRequiredArguments, |
2528 | /// parameter packs are not treated specially here. |
2529 | bool hasOneParamOrDefaultArgs() const; |
2530 | |
2531 | /// Find the source location information for how the type of this function |
2532 | /// was written. May be absent (for example if the function was declared via |
2533 | /// a typedef) and may contain a different type from that of the function |
2534 | /// (for example if the function type was adjusted by an attribute). |
2535 | FunctionTypeLoc getFunctionTypeLoc() const; |
2536 | |
2537 | QualType getReturnType() const { |
2538 | return getType()->castAs<FunctionType>()->getReturnType(); |
2539 | } |
2540 | |
2541 | /// Attempt to compute an informative source range covering the |
2542 | /// function return type. This may omit qualifiers and other information with |
2543 | /// limited representation in the AST. |
2544 | SourceRange getReturnTypeSourceRange() const; |
2545 | |
2546 | /// Attempt to compute an informative source range covering the |
2547 | /// function parameters, including the ellipsis of a variadic function. |
2548 | /// The source range excludes the parentheses, and is invalid if there are |
2549 | /// no parameters and no ellipsis. |
2550 | SourceRange getParametersSourceRange() const; |
2551 | |
2552 | /// Get the declared return type, which may differ from the actual return |
2553 | /// type if the return type is deduced. |
2554 | QualType getDeclaredReturnType() const { |
2555 | auto *TSI = getTypeSourceInfo(); |
2556 | QualType T = TSI ? TSI->getType() : getType(); |
2557 | return T->castAs<FunctionType>()->getReturnType(); |
2558 | } |
2559 | |
2560 | /// Gets the ExceptionSpecificationType as declared. |
2561 | ExceptionSpecificationType getExceptionSpecType() const { |
2562 | auto *TSI = getTypeSourceInfo(); |
2563 | QualType T = TSI ? TSI->getType() : getType(); |
2564 | const auto *FPT = T->getAs<FunctionProtoType>(); |
2565 | return FPT ? FPT->getExceptionSpecType() : EST_None; |
2566 | } |
2567 | |
2568 | /// Attempt to compute an informative source range covering the |
2569 | /// function exception specification, if any. |
2570 | SourceRange getExceptionSpecSourceRange() const; |
2571 | |
2572 | /// Determine the type of an expression that calls this function. |
2573 | QualType getCallResultType() const { |
2574 | return getType()->castAs<FunctionType>()->getCallResultType( |
2575 | getASTContext()); |
2576 | } |
2577 | |
2578 | /// Returns the storage class as written in the source. For the |
2579 | /// computed linkage of symbol, see getLinkage. |
2580 | StorageClass getStorageClass() const { |
2581 | return static_cast<StorageClass>(FunctionDeclBits.SClass); |
2582 | } |
2583 | |
2584 | /// Sets the storage class as written in the source. |
2585 | void setStorageClass(StorageClass SClass) { |
2586 | FunctionDeclBits.SClass = SClass; |
2587 | } |
2588 | |
2589 | /// Determine whether the "inline" keyword was specified for this |
2590 | /// function. |
2591 | bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; } |
2592 | |
2593 | /// Set whether the "inline" keyword was specified for this function. |
2594 | void setInlineSpecified(bool I) { |
2595 | FunctionDeclBits.IsInlineSpecified = I; |
2596 | FunctionDeclBits.IsInline = I; |
2597 | } |
2598 | |
2599 | /// Determine whether the function was declared in source context |
2600 | /// that requires constrained FP intrinsics |
2601 | bool UsesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; } |
2602 | |
2603 | /// Set whether the function was declared in source context |
2604 | /// that requires constrained FP intrinsics |
2605 | void setUsesFPIntrin(bool I) { FunctionDeclBits.UsesFPIntrin = I; } |
2606 | |
2607 | /// Flag that this function is implicitly inline. |
2608 | void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; } |
2609 | |
2610 | /// Determine whether this function should be inlined, because it is |
2611 | /// either marked "inline" or "constexpr" or is a member function of a class |
2612 | /// that was defined in the class body. |
2613 | bool isInlined() const { return FunctionDeclBits.IsInline; } |
2614 | |
2615 | bool isInlineDefinitionExternallyVisible() const; |
2616 | |
2617 | bool isMSExternInline() const; |
2618 | |
2619 | bool doesDeclarationForceExternallyVisibleDefinition() const; |
2620 | |
2621 | bool isStatic() const { return getStorageClass() == SC_Static; } |
2622 | |
2623 | /// Whether this function declaration represents an C++ overloaded |
2624 | /// operator, e.g., "operator+". |
2625 | bool isOverloadedOperator() const { |
2626 | return getOverloadedOperator() != OO_None; |
2627 | } |
2628 | |
2629 | OverloadedOperatorKind getOverloadedOperator() const; |
2630 | |
2631 | const IdentifierInfo *getLiteralIdentifier() const; |
2632 | |
2633 | /// If this function is an instantiation of a member function |
2634 | /// of a class template specialization, retrieves the function from |
2635 | /// which it was instantiated. |
2636 | /// |
2637 | /// This routine will return non-NULL for (non-templated) member |
2638 | /// functions of class templates and for instantiations of function |
2639 | /// templates. For example, given: |
2640 | /// |
2641 | /// \code |
2642 | /// template<typename T> |
2643 | /// struct X { |
2644 | /// void f(T); |
2645 | /// }; |
2646 | /// \endcode |
2647 | /// |
2648 | /// The declaration for X<int>::f is a (non-templated) FunctionDecl |
2649 | /// whose parent is the class template specialization X<int>. For |
2650 | /// this declaration, getInstantiatedFromFunction() will return |
2651 | /// the FunctionDecl X<T>::A. When a complete definition of |
2652 | /// X<int>::A is required, it will be instantiated from the |
2653 | /// declaration returned by getInstantiatedFromMemberFunction(). |
2654 | FunctionDecl *getInstantiatedFromMemberFunction() const; |
2655 | |
2656 | /// What kind of templated function this is. |
2657 | TemplatedKind getTemplatedKind() const; |
2658 | |
2659 | /// If this function is an instantiation of a member function of a |
2660 | /// class template specialization, retrieves the member specialization |
2661 | /// information. |
2662 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
2663 | |
2664 | /// Specify that this record is an instantiation of the |
2665 | /// member function FD. |
2666 | void setInstantiationOfMemberFunction(FunctionDecl *FD, |
2667 | TemplateSpecializationKind TSK) { |
2668 | setInstantiationOfMemberFunction(getASTContext(), FD, TSK); |
2669 | } |
2670 | |
2671 | /// Retrieves the function template that is described by this |
2672 | /// function declaration. |
2673 | /// |
2674 | /// Every function template is represented as a FunctionTemplateDecl |
2675 | /// and a FunctionDecl (or something derived from FunctionDecl). The |
2676 | /// former contains template properties (such as the template |
2677 | /// parameter lists) while the latter contains the actual |
2678 | /// description of the template's |
2679 | /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the |
2680 | /// FunctionDecl that describes the function template, |
2681 | /// getDescribedFunctionTemplate() retrieves the |
2682 | /// FunctionTemplateDecl from a FunctionDecl. |
2683 | FunctionTemplateDecl *getDescribedFunctionTemplate() const; |
2684 | |
2685 | void setDescribedFunctionTemplate(FunctionTemplateDecl *Template); |
2686 | |
2687 | /// Determine whether this function is a function template |
2688 | /// specialization. |
2689 | bool isFunctionTemplateSpecialization() const { |
2690 | return getPrimaryTemplate() != nullptr; |
2691 | } |
2692 | |
2693 | /// If this function is actually a function template specialization, |
2694 | /// retrieve information about this function template specialization. |
2695 | /// Otherwise, returns NULL. |
2696 | FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const; |
2697 | |
2698 | /// Determines whether this function is a function template |
2699 | /// specialization or a member of a class template specialization that can |
2700 | /// be implicitly instantiated. |
2701 | bool isImplicitlyInstantiable() const; |
2702 | |
2703 | /// Determines if the given function was instantiated from a |
2704 | /// function template. |
2705 | bool isTemplateInstantiation() const; |
2706 | |
2707 | /// Retrieve the function declaration from which this function could |
2708 | /// be instantiated, if it is an instantiation (rather than a non-template |
2709 | /// or a specialization, for example). |
2710 | /// |
2711 | /// If \p ForDefinition is \c false, explicit specializations will be treated |
2712 | /// as if they were implicit instantiations. This will then find the pattern |
2713 | /// corresponding to non-definition portions of the declaration, such as |
2714 | /// default arguments and the exception specification. |
2715 | FunctionDecl * |
2716 | getTemplateInstantiationPattern(bool ForDefinition = true) const; |
2717 | |
2718 | /// Retrieve the primary template that this function template |
2719 | /// specialization either specializes or was instantiated from. |
2720 | /// |
2721 | /// If this function declaration is not a function template specialization, |
2722 | /// returns NULL. |
2723 | FunctionTemplateDecl *getPrimaryTemplate() const; |
2724 | |
2725 | /// Retrieve the template arguments used to produce this function |
2726 | /// template specialization from the primary template. |
2727 | /// |
2728 | /// If this function declaration is not a function template specialization, |
2729 | /// returns NULL. |
2730 | const TemplateArgumentList *getTemplateSpecializationArgs() const; |
2731 | |
2732 | /// Retrieve the template argument list as written in the sources, |
2733 | /// if any. |
2734 | /// |
2735 | /// If this function declaration is not a function template specialization |
2736 | /// or if it had no explicit template argument list, returns NULL. |
2737 | /// Note that it an explicit template argument list may be written empty, |
2738 | /// e.g., template<> void foo<>(char* s); |
2739 | const ASTTemplateArgumentListInfo* |
2740 | getTemplateSpecializationArgsAsWritten() const; |
2741 | |
2742 | /// Specify that this function declaration is actually a function |
2743 | /// template specialization. |
2744 | /// |
2745 | /// \param Template the function template that this function template |
2746 | /// specialization specializes. |
2747 | /// |
2748 | /// \param TemplateArgs the template arguments that produced this |
2749 | /// function template specialization from the template. |
2750 | /// |
2751 | /// \param InsertPos If non-NULL, the position in the function template |
2752 | /// specialization set where the function template specialization data will |
2753 | /// be inserted. |
2754 | /// |
2755 | /// \param TSK the kind of template specialization this is. |
2756 | /// |
2757 | /// \param TemplateArgsAsWritten location info of template arguments. |
2758 | /// |
2759 | /// \param PointOfInstantiation point at which the function template |
2760 | /// specialization was first instantiated. |
2761 | void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, |
2762 | const TemplateArgumentList *TemplateArgs, |
2763 | void *InsertPos, |
2764 | TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, |
2765 | const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr, |
2766 | SourceLocation PointOfInstantiation = SourceLocation()) { |
2767 | setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, |
2768 | InsertPos, TSK, TemplateArgsAsWritten, |
2769 | PointOfInstantiation); |
2770 | } |
2771 | |
2772 | /// Specifies that this function declaration is actually a |
2773 | /// dependent function template specialization. |
2774 | void setDependentTemplateSpecialization(ASTContext &Context, |
2775 | const UnresolvedSetImpl &Templates, |
2776 | const TemplateArgumentListInfo &TemplateArgs); |
2777 | |
2778 | DependentFunctionTemplateSpecializationInfo * |
2779 | getDependentSpecializationInfo() const; |
2780 | |
2781 | /// Determine what kind of template instantiation this function |
2782 | /// represents. |
2783 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
2784 | |
2785 | /// Determine the kind of template specialization this function represents |
2786 | /// for the purpose of template instantiation. |
2787 | TemplateSpecializationKind |
2788 | getTemplateSpecializationKindForInstantiation() const; |
2789 | |
2790 | /// Determine what kind of template instantiation this function |
2791 | /// represents. |
2792 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
2793 | SourceLocation PointOfInstantiation = SourceLocation()); |
2794 | |
2795 | /// Retrieve the (first) point of instantiation of a function template |
2796 | /// specialization or a member of a class template specialization. |
2797 | /// |
2798 | /// \returns the first point of instantiation, if this function was |
2799 | /// instantiated from a template; otherwise, returns an invalid source |
2800 | /// location. |
2801 | SourceLocation getPointOfInstantiation() const; |
2802 | |
2803 | /// Determine whether this is or was instantiated from an out-of-line |
2804 | /// definition of a member function. |
2805 | bool isOutOfLine() const override; |
2806 | |
2807 | /// Identify a memory copying or setting function. |
2808 | /// If the given function is a memory copy or setting function, returns |
2809 | /// the corresponding Builtin ID. If the function is not a memory function, |
2810 | /// returns 0. |
2811 | unsigned getMemoryFunctionKind() const; |
2812 | |
2813 | /// Returns ODRHash of the function. This value is calculated and |
2814 | /// stored on first call, then the stored value returned on the other calls. |
2815 | unsigned getODRHash(); |
2816 | |
2817 | /// Returns cached ODRHash of the function. This must have been previously |
2818 | /// computed and stored. |
2819 | unsigned getODRHash() const; |
2820 | |
2821 | // Implement isa/cast/dyncast/etc. |
2822 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2823 | static bool classofKind(Kind K) { |
2824 | return K >= firstFunction && K <= lastFunction; |
2825 | } |
2826 | static DeclContext *castToDeclContext(const FunctionDecl *D) { |
2827 | return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D)); |
2828 | } |
2829 | static FunctionDecl *castFromDeclContext(const DeclContext *DC) { |
2830 | return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC)); |
2831 | } |
2832 | }; |
2833 | |
2834 | /// Represents a member of a struct/union/class. |
2835 | class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> { |
2836 | unsigned BitField : 1; |
2837 | unsigned Mutable : 1; |
2838 | mutable unsigned CachedFieldIndex : 30; |
2839 | |
2840 | /// The kinds of value we can store in InitializerOrBitWidth. |
2841 | /// |
2842 | /// Note that this is compatible with InClassInitStyle except for |
2843 | /// ISK_CapturedVLAType. |
2844 | enum InitStorageKind { |
2845 | /// If the pointer is null, there's nothing special. Otherwise, |
2846 | /// this is a bitfield and the pointer is the Expr* storing the |
2847 | /// bit-width. |
2848 | ISK_NoInit = (unsigned) ICIS_NoInit, |
2849 | |
2850 | /// The pointer is an (optional due to delayed parsing) Expr* |
2851 | /// holding the copy-initializer. |
2852 | ISK_InClassCopyInit = (unsigned) ICIS_CopyInit, |
2853 | |
2854 | /// The pointer is an (optional due to delayed parsing) Expr* |
2855 | /// holding the list-initializer. |
2856 | ISK_InClassListInit = (unsigned) ICIS_ListInit, |
2857 | |
2858 | /// The pointer is a VariableArrayType* that's been captured; |
2859 | /// the enclosing context is a lambda or captured statement. |
2860 | ISK_CapturedVLAType, |
2861 | }; |
2862 | |
2863 | /// If this is a bitfield with a default member initializer, this |
2864 | /// structure is used to represent the two expressions. |
2865 | struct InitAndBitWidth { |
2866 | Expr *Init; |
2867 | Expr *BitWidth; |
2868 | }; |
2869 | |
2870 | /// Storage for either the bit-width, the in-class initializer, or |
2871 | /// both (via InitAndBitWidth), or the captured variable length array bound. |
2872 | /// |
2873 | /// If the storage kind is ISK_InClassCopyInit or |
2874 | /// ISK_InClassListInit, but the initializer is null, then this |
2875 | /// field has an in-class initializer that has not yet been parsed |
2876 | /// and attached. |
2877 | // FIXME: Tail-allocate this to reduce the size of FieldDecl in the |
2878 | // overwhelmingly common case that we have none of these things. |
2879 | llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage; |
2880 | |
2881 | protected: |
2882 | FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, |
2883 | SourceLocation IdLoc, IdentifierInfo *Id, |
2884 | QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2885 | InClassInitStyle InitStyle) |
2886 | : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), |
2887 | BitField(false), Mutable(Mutable), CachedFieldIndex(0), |
2888 | InitStorage(nullptr, (InitStorageKind) InitStyle) { |
2889 | if (BW) |
2890 | setBitWidth(BW); |
2891 | } |
2892 | |
2893 | public: |
2894 | friend class ASTDeclReader; |
2895 | friend class ASTDeclWriter; |
2896 | |
2897 | static FieldDecl *Create(const ASTContext &C, DeclContext *DC, |
2898 | SourceLocation StartLoc, SourceLocation IdLoc, |
2899 | IdentifierInfo *Id, QualType T, |
2900 | TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2901 | InClassInitStyle InitStyle); |
2902 | |
2903 | static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2904 | |
2905 | /// Returns the index of this field within its record, |
2906 | /// as appropriate for passing to ASTRecordLayout::getFieldOffset. |
2907 | unsigned getFieldIndex() const; |
2908 | |
2909 | /// Determines whether this field is mutable (C++ only). |
2910 | bool isMutable() const { return Mutable; } |
2911 | |
2912 | /// Determines whether this field is a bitfield. |
2913 | bool isBitField() const { return BitField; } |
2914 | |
2915 | /// Determines whether this is an unnamed bitfield. |
2916 | bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); } |
2917 | |
2918 | /// Determines whether this field is a |
2919 | /// representative for an anonymous struct or union. Such fields are |
2920 | /// unnamed and are implicitly generated by the implementation to |
2921 | /// store the data for the anonymous union or struct. |
2922 | bool isAnonymousStructOrUnion() const; |
2923 | |
2924 | Expr *getBitWidth() const { |
2925 | if (!BitField) |
2926 | return nullptr; |
2927 | void *Ptr = InitStorage.getPointer(); |
2928 | if (getInClassInitStyle()) |
2929 | return static_cast<InitAndBitWidth*>(Ptr)->BitWidth; |
2930 | return static_cast<Expr*>(Ptr); |
2931 | } |
2932 | |
2933 | unsigned getBitWidthValue(const ASTContext &Ctx) const; |
2934 | |
2935 | /// Set the bit-field width for this member. |
2936 | // Note: used by some clients (i.e., do not remove it). |
2937 | void setBitWidth(Expr *Width) { |
2938 | assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && ! BitField && "bit width or captured type already set") ? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 2939, __extension__ __PRETTY_FUNCTION__)) |
2939 | "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && ! BitField && "bit width or captured type already set") ? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 2939, __extension__ __PRETTY_FUNCTION__)); |
2940 | assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified" ) ? void (0) : __assert_fail ("Width && \"no bit width specified\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 2940, __extension__ __PRETTY_FUNCTION__)); |
2941 | InitStorage.setPointer( |
2942 | InitStorage.getInt() |
2943 | ? new (getASTContext()) |
2944 | InitAndBitWidth{getInClassInitializer(), Width} |
2945 | : static_cast<void*>(Width)); |
2946 | BitField = true; |
2947 | } |
2948 | |
2949 | /// Remove the bit-field width from this member. |
2950 | // Note: used by some clients (i.e., do not remove it). |
2951 | void removeBitWidth() { |
2952 | assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove" ) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 2952, __extension__ __PRETTY_FUNCTION__)); |
2953 | InitStorage.setPointer(getInClassInitializer()); |
2954 | BitField = false; |
2955 | } |
2956 | |
2957 | /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields |
2958 | /// at all and instead act as a separator between contiguous runs of other |
2959 | /// bit-fields. |
2960 | bool isZeroLengthBitField(const ASTContext &Ctx) const; |
2961 | |
2962 | /// Determine if this field is a subobject of zero size, that is, either a |
2963 | /// zero-length bit-field or a field of empty class type with the |
2964 | /// [[no_unique_address]] attribute. |
2965 | bool isZeroSize(const ASTContext &Ctx) const; |
2966 | |
2967 | /// Get the kind of (C++11) default member initializer that this field has. |
2968 | InClassInitStyle getInClassInitStyle() const { |
2969 | InitStorageKind storageKind = InitStorage.getInt(); |
2970 | return (storageKind == ISK_CapturedVLAType |
2971 | ? ICIS_NoInit : (InClassInitStyle) storageKind); |
2972 | } |
2973 | |
2974 | /// Determine whether this member has a C++11 default member initializer. |
2975 | bool hasInClassInitializer() const { |
2976 | return getInClassInitStyle() != ICIS_NoInit; |
2977 | } |
2978 | |
2979 | /// Get the C++11 default member initializer for this member, or null if one |
2980 | /// has not been set. If a valid declaration has a default member initializer, |
2981 | /// but this returns null, then we have not parsed and attached it yet. |
2982 | Expr *getInClassInitializer() const { |
2983 | if (!hasInClassInitializer()) |
2984 | return nullptr; |
2985 | void *Ptr = InitStorage.getPointer(); |
2986 | if (BitField) |
2987 | return static_cast<InitAndBitWidth*>(Ptr)->Init; |
2988 | return static_cast<Expr*>(Ptr); |
2989 | } |
2990 | |
2991 | /// Set the C++11 in-class initializer for this member. |
2992 | void setInClassInitializer(Expr *Init) { |
2993 | assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() && !getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 2993, __extension__ __PRETTY_FUNCTION__)); |
2994 | if (BitField) |
2995 | static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init; |
2996 | else |
2997 | InitStorage.setPointer(Init); |
2998 | } |
2999 | |
3000 | /// Remove the C++11 in-class initializer from this member. |
3001 | void removeInClassInitializer() { |
3002 | assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() && "no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 3002, __extension__ __PRETTY_FUNCTION__)); |
3003 | InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit); |
3004 | } |
3005 | |
3006 | /// Determine whether this member captures the variable length array |
3007 | /// type. |
3008 | bool hasCapturedVLAType() const { |
3009 | return InitStorage.getInt() == ISK_CapturedVLAType; |
3010 | } |
3011 | |
3012 | /// Get the captured variable length array type. |
3013 | const VariableArrayType *getCapturedVLAType() const { |
3014 | return hasCapturedVLAType() ? static_cast<const VariableArrayType *>( |
3015 | InitStorage.getPointer()) |
3016 | : nullptr; |
3017 | } |
3018 | |
3019 | /// Set the captured variable length array type for this field. |
3020 | void setCapturedVLAType(const VariableArrayType *VLAType); |
3021 | |
3022 | /// Returns the parent of this field declaration, which |
3023 | /// is the struct in which this field is defined. |
3024 | /// |
3025 | /// Returns null if this is not a normal class/struct field declaration, e.g. |
3026 | /// ObjCAtDefsFieldDecl, ObjCIvarDecl. |
3027 | const RecordDecl *getParent() const { |
3028 | return dyn_cast<RecordDecl>(getDeclContext()); |
3029 | } |
3030 | |
3031 | RecordDecl *getParent() { |
3032 | return dyn_cast<RecordDecl>(getDeclContext()); |
3033 | } |
3034 | |
3035 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3036 | |
3037 | /// Retrieves the canonical declaration of this field. |
3038 | FieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3039 | const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3040 | |
3041 | // Implement isa/cast/dyncast/etc. |
3042 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3043 | static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } |
3044 | }; |
3045 | |
3046 | /// An instance of this object exists for each enum constant |
3047 | /// that is defined. For example, in "enum X {a,b}", each of a/b are |
3048 | /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a |
3049 | /// TagType for the X EnumDecl. |
3050 | class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> { |
3051 | Stmt *Init; // an integer constant expression |
3052 | llvm::APSInt Val; // The value. |
3053 | |
3054 | protected: |
3055 | EnumConstantDecl(DeclContext *DC, SourceLocation L, |
3056 | IdentifierInfo *Id, QualType T, Expr *E, |
3057 | const llvm::APSInt &V) |
3058 | : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} |
3059 | |
3060 | public: |
3061 | friend class StmtIteratorBase; |
3062 | |
3063 | static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, |
3064 | SourceLocation L, IdentifierInfo *Id, |
3065 | QualType T, Expr *E, |
3066 | const llvm::APSInt &V); |
3067 | static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3068 | |
3069 | const Expr *getInitExpr() const { return (const Expr*) Init; } |
3070 | Expr *getInitExpr() { return (Expr*) Init; } |
3071 | const llvm::APSInt &getInitVal() const { return Val; } |
3072 | |
3073 | void setInitExpr(Expr *E) { Init = (Stmt*) E; } |
3074 | void setInitVal(const llvm::APSInt &V) { Val = V; } |
3075 | |
3076 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3077 | |
3078 | /// Retrieves the canonical declaration of this enumerator. |
3079 | EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3080 | const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3081 | |
3082 | // Implement isa/cast/dyncast/etc. |
3083 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3084 | static bool classofKind(Kind K) { return K == EnumConstant; } |
3085 | }; |
3086 | |
3087 | /// Represents a field injected from an anonymous union/struct into the parent |
3088 | /// scope. These are always implicit. |
3089 | class IndirectFieldDecl : public ValueDecl, |
3090 | public Mergeable<IndirectFieldDecl> { |
3091 | NamedDecl **Chaining; |
3092 | unsigned ChainingSize; |
3093 | |
3094 | IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L, |
3095 | DeclarationName N, QualType T, |
3096 | MutableArrayRef<NamedDecl *> CH); |
3097 | |
3098 | void anchor() override; |
3099 | |
3100 | public: |
3101 | friend class ASTDeclReader; |
3102 | |
3103 | static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, |
3104 | SourceLocation L, IdentifierInfo *Id, |
3105 | QualType T, llvm::MutableArrayRef<NamedDecl *> CH); |
3106 | |
3107 | static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3108 | |
3109 | using chain_iterator = ArrayRef<NamedDecl *>::const_iterator; |
3110 | |
3111 | ArrayRef<NamedDecl *> chain() const { |
3112 | return llvm::makeArrayRef(Chaining, ChainingSize); |
3113 | } |
3114 | chain_iterator chain_begin() const { return chain().begin(); } |
3115 | chain_iterator chain_end() const { return chain().end(); } |
3116 | |
3117 | unsigned getChainingSize() const { return ChainingSize; } |
3118 | |
3119 | FieldDecl *getAnonField() const { |
3120 | assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 3120, __extension__ __PRETTY_FUNCTION__)); |
3121 | return cast<FieldDecl>(chain().back()); |
3122 | } |
3123 | |
3124 | VarDecl *getVarDecl() const { |
3125 | assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 3125, __extension__ __PRETTY_FUNCTION__)); |
3126 | return dyn_cast<VarDecl>(chain().front()); |
3127 | } |
3128 | |
3129 | IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3130 | const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3131 | |
3132 | // Implement isa/cast/dyncast/etc. |
3133 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3134 | static bool classofKind(Kind K) { return K == IndirectField; } |
3135 | }; |
3136 | |
3137 | /// Represents a declaration of a type. |
3138 | class TypeDecl : public NamedDecl { |
3139 | friend class ASTContext; |
3140 | |
3141 | /// This indicates the Type object that represents |
3142 | /// this TypeDecl. It is a cache maintained by |
3143 | /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and |
3144 | /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. |
3145 | mutable const Type *TypeForDecl = nullptr; |
3146 | |
3147 | /// The start of the source range for this declaration. |
3148 | SourceLocation LocStart; |
3149 | |
3150 | void anchor() override; |
3151 | |
3152 | protected: |
3153 | TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, |
3154 | SourceLocation StartL = SourceLocation()) |
3155 | : NamedDecl(DK, DC, L, Id), LocStart(StartL) {} |
3156 | |
3157 | public: |
3158 | // Low-level accessor. If you just want the type defined by this node, |
3159 | // check out ASTContext::getTypeDeclType or one of |
3160 | // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you |
3161 | // already know the specific kind of node this is. |
3162 | const Type *getTypeForDecl() const { return TypeForDecl; } |
3163 | void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } |
3164 | |
3165 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
3166 | void setLocStart(SourceLocation L) { LocStart = L; } |
3167 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3168 | if (LocStart.isValid()) |
3169 | return SourceRange(LocStart, getLocation()); |
3170 | else |
3171 | return SourceRange(getLocation()); |
3172 | } |
3173 | |
3174 | // Implement isa/cast/dyncast/etc. |
3175 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3176 | static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } |
3177 | }; |
3178 | |
3179 | /// Base class for declarations which introduce a typedef-name. |
3180 | class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> { |
3181 | struct alignas(8) ModedTInfo { |
3182 | TypeSourceInfo *first; |
3183 | QualType second; |
3184 | }; |
3185 | |
3186 | /// If int part is 0, we have not computed IsTransparentTag. |
3187 | /// Otherwise, IsTransparentTag is (getInt() >> 1). |
3188 | mutable llvm::PointerIntPair< |
3189 | llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2> |
3190 | MaybeModedTInfo; |
3191 | |
3192 | void anchor() override; |
3193 | |
3194 | protected: |
3195 | TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC, |
3196 | SourceLocation StartLoc, SourceLocation IdLoc, |
3197 | IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3198 | : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C), |
3199 | MaybeModedTInfo(TInfo, 0) {} |
3200 | |
3201 | using redeclarable_base = Redeclarable<TypedefNameDecl>; |
3202 | |
3203 | TypedefNameDecl *getNextRedeclarationImpl() override { |
3204 | return getNextRedeclaration(); |
3205 | } |
3206 | |
3207 | TypedefNameDecl *getPreviousDeclImpl() override { |
3208 | return getPreviousDecl(); |
3209 | } |
3210 | |
3211 | TypedefNameDecl *getMostRecentDeclImpl() override { |
3212 | return getMostRecentDecl(); |
3213 | } |
3214 | |
3215 | public: |
3216 | using redecl_range = redeclarable_base::redecl_range; |
3217 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3218 | |
3219 | using redeclarable_base::redecls_begin; |
3220 | using redeclarable_base::redecls_end; |
3221 | using redeclarable_base::redecls; |
3222 | using redeclarable_base::getPreviousDecl; |
3223 | using redeclarable_base::getMostRecentDecl; |
3224 | using redeclarable_base::isFirstDecl; |
3225 | |
3226 | bool isModed() const { |
3227 | return MaybeModedTInfo.getPointer().is<ModedTInfo *>(); |
3228 | } |
3229 | |
3230 | TypeSourceInfo *getTypeSourceInfo() const { |
3231 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first |
3232 | : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>(); |
3233 | } |
3234 | |
3235 | QualType getUnderlyingType() const { |
3236 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second |
3237 | : MaybeModedTInfo.getPointer() |
3238 | .get<TypeSourceInfo *>() |
3239 | ->getType(); |
3240 | } |
3241 | |
3242 | void setTypeSourceInfo(TypeSourceInfo *newType) { |
3243 | MaybeModedTInfo.setPointer(newType); |
3244 | } |
3245 | |
3246 | void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) { |
3247 | MaybeModedTInfo.setPointer(new (getASTContext(), 8) |
3248 | ModedTInfo({unmodedTSI, modedTy})); |
3249 | } |
3250 | |
3251 | /// Retrieves the canonical declaration of this typedef-name. |
3252 | TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3253 | const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3254 | |
3255 | /// Retrieves the tag declaration for which this is the typedef name for |
3256 | /// linkage purposes, if any. |
3257 | /// |
3258 | /// \param AnyRedecl Look for the tag declaration in any redeclaration of |
3259 | /// this typedef declaration. |
3260 | TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const; |
3261 | |
3262 | /// Determines if this typedef shares a name and spelling location with its |
3263 | /// underlying tag type, as is the case with the NS_ENUM macro. |
3264 | bool isTransparentTag() const { |
3265 | if (MaybeModedTInfo.getInt()) |
3266 | return MaybeModedTInfo.getInt() & 0x2; |
3267 | return isTransparentTagSlow(); |
3268 | } |
3269 | |
3270 | // Implement isa/cast/dyncast/etc. |
3271 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3272 | static bool classofKind(Kind K) { |
3273 | return K >= firstTypedefName && K <= lastTypedefName; |
3274 | } |
3275 | |
3276 | private: |
3277 | bool isTransparentTagSlow() const; |
3278 | }; |
3279 | |
3280 | /// Represents the declaration of a typedef-name via the 'typedef' |
3281 | /// type specifier. |
3282 | class TypedefDecl : public TypedefNameDecl { |
3283 | TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3284 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3285 | : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {} |
3286 | |
3287 | public: |
3288 | static TypedefDecl *Create(ASTContext &C, DeclContext *DC, |
3289 | SourceLocation StartLoc, SourceLocation IdLoc, |
3290 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
3291 | static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3292 | |
3293 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3294 | |
3295 | // Implement isa/cast/dyncast/etc. |
3296 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3297 | static bool classofKind(Kind K) { return K == Typedef; } |
3298 | }; |
3299 | |
3300 | /// Represents the declaration of a typedef-name via a C++11 |
3301 | /// alias-declaration. |
3302 | class TypeAliasDecl : public TypedefNameDecl { |
3303 | /// The template for which this is the pattern, if any. |
3304 | TypeAliasTemplateDecl *Template; |
3305 | |
3306 | TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3307 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3308 | : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo), |
3309 | Template(nullptr) {} |
3310 | |
3311 | public: |
3312 | static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC, |
3313 | SourceLocation StartLoc, SourceLocation IdLoc, |
3314 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
3315 | static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3316 | |
3317 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3318 | |
3319 | TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; } |
3320 | void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; } |
3321 | |
3322 | // Implement isa/cast/dyncast/etc. |
3323 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3324 | static bool classofKind(Kind K) { return K == TypeAlias; } |
3325 | }; |
3326 | |
3327 | /// Represents the declaration of a struct/union/class/enum. |
3328 | class TagDecl : public TypeDecl, |
3329 | public DeclContext, |
3330 | public Redeclarable<TagDecl> { |
3331 | // This class stores some data in DeclContext::TagDeclBits |
3332 | // to save some space. Use the provided accessors to access it. |
3333 | public: |
3334 | // This is really ugly. |
3335 | using TagKind = TagTypeKind; |
3336 | |
3337 | private: |
3338 | SourceRange BraceRange; |
3339 | |
3340 | // A struct representing syntactic qualifier info, |
3341 | // to be used for the (uncommon) case of out-of-line declarations. |
3342 | using ExtInfo = QualifierInfo; |
3343 | |
3344 | /// If the (out-of-line) tag declaration name |
3345 | /// is qualified, it points to the qualifier info (nns and range); |
3346 | /// otherwise, if the tag declaration is anonymous and it is part of |
3347 | /// a typedef or alias, it points to the TypedefNameDecl (used for mangling); |
3348 | /// otherwise, if the tag declaration is anonymous and it is used as a |
3349 | /// declaration specifier for variables, it points to the first VarDecl (used |
3350 | /// for mangling); |
3351 | /// otherwise, it is a null (TypedefNameDecl) pointer. |
3352 | llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier; |
3353 | |
3354 | bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); } |
3355 | ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); } |
3356 | const ExtInfo *getExtInfo() const { |
3357 | return TypedefNameDeclOrQualifier.get<ExtInfo *>(); |
3358 | } |
3359 | |
3360 | protected: |
3361 | TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3362 | SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, |
3363 | SourceLocation StartL); |
3364 | |
3365 | using redeclarable_base = Redeclarable<TagDecl>; |
3366 | |
3367 | TagDecl *getNextRedeclarationImpl() override { |
3368 | return getNextRedeclaration(); |
3369 | } |
3370 | |
3371 | TagDecl *getPreviousDeclImpl() override { |
3372 | return getPreviousDecl(); |
3373 | } |
3374 | |
3375 | TagDecl *getMostRecentDeclImpl() override { |
3376 | return getMostRecentDecl(); |
3377 | } |
3378 | |
3379 | /// Completes the definition of this tag declaration. |
3380 | /// |
3381 | /// This is a helper function for derived classes. |
3382 | void completeDefinition(); |
3383 | |
3384 | /// True if this decl is currently being defined. |
3385 | void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; } |
3386 | |
3387 | /// Indicates whether it is possible for declarations of this kind |
3388 | /// to have an out-of-date definition. |
3389 | /// |
3390 | /// This option is only enabled when modules are enabled. |
3391 | void setMayHaveOutOfDateDef(bool V = true) { |
3392 | TagDeclBits.MayHaveOutOfDateDef = V; |
3393 | } |
3394 | |
3395 | public: |
3396 | friend class ASTDeclReader; |
3397 | friend class ASTDeclWriter; |
3398 | |
3399 | using redecl_range = redeclarable_base::redecl_range; |
3400 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3401 | |
3402 | using redeclarable_base::redecls_begin; |
3403 | using redeclarable_base::redecls_end; |
3404 | using redeclarable_base::redecls; |
3405 | using redeclarable_base::getPreviousDecl; |
3406 | using redeclarable_base::getMostRecentDecl; |
3407 | using redeclarable_base::isFirstDecl; |
3408 | |
3409 | SourceRange getBraceRange() const { return BraceRange; } |
3410 | void setBraceRange(SourceRange R) { BraceRange = R; } |
3411 | |
3412 | /// Return SourceLocation representing start of source |
3413 | /// range ignoring outer template declarations. |
3414 | SourceLocation getInnerLocStart() const { return getBeginLoc(); } |
3415 | |
3416 | /// Return SourceLocation representing start of source |
3417 | /// range taking into account any outer template declarations. |
3418 | SourceLocation getOuterLocStart() const; |
3419 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3420 | |
3421 | TagDecl *getCanonicalDecl() override; |
3422 | const TagDecl *getCanonicalDecl() const { |
3423 | return const_cast<TagDecl*>(this)->getCanonicalDecl(); |
3424 | } |
3425 | |
3426 | /// Return true if this declaration is a completion definition of the type. |
3427 | /// Provided for consistency. |
3428 | bool isThisDeclarationADefinition() const { |
3429 | return isCompleteDefinition(); |
3430 | } |
3431 | |
3432 | /// Return true if this decl has its body fully specified. |
3433 | bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; } |
3434 | |
3435 | /// True if this decl has its body fully specified. |
3436 | void setCompleteDefinition(bool V = true) { |
3437 | TagDeclBits.IsCompleteDefinition = V; |
3438 | } |
3439 | |
3440 | /// Return true if this complete decl is |
3441 | /// required to be complete for some existing use. |
3442 | bool isCompleteDefinitionRequired() const { |
3443 | return TagDeclBits.IsCompleteDefinitionRequired; |
3444 | } |
3445 | |
3446 | /// True if this complete decl is |
3447 | /// required to be complete for some existing use. |
3448 | void setCompleteDefinitionRequired(bool V = true) { |
3449 | TagDeclBits.IsCompleteDefinitionRequired = V; |
3450 | } |
3451 | |
3452 | /// Return true if this decl is currently being defined. |
3453 | bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; } |
3454 | |
3455 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
3456 | /// for the very first time) in the syntax of a declarator. |
3457 | bool isEmbeddedInDeclarator() const { |
3458 | return TagDeclBits.IsEmbeddedInDeclarator; |
3459 | } |
3460 | |
3461 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
3462 | /// for the very first time) in the syntax of a declarator. |
3463 | void setEmbeddedInDeclarator(bool isInDeclarator) { |
3464 | TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator; |
3465 | } |
3466 | |
3467 | /// True if this tag is free standing, e.g. "struct foo;". |
3468 | bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; } |
3469 | |
3470 | /// True if this tag is free standing, e.g. "struct foo;". |
3471 | void setFreeStanding(bool isFreeStanding = true) { |
3472 | TagDeclBits.IsFreeStanding = isFreeStanding; |
3473 | } |
3474 | |
3475 | /// Indicates whether it is possible for declarations of this kind |
3476 | /// to have an out-of-date definition. |
3477 | /// |
3478 | /// This option is only enabled when modules are enabled. |
3479 | bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; } |
3480 | |
3481 | /// Whether this declaration declares a type that is |
3482 | /// dependent, i.e., a type that somehow depends on template |
3483 | /// parameters. |
3484 | bool isDependentType() const { return isDependentContext(); } |
3485 | |
3486 | /// Starts the definition of this tag declaration. |
3487 | /// |
3488 | /// This method should be invoked at the beginning of the definition |
3489 | /// of this tag declaration. It will set the tag type into a state |
3490 | /// where it is in the process of being defined. |
3491 | void startDefinition(); |
3492 | |
3493 | /// Returns the TagDecl that actually defines this |
3494 | /// struct/union/class/enum. When determining whether or not a |
3495 | /// struct/union/class/enum has a definition, one should use this |
3496 | /// method as opposed to 'isDefinition'. 'isDefinition' indicates |
3497 | /// whether or not a specific TagDecl is defining declaration, not |
3498 | /// whether or not the struct/union/class/enum type is defined. |
3499 | /// This method returns NULL if there is no TagDecl that defines |
3500 | /// the struct/union/class/enum. |
3501 | TagDecl *getDefinition() const; |
3502 | |
3503 | StringRef getKindName() const { |
3504 | return TypeWithKeyword::getTagTypeKindName(getTagKind()); |
3505 | } |
3506 | |
3507 | TagKind getTagKind() const { |
3508 | return static_cast<TagKind>(TagDeclBits.TagDeclKind); |
3509 | } |
3510 | |
3511 | void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; } |
3512 | |
3513 | bool isStruct() const { return getTagKind() == TTK_Struct; } |
3514 | bool isInterface() const { return getTagKind() == TTK_Interface; } |
3515 | bool isClass() const { return getTagKind() == TTK_Class; } |
3516 | bool isUnion() const { return getTagKind() == TTK_Union; } |
3517 | bool isEnum() const { return getTagKind() == TTK_Enum; } |
3518 | |
3519 | /// Is this tag type named, either directly or via being defined in |
3520 | /// a typedef of this type? |
3521 | /// |
3522 | /// C++11 [basic.link]p8: |
3523 | /// A type is said to have linkage if and only if: |
3524 | /// - it is a class or enumeration type that is named (or has a |
3525 | /// name for linkage purposes) and the name has linkage; ... |
3526 | /// C++11 [dcl.typedef]p9: |
3527 | /// If the typedef declaration defines an unnamed class (or enum), |
3528 | /// the first typedef-name declared by the declaration to be that |
3529 | /// class type (or enum type) is used to denote the class type (or |
3530 | /// enum type) for linkage purposes only. |
3531 | /// |
3532 | /// C does not have an analogous rule, but the same concept is |
3533 | /// nonetheless useful in some places. |
3534 | bool hasNameForLinkage() const { |
3535 | return (getDeclName() || getTypedefNameForAnonDecl()); |
3536 | } |
3537 | |
3538 | TypedefNameDecl *getTypedefNameForAnonDecl() const { |
3539 | return hasExtInfo() ? nullptr |
3540 | : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>(); |
3541 | } |
3542 | |
3543 | void setTypedefNameForAnonDecl(TypedefNameDecl *TDD); |
3544 | |
3545 | /// Retrieve the nested-name-specifier that qualifies the name of this |
3546 | /// declaration, if it was present in the source. |
3547 | NestedNameSpecifier *getQualifier() const { |
3548 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
3549 | : nullptr; |
3550 | } |
3551 | |
3552 | /// Retrieve the nested-name-specifier (with source-location |
3553 | /// information) that qualifies the name of this declaration, if it was |
3554 | /// present in the source. |
3555 | NestedNameSpecifierLoc getQualifierLoc() const { |
3556 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
3557 | : NestedNameSpecifierLoc(); |
3558 | } |
3559 | |
3560 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
3561 | |
3562 | unsigned getNumTemplateParameterLists() const { |
3563 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
3564 | } |
3565 | |
3566 | TemplateParameterList *getTemplateParameterList(unsigned i) const { |
3567 | assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists ()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 3567, __extension__ __PRETTY_FUNCTION__)); |
3568 | return getExtInfo()->TemplParamLists[i]; |
3569 | } |
3570 | |
3571 | void setTemplateParameterListsInfo(ASTContext &Context, |
3572 | ArrayRef<TemplateParameterList *> TPLists); |
3573 | |
3574 | // Implement isa/cast/dyncast/etc. |
3575 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3576 | static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } |
3577 | |
3578 | static DeclContext *castToDeclContext(const TagDecl *D) { |
3579 | return static_cast<DeclContext *>(const_cast<TagDecl*>(D)); |
3580 | } |
3581 | |
3582 | static TagDecl *castFromDeclContext(const DeclContext *DC) { |
3583 | return static_cast<TagDecl *>(const_cast<DeclContext*>(DC)); |
3584 | } |
3585 | }; |
3586 | |
3587 | /// Represents an enum. In C++11, enums can be forward-declared |
3588 | /// with a fixed underlying type, and in C we allow them to be forward-declared |
3589 | /// with no underlying type as an extension. |
3590 | class EnumDecl : public TagDecl { |
3591 | // This class stores some data in DeclContext::EnumDeclBits |
3592 | // to save some space. Use the provided accessors to access it. |
3593 | |
3594 | /// This represent the integer type that the enum corresponds |
3595 | /// to for code generation purposes. Note that the enumerator constants may |
3596 | /// have a different type than this does. |
3597 | /// |
3598 | /// If the underlying integer type was explicitly stated in the source |
3599 | /// code, this is a TypeSourceInfo* for that type. Otherwise this type |
3600 | /// was automatically deduced somehow, and this is a Type*. |
3601 | /// |
3602 | /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in |
3603 | /// some cases it won't. |
3604 | /// |
3605 | /// The underlying type of an enumeration never has any qualifiers, so |
3606 | /// we can get away with just storing a raw Type*, and thus save an |
3607 | /// extra pointer when TypeSourceInfo is needed. |
3608 | llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType; |
3609 | |
3610 | /// The integer type that values of this type should |
3611 | /// promote to. In C, enumerators are generally of an integer type |
3612 | /// directly, but gcc-style large enumerators (and all enumerators |
3613 | /// in C++) are of the enum type instead. |
3614 | QualType PromotionType; |
3615 | |
3616 | /// If this enumeration is an instantiation of a member enumeration |
3617 | /// of a class template specialization, this is the member specialization |
3618 | /// information. |
3619 | MemberSpecializationInfo *SpecializationInfo = nullptr; |
3620 | |
3621 | /// Store the ODRHash after first calculation. |
3622 | /// The corresponding flag HasODRHash is in EnumDeclBits |
3623 | /// and can be accessed with the provided accessors. |
3624 | unsigned ODRHash; |
3625 | |
3626 | EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3627 | SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, |
3628 | bool Scoped, bool ScopedUsingClassTag, bool Fixed); |
3629 | |
3630 | void anchor() override; |
3631 | |
3632 | void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, |
3633 | TemplateSpecializationKind TSK); |
3634 | |
3635 | /// Sets the width in bits required to store all the |
3636 | /// non-negative enumerators of this enum. |
3637 | void setNumPositiveBits(unsigned Num) { |
3638 | EnumDeclBits.NumPositiveBits = Num; |
3639 | assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount") ? void (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 3639, __extension__ __PRETTY_FUNCTION__)); |
3640 | } |
3641 | |
3642 | /// Returns the width in bits required to store all the |
3643 | /// negative enumerators of this enum. (see getNumNegativeBits) |
3644 | void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; } |
3645 | |
3646 | public: |
3647 | /// True if this tag declaration is a scoped enumeration. Only |
3648 | /// possible in C++11 mode. |
3649 | void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; } |
3650 | |
3651 | /// If this tag declaration is a scoped enum, |
3652 | /// then this is true if the scoped enum was declared using the class |
3653 | /// tag, false if it was declared with the struct tag. No meaning is |
3654 | /// associated if this tag declaration is not a scoped enum. |
3655 | void setScopedUsingClassTag(bool ScopedUCT = true) { |
3656 | EnumDeclBits.IsScopedUsingClassTag = ScopedUCT; |
3657 | } |
3658 | |
3659 | /// True if this is an Objective-C, C++11, or |
3660 | /// Microsoft-style enumeration with a fixed underlying type. |
3661 | void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; } |
3662 | |
3663 | private: |
3664 | /// True if a valid hash is stored in ODRHash. |
3665 | bool hasODRHash() const { return EnumDeclBits.HasODRHash; } |
3666 | void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; } |
3667 | |
3668 | public: |
3669 | friend class ASTDeclReader; |
3670 | |
3671 | EnumDecl *getCanonicalDecl() override { |
3672 | return cast<EnumDecl>(TagDecl::getCanonicalDecl()); |
3673 | } |
3674 | const EnumDecl *getCanonicalDecl() const { |
3675 | return const_cast<EnumDecl*>(this)->getCanonicalDecl(); |
3676 | } |
3677 | |
3678 | EnumDecl *getPreviousDecl() { |
3679 | return cast_or_null<EnumDecl>( |
3680 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3681 | } |
3682 | const EnumDecl *getPreviousDecl() const { |
3683 | return const_cast<EnumDecl*>(this)->getPreviousDecl(); |
3684 | } |
3685 | |
3686 | EnumDecl *getMostRecentDecl() { |
3687 | return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3688 | } |
3689 | const EnumDecl *getMostRecentDecl() const { |
3690 | return const_cast<EnumDecl*>(this)->getMostRecentDecl(); |
3691 | } |
3692 | |
3693 | EnumDecl *getDefinition() const { |
3694 | return cast_or_null<EnumDecl>(TagDecl::getDefinition()); |
3695 | } |
3696 | |
3697 | static EnumDecl *Create(ASTContext &C, DeclContext *DC, |
3698 | SourceLocation StartLoc, SourceLocation IdLoc, |
3699 | IdentifierInfo *Id, EnumDecl *PrevDecl, |
3700 | bool IsScoped, bool IsScopedUsingClassTag, |
3701 | bool IsFixed); |
3702 | static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3703 | |
3704 | /// When created, the EnumDecl corresponds to a |
3705 | /// forward-declared enum. This method is used to mark the |
3706 | /// declaration as being defined; its enumerators have already been |
3707 | /// added (via DeclContext::addDecl). NewType is the new underlying |
3708 | /// type of the enumeration type. |
3709 | void completeDefinition(QualType NewType, |
3710 | QualType PromotionType, |
3711 | unsigned NumPositiveBits, |
3712 | unsigned NumNegativeBits); |
3713 | |
3714 | // Iterates through the enumerators of this enumeration. |
3715 | using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>; |
3716 | using enumerator_range = |
3717 | llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>; |
3718 | |
3719 | enumerator_range enumerators() const { |
3720 | return enumerator_range(enumerator_begin(), enumerator_end()); |
3721 | } |
3722 | |
3723 | enumerator_iterator enumerator_begin() const { |
3724 | const EnumDecl *E = getDefinition(); |
3725 | if (!E) |
3726 | E = this; |
3727 | return enumerator_iterator(E->decls_begin()); |
3728 | } |
3729 | |
3730 | enumerator_iterator enumerator_end() const { |
3731 | const EnumDecl *E = getDefinition(); |
3732 | if (!E) |
3733 | E = this; |
3734 | return enumerator_iterator(E->decls_end()); |
3735 | } |
3736 | |
3737 | /// Return the integer type that enumerators should promote to. |
3738 | QualType getPromotionType() const { return PromotionType; } |
3739 | |
3740 | /// Set the promotion type. |
3741 | void setPromotionType(QualType T) { PromotionType = T; } |
3742 | |
3743 | /// Return the integer type this enum decl corresponds to. |
3744 | /// This returns a null QualType for an enum forward definition with no fixed |
3745 | /// underlying type. |
3746 | QualType getIntegerType() const { |
3747 | if (!IntegerType) |
3748 | return QualType(); |
3749 | if (const Type *T = IntegerType.dyn_cast<const Type*>()) |
3750 | return QualType(T, 0); |
3751 | return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType(); |
3752 | } |
3753 | |
3754 | /// Set the underlying integer type. |
3755 | void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } |
3756 | |
3757 | /// Set the underlying integer type source info. |
3758 | void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; } |
3759 | |
3760 | /// Return the type source info for the underlying integer type, |
3761 | /// if no type source info exists, return 0. |
3762 | TypeSourceInfo *getIntegerTypeSourceInfo() const { |
3763 | return IntegerType.dyn_cast<TypeSourceInfo*>(); |
3764 | } |
3765 | |
3766 | /// Retrieve the source range that covers the underlying type if |
3767 | /// specified. |
3768 | SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__)); |
3769 | |
3770 | /// Returns the width in bits required to store all the |
3771 | /// non-negative enumerators of this enum. |
3772 | unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; } |
3773 | |
3774 | /// Returns the width in bits required to store all the |
3775 | /// negative enumerators of this enum. These widths include |
3776 | /// the rightmost leading 1; that is: |
3777 | /// |
3778 | /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS |
3779 | /// ------------------------ ------- ----------------- |
3780 | /// -1 1111111 1 |
3781 | /// -10 1110110 5 |
3782 | /// -101 1001011 8 |
3783 | unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; } |
3784 | |
3785 | /// Returns true if this is a C++11 scoped enumeration. |
3786 | bool isScoped() const { return EnumDeclBits.IsScoped; } |
3787 | |
3788 | /// Returns true if this is a C++11 scoped enumeration. |
3789 | bool isScopedUsingClassTag() const { |
3790 | return EnumDeclBits.IsScopedUsingClassTag; |
3791 | } |
3792 | |
3793 | /// Returns true if this is an Objective-C, C++11, or |
3794 | /// Microsoft-style enumeration with a fixed underlying type. |
3795 | bool isFixed() const { return EnumDeclBits.IsFixed; } |
3796 | |
3797 | unsigned getODRHash(); |
3798 | |
3799 | /// Returns true if this can be considered a complete type. |
3800 | bool isComplete() const { |
3801 | // IntegerType is set for fixed type enums and non-fixed but implicitly |
3802 | // int-sized Microsoft enums. |
3803 | return isCompleteDefinition() || IntegerType; |
3804 | } |
3805 | |
3806 | /// Returns true if this enum is either annotated with |
3807 | /// enum_extensibility(closed) or isn't annotated with enum_extensibility. |
3808 | bool isClosed() const; |
3809 | |
3810 | /// Returns true if this enum is annotated with flag_enum and isn't annotated |
3811 | /// with enum_extensibility(open). |
3812 | bool isClosedFlag() const; |
3813 | |
3814 | /// Returns true if this enum is annotated with neither flag_enum nor |
3815 | /// enum_extensibility(open). |
3816 | bool isClosedNonFlag() const; |
3817 | |
3818 | /// Retrieve the enum definition from which this enumeration could |
3819 | /// be instantiated, if it is an instantiation (rather than a non-template). |
3820 | EnumDecl *getTemplateInstantiationPattern() const; |
3821 | |
3822 | /// Returns the enumeration (declared within the template) |
3823 | /// from which this enumeration type was instantiated, or NULL if |
3824 | /// this enumeration was not instantiated from any template. |
3825 | EnumDecl *getInstantiatedFromMemberEnum() const; |
3826 | |
3827 | /// If this enumeration is a member of a specialization of a |
3828 | /// templated class, determine what kind of template specialization |
3829 | /// or instantiation this is. |
3830 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
3831 | |
3832 | /// For an enumeration member that was instantiated from a member |
3833 | /// enumeration of a templated class, set the template specialiation kind. |
3834 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
3835 | SourceLocation PointOfInstantiation = SourceLocation()); |
3836 | |
3837 | /// If this enumeration is an instantiation of a member enumeration of |
3838 | /// a class template specialization, retrieves the member specialization |
3839 | /// information. |
3840 | MemberSpecializationInfo *getMemberSpecializationInfo() const { |
3841 | return SpecializationInfo; |
3842 | } |
3843 | |
3844 | /// Specify that this enumeration is an instantiation of the |
3845 | /// member enumeration ED. |
3846 | void setInstantiationOfMemberEnum(EnumDecl *ED, |
3847 | TemplateSpecializationKind TSK) { |
3848 | setInstantiationOfMemberEnum(getASTContext(), ED, TSK); |
3849 | } |
3850 | |
3851 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3852 | static bool classofKind(Kind K) { return K == Enum; } |
3853 | }; |
3854 | |
3855 | /// Represents a struct/union/class. For example: |
3856 | /// struct X; // Forward declaration, no "body". |
3857 | /// union Y { int A, B; }; // Has body with members A and B (FieldDecls). |
3858 | /// This decl will be marked invalid if *any* members are invalid. |
3859 | class RecordDecl : public TagDecl { |
3860 | // This class stores some data in DeclContext::RecordDeclBits |
3861 | // to save some space. Use the provided accessors to access it. |
3862 | public: |
3863 | friend class DeclContext; |
3864 | /// Enum that represents the different ways arguments are passed to and |
3865 | /// returned from function calls. This takes into account the target-specific |
3866 | /// and version-specific rules along with the rules determined by the |
3867 | /// language. |
3868 | enum ArgPassingKind : unsigned { |
3869 | /// The argument of this type can be passed directly in registers. |
3870 | APK_CanPassInRegs, |
3871 | |
3872 | /// The argument of this type cannot be passed directly in registers. |
3873 | /// Records containing this type as a subobject are not forced to be passed |
3874 | /// indirectly. This value is used only in C++. This value is required by |
3875 | /// C++ because, in uncommon situations, it is possible for a class to have |
3876 | /// only trivial copy/move constructors even when one of its subobjects has |
3877 | /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move |
3878 | /// constructor in the derived class is deleted). |
3879 | APK_CannotPassInRegs, |
3880 | |
3881 | /// The argument of this type cannot be passed directly in registers. |
3882 | /// Records containing this type as a subobject are forced to be passed |
3883 | /// indirectly. |
3884 | APK_CanNeverPassInRegs |
3885 | }; |
3886 | |
3887 | protected: |
3888 | RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3889 | SourceLocation StartLoc, SourceLocation IdLoc, |
3890 | IdentifierInfo *Id, RecordDecl *PrevDecl); |
3891 | |
3892 | public: |
3893 | static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
3894 | SourceLocation StartLoc, SourceLocation IdLoc, |
3895 | IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr); |
3896 | static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); |
3897 | |
3898 | RecordDecl *getPreviousDecl() { |
3899 | return cast_or_null<RecordDecl>( |
3900 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3901 | } |
3902 | const RecordDecl *getPreviousDecl() const { |
3903 | return const_cast<RecordDecl*>(this)->getPreviousDecl(); |
3904 | } |
3905 | |
3906 | RecordDecl *getMostRecentDecl() { |
3907 | return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3908 | } |
3909 | const RecordDecl *getMostRecentDecl() const { |
3910 | return const_cast<RecordDecl*>(this)->getMostRecentDecl(); |
3911 | } |
3912 | |
3913 | bool hasFlexibleArrayMember() const { |
3914 | return RecordDeclBits.HasFlexibleArrayMember; |
3915 | } |
3916 | |
3917 | void setHasFlexibleArrayMember(bool V) { |
3918 | RecordDeclBits.HasFlexibleArrayMember = V; |
3919 | } |
3920 | |
3921 | /// Whether this is an anonymous struct or union. To be an anonymous |
3922 | /// struct or union, it must have been declared without a name and |
3923 | /// there must be no objects of this type declared, e.g., |
3924 | /// @code |
3925 | /// union { int i; float f; }; |
3926 | /// @endcode |
3927 | /// is an anonymous union but neither of the following are: |
3928 | /// @code |
3929 | /// union X { int i; float f; }; |
3930 | /// union { int i; float f; } obj; |
3931 | /// @endcode |
3932 | bool isAnonymousStructOrUnion() const { |
3933 | return RecordDeclBits.AnonymousStructOrUnion; |
3934 | } |
3935 | |
3936 | void setAnonymousStructOrUnion(bool Anon) { |
3937 | RecordDeclBits.AnonymousStructOrUnion = Anon; |
3938 | } |
3939 | |
3940 | bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; } |
3941 | void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; } |
3942 | |
3943 | bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; } |
3944 | |
3945 | void setHasVolatileMember(bool val) { |
3946 | RecordDeclBits.HasVolatileMember = val; |
3947 | } |
3948 | |
3949 | bool hasLoadedFieldsFromExternalStorage() const { |
3950 | return RecordDeclBits.LoadedFieldsFromExternalStorage; |
3951 | } |
3952 | |
3953 | void setHasLoadedFieldsFromExternalStorage(bool val) const { |
3954 | RecordDeclBits.LoadedFieldsFromExternalStorage = val; |
3955 | } |
3956 | |
3957 | /// Functions to query basic properties of non-trivial C structs. |
3958 | bool isNonTrivialToPrimitiveDefaultInitialize() const { |
3959 | return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize; |
3960 | } |
3961 | |
3962 | void setNonTrivialToPrimitiveDefaultInitialize(bool V) { |
3963 | RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V; |
3964 | } |
3965 | |
3966 | bool isNonTrivialToPrimitiveCopy() const { |
3967 | return RecordDeclBits.NonTrivialToPrimitiveCopy; |
3968 | } |
3969 | |
3970 | void setNonTrivialToPrimitiveCopy(bool V) { |
3971 | RecordDeclBits.NonTrivialToPrimitiveCopy = V; |
3972 | } |
3973 | |
3974 | bool isNonTrivialToPrimitiveDestroy() const { |
3975 | return RecordDeclBits.NonTrivialToPrimitiveDestroy; |
3976 | } |
3977 | |
3978 | void setNonTrivialToPrimitiveDestroy(bool V) { |
3979 | RecordDeclBits.NonTrivialToPrimitiveDestroy = V; |
3980 | } |
3981 | |
3982 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
3983 | return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion; |
3984 | } |
3985 | |
3986 | void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) { |
3987 | RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V; |
3988 | } |
3989 | |
3990 | bool hasNonTrivialToPrimitiveDestructCUnion() const { |
3991 | return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion; |
3992 | } |
3993 | |
3994 | void setHasNonTrivialToPrimitiveDestructCUnion(bool V) { |
3995 | RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V; |
3996 | } |
3997 | |
3998 | bool hasNonTrivialToPrimitiveCopyCUnion() const { |
3999 | return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion; |
4000 | } |
4001 | |
4002 | void setHasNonTrivialToPrimitiveCopyCUnion(bool V) { |
4003 | RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V; |
4004 | } |
4005 | |
4006 | /// Determine whether this class can be passed in registers. In C++ mode, |
4007 | /// it must have at least one trivial, non-deleted copy or move constructor. |
4008 | /// FIXME: This should be set as part of completeDefinition. |
4009 | bool canPassInRegisters() const { |
4010 | return getArgPassingRestrictions() == APK_CanPassInRegs; |
4011 | } |
4012 | |
4013 | ArgPassingKind getArgPassingRestrictions() const { |
4014 | return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions); |
4015 | } |
4016 | |
4017 | void setArgPassingRestrictions(ArgPassingKind Kind) { |
4018 | RecordDeclBits.ArgPassingRestrictions = Kind; |
4019 | } |
4020 | |
4021 | bool isParamDestroyedInCallee() const { |
4022 | return RecordDeclBits.ParamDestroyedInCallee; |
4023 | } |
4024 | |
4025 | void setParamDestroyedInCallee(bool V) { |
4026 | RecordDeclBits.ParamDestroyedInCallee = V; |
4027 | } |
4028 | |
4029 | /// Determines whether this declaration represents the |
4030 | /// injected class name. |
4031 | /// |
4032 | /// The injected class name in C++ is the name of the class that |
4033 | /// appears inside the class itself. For example: |
4034 | /// |
4035 | /// \code |
4036 | /// struct C { |
4037 | /// // C is implicitly declared here as a synonym for the class name. |
4038 | /// }; |
4039 | /// |
4040 | /// C::C c; // same as "C c;" |
4041 | /// \endcode |
4042 | bool isInjectedClassName() const; |
4043 | |
4044 | /// Determine whether this record is a class describing a lambda |
4045 | /// function object. |
4046 | bool isLambda() const; |
4047 | |
4048 | /// Determine whether this record is a record for captured variables in |
4049 | /// CapturedStmt construct. |
4050 | bool isCapturedRecord() const; |
4051 | |
4052 | /// Mark the record as a record for captured variables in CapturedStmt |
4053 | /// construct. |
4054 | void setCapturedRecord(); |
4055 | |
4056 | /// Returns the RecordDecl that actually defines |
4057 | /// this struct/union/class. When determining whether or not a |
4058 | /// struct/union/class is completely defined, one should use this |
4059 | /// method as opposed to 'isCompleteDefinition'. |
4060 | /// 'isCompleteDefinition' indicates whether or not a specific |
4061 | /// RecordDecl is a completed definition, not whether or not the |
4062 | /// record type is defined. This method returns NULL if there is |
4063 | /// no RecordDecl that defines the struct/union/tag. |
4064 | RecordDecl *getDefinition() const { |
4065 | return cast_or_null<RecordDecl>(TagDecl::getDefinition()); |
4066 | } |
4067 | |
4068 | /// Returns whether this record is a union, or contains (at any nesting level) |
4069 | /// a union member. This is used by CMSE to warn about possible information |
4070 | /// leaks. |
4071 | bool isOrContainsUnion() const; |
4072 | |
4073 | // Iterator access to field members. The field iterator only visits |
4074 | // the non-static data members of this class, ignoring any static |
4075 | // data members, functions, constructors, destructors, etc. |
4076 | using field_iterator = specific_decl_iterator<FieldDecl>; |
4077 | using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>; |
4078 | |
4079 | field_range fields() const { return field_range(field_begin(), field_end()); } |
4080 | field_iterator field_begin() const; |
4081 | |
4082 | field_iterator field_end() const { |
4083 | return field_iterator(decl_iterator()); |
4084 | } |
4085 | |
4086 | // Whether there are any fields (non-static data members) in this record. |
4087 | bool field_empty() const { |
4088 | return field_begin() == field_end(); |
4089 | } |
4090 | |
4091 | /// Note that the definition of this type is now complete. |
4092 | virtual void completeDefinition(); |
4093 | |
4094 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4095 | static bool classofKind(Kind K) { |
4096 | return K >= firstRecord && K <= lastRecord; |
4097 | } |
4098 | |
4099 | /// Get whether or not this is an ms_struct which can |
4100 | /// be turned on with an attribute, pragma, or -mms-bitfields |
4101 | /// commandline option. |
4102 | bool isMsStruct(const ASTContext &C) const; |
4103 | |
4104 | /// Whether we are allowed to insert extra padding between fields. |
4105 | /// These padding are added to help AddressSanitizer detect |
4106 | /// intra-object-overflow bugs. |
4107 | bool mayInsertExtraPadding(bool EmitRemark = false) const; |
4108 | |
4109 | /// Finds the first data member which has a name. |
4110 | /// nullptr is returned if no named data member exists. |
4111 | const FieldDecl *findFirstNamedDataMember() const; |
4112 | |
4113 | private: |
4114 | /// Deserialize just the fields. |
4115 | void LoadFieldsFromExternalStorage() const; |
4116 | }; |
4117 | |
4118 | class FileScopeAsmDecl : public Decl { |
4119 | StringLiteral *AsmString; |
4120 | SourceLocation RParenLoc; |
4121 | |
4122 | FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, |
4123 | SourceLocation StartL, SourceLocation EndL) |
4124 | : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} |
4125 | |
4126 | virtual void anchor(); |
4127 | |
4128 | public: |
4129 | static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, |
4130 | StringLiteral *Str, SourceLocation AsmLoc, |
4131 | SourceLocation RParenLoc); |
4132 | |
4133 | static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4134 | |
4135 | SourceLocation getAsmLoc() const { return getLocation(); } |
4136 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4137 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
4138 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
4139 | return SourceRange(getAsmLoc(), getRParenLoc()); |
4140 | } |
4141 | |
4142 | const StringLiteral *getAsmString() const { return AsmString; } |
4143 | StringLiteral *getAsmString() { return AsmString; } |
4144 | void setAsmString(StringLiteral *Asm) { AsmString = Asm; } |
4145 | |
4146 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4147 | static bool classofKind(Kind K) { return K == FileScopeAsm; } |
4148 | }; |
4149 | |
4150 | /// Represents a block literal declaration, which is like an |
4151 | /// unnamed FunctionDecl. For example: |
4152 | /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } |
4153 | class BlockDecl : public Decl, public DeclContext { |
4154 | // This class stores some data in DeclContext::BlockDeclBits |
4155 | // to save some space. Use the provided accessors to access it. |
4156 | public: |
4157 | /// A class which contains all the information about a particular |
4158 | /// captured value. |
4159 | class Capture { |
4160 | enum { |
4161 | flag_isByRef = 0x1, |
4162 | flag_isNested = 0x2 |
4163 | }; |
4164 | |
4165 | /// The variable being captured. |
4166 | llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags; |
4167 | |
4168 | /// The copy expression, expressed in terms of a DeclRef (or |
4169 | /// BlockDeclRef) to the captured variable. Only required if the |
4170 | /// variable has a C++ class type. |
4171 | Expr *CopyExpr; |
4172 | |
4173 | public: |
4174 | Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) |
4175 | : VariableAndFlags(variable, |
4176 | (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), |
4177 | CopyExpr(copy) {} |
4178 | |
4179 | /// The variable being captured. |
4180 | VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } |
4181 | |
4182 | /// Whether this is a "by ref" capture, i.e. a capture of a __block |
4183 | /// variable. |
4184 | bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } |
4185 | |
4186 | bool isEscapingByref() const { |
4187 | return getVariable()->isEscapingByref(); |
4188 | } |
4189 | |
4190 | bool isNonEscapingByref() const { |
4191 | return getVariable()->isNonEscapingByref(); |
4192 | } |
4193 | |
4194 | /// Whether this is a nested capture, i.e. the variable captured |
4195 | /// is not from outside the immediately enclosing function/block. |
4196 | bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } |
4197 | |
4198 | bool hasCopyExpr() const { return CopyExpr != nullptr; } |
4199 | Expr *getCopyExpr() const { return CopyExpr; } |
4200 | void setCopyExpr(Expr *e) { CopyExpr = e; } |
4201 | }; |
4202 | |
4203 | private: |
4204 | /// A new[]'d array of pointers to ParmVarDecls for the formal |
4205 | /// parameters of this function. This is null if a prototype or if there are |
4206 | /// no formals. |
4207 | ParmVarDecl **ParamInfo = nullptr; |
4208 | unsigned NumParams = 0; |
4209 | |
4210 | Stmt *Body = nullptr; |
4211 | TypeSourceInfo *SignatureAsWritten = nullptr; |
4212 | |
4213 | const Capture *Captures = nullptr; |
4214 | unsigned NumCaptures = 0; |
4215 | |
4216 | unsigned ManglingNumber = 0; |
4217 | Decl *ManglingContextDecl = nullptr; |
4218 | |
4219 | protected: |
4220 | BlockDecl(DeclContext *DC, SourceLocation CaretLoc); |
4221 | |
4222 | public: |
4223 | static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); |
4224 | static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4225 | |
4226 | SourceLocation getCaretLocation() const { return getLocation(); } |
4227 | |
4228 | bool isVariadic() const { return BlockDeclBits.IsVariadic; } |
4229 | void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; } |
4230 | |
4231 | CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } |
4232 | Stmt *getBody() const override { return (Stmt*) Body; } |
4233 | void setBody(CompoundStmt *B) { Body = (Stmt*) B; } |
4234 | |
4235 | void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } |
4236 | TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } |
4237 | |
4238 | // ArrayRef access to formal parameters. |
4239 | ArrayRef<ParmVarDecl *> parameters() const { |
4240 | return {ParamInfo, getNumParams()}; |
4241 | } |
4242 | MutableArrayRef<ParmVarDecl *> parameters() { |
4243 | return {ParamInfo, getNumParams()}; |
4244 | } |
4245 | |
4246 | // Iterator access to formal parameters. |
4247 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
4248 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
4249 | |
4250 | bool param_empty() const { return parameters().empty(); } |
4251 | param_iterator param_begin() { return parameters().begin(); } |
4252 | param_iterator param_end() { return parameters().end(); } |
4253 | param_const_iterator param_begin() const { return parameters().begin(); } |
4254 | param_const_iterator param_end() const { return parameters().end(); } |
4255 | size_t param_size() const { return parameters().size(); } |
4256 | |
4257 | unsigned getNumParams() const { return NumParams; } |
4258 | |
4259 | const ParmVarDecl *getParamDecl(unsigned i) const { |
4260 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4260, __extension__ __PRETTY_FUNCTION__)); |
4261 | return ParamInfo[i]; |
4262 | } |
4263 | ParmVarDecl *getParamDecl(unsigned i) { |
4264 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4264, __extension__ __PRETTY_FUNCTION__)); |
4265 | return ParamInfo[i]; |
4266 | } |
4267 | |
4268 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo); |
4269 | |
4270 | /// True if this block (or its nested blocks) captures |
4271 | /// anything of local storage from its enclosing scopes. |
4272 | bool hasCaptures() const { return NumCaptures || capturesCXXThis(); } |
4273 | |
4274 | /// Returns the number of captured variables. |
4275 | /// Does not include an entry for 'this'. |
4276 | unsigned getNumCaptures() const { return NumCaptures; } |
4277 | |
4278 | using capture_const_iterator = ArrayRef<Capture>::const_iterator; |
4279 | |
4280 | ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; } |
4281 | |
4282 | capture_const_iterator capture_begin() const { return captures().begin(); } |
4283 | capture_const_iterator capture_end() const { return captures().end(); } |
4284 | |
4285 | bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; } |
4286 | void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; } |
4287 | |
4288 | bool blockMissingReturnType() const { |
4289 | return BlockDeclBits.BlockMissingReturnType; |
4290 | } |
4291 | |
4292 | void setBlockMissingReturnType(bool val = true) { |
4293 | BlockDeclBits.BlockMissingReturnType = val; |
4294 | } |
4295 | |
4296 | bool isConversionFromLambda() const { |
4297 | return BlockDeclBits.IsConversionFromLambda; |
4298 | } |
4299 | |
4300 | void setIsConversionFromLambda(bool val = true) { |
4301 | BlockDeclBits.IsConversionFromLambda = val; |
4302 | } |
4303 | |
4304 | bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; } |
4305 | void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; } |
4306 | |
4307 | bool canAvoidCopyToHeap() const { |
4308 | return BlockDeclBits.CanAvoidCopyToHeap; |
4309 | } |
4310 | void setCanAvoidCopyToHeap(bool B = true) { |
4311 | BlockDeclBits.CanAvoidCopyToHeap = B; |
4312 | } |
4313 | |
4314 | bool capturesVariable(const VarDecl *var) const; |
4315 | |
4316 | void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, |
4317 | bool CapturesCXXThis); |
4318 | |
4319 | unsigned getBlockManglingNumber() const { return ManglingNumber; } |
4320 | |
4321 | Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; } |
4322 | |
4323 | void setBlockMangling(unsigned Number, Decl *Ctx) { |
4324 | ManglingNumber = Number; |
4325 | ManglingContextDecl = Ctx; |
4326 | } |
4327 | |
4328 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
4329 | |
4330 | // Implement isa/cast/dyncast/etc. |
4331 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4332 | static bool classofKind(Kind K) { return K == Block; } |
4333 | static DeclContext *castToDeclContext(const BlockDecl *D) { |
4334 | return static_cast<DeclContext *>(const_cast<BlockDecl*>(D)); |
4335 | } |
4336 | static BlockDecl *castFromDeclContext(const DeclContext *DC) { |
4337 | return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC)); |
4338 | } |
4339 | }; |
4340 | |
4341 | /// Represents the body of a CapturedStmt, and serves as its DeclContext. |
4342 | class CapturedDecl final |
4343 | : public Decl, |
4344 | public DeclContext, |
4345 | private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> { |
4346 | protected: |
4347 | size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) { |
4348 | return NumParams; |
4349 | } |
4350 | |
4351 | private: |
4352 | /// The number of parameters to the outlined function. |
4353 | unsigned NumParams; |
4354 | |
4355 | /// The position of context parameter in list of parameters. |
4356 | unsigned ContextParam; |
4357 | |
4358 | /// The body of the outlined function. |
4359 | llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow; |
4360 | |
4361 | explicit CapturedDecl(DeclContext *DC, unsigned NumParams); |
4362 | |
4363 | ImplicitParamDecl *const *getParams() const { |
4364 | return getTrailingObjects<ImplicitParamDecl *>(); |
4365 | } |
4366 | |
4367 | ImplicitParamDecl **getParams() { |
4368 | return getTrailingObjects<ImplicitParamDecl *>(); |
4369 | } |
4370 | |
4371 | public: |
4372 | friend class ASTDeclReader; |
4373 | friend class ASTDeclWriter; |
4374 | friend TrailingObjects; |
4375 | |
4376 | static CapturedDecl *Create(ASTContext &C, DeclContext *DC, |
4377 | unsigned NumParams); |
4378 | static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
4379 | unsigned NumParams); |
4380 | |
4381 | Stmt *getBody() const override; |
4382 | void setBody(Stmt *B); |
4383 | |
4384 | bool isNothrow() const; |
4385 | void setNothrow(bool Nothrow = true); |
4386 | |
4387 | unsigned getNumParams() const { return NumParams; } |
4388 | |
4389 | ImplicitParamDecl *getParam(unsigned i) const { |
4390 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4390, __extension__ __PRETTY_FUNCTION__)); |
4391 | return getParams()[i]; |
4392 | } |
4393 | void setParam(unsigned i, ImplicitParamDecl *P) { |
4394 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4394, __extension__ __PRETTY_FUNCTION__)); |
4395 | getParams()[i] = P; |
4396 | } |
4397 | |
4398 | // ArrayRef interface to parameters. |
4399 | ArrayRef<ImplicitParamDecl *> parameters() const { |
4400 | return {getParams(), getNumParams()}; |
4401 | } |
4402 | MutableArrayRef<ImplicitParamDecl *> parameters() { |
4403 | return {getParams(), getNumParams()}; |
4404 | } |
4405 | |
4406 | /// Retrieve the parameter containing captured variables. |
4407 | ImplicitParamDecl *getContextParam() const { |
4408 | assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void (0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4408, __extension__ __PRETTY_FUNCTION__)); |
4409 | return getParam(ContextParam); |
4410 | } |
4411 | void setContextParam(unsigned i, ImplicitParamDecl *P) { |
4412 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4412, __extension__ __PRETTY_FUNCTION__)); |
4413 | ContextParam = i; |
4414 | setParam(i, P); |
4415 | } |
4416 | unsigned getContextParamPosition() const { return ContextParam; } |
4417 | |
4418 | using param_iterator = ImplicitParamDecl *const *; |
4419 | using param_range = llvm::iterator_range<param_iterator>; |
4420 | |
4421 | /// Retrieve an iterator pointing to the first parameter decl. |
4422 | param_iterator param_begin() const { return getParams(); } |
4423 | /// Retrieve an iterator one past the last parameter decl. |
4424 | param_iterator param_end() const { return getParams() + NumParams; } |
4425 | |
4426 | // Implement isa/cast/dyncast/etc. |
4427 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4428 | static bool classofKind(Kind K) { return K == Captured; } |
4429 | static DeclContext *castToDeclContext(const CapturedDecl *D) { |
4430 | return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D)); |
4431 | } |
4432 | static CapturedDecl *castFromDeclContext(const DeclContext *DC) { |
4433 | return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC)); |
4434 | } |
4435 | }; |
4436 | |
4437 | /// Describes a module import declaration, which makes the contents |
4438 | /// of the named module visible in the current translation unit. |
4439 | /// |
4440 | /// An import declaration imports the named module (or submodule). For example: |
4441 | /// \code |
4442 | /// @import std.vector; |
4443 | /// \endcode |
4444 | /// |
4445 | /// Import declarations can also be implicitly generated from |
4446 | /// \#include/\#import directives. |
4447 | class ImportDecl final : public Decl, |
4448 | llvm::TrailingObjects<ImportDecl, SourceLocation> { |
4449 | friend class ASTContext; |
4450 | friend class ASTDeclReader; |
4451 | friend class ASTReader; |
4452 | friend TrailingObjects; |
4453 | |
4454 | /// The imported module. |
4455 | Module *ImportedModule = nullptr; |
4456 | |
4457 | /// The next import in the list of imports local to the translation |
4458 | /// unit being parsed (not loaded from an AST file). |
4459 | /// |
4460 | /// Includes a bit that indicates whether we have source-location information |
4461 | /// for each identifier in the module name. |
4462 | /// |
4463 | /// When the bit is false, we only have a single source location for the |
4464 | /// end of the import declaration. |
4465 | llvm::PointerIntPair<ImportDecl *, 1, bool> NextLocalImportAndComplete; |
4466 | |
4467 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
4468 | ArrayRef<SourceLocation> IdentifierLocs); |
4469 | |
4470 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
4471 | SourceLocation EndLoc); |
4472 | |
4473 | ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {} |
4474 | |
4475 | bool isImportComplete() const { return NextLocalImportAndComplete.getInt(); } |
4476 | |
4477 | void setImportComplete(bool C) { NextLocalImportAndComplete.setInt(C); } |
4478 | |
4479 | /// The next import in the list of imports local to the translation |
4480 | /// unit being parsed (not loaded from an AST file). |
4481 | ImportDecl *getNextLocalImport() const { |
4482 | return NextLocalImportAndComplete.getPointer(); |
4483 | } |
4484 | |
4485 | void setNextLocalImport(ImportDecl *Import) { |
4486 | NextLocalImportAndComplete.setPointer(Import); |
4487 | } |
4488 | |
4489 | public: |
4490 | /// Create a new module import declaration. |
4491 | static ImportDecl *Create(ASTContext &C, DeclContext *DC, |
4492 | SourceLocation StartLoc, Module *Imported, |
4493 | ArrayRef<SourceLocation> IdentifierLocs); |
4494 | |
4495 | /// Create a new module import declaration for an implicitly-generated |
4496 | /// import. |
4497 | static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, |
4498 | SourceLocation StartLoc, Module *Imported, |
4499 | SourceLocation EndLoc); |
4500 | |
4501 | /// Create a new, deserialized module import declaration. |
4502 | static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
4503 | unsigned NumLocations); |
4504 | |
4505 | /// Retrieve the module that was imported by the import declaration. |
4506 | Module *getImportedModule() const { return ImportedModule; } |
4507 | |
4508 | /// Retrieves the locations of each of the identifiers that make up |
4509 | /// the complete module name in the import declaration. |
4510 | /// |
4511 | /// This will return an empty array if the locations of the individual |
4512 | /// identifiers aren't available. |
4513 | ArrayRef<SourceLocation> getIdentifierLocs() const; |
4514 | |
4515 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
4516 | |
4517 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4518 | static bool classofKind(Kind K) { return K == Import; } |
4519 | }; |
4520 | |
4521 | /// Represents a C++ Modules TS module export declaration. |
4522 | /// |
4523 | /// For example: |
4524 | /// \code |
4525 | /// export void foo(); |
4526 | /// \endcode |
4527 | class ExportDecl final : public Decl, public DeclContext { |
4528 | virtual void anchor(); |
4529 | |
4530 | private: |
4531 | friend class ASTDeclReader; |
4532 | |
4533 | /// The source location for the right brace (if valid). |
4534 | SourceLocation RBraceLoc; |
4535 | |
4536 | ExportDecl(DeclContext *DC, SourceLocation ExportLoc) |
4537 | : Decl(Export, DC, ExportLoc), DeclContext(Export), |
4538 | RBraceLoc(SourceLocation()) {} |
4539 | |
4540 | public: |
4541 | static ExportDecl *Create(ASTContext &C, DeclContext *DC, |
4542 | SourceLocation ExportLoc); |
4543 | static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4544 | |
4545 | SourceLocation getExportLoc() const { return getLocation(); } |
4546 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
4547 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
4548 | |
4549 | bool hasBraces() const { return RBraceLoc.isValid(); } |
4550 | |
4551 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
4552 | if (hasBraces()) |
4553 | return RBraceLoc; |
4554 | // No braces: get the end location of the (only) declaration in context |
4555 | // (if present). |
4556 | return decls_empty() ? getLocation() : decls_begin()->getEndLoc(); |
4557 | } |
4558 | |
4559 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
4560 | return SourceRange(getLocation(), getEndLoc()); |
4561 | } |
4562 | |
4563 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4564 | static bool classofKind(Kind K) { return K == Export; } |
4565 | static DeclContext *castToDeclContext(const ExportDecl *D) { |
4566 | return static_cast<DeclContext *>(const_cast<ExportDecl*>(D)); |
4567 | } |
4568 | static ExportDecl *castFromDeclContext(const DeclContext *DC) { |
4569 | return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC)); |
4570 | } |
4571 | }; |
4572 | |
4573 | /// Represents an empty-declaration. |
4574 | class EmptyDecl : public Decl { |
4575 | EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {} |
4576 | |
4577 | virtual void anchor(); |
4578 | |
4579 | public: |
4580 | static EmptyDecl *Create(ASTContext &C, DeclContext *DC, |
4581 | SourceLocation L); |
4582 | static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4583 | |
4584 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4585 | static bool classofKind(Kind K) { return K == Empty; } |
4586 | }; |
4587 | |
4588 | /// Insertion operator for diagnostics. This allows sending NamedDecl's |
4589 | /// into a diagnostic with <<. |
4590 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, |
4591 | const NamedDecl *ND) { |
4592 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4593 | DiagnosticsEngine::ak_nameddecl); |
4594 | return PD; |
4595 | } |
4596 | |
4597 | template<typename decl_type> |
4598 | void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) { |
4599 | // Note: This routine is implemented here because we need both NamedDecl |
4600 | // and Redeclarable to be defined. |
4601 | assert(RedeclLink.isFirst() &&(static_cast <bool> (RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? void (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4602, __extension__ __PRETTY_FUNCTION__)) |
4602 | "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? void (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4602, __extension__ __PRETTY_FUNCTION__)); |
4603 | |
4604 | if (PrevDecl) { |
4605 | // Point to previous. Make sure that this is actually the most recent |
4606 | // redeclaration, or we can build invalid chains. If the most recent |
4607 | // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. |
4608 | First = PrevDecl->getFirstDecl(); |
4609 | assert(First->RedeclLink.isFirst() && "Expected first")(static_cast <bool> (First->RedeclLink.isFirst() && "Expected first") ? void (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4609, __extension__ __PRETTY_FUNCTION__)); |
4610 | decl_type *MostRecent = First->getNextRedeclaration(); |
4611 | RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent)); |
4612 | |
4613 | // If the declaration was previously visible, a redeclaration of it remains |
4614 | // visible even if it wouldn't be visible by itself. |
4615 | static_cast<decl_type*>(this)->IdentifierNamespace |= |
4616 | MostRecent->getIdentifierNamespace() & |
4617 | (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type); |
4618 | } else { |
4619 | // Make this first. |
4620 | First = static_cast<decl_type*>(this); |
4621 | } |
4622 | |
4623 | // First one will point to this one as latest. |
4624 | First->RedeclLink.setLatest(static_cast<decl_type*>(this)); |
4625 | |
4626 | assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast< decl_type*>(this)) || cast<NamedDecl>(static_cast< decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4627, __extension__ __PRETTY_FUNCTION__)) |
4627 | cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast< decl_type*>(this)) || cast<NamedDecl>(static_cast< decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/Decl.h" , 4627, __extension__ __PRETTY_FUNCTION__)); |
4628 | } |
4629 | |
4630 | // Inline function definitions. |
4631 | |
4632 | /// Check if the given decl is complete. |
4633 | /// |
4634 | /// We use this function to break a cycle between the inline definitions in |
4635 | /// Type.h and Decl.h. |
4636 | inline bool IsEnumDeclComplete(EnumDecl *ED) { |
4637 | return ED->isComplete(); |
4638 | } |
4639 | |
4640 | /// Check if the given decl is scoped. |
4641 | /// |
4642 | /// We use this function to break a cycle between the inline definitions in |
4643 | /// Type.h and Decl.h. |
4644 | inline bool IsEnumDeclScoped(EnumDecl *ED) { |
4645 | return ED->isScoped(); |
4646 | } |
4647 | |
4648 | /// OpenMP variants are mangled early based on their OpenMP context selector. |
4649 | /// The new name looks likes this: |
4650 | /// <name> + OpenMPVariantManglingSeparatorStr + <mangled OpenMP context> |
4651 | static constexpr StringRef getOpenMPVariantManglingSeparatorStr() { |
4652 | return "$ompvariant"; |
4653 | } |
4654 | |
4655 | } // namespace clang |
4656 | |
4657 | #endif // LLVM_CLANG_AST_DECL_H |
1 | //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- 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 | // This file defines the SmallVector class. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_ADT_SMALLVECTOR_H |
14 | #define LLVM_ADT_SMALLVECTOR_H |
15 | |
16 | #include "llvm/ADT/iterator_range.h" |
17 | #include "llvm/Support/Compiler.h" |
18 | #include "llvm/Support/ErrorHandling.h" |
19 | #include "llvm/Support/MemAlloc.h" |
20 | #include "llvm/Support/type_traits.h" |
21 | #include <algorithm> |
22 | #include <cassert> |
23 | #include <cstddef> |
24 | #include <cstdlib> |
25 | #include <cstring> |
26 | #include <functional> |
27 | #include <initializer_list> |
28 | #include <iterator> |
29 | #include <limits> |
30 | #include <memory> |
31 | #include <new> |
32 | #include <type_traits> |
33 | #include <utility> |
34 | |
35 | namespace llvm { |
36 | |
37 | /// This is all the stuff common to all SmallVectors. |
38 | /// |
39 | /// The template parameter specifies the type which should be used to hold the |
40 | /// Size and Capacity of the SmallVector, so it can be adjusted. |
41 | /// Using 32 bit size is desirable to shrink the size of the SmallVector. |
42 | /// Using 64 bit size is desirable for cases like SmallVector<char>, where a |
43 | /// 32 bit size would limit the vector to ~4GB. SmallVectors are used for |
44 | /// buffering bitcode output - which can exceed 4GB. |
45 | template <class Size_T> class SmallVectorBase { |
46 | protected: |
47 | void *BeginX; |
48 | Size_T Size = 0, Capacity; |
49 | |
50 | /// The maximum value of the Size_T used. |
51 | static constexpr size_t SizeTypeMax() { |
52 | return std::numeric_limits<Size_T>::max(); |
53 | } |
54 | |
55 | SmallVectorBase() = delete; |
56 | SmallVectorBase(void *FirstEl, size_t TotalCapacity) |
57 | : BeginX(FirstEl), Capacity(TotalCapacity) {} |
58 | |
59 | /// This is a helper for \a grow() that's out of line to reduce code |
60 | /// duplication. This function will report a fatal error if it can't grow at |
61 | /// least to \p MinSize. |
62 | void *mallocForGrow(size_t MinSize, size_t TSize, size_t &NewCapacity); |
63 | |
64 | /// This is an implementation of the grow() method which only works |
65 | /// on POD-like data types and is out of line to reduce code duplication. |
66 | /// This function will report a fatal error if it cannot increase capacity. |
67 | void grow_pod(void *FirstEl, size_t MinSize, size_t TSize); |
68 | |
69 | public: |
70 | size_t size() const { return Size; } |
71 | size_t capacity() const { return Capacity; } |
72 | |
73 | LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; } |
74 | |
75 | /// Set the array size to \p N, which the current array must have enough |
76 | /// capacity for. |
77 | /// |
78 | /// This does not construct or destroy any elements in the vector. |
79 | /// |
80 | /// Clients can use this in conjunction with capacity() to write past the end |
81 | /// of the buffer when they know that more elements are available, and only |
82 | /// update the size later. This avoids the cost of value initializing elements |
83 | /// which will only be overwritten. |
84 | void set_size(size_t N) { |
85 | assert(N <= capacity())(static_cast <bool> (N <= capacity()) ? void (0) : __assert_fail ("N <= capacity()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 85, __extension__ __PRETTY_FUNCTION__)); |
86 | Size = N; |
87 | } |
88 | }; |
89 | |
90 | template <class T> |
91 | using SmallVectorSizeType = |
92 | typename std::conditional<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t, |
93 | uint32_t>::type; |
94 | |
95 | /// Figure out the offset of the first element. |
96 | template <class T, typename = void> struct SmallVectorAlignmentAndSize { |
97 | alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof( |
98 | SmallVectorBase<SmallVectorSizeType<T>>)]; |
99 | alignas(T) char FirstEl[sizeof(T)]; |
100 | }; |
101 | |
102 | /// This is the part of SmallVectorTemplateBase which does not depend on whether |
103 | /// the type T is a POD. The extra dummy template argument is used by ArrayRef |
104 | /// to avoid unnecessarily requiring T to be complete. |
105 | template <typename T, typename = void> |
106 | class SmallVectorTemplateCommon |
107 | : public SmallVectorBase<SmallVectorSizeType<T>> { |
108 | using Base = SmallVectorBase<SmallVectorSizeType<T>>; |
109 | |
110 | /// Find the address of the first element. For this pointer math to be valid |
111 | /// with small-size of 0 for T with lots of alignment, it's important that |
112 | /// SmallVectorStorage is properly-aligned even for small-size of 0. |
113 | void *getFirstEl() const { |
114 | return const_cast<void *>(reinterpret_cast<const void *>( |
115 | reinterpret_cast<const char *>(this) + |
116 | offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl ))); |
117 | } |
118 | // Space after 'FirstEl' is clobbered, do not add any instance vars after it. |
119 | |
120 | protected: |
121 | SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {} |
122 | |
123 | void grow_pod(size_t MinSize, size_t TSize) { |
124 | Base::grow_pod(getFirstEl(), MinSize, TSize); |
125 | } |
126 | |
127 | /// Return true if this is a smallvector which has not had dynamic |
128 | /// memory allocated for it. |
129 | bool isSmall() const { return this->BeginX == getFirstEl(); } |
130 | |
131 | /// Put this vector in a state of being small. |
132 | void resetToSmall() { |
133 | this->BeginX = getFirstEl(); |
134 | this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect. |
135 | } |
136 | |
137 | /// Return true if V is an internal reference to the given range. |
138 | bool isReferenceToRange(const void *V, const void *First, const void *Last) const { |
139 | // Use std::less to avoid UB. |
140 | std::less<> LessThan; |
141 | return !LessThan(V, First) && LessThan(V, Last); |
142 | } |
143 | |
144 | /// Return true if V is an internal reference to this vector. |
145 | bool isReferenceToStorage(const void *V) const { |
146 | return isReferenceToRange(V, this->begin(), this->end()); |
147 | } |
148 | |
149 | /// Return true if First and Last form a valid (possibly empty) range in this |
150 | /// vector's storage. |
151 | bool isRangeInStorage(const void *First, const void *Last) const { |
152 | // Use std::less to avoid UB. |
153 | std::less<> LessThan; |
154 | return !LessThan(First, this->begin()) && !LessThan(Last, First) && |
155 | !LessThan(this->end(), Last); |
156 | } |
157 | |
158 | /// Return true unless Elt will be invalidated by resizing the vector to |
159 | /// NewSize. |
160 | bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) { |
161 | // Past the end. |
162 | if (LLVM_LIKELY(!isReferenceToStorage(Elt))__builtin_expect((bool)(!isReferenceToStorage(Elt)), true)) |
163 | return true; |
164 | |
165 | // Return false if Elt will be destroyed by shrinking. |
166 | if (NewSize <= this->size()) |
167 | return Elt < this->begin() + NewSize; |
168 | |
169 | // Return false if we need to grow. |
170 | return NewSize <= this->capacity(); |
171 | } |
172 | |
173 | /// Check whether Elt will be invalidated by resizing the vector to NewSize. |
174 | void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) { |
175 | assert(isSafeToReferenceAfterResize(Elt, NewSize) &&(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize ) && "Attempting to reference an element of the vector in an operation " "that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 177, __extension__ __PRETTY_FUNCTION__)) |
176 | "Attempting to reference an element of the vector in an operation "(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize ) && "Attempting to reference an element of the vector in an operation " "that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 177, __extension__ __PRETTY_FUNCTION__)) |
177 | "that invalidates it")(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize ) && "Attempting to reference an element of the vector in an operation " "that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 177, __extension__ __PRETTY_FUNCTION__)); |
178 | } |
179 | |
180 | /// Check whether Elt will be invalidated by increasing the size of the |
181 | /// vector by N. |
182 | void assertSafeToAdd(const void *Elt, size_t N = 1) { |
183 | this->assertSafeToReferenceAfterResize(Elt, this->size() + N); |
184 | } |
185 | |
186 | /// Check whether any part of the range will be invalidated by clearing. |
187 | void assertSafeToReferenceAfterClear(const T *From, const T *To) { |
188 | if (From == To) |
189 | return; |
190 | this->assertSafeToReferenceAfterResize(From, 0); |
191 | this->assertSafeToReferenceAfterResize(To - 1, 0); |
192 | } |
193 | template < |
194 | class ItTy, |
195 | std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value, |
196 | bool> = false> |
197 | void assertSafeToReferenceAfterClear(ItTy, ItTy) {} |
198 | |
199 | /// Check whether any part of the range will be invalidated by growing. |
200 | void assertSafeToAddRange(const T *From, const T *To) { |
201 | if (From == To) |
202 | return; |
203 | this->assertSafeToAdd(From, To - From); |
204 | this->assertSafeToAdd(To - 1, To - From); |
205 | } |
206 | template < |
207 | class ItTy, |
208 | std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value, |
209 | bool> = false> |
210 | void assertSafeToAddRange(ItTy, ItTy) {} |
211 | |
212 | /// Reserve enough space to add one element, and return the updated element |
213 | /// pointer in case it was a reference to the storage. |
214 | template <class U> |
215 | static const T *reserveForParamAndGetAddressImpl(U *This, const T &Elt, |
216 | size_t N) { |
217 | size_t NewSize = This->size() + N; |
218 | if (LLVM_LIKELY(NewSize <= This->capacity())__builtin_expect((bool)(NewSize <= This->capacity()), true )) |
219 | return &Elt; |
220 | |
221 | bool ReferencesStorage = false; |
222 | int64_t Index = -1; |
223 | if (!U::TakesParamByValue) { |
224 | if (LLVM_UNLIKELY(This->isReferenceToStorage(&Elt))__builtin_expect((bool)(This->isReferenceToStorage(&Elt )), false)) { |
225 | ReferencesStorage = true; |
226 | Index = &Elt - This->begin(); |
227 | } |
228 | } |
229 | This->grow(NewSize); |
230 | return ReferencesStorage ? This->begin() + Index : &Elt; |
231 | } |
232 | |
233 | public: |
234 | using size_type = size_t; |
235 | using difference_type = ptrdiff_t; |
236 | using value_type = T; |
237 | using iterator = T *; |
238 | using const_iterator = const T *; |
239 | |
240 | using const_reverse_iterator = std::reverse_iterator<const_iterator>; |
241 | using reverse_iterator = std::reverse_iterator<iterator>; |
242 | |
243 | using reference = T &; |
244 | using const_reference = const T &; |
245 | using pointer = T *; |
246 | using const_pointer = const T *; |
247 | |
248 | using Base::capacity; |
249 | using Base::empty; |
250 | using Base::size; |
251 | |
252 | // forward iterator creation methods. |
253 | iterator begin() { return (iterator)this->BeginX; } |
254 | const_iterator begin() const { return (const_iterator)this->BeginX; } |
255 | iterator end() { return begin() + size(); } |
256 | const_iterator end() const { return begin() + size(); } |
257 | |
258 | // reverse iterator creation methods. |
259 | reverse_iterator rbegin() { return reverse_iterator(end()); } |
260 | const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); } |
261 | reverse_iterator rend() { return reverse_iterator(begin()); } |
262 | const_reverse_iterator rend() const { return const_reverse_iterator(begin());} |
263 | |
264 | size_type size_in_bytes() const { return size() * sizeof(T); } |
265 | size_type max_size() const { |
266 | return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T)); |
267 | } |
268 | |
269 | size_t capacity_in_bytes() const { return capacity() * sizeof(T); } |
270 | |
271 | /// Return a pointer to the vector's buffer, even if empty(). |
272 | pointer data() { return pointer(begin()); } |
273 | /// Return a pointer to the vector's buffer, even if empty(). |
274 | const_pointer data() const { return const_pointer(begin()); } |
275 | |
276 | reference operator[](size_type idx) { |
277 | assert(idx < size())(static_cast <bool> (idx < size()) ? void (0) : __assert_fail ("idx < size()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 277, __extension__ __PRETTY_FUNCTION__)); |
278 | return begin()[idx]; |
279 | } |
280 | const_reference operator[](size_type idx) const { |
281 | assert(idx < size())(static_cast <bool> (idx < size()) ? void (0) : __assert_fail ("idx < size()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 281, __extension__ __PRETTY_FUNCTION__)); |
282 | return begin()[idx]; |
283 | } |
284 | |
285 | reference front() { |
286 | assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail ("!empty()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 286, __extension__ __PRETTY_FUNCTION__)); |
287 | return begin()[0]; |
288 | } |
289 | const_reference front() const { |
290 | assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail ("!empty()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 290, __extension__ __PRETTY_FUNCTION__)); |
291 | return begin()[0]; |
292 | } |
293 | |
294 | reference back() { |
295 | assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail ("!empty()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 295, __extension__ __PRETTY_FUNCTION__)); |
296 | return end()[-1]; |
297 | } |
298 | const_reference back() const { |
299 | assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail ("!empty()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 299, __extension__ __PRETTY_FUNCTION__)); |
300 | return end()[-1]; |
301 | } |
302 | }; |
303 | |
304 | /// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put |
305 | /// method implementations that are designed to work with non-trivial T's. |
306 | /// |
307 | /// We approximate is_trivially_copyable with trivial move/copy construction and |
308 | /// trivial destruction. While the standard doesn't specify that you're allowed |
309 | /// copy these types with memcpy, there is no way for the type to observe this. |
310 | /// This catches the important case of std::pair<POD, POD>, which is not |
311 | /// trivially assignable. |
312 | template <typename T, bool = (is_trivially_copy_constructible<T>::value) && |
313 | (is_trivially_move_constructible<T>::value) && |
314 | std::is_trivially_destructible<T>::value> |
315 | class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> { |
316 | friend class SmallVectorTemplateCommon<T>; |
317 | |
318 | protected: |
319 | static constexpr bool TakesParamByValue = false; |
320 | using ValueParamT = const T &; |
321 | |
322 | SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {} |
323 | |
324 | static void destroy_range(T *S, T *E) { |
325 | while (S != E) { |
326 | --E; |
327 | E->~T(); |
328 | } |
329 | } |
330 | |
331 | /// Move the range [I, E) into the uninitialized memory starting with "Dest", |
332 | /// constructing elements as needed. |
333 | template<typename It1, typename It2> |
334 | static void uninitialized_move(It1 I, It1 E, It2 Dest) { |
335 | std::uninitialized_copy(std::make_move_iterator(I), |
336 | std::make_move_iterator(E), Dest); |
337 | } |
338 | |
339 | /// Copy the range [I, E) onto the uninitialized memory starting with "Dest", |
340 | /// constructing elements as needed. |
341 | template<typename It1, typename It2> |
342 | static void uninitialized_copy(It1 I, It1 E, It2 Dest) { |
343 | std::uninitialized_copy(I, E, Dest); |
344 | } |
345 | |
346 | /// Grow the allocated memory (without initializing new elements), doubling |
347 | /// the size of the allocated memory. Guarantees space for at least one more |
348 | /// element, or MinSize more elements if specified. |
349 | void grow(size_t MinSize = 0); |
350 | |
351 | /// Create a new allocation big enough for \p MinSize and pass back its size |
352 | /// in \p NewCapacity. This is the first section of \a grow(). |
353 | T *mallocForGrow(size_t MinSize, size_t &NewCapacity) { |
354 | return static_cast<T *>( |
355 | SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow( |
356 | MinSize, sizeof(T), NewCapacity)); |
357 | } |
358 | |
359 | /// Move existing elements over to the new allocation \p NewElts, the middle |
360 | /// section of \a grow(). |
361 | void moveElementsForGrow(T *NewElts); |
362 | |
363 | /// Transfer ownership of the allocation, finishing up \a grow(). |
364 | void takeAllocationForGrow(T *NewElts, size_t NewCapacity); |
365 | |
366 | /// Reserve enough space to add one element, and return the updated element |
367 | /// pointer in case it was a reference to the storage. |
368 | const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) { |
369 | return this->reserveForParamAndGetAddressImpl(this, Elt, N); |
370 | } |
371 | |
372 | /// Reserve enough space to add one element, and return the updated element |
373 | /// pointer in case it was a reference to the storage. |
374 | T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) { |
375 | return const_cast<T *>( |
376 | this->reserveForParamAndGetAddressImpl(this, Elt, N)); |
377 | } |
378 | |
379 | static T &&forward_value_param(T &&V) { return std::move(V); } |
380 | static const T &forward_value_param(const T &V) { return V; } |
381 | |
382 | void growAndAssign(size_t NumElts, const T &Elt) { |
383 | // Grow manually in case Elt is an internal reference. |
384 | size_t NewCapacity; |
385 | T *NewElts = mallocForGrow(NumElts, NewCapacity); |
386 | std::uninitialized_fill_n(NewElts, NumElts, Elt); |
387 | this->destroy_range(this->begin(), this->end()); |
388 | takeAllocationForGrow(NewElts, NewCapacity); |
389 | this->set_size(NumElts); |
390 | } |
391 | |
392 | template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) { |
393 | // Grow manually in case one of Args is an internal reference. |
394 | size_t NewCapacity; |
395 | T *NewElts = mallocForGrow(0, NewCapacity); |
396 | ::new ((void *)(NewElts + this->size())) T(std::forward<ArgTypes>(Args)...); |
397 | moveElementsForGrow(NewElts); |
398 | takeAllocationForGrow(NewElts, NewCapacity); |
399 | this->set_size(this->size() + 1); |
400 | return this->back(); |
401 | } |
402 | |
403 | public: |
404 | void push_back(const T &Elt) { |
405 | const T *EltPtr = reserveForParamAndGetAddress(Elt); |
406 | ::new ((void *)this->end()) T(*EltPtr); |
407 | this->set_size(this->size() + 1); |
408 | } |
409 | |
410 | void push_back(T &&Elt) { |
411 | T *EltPtr = reserveForParamAndGetAddress(Elt); |
412 | ::new ((void *)this->end()) T(::std::move(*EltPtr)); |
413 | this->set_size(this->size() + 1); |
414 | } |
415 | |
416 | void pop_back() { |
417 | this->set_size(this->size() - 1); |
418 | this->end()->~T(); |
419 | } |
420 | }; |
421 | |
422 | // Define this out-of-line to dissuade the C++ compiler from inlining it. |
423 | template <typename T, bool TriviallyCopyable> |
424 | void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) { |
425 | size_t NewCapacity; |
426 | T *NewElts = mallocForGrow(MinSize, NewCapacity); |
427 | moveElementsForGrow(NewElts); |
428 | takeAllocationForGrow(NewElts, NewCapacity); |
429 | } |
430 | |
431 | // Define this out-of-line to dissuade the C++ compiler from inlining it. |
432 | template <typename T, bool TriviallyCopyable> |
433 | void SmallVectorTemplateBase<T, TriviallyCopyable>::moveElementsForGrow( |
434 | T *NewElts) { |
435 | // Move the elements over. |
436 | this->uninitialized_move(this->begin(), this->end(), NewElts); |
437 | |
438 | // Destroy the original elements. |
439 | destroy_range(this->begin(), this->end()); |
440 | } |
441 | |
442 | // Define this out-of-line to dissuade the C++ compiler from inlining it. |
443 | template <typename T, bool TriviallyCopyable> |
444 | void SmallVectorTemplateBase<T, TriviallyCopyable>::takeAllocationForGrow( |
445 | T *NewElts, size_t NewCapacity) { |
446 | // If this wasn't grown from the inline copy, deallocate the old space. |
447 | if (!this->isSmall()) |
448 | free(this->begin()); |
449 | |
450 | this->BeginX = NewElts; |
451 | this->Capacity = NewCapacity; |
452 | } |
453 | |
454 | /// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put |
455 | /// method implementations that are designed to work with trivially copyable |
456 | /// T's. This allows using memcpy in place of copy/move construction and |
457 | /// skipping destruction. |
458 | template <typename T> |
459 | class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> { |
460 | friend class SmallVectorTemplateCommon<T>; |
461 | |
462 | protected: |
463 | /// True if it's cheap enough to take parameters by value. Doing so avoids |
464 | /// overhead related to mitigations for reference invalidation. |
465 | static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void *); |
466 | |
467 | /// Either const T& or T, depending on whether it's cheap enough to take |
468 | /// parameters by value. |
469 | using ValueParamT = |
470 | typename std::conditional<TakesParamByValue, T, const T &>::type; |
471 | |
472 | SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {} |
473 | |
474 | // No need to do a destroy loop for POD's. |
475 | static void destroy_range(T *, T *) {} |
476 | |
477 | /// Move the range [I, E) onto the uninitialized memory |
478 | /// starting with "Dest", constructing elements into it as needed. |
479 | template<typename It1, typename It2> |
480 | static void uninitialized_move(It1 I, It1 E, It2 Dest) { |
481 | // Just do a copy. |
482 | uninitialized_copy(I, E, Dest); |
483 | } |
484 | |
485 | /// Copy the range [I, E) onto the uninitialized memory |
486 | /// starting with "Dest", constructing elements into it as needed. |
487 | template<typename It1, typename It2> |
488 | static void uninitialized_copy(It1 I, It1 E, It2 Dest) { |
489 | // Arbitrary iterator types; just use the basic implementation. |
490 | std::uninitialized_copy(I, E, Dest); |
491 | } |
492 | |
493 | /// Copy the range [I, E) onto the uninitialized memory |
494 | /// starting with "Dest", constructing elements into it as needed. |
495 | template <typename T1, typename T2> |
496 | static void uninitialized_copy( |
497 | T1 *I, T1 *E, T2 *Dest, |
498 | std::enable_if_t<std::is_same<typename std::remove_const<T1>::type, |
499 | T2>::value> * = nullptr) { |
500 | // Use memcpy for PODs iterated by pointers (which includes SmallVector |
501 | // iterators): std::uninitialized_copy optimizes to memmove, but we can |
502 | // use memcpy here. Note that I and E are iterators and thus might be |
503 | // invalid for memcpy if they are equal. |
504 | if (I != E) |
505 | memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T)); |
506 | } |
507 | |
508 | /// Double the size of the allocated memory, guaranteeing space for at |
509 | /// least one more element or MinSize if specified. |
510 | void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); } |
511 | |
512 | /// Reserve enough space to add one element, and return the updated element |
513 | /// pointer in case it was a reference to the storage. |
514 | const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) { |
515 | return this->reserveForParamAndGetAddressImpl(this, Elt, N); |
516 | } |
517 | |
518 | /// Reserve enough space to add one element, and return the updated element |
519 | /// pointer in case it was a reference to the storage. |
520 | T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) { |
521 | return const_cast<T *>( |
522 | this->reserveForParamAndGetAddressImpl(this, Elt, N)); |
523 | } |
524 | |
525 | /// Copy \p V or return a reference, depending on \a ValueParamT. |
526 | static ValueParamT forward_value_param(ValueParamT V) { return V; } |
527 | |
528 | void growAndAssign(size_t NumElts, T Elt) { |
529 | // Elt has been copied in case it's an internal reference, side-stepping |
530 | // reference invalidation problems without losing the realloc optimization. |
531 | this->set_size(0); |
532 | this->grow(NumElts); |
533 | std::uninitialized_fill_n(this->begin(), NumElts, Elt); |
534 | this->set_size(NumElts); |
535 | } |
536 | |
537 | template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) { |
538 | // Use push_back with a copy in case Args has an internal reference, |
539 | // side-stepping reference invalidation problems without losing the realloc |
540 | // optimization. |
541 | push_back(T(std::forward<ArgTypes>(Args)...)); |
542 | return this->back(); |
543 | } |
544 | |
545 | public: |
546 | void push_back(ValueParamT Elt) { |
547 | const T *EltPtr = reserveForParamAndGetAddress(Elt); |
548 | memcpy(reinterpret_cast<void *>(this->end()), EltPtr, sizeof(T)); |
549 | this->set_size(this->size() + 1); |
550 | } |
551 | |
552 | void pop_back() { this->set_size(this->size() - 1); } |
553 | }; |
554 | |
555 | /// This class consists of common code factored out of the SmallVector class to |
556 | /// reduce code duplication based on the SmallVector 'N' template parameter. |
557 | template <typename T> |
558 | class SmallVectorImpl : public SmallVectorTemplateBase<T> { |
559 | using SuperClass = SmallVectorTemplateBase<T>; |
560 | |
561 | public: |
562 | using iterator = typename SuperClass::iterator; |
563 | using const_iterator = typename SuperClass::const_iterator; |
564 | using reference = typename SuperClass::reference; |
565 | using size_type = typename SuperClass::size_type; |
566 | |
567 | protected: |
568 | using SmallVectorTemplateBase<T>::TakesParamByValue; |
569 | using ValueParamT = typename SuperClass::ValueParamT; |
570 | |
571 | // Default ctor - Initialize to empty. |
572 | explicit SmallVectorImpl(unsigned N) |
573 | : SmallVectorTemplateBase<T>(N) {} |
574 | |
575 | public: |
576 | SmallVectorImpl(const SmallVectorImpl &) = delete; |
577 | |
578 | ~SmallVectorImpl() { |
579 | // Subclass has already destructed this vector's elements. |
580 | // If this wasn't grown from the inline copy, deallocate the old space. |
581 | if (!this->isSmall()) |
582 | free(this->begin()); |
583 | } |
584 | |
585 | void clear() { |
586 | this->destroy_range(this->begin(), this->end()); |
587 | this->Size = 0; |
588 | } |
589 | |
590 | private: |
591 | template <bool ForOverwrite> void resizeImpl(size_type N) { |
592 | if (N < this->size()) { |
593 | this->pop_back_n(this->size() - N); |
594 | } else if (N > this->size()) { |
595 | this->reserve(N); |
596 | for (auto I = this->end(), E = this->begin() + N; I != E; ++I) |
597 | if (ForOverwrite) |
598 | new (&*I) T; |
599 | else |
600 | new (&*I) T(); |
601 | this->set_size(N); |
602 | } |
603 | } |
604 | |
605 | public: |
606 | void resize(size_type N) { resizeImpl<false>(N); } |
607 | |
608 | /// Like resize, but \ref T is POD, the new values won't be initialized. |
609 | void resize_for_overwrite(size_type N) { resizeImpl<true>(N); } |
610 | |
611 | void resize(size_type N, ValueParamT NV) { |
612 | if (N == this->size()) |
613 | return; |
614 | |
615 | if (N < this->size()) { |
616 | this->pop_back_n(this->size() - N); |
617 | return; |
618 | } |
619 | |
620 | // N > this->size(). Defer to append. |
621 | this->append(N - this->size(), NV); |
622 | } |
623 | |
624 | void reserve(size_type N) { |
625 | if (this->capacity() < N) |
626 | this->grow(N); |
627 | } |
628 | |
629 | void pop_back_n(size_type NumItems) { |
630 | assert(this->size() >= NumItems)(static_cast <bool> (this->size() >= NumItems) ? void (0) : __assert_fail ("this->size() >= NumItems", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 630, __extension__ __PRETTY_FUNCTION__)); |
631 | this->destroy_range(this->end() - NumItems, this->end()); |
632 | this->set_size(this->size() - NumItems); |
633 | } |
634 | |
635 | LLVM_NODISCARD[[clang::warn_unused_result]] T pop_back_val() { |
636 | T Result = ::std::move(this->back()); |
637 | this->pop_back(); |
638 | return Result; |
639 | } |
640 | |
641 | void swap(SmallVectorImpl &RHS); |
642 | |
643 | /// Add the specified range to the end of the SmallVector. |
644 | template <typename in_iter, |
645 | typename = std::enable_if_t<std::is_convertible< |
646 | typename std::iterator_traits<in_iter>::iterator_category, |
647 | std::input_iterator_tag>::value>> |
648 | void append(in_iter in_start, in_iter in_end) { |
649 | this->assertSafeToAddRange(in_start, in_end); |
650 | size_type NumInputs = std::distance(in_start, in_end); |
651 | this->reserve(this->size() + NumInputs); |
652 | this->uninitialized_copy(in_start, in_end, this->end()); |
653 | this->set_size(this->size() + NumInputs); |
654 | } |
655 | |
656 | /// Append \p NumInputs copies of \p Elt to the end. |
657 | void append(size_type NumInputs, ValueParamT Elt) { |
658 | const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs); |
659 | std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr); |
660 | this->set_size(this->size() + NumInputs); |
661 | } |
662 | |
663 | void append(std::initializer_list<T> IL) { |
664 | append(IL.begin(), IL.end()); |
665 | } |
666 | |
667 | void append(const SmallVectorImpl &RHS) { append(RHS.begin(), RHS.end()); } |
668 | |
669 | void assign(size_type NumElts, ValueParamT Elt) { |
670 | // Note that Elt could be an internal reference. |
671 | if (NumElts > this->capacity()) { |
672 | this->growAndAssign(NumElts, Elt); |
673 | return; |
674 | } |
675 | |
676 | // Assign over existing elements. |
677 | std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt); |
678 | if (NumElts > this->size()) |
679 | std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt); |
680 | else if (NumElts < this->size()) |
681 | this->destroy_range(this->begin() + NumElts, this->end()); |
682 | this->set_size(NumElts); |
683 | } |
684 | |
685 | // FIXME: Consider assigning over existing elements, rather than clearing & |
686 | // re-initializing them - for all assign(...) variants. |
687 | |
688 | template <typename in_iter, |
689 | typename = std::enable_if_t<std::is_convertible< |
690 | typename std::iterator_traits<in_iter>::iterator_category, |
691 | std::input_iterator_tag>::value>> |
692 | void assign(in_iter in_start, in_iter in_end) { |
693 | this->assertSafeToReferenceAfterClear(in_start, in_end); |
694 | clear(); |
695 | append(in_start, in_end); |
696 | } |
697 | |
698 | void assign(std::initializer_list<T> IL) { |
699 | clear(); |
700 | append(IL); |
701 | } |
702 | |
703 | void assign(const SmallVectorImpl &RHS) { assign(RHS.begin(), RHS.end()); } |
704 | |
705 | iterator erase(const_iterator CI) { |
706 | // Just cast away constness because this is a non-const member function. |
707 | iterator I = const_cast<iterator>(CI); |
708 | |
709 | assert(this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds.")(static_cast <bool> (this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds.") ? void (0) : __assert_fail ("this->isReferenceToStorage(CI) && \"Iterator to erase is out of bounds.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 709, __extension__ __PRETTY_FUNCTION__)); |
710 | |
711 | iterator N = I; |
712 | // Shift all elts down one. |
713 | std::move(I+1, this->end(), I); |
714 | // Drop the last elt. |
715 | this->pop_back(); |
716 | return(N); |
717 | } |
718 | |
719 | iterator erase(const_iterator CS, const_iterator CE) { |
720 | // Just cast away constness because this is a non-const member function. |
721 | iterator S = const_cast<iterator>(CS); |
722 | iterator E = const_cast<iterator>(CE); |
723 | |
724 | assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds.")(static_cast <bool> (this->isRangeInStorage(S, E) && "Range to erase is out of bounds.") ? void (0) : __assert_fail ("this->isRangeInStorage(S, E) && \"Range to erase is out of bounds.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 724, __extension__ __PRETTY_FUNCTION__)); |
725 | |
726 | iterator N = S; |
727 | // Shift all elts down. |
728 | iterator I = std::move(E, this->end(), S); |
729 | // Drop the last elts. |
730 | this->destroy_range(I, this->end()); |
731 | this->set_size(I - this->begin()); |
732 | return(N); |
733 | } |
734 | |
735 | private: |
736 | template <class ArgType> iterator insert_one_impl(iterator I, ArgType &&Elt) { |
737 | // Callers ensure that ArgType is derived from T. |
738 | static_assert( |
739 | std::is_same<std::remove_const_t<std::remove_reference_t<ArgType>>, |
740 | T>::value, |
741 | "ArgType must be derived from T!"); |
742 | |
743 | if (I == this->end()) { // Important special case for empty vector. |
744 | this->push_back(::std::forward<ArgType>(Elt)); |
745 | return this->end()-1; |
746 | } |
747 | |
748 | assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")(static_cast <bool> (this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.") ? void (0) : __assert_fail ("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 748, __extension__ __PRETTY_FUNCTION__)); |
749 | |
750 | // Grow if necessary. |
751 | size_t Index = I - this->begin(); |
752 | std::remove_reference_t<ArgType> *EltPtr = |
753 | this->reserveForParamAndGetAddress(Elt); |
754 | I = this->begin() + Index; |
755 | |
756 | ::new ((void*) this->end()) T(::std::move(this->back())); |
757 | // Push everything else over. |
758 | std::move_backward(I, this->end()-1, this->end()); |
759 | this->set_size(this->size() + 1); |
760 | |
761 | // If we just moved the element we're inserting, be sure to update |
762 | // the reference (never happens if TakesParamByValue). |
763 | static_assert(!TakesParamByValue || std::is_same<ArgType, T>::value, |
764 | "ArgType must be 'T' when taking by value!"); |
765 | if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end())) |
766 | ++EltPtr; |
767 | |
768 | *I = ::std::forward<ArgType>(*EltPtr); |
769 | return I; |
770 | } |
771 | |
772 | public: |
773 | iterator insert(iterator I, T &&Elt) { |
774 | return insert_one_impl(I, this->forward_value_param(std::move(Elt))); |
775 | } |
776 | |
777 | iterator insert(iterator I, const T &Elt) { |
778 | return insert_one_impl(I, this->forward_value_param(Elt)); |
779 | } |
780 | |
781 | iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) { |
782 | // Convert iterator to elt# to avoid invalidating iterator when we reserve() |
783 | size_t InsertElt = I - this->begin(); |
784 | |
785 | if (I == this->end()) { // Important special case for empty vector. |
786 | append(NumToInsert, Elt); |
787 | return this->begin()+InsertElt; |
788 | } |
789 | |
790 | assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")(static_cast <bool> (this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.") ? void (0) : __assert_fail ("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 790, __extension__ __PRETTY_FUNCTION__)); |
791 | |
792 | // Ensure there is enough space, and get the (maybe updated) address of |
793 | // Elt. |
794 | const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert); |
795 | |
796 | // Uninvalidate the iterator. |
797 | I = this->begin()+InsertElt; |
798 | |
799 | // If there are more elements between the insertion point and the end of the |
800 | // range than there are being inserted, we can use a simple approach to |
801 | // insertion. Since we already reserved space, we know that this won't |
802 | // reallocate the vector. |
803 | if (size_t(this->end()-I) >= NumToInsert) { |
804 | T *OldEnd = this->end(); |
805 | append(std::move_iterator<iterator>(this->end() - NumToInsert), |
806 | std::move_iterator<iterator>(this->end())); |
807 | |
808 | // Copy the existing elements that get replaced. |
809 | std::move_backward(I, OldEnd-NumToInsert, OldEnd); |
810 | |
811 | // If we just moved the element we're inserting, be sure to update |
812 | // the reference (never happens if TakesParamByValue). |
813 | if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end()) |
814 | EltPtr += NumToInsert; |
815 | |
816 | std::fill_n(I, NumToInsert, *EltPtr); |
817 | return I; |
818 | } |
819 | |
820 | // Otherwise, we're inserting more elements than exist already, and we're |
821 | // not inserting at the end. |
822 | |
823 | // Move over the elements that we're about to overwrite. |
824 | T *OldEnd = this->end(); |
825 | this->set_size(this->size() + NumToInsert); |
826 | size_t NumOverwritten = OldEnd-I; |
827 | this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten); |
828 | |
829 | // If we just moved the element we're inserting, be sure to update |
830 | // the reference (never happens if TakesParamByValue). |
831 | if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end()) |
832 | EltPtr += NumToInsert; |
833 | |
834 | // Replace the overwritten part. |
835 | std::fill_n(I, NumOverwritten, *EltPtr); |
836 | |
837 | // Insert the non-overwritten middle part. |
838 | std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr); |
839 | return I; |
840 | } |
841 | |
842 | template <typename ItTy, |
843 | typename = std::enable_if_t<std::is_convertible< |
844 | typename std::iterator_traits<ItTy>::iterator_category, |
845 | std::input_iterator_tag>::value>> |
846 | iterator insert(iterator I, ItTy From, ItTy To) { |
847 | // Convert iterator to elt# to avoid invalidating iterator when we reserve() |
848 | size_t InsertElt = I - this->begin(); |
849 | |
850 | if (I == this->end()) { // Important special case for empty vector. |
851 | append(From, To); |
852 | return this->begin()+InsertElt; |
853 | } |
854 | |
855 | assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")(static_cast <bool> (this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.") ? void (0) : __assert_fail ("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\"" , "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/ADT/SmallVector.h" , 855, __extension__ __PRETTY_FUNCTION__)); |
856 | |
857 | // Check that the reserve that follows doesn't invalidate the iterators. |
858 | this->assertSafeToAddRange(From, To); |
859 | |
860 | size_t NumToInsert = std::distance(From, To); |
861 | |
862 | // Ensure there is enough space. |
863 | reserve(this->size() + NumToInsert); |
864 | |
865 | // Uninvalidate the iterator. |
866 | I = this->begin()+InsertElt; |
867 | |
868 | // If there are more elements between the insertion point and the end of the |
869 | // range than there are being inserted, we can use a simple approach to |
870 | // insertion. Since we already reserved space, we know that this won't |
871 | // reallocate the vector. |
872 | if (size_t(this->end()-I) >= NumToInsert) { |
873 | T *OldEnd = this->end(); |
874 | append(std::move_iterator<iterator>(this->end() - NumToInsert), |
875 | std::move_iterator<iterator>(this->end())); |
876 | |
877 | // Copy the existing elements that get replaced. |
878 | std::move_backward(I, OldEnd-NumToInsert, OldEnd); |
879 | |
880 | std::copy(From, To, I); |
881 | return I; |
882 | } |
883 | |
884 | // Otherwise, we're inserting more elements than exist already, and we're |
885 | // not inserting at the end. |
886 | |
887 | // Move over the elements that we're about to overwrite. |
888 | T *OldEnd = this->end(); |
889 | this->set_size(this->size() + NumToInsert); |
890 | size_t NumOverwritten = OldEnd-I; |
891 | this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten); |
892 | |
893 | // Replace the overwritten part. |
894 | for (T *J = I; NumOverwritten > 0; --NumOverwritten) { |
895 | *J = *From; |
896 | ++J; ++From; |
897 | } |
898 | |
899 | // Insert the non-overwritten middle part. |
900 | this->uninitialized_copy(From, To, OldEnd); |
901 | return I; |
902 | } |
903 | |
904 | void insert(iterator I, std::initializer_list<T> IL) { |
905 | insert(I, IL.begin(), IL.end()); |
906 | } |
907 | |
908 | template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) { |
909 | if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity ()), false)) |
910 | return this->growAndEmplaceBack(std::forward<ArgTypes>(Args)...); |
911 | |
912 | ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...); |
913 | this->set_size(this->size() + 1); |
914 | return this->back(); |
915 | } |
916 | |
917 | SmallVectorImpl &operator=(const SmallVectorImpl &RHS); |
918 | |
919 | SmallVectorImpl &operator=(SmallVectorImpl &&RHS); |
920 | |
921 | bool operator==(const SmallVectorImpl &RHS) const { |
922 | if (this->size() != RHS.size()) return false; |
923 | return std::equal(this->begin(), this->end(), RHS.begin()); |
924 | } |
925 | bool operator!=(const SmallVectorImpl &RHS) const { |
926 | return !(*this == RHS); |
927 | } |
928 | |
929 | bool operator<(const SmallVectorImpl &RHS) const { |
930 | return std::lexicographical_compare(this->begin(), this->end(), |
931 | RHS.begin(), RHS.end()); |
932 | } |
933 | }; |
934 | |
935 | template <typename T> |
936 | void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) { |
937 | if (this == &RHS) return; |
938 | |
939 | // We can only avoid copying elements if neither vector is small. |
940 | if (!this->isSmall() && !RHS.isSmall()) { |
941 | std::swap(this->BeginX, RHS.BeginX); |
942 | std::swap(this->Size, RHS.Size); |
943 | std::swap(this->Capacity, RHS.Capacity); |
944 | return; |
945 | } |
946 | this->reserve(RHS.size()); |
947 | RHS.reserve(this->size()); |
948 | |
949 | // Swap the shared elements. |
950 | size_t NumShared = this->size(); |
951 | if (NumShared > RHS.size()) NumShared = RHS.size(); |
952 | for (size_type i = 0; i != NumShared; ++i) |
953 | std::swap((*this)[i], RHS[i]); |
954 | |
955 | // Copy over the extra elts. |
956 | if (this->size() > RHS.size()) { |
957 | size_t EltDiff = this->size() - RHS.size(); |
958 | this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end()); |
959 | RHS.set_size(RHS.size() + EltDiff); |
960 | this->destroy_range(this->begin()+NumShared, this->end()); |
961 | this->set_size(NumShared); |
962 | } else if (RHS.size() > this->size()) { |
963 | size_t EltDiff = RHS.size() - this->size(); |
964 | this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end()); |
965 | this->set_size(this->size() + EltDiff); |
966 | this->destroy_range(RHS.begin()+NumShared, RHS.end()); |
967 | RHS.set_size(NumShared); |
968 | } |
969 | } |
970 | |
971 | template <typename T> |
972 | SmallVectorImpl<T> &SmallVectorImpl<T>:: |
973 | operator=(const SmallVectorImpl<T> &RHS) { |
974 | // Avoid self-assignment. |
975 | if (this == &RHS) return *this; |
976 | |
977 | // If we already have sufficient space, assign the common elements, then |
978 | // destroy any excess. |
979 | size_t RHSSize = RHS.size(); |
980 | size_t CurSize = this->size(); |
981 | if (CurSize >= RHSSize) { |
982 | // Assign common elements. |
983 | iterator NewEnd; |
984 | if (RHSSize) |
985 | NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin()); |
986 | else |
987 | NewEnd = this->begin(); |
988 | |
989 | // Destroy excess elements. |
990 | this->destroy_range(NewEnd, this->end()); |
991 | |
992 | // Trim. |
993 | this->set_size(RHSSize); |
994 | return *this; |
995 | } |
996 | |
997 | // If we have to grow to have enough elements, destroy the current elements. |
998 | // This allows us to avoid copying them during the grow. |
999 | // FIXME: don't do this if they're efficiently moveable. |
1000 | if (this->capacity() < RHSSize) { |
1001 | // Destroy current elements. |
1002 | this->clear(); |
1003 | CurSize = 0; |
1004 | this->grow(RHSSize); |
1005 | } else if (CurSize) { |
1006 | // Otherwise, use assignment for the already-constructed elements. |
1007 | std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin()); |
1008 | } |
1009 | |
1010 | // Copy construct the new elements in place. |
1011 | this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(), |
1012 | this->begin()+CurSize); |
1013 | |
1014 | // Set end. |
1015 | this->set_size(RHSSize); |
1016 | return *this; |
1017 | } |
1018 | |
1019 | template <typename T> |
1020 | SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) { |
1021 | // Avoid self-assignment. |
1022 | if (this == &RHS) return *this; |
1023 | |
1024 | // If the RHS isn't small, clear this vector and then steal its buffer. |
1025 | if (!RHS.isSmall()) { |
1026 | this->destroy_range(this->begin(), this->end()); |
1027 | if (!this->isSmall()) free(this->begin()); |
1028 | this->BeginX = RHS.BeginX; |
1029 | this->Size = RHS.Size; |
1030 | this->Capacity = RHS.Capacity; |
1031 | RHS.resetToSmall(); |
1032 | return *this; |
1033 | } |
1034 | |
1035 | // If we already have sufficient space, assign the common elements, then |
1036 | // destroy any excess. |
1037 | size_t RHSSize = RHS.size(); |
1038 | size_t CurSize = this->size(); |
1039 | if (CurSize >= RHSSize) { |
1040 | // Assign common elements. |
1041 | iterator NewEnd = this->begin(); |
1042 | if (RHSSize) |
1043 | NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd); |
1044 | |
1045 | // Destroy excess elements and trim the bounds. |
1046 | this->destroy_range(NewEnd, this->end()); |
1047 | this->set_size(RHSSize); |
1048 | |
1049 | // Clear the RHS. |
1050 | RHS.clear(); |
1051 | |
1052 | return *this; |
1053 | } |
1054 | |
1055 | // If we have to grow to have enough elements, destroy the current elements. |
1056 | // This allows us to avoid copying them during the grow. |
1057 | // FIXME: this may not actually make any sense if we can efficiently move |
1058 | // elements. |
1059 | if (this->capacity() < RHSSize) { |
1060 | // Destroy current elements. |
1061 | this->clear(); |
1062 | CurSize = 0; |
1063 | this->grow(RHSSize); |
1064 | } else if (CurSize) { |
1065 | // Otherwise, use assignment for the already-constructed elements. |
1066 | std::move(RHS.begin(), RHS.begin()+CurSize, this->begin()); |
1067 | } |
1068 | |
1069 | // Move-construct the new elements in place. |
1070 | this->uninitialized_move(RHS.begin()+CurSize, RHS.end(), |
1071 | this->begin()+CurSize); |
1072 | |
1073 | // Set end. |
1074 | this->set_size(RHSSize); |
1075 | |
1076 | RHS.clear(); |
1077 | return *this; |
1078 | } |
1079 | |
1080 | /// Storage for the SmallVector elements. This is specialized for the N=0 case |
1081 | /// to avoid allocating unnecessary storage. |
1082 | template <typename T, unsigned N> |
1083 | struct SmallVectorStorage { |
1084 | alignas(T) char InlineElts[N * sizeof(T)]; |
1085 | }; |
1086 | |
1087 | /// We need the storage to be properly aligned even for small-size of 0 so that |
1088 | /// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is |
1089 | /// well-defined. |
1090 | template <typename T> struct alignas(T) SmallVectorStorage<T, 0> {}; |
1091 | |
1092 | /// Forward declaration of SmallVector so that |
1093 | /// calculateSmallVectorDefaultInlinedElements can reference |
1094 | /// `sizeof(SmallVector<T, 0>)`. |
1095 | template <typename T, unsigned N> class LLVM_GSL_OWNER[[gsl::Owner]] SmallVector; |
1096 | |
1097 | /// Helper class for calculating the default number of inline elements for |
1098 | /// `SmallVector<T>`. |
1099 | /// |
1100 | /// This should be migrated to a constexpr function when our minimum |
1101 | /// compiler support is enough for multi-statement constexpr functions. |
1102 | template <typename T> struct CalculateSmallVectorDefaultInlinedElements { |
1103 | // Parameter controlling the default number of inlined elements |
1104 | // for `SmallVector<T>`. |
1105 | // |
1106 | // The default number of inlined elements ensures that |
1107 | // 1. There is at least one inlined element. |
1108 | // 2. `sizeof(SmallVector<T>) <= kPreferredSmallVectorSizeof` unless |
1109 | // it contradicts 1. |
1110 | static constexpr size_t kPreferredSmallVectorSizeof = 64; |
1111 | |
1112 | // static_assert that sizeof(T) is not "too big". |
1113 | // |
1114 | // Because our policy guarantees at least one inlined element, it is possible |
1115 | // for an arbitrarily large inlined element to allocate an arbitrarily large |
1116 | // amount of inline storage. We generally consider it an antipattern for a |
1117 | // SmallVector to allocate an excessive amount of inline storage, so we want |
1118 | // to call attention to these cases and make sure that users are making an |
1119 | // intentional decision if they request a lot of inline storage. |
1120 | // |
1121 | // We want this assertion to trigger in pathological cases, but otherwise |
1122 | // not be too easy to hit. To accomplish that, the cutoff is actually somewhat |
1123 | // larger than kPreferredSmallVectorSizeof (otherwise, |
1124 | // `SmallVector<SmallVector<T>>` would be one easy way to trip it, and that |
1125 | // pattern seems useful in practice). |
1126 | // |
1127 | // One wrinkle is that this assertion is in theory non-portable, since |
1128 | // sizeof(T) is in general platform-dependent. However, we don't expect this |
1129 | // to be much of an issue, because most LLVM development happens on 64-bit |
1130 | // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for |
1131 | // 32-bit hosts, dodging the issue. The reverse situation, where development |
1132 | // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a |
1133 | // 64-bit host, is expected to be very rare. |
1134 | static_assert( |
1135 | sizeof(T) <= 256, |
1136 | "You are trying to use a default number of inlined elements for " |
1137 | "`SmallVector<T>` but `sizeof(T)` is really big! Please use an " |
1138 | "explicit number of inlined elements with `SmallVector<T, N>` to make " |
1139 | "sure you really want that much inline storage."); |
1140 | |
1141 | // Discount the size of the header itself when calculating the maximum inline |
1142 | // bytes. |
1143 | static constexpr size_t PreferredInlineBytes = |
1144 | kPreferredSmallVectorSizeof - sizeof(SmallVector<T, 0>); |
1145 | static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T); |
1146 | static constexpr size_t value = |
1147 | NumElementsThatFit == 0 ? 1 : NumElementsThatFit; |
1148 | }; |
1149 | |
1150 | /// This is a 'vector' (really, a variable-sized array), optimized |
1151 | /// for the case when the array is small. It contains some number of elements |
1152 | /// in-place, which allows it to avoid heap allocation when the actual number of |
1153 | /// elements is below that threshold. This allows normal "small" cases to be |
1154 | /// fast without losing generality for large inputs. |
1155 | /// |
1156 | /// \note |
1157 | /// In the absence of a well-motivated choice for the number of inlined |
1158 | /// elements \p N, it is recommended to use \c SmallVector<T> (that is, |
1159 | /// omitting the \p N). This will choose a default number of inlined elements |
1160 | /// reasonable for allocation on the stack (for example, trying to keep \c |
1161 | /// sizeof(SmallVector<T>) around 64 bytes). |
1162 | /// |
1163 | /// \warning This does not attempt to be exception safe. |
1164 | /// |
1165 | /// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h |
1166 | template <typename T, |
1167 | unsigned N = CalculateSmallVectorDefaultInlinedElements<T>::value> |
1168 | class LLVM_GSL_OWNER[[gsl::Owner]] SmallVector : public SmallVectorImpl<T>, |
1169 | SmallVectorStorage<T, N> { |
1170 | public: |
1171 | SmallVector() : SmallVectorImpl<T>(N) {} |
1172 | |
1173 | ~SmallVector() { |
1174 | // Destroy the constructed elements in the vector. |
1175 | this->destroy_range(this->begin(), this->end()); |
1176 | } |
1177 | |
1178 | explicit SmallVector(size_t Size, const T &Value = T()) |
1179 | : SmallVectorImpl<T>(N) { |
1180 | this->assign(Size, Value); |
1181 | } |
1182 | |
1183 | template <typename ItTy, |
1184 | typename = std::enable_if_t<std::is_convertible< |
1185 | typename std::iterator_traits<ItTy>::iterator_category, |
1186 | std::input_iterator_tag>::value>> |
1187 | SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) { |
1188 | this->append(S, E); |
1189 | } |
1190 | |
1191 | template <typename RangeTy> |
1192 | explicit SmallVector(const iterator_range<RangeTy> &R) |
1193 | : SmallVectorImpl<T>(N) { |
1194 | this->append(R.begin(), R.end()); |
1195 | } |
1196 | |
1197 | SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) { |
1198 | this->assign(IL); |
1199 | } |
1200 | |
1201 | SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) { |
1202 | if (!RHS.empty()) |
1203 | SmallVectorImpl<T>::operator=(RHS); |
1204 | } |
1205 | |
1206 | SmallVector &operator=(const SmallVector &RHS) { |
1207 | SmallVectorImpl<T>::operator=(RHS); |
1208 | return *this; |
1209 | } |
1210 | |
1211 | SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) { |
1212 | if (!RHS.empty()) |
1213 | SmallVectorImpl<T>::operator=(::std::move(RHS)); |
1214 | } |
1215 | |
1216 | SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) { |
1217 | if (!RHS.empty()) |
1218 | SmallVectorImpl<T>::operator=(::std::move(RHS)); |
1219 | } |
1220 | |
1221 | SmallVector &operator=(SmallVector &&RHS) { |
1222 | SmallVectorImpl<T>::operator=(::std::move(RHS)); |
1223 | return *this; |
1224 | } |
1225 | |
1226 | SmallVector &operator=(SmallVectorImpl<T> &&RHS) { |
1227 | SmallVectorImpl<T>::operator=(::std::move(RHS)); |
1228 | return *this; |
1229 | } |
1230 | |
1231 | SmallVector &operator=(std::initializer_list<T> IL) { |
1232 | this->assign(IL); |
1233 | return *this; |
1234 | } |
1235 | }; |
1236 | |
1237 | template <typename T, unsigned N> |
1238 | inline size_t capacity_in_bytes(const SmallVector<T, N> &X) { |
1239 | return X.capacity_in_bytes(); |
1240 | } |
1241 | |
1242 | /// Given a range of type R, iterate the entire range and return a |
1243 | /// SmallVector with elements of the vector. This is useful, for example, |
1244 | /// when you want to iterate a range and then sort the results. |
1245 | template <unsigned Size, typename R> |
1246 | SmallVector<typename std::remove_const<typename std::remove_reference< |
1247 | decltype(*std::begin(std::declval<R &>()))>::type>::type, |
1248 | Size> |
1249 | to_vector(R &&Range) { |
1250 | return {std::begin(Range), std::end(Range)}; |
1251 | } |
1252 | |
1253 | } // end namespace llvm |
1254 | |
1255 | namespace std { |
1256 | |
1257 | /// Implement std::swap in terms of SmallVector swap. |
1258 | template<typename T> |
1259 | inline void |
1260 | swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) { |
1261 | LHS.swap(RHS); |
1262 | } |
1263 | |
1264 | /// Implement std::swap in terms of SmallVector swap. |
1265 | template<typename T, unsigned N> |
1266 | inline void |
1267 | swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) { |
1268 | LHS.swap(RHS); |
1269 | } |
1270 | |
1271 | } // end namespace std |
1272 | |
1273 | #endif // LLVM_ADT_SMALLVECTOR_H |