File: | tools/clang/lib/AST/ExprConstant.cpp |
Warning: | line 11532, column 28 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 <cstring> | ||||||
36 | #include <functional> | ||||||
37 | #include "Interp/Context.h" | ||||||
38 | #include "Interp/Frame.h" | ||||||
39 | #include "Interp/State.h" | ||||||
40 | #include "clang/AST/APValue.h" | ||||||
41 | #include "clang/AST/ASTContext.h" | ||||||
42 | #include "clang/AST/ASTDiagnostic.h" | ||||||
43 | #include "clang/AST/ASTLambda.h" | ||||||
44 | #include "clang/AST/CXXInheritance.h" | ||||||
45 | #include "clang/AST/CharUnits.h" | ||||||
46 | #include "clang/AST/CurrentSourceLocExprScope.h" | ||||||
47 | #include "clang/AST/Expr.h" | ||||||
48 | #include "clang/AST/OSLog.h" | ||||||
49 | #include "clang/AST/OptionalDiagnostic.h" | ||||||
50 | #include "clang/AST/RecordLayout.h" | ||||||
51 | #include "clang/AST/StmtVisitor.h" | ||||||
52 | #include "clang/AST/TypeLoc.h" | ||||||
53 | #include "clang/Basic/Builtins.h" | ||||||
54 | #include "clang/Basic/FixedPoint.h" | ||||||
55 | #include "clang/Basic/TargetInfo.h" | ||||||
56 | #include "llvm/ADT/Optional.h" | ||||||
57 | #include "llvm/ADT/SmallBitVector.h" | ||||||
58 | #include "llvm/Support/SaveAndRestore.h" | ||||||
59 | #include "llvm/Support/raw_ostream.h" | ||||||
60 | |||||||
61 | #define DEBUG_TYPE"exprconstant" "exprconstant" | ||||||
62 | |||||||
63 | using namespace clang; | ||||||
64 | using llvm::APInt; | ||||||
65 | using llvm::APSInt; | ||||||
66 | using llvm::APFloat; | ||||||
67 | using llvm::Optional; | ||||||
68 | |||||||
69 | namespace { | ||||||
70 | struct LValue; | ||||||
71 | class CallStackFrame; | ||||||
72 | class EvalInfo; | ||||||
73 | |||||||
74 | using SourceLocExprScopeGuard = | ||||||
75 | CurrentSourceLocExprScope::SourceLocExprScopeGuard; | ||||||
76 | |||||||
77 | static QualType getType(APValue::LValueBase B) { | ||||||
78 | if (!B) return QualType(); | ||||||
79 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | ||||||
80 | // FIXME: It's unclear where we're supposed to take the type from, and | ||||||
81 | // this actually matters for arrays of unknown bound. Eg: | ||||||
82 | // | ||||||
83 | // extern int arr[]; void f() { extern int arr[3]; }; | ||||||
84 | // constexpr int *p = &arr[1]; // valid? | ||||||
85 | // | ||||||
86 | // For now, we take the array bound from the most recent declaration. | ||||||
87 | for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; | ||||||
88 | Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { | ||||||
89 | QualType T = Redecl->getType(); | ||||||
90 | if (!T->isIncompleteArrayType()) | ||||||
91 | return T; | ||||||
92 | } | ||||||
93 | return D->getType(); | ||||||
94 | } | ||||||
95 | |||||||
96 | if (B.is<TypeInfoLValue>()) | ||||||
97 | return B.getTypeInfoType(); | ||||||
98 | |||||||
99 | if (B.is<DynamicAllocLValue>()) | ||||||
100 | return B.getDynamicAllocType(); | ||||||
101 | |||||||
102 | const Expr *Base = B.get<const Expr*>(); | ||||||
103 | |||||||
104 | // For a materialized temporary, the type of the temporary we materialized | ||||||
105 | // may not be the type of the expression. | ||||||
106 | if (const MaterializeTemporaryExpr *MTE = | ||||||
107 | dyn_cast<MaterializeTemporaryExpr>(Base)) { | ||||||
108 | SmallVector<const Expr *, 2> CommaLHSs; | ||||||
109 | SmallVector<SubobjectAdjustment, 2> Adjustments; | ||||||
110 | const Expr *Temp = MTE->GetTemporaryExpr(); | ||||||
111 | const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, | ||||||
112 | Adjustments); | ||||||
113 | // Keep any cv-qualifiers from the reference if we generated a temporary | ||||||
114 | // for it directly. Otherwise use the type after adjustment. | ||||||
115 | if (!Adjustments.empty()) | ||||||
116 | return Inner->getType(); | ||||||
117 | } | ||||||
118 | |||||||
119 | return Base->getType(); | ||||||
120 | } | ||||||
121 | |||||||
122 | /// Get an LValue path entry, which is known to not be an array index, as a | ||||||
123 | /// field declaration. | ||||||
124 | static const FieldDecl *getAsField(APValue::LValuePathEntry E) { | ||||||
125 | return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); | ||||||
126 | } | ||||||
127 | /// Get an LValue path entry, which is known to not be an array index, as a | ||||||
128 | /// base class declaration. | ||||||
129 | static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { | ||||||
130 | return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); | ||||||
131 | } | ||||||
132 | /// Determine whether this LValue path entry for a base class names a virtual | ||||||
133 | /// base class. | ||||||
134 | static bool isVirtualBaseClass(APValue::LValuePathEntry E) { | ||||||
135 | return E.getAsBaseOrMember().getInt(); | ||||||
136 | } | ||||||
137 | |||||||
138 | /// Given an expression, determine the type used to store the result of | ||||||
139 | /// evaluating that expression. | ||||||
140 | static QualType getStorageType(ASTContext &Ctx, Expr *E) { | ||||||
141 | if (E->isRValue()) | ||||||
142 | return E->getType(); | ||||||
143 | return Ctx.getLValueReferenceType(E->getType()); | ||||||
144 | } | ||||||
145 | |||||||
146 | /// Given a CallExpr, try to get the alloc_size attribute. May return null. | ||||||
147 | static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { | ||||||
148 | const FunctionDecl *Callee = CE->getDirectCallee(); | ||||||
149 | return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; | ||||||
150 | } | ||||||
151 | |||||||
152 | /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. | ||||||
153 | /// This will look through a single cast. | ||||||
154 | /// | ||||||
155 | /// Returns null if we couldn't unwrap a function with alloc_size. | ||||||
156 | static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { | ||||||
157 | if (!E->getType()->isPointerType()) | ||||||
158 | return nullptr; | ||||||
159 | |||||||
160 | E = E->IgnoreParens(); | ||||||
161 | // If we're doing a variable assignment from e.g. malloc(N), there will | ||||||
162 | // probably be a cast of some kind. In exotic cases, we might also see a | ||||||
163 | // top-level ExprWithCleanups. Ignore them either way. | ||||||
164 | if (const auto *FE = dyn_cast<FullExpr>(E)) | ||||||
165 | E = FE->getSubExpr()->IgnoreParens(); | ||||||
166 | |||||||
167 | if (const auto *Cast = dyn_cast<CastExpr>(E)) | ||||||
168 | E = Cast->getSubExpr()->IgnoreParens(); | ||||||
169 | |||||||
170 | if (const auto *CE = dyn_cast<CallExpr>(E)) | ||||||
171 | return getAllocSizeAttr(CE) ? CE : nullptr; | ||||||
172 | return nullptr; | ||||||
173 | } | ||||||
174 | |||||||
175 | /// Determines whether or not the given Base contains a call to a function | ||||||
176 | /// with the alloc_size attribute. | ||||||
177 | static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { | ||||||
178 | const auto *E = Base.dyn_cast<const Expr *>(); | ||||||
179 | return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); | ||||||
180 | } | ||||||
181 | |||||||
182 | /// The bound to claim that an array of unknown bound has. | ||||||
183 | /// The value in MostDerivedArraySize is undefined in this case. So, set it | ||||||
184 | /// to an arbitrary value that's likely to loudly break things if it's used. | ||||||
185 | static const uint64_t AssumedSizeForUnsizedArray = | ||||||
186 | std::numeric_limits<uint64_t>::max() / 2; | ||||||
187 | |||||||
188 | /// Determines if an LValue with the given LValueBase will have an unsized | ||||||
189 | /// array in its designator. | ||||||
190 | /// Find the path length and type of the most-derived subobject in the given | ||||||
191 | /// path, and find the size of the containing array, if any. | ||||||
192 | static unsigned | ||||||
193 | findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, | ||||||
194 | ArrayRef<APValue::LValuePathEntry> Path, | ||||||
195 | uint64_t &ArraySize, QualType &Type, bool &IsArray, | ||||||
196 | bool &FirstEntryIsUnsizedArray) { | ||||||
197 | // This only accepts LValueBases from APValues, and APValues don't support | ||||||
198 | // arrays that lack size info. | ||||||
199 | assert(!isBaseAnAllocSizeCall(Base) &&((!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here" ) ? static_cast<void> (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 200, __PRETTY_FUNCTION__)) | ||||||
200 | "Unsized arrays shouldn't appear here")((!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here" ) ? static_cast<void> (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 200, __PRETTY_FUNCTION__)); | ||||||
201 | unsigned MostDerivedLength = 0; | ||||||
202 | Type = getType(Base); | ||||||
203 | |||||||
204 | for (unsigned I = 0, N = Path.size(); I != N; ++I) { | ||||||
205 | if (Type->isArrayType()) { | ||||||
206 | const ArrayType *AT = Ctx.getAsArrayType(Type); | ||||||
207 | Type = AT->getElementType(); | ||||||
208 | MostDerivedLength = I + 1; | ||||||
209 | IsArray = true; | ||||||
210 | |||||||
211 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { | ||||||
212 | ArraySize = CAT->getSize().getZExtValue(); | ||||||
213 | } else { | ||||||
214 | assert(I == 0 && "unexpected unsized array designator")((I == 0 && "unexpected unsized array designator") ? static_cast <void> (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 214, __PRETTY_FUNCTION__)); | ||||||
215 | FirstEntryIsUnsizedArray = true; | ||||||
216 | ArraySize = AssumedSizeForUnsizedArray; | ||||||
217 | } | ||||||
218 | } else if (Type->isAnyComplexType()) { | ||||||
219 | const ComplexType *CT = Type->castAs<ComplexType>(); | ||||||
220 | Type = CT->getElementType(); | ||||||
221 | ArraySize = 2; | ||||||
222 | MostDerivedLength = I + 1; | ||||||
223 | IsArray = true; | ||||||
224 | } else if (const FieldDecl *FD = getAsField(Path[I])) { | ||||||
225 | Type = FD->getType(); | ||||||
226 | ArraySize = 0; | ||||||
227 | MostDerivedLength = I + 1; | ||||||
228 | IsArray = false; | ||||||
229 | } else { | ||||||
230 | // Path[I] describes a base class. | ||||||
231 | ArraySize = 0; | ||||||
232 | IsArray = false; | ||||||
233 | } | ||||||
234 | } | ||||||
235 | return MostDerivedLength; | ||||||
236 | } | ||||||
237 | |||||||
238 | /// A path from a glvalue to a subobject of that glvalue. | ||||||
239 | struct SubobjectDesignator { | ||||||
240 | /// True if the subobject was named in a manner not supported by C++11. Such | ||||||
241 | /// lvalues can still be folded, but they are not core constant expressions | ||||||
242 | /// and we cannot perform lvalue-to-rvalue conversions on them. | ||||||
243 | unsigned Invalid : 1; | ||||||
244 | |||||||
245 | /// Is this a pointer one past the end of an object? | ||||||
246 | unsigned IsOnePastTheEnd : 1; | ||||||
247 | |||||||
248 | /// Indicator of whether the first entry is an unsized array. | ||||||
249 | unsigned FirstEntryIsAnUnsizedArray : 1; | ||||||
250 | |||||||
251 | /// Indicator of whether the most-derived object is an array element. | ||||||
252 | unsigned MostDerivedIsArrayElement : 1; | ||||||
253 | |||||||
254 | /// The length of the path to the most-derived object of which this is a | ||||||
255 | /// subobject. | ||||||
256 | unsigned MostDerivedPathLength : 28; | ||||||
257 | |||||||
258 | /// The size of the array of which the most-derived object is an element. | ||||||
259 | /// This will always be 0 if the most-derived object is not an array | ||||||
260 | /// element. 0 is not an indicator of whether or not the most-derived object | ||||||
261 | /// is an array, however, because 0-length arrays are allowed. | ||||||
262 | /// | ||||||
263 | /// If the current array is an unsized array, the value of this is | ||||||
264 | /// undefined. | ||||||
265 | uint64_t MostDerivedArraySize; | ||||||
266 | |||||||
267 | /// The type of the most derived object referred to by this address. | ||||||
268 | QualType MostDerivedType; | ||||||
269 | |||||||
270 | typedef APValue::LValuePathEntry PathEntry; | ||||||
271 | |||||||
272 | /// The entries on the path from the glvalue to the designated subobject. | ||||||
273 | SmallVector<PathEntry, 8> Entries; | ||||||
274 | |||||||
275 | SubobjectDesignator() : Invalid(true) {} | ||||||
276 | |||||||
277 | explicit SubobjectDesignator(QualType T) | ||||||
278 | : Invalid(false), IsOnePastTheEnd(false), | ||||||
279 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), | ||||||
280 | MostDerivedPathLength(0), MostDerivedArraySize(0), | ||||||
281 | MostDerivedType(T) {} | ||||||
282 | |||||||
283 | SubobjectDesignator(ASTContext &Ctx, const APValue &V) | ||||||
284 | : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), | ||||||
285 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), | ||||||
286 | MostDerivedPathLength(0), MostDerivedArraySize(0) { | ||||||
287 | assert(V.isLValue() && "Non-LValue used to make an LValue designator?")((V.isLValue() && "Non-LValue used to make an LValue designator?" ) ? static_cast<void> (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 287, __PRETTY_FUNCTION__)); | ||||||
288 | if (!Invalid) { | ||||||
289 | IsOnePastTheEnd = V.isLValueOnePastTheEnd(); | ||||||
290 | ArrayRef<PathEntry> VEntries = V.getLValuePath(); | ||||||
291 | Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); | ||||||
292 | if (V.getLValueBase()) { | ||||||
293 | bool IsArray = false; | ||||||
294 | bool FirstIsUnsizedArray = false; | ||||||
295 | MostDerivedPathLength = findMostDerivedSubobject( | ||||||
296 | Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, | ||||||
297 | MostDerivedType, IsArray, FirstIsUnsizedArray); | ||||||
298 | MostDerivedIsArrayElement = IsArray; | ||||||
299 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; | ||||||
300 | } | ||||||
301 | } | ||||||
302 | } | ||||||
303 | |||||||
304 | void truncate(ASTContext &Ctx, APValue::LValueBase Base, | ||||||
305 | unsigned NewLength) { | ||||||
306 | if (Invalid) | ||||||
307 | return; | ||||||
308 | |||||||
309 | assert(Base && "cannot truncate path for null pointer")((Base && "cannot truncate path for null pointer") ? static_cast <void> (0) : __assert_fail ("Base && \"cannot truncate path for null pointer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 309, __PRETTY_FUNCTION__)); | ||||||
310 | assert(NewLength <= Entries.size() && "not a truncation")((NewLength <= Entries.size() && "not a truncation" ) ? static_cast<void> (0) : __assert_fail ("NewLength <= Entries.size() && \"not a truncation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 310, __PRETTY_FUNCTION__)); | ||||||
311 | |||||||
312 | if (NewLength == Entries.size()) | ||||||
313 | return; | ||||||
314 | Entries.resize(NewLength); | ||||||
315 | |||||||
316 | bool IsArray = false; | ||||||
317 | bool FirstIsUnsizedArray = false; | ||||||
318 | MostDerivedPathLength = findMostDerivedSubobject( | ||||||
319 | Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, | ||||||
320 | FirstIsUnsizedArray); | ||||||
321 | MostDerivedIsArrayElement = IsArray; | ||||||
322 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; | ||||||
323 | } | ||||||
324 | |||||||
325 | void setInvalid() { | ||||||
326 | Invalid = true; | ||||||
327 | Entries.clear(); | ||||||
328 | } | ||||||
329 | |||||||
330 | /// Determine whether the most derived subobject is an array without a | ||||||
331 | /// known bound. | ||||||
332 | bool isMostDerivedAnUnsizedArray() const { | ||||||
333 | assert(!Invalid && "Calling this makes no sense on invalid designators")((!Invalid && "Calling this makes no sense on invalid designators" ) ? static_cast<void> (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 333, __PRETTY_FUNCTION__)); | ||||||
334 | return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; | ||||||
335 | } | ||||||
336 | |||||||
337 | /// Determine what the most derived array's size is. Results in an assertion | ||||||
338 | /// failure if the most derived array lacks a size. | ||||||
339 | uint64_t getMostDerivedArraySize() const { | ||||||
340 | assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")((!isMostDerivedAnUnsizedArray() && "Unsized array has no size" ) ? static_cast<void> (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 340, __PRETTY_FUNCTION__)); | ||||||
341 | return MostDerivedArraySize; | ||||||
342 | } | ||||||
343 | |||||||
344 | /// Determine whether this is a one-past-the-end pointer. | ||||||
345 | bool isOnePastTheEnd() const { | ||||||
346 | assert(!Invalid)((!Invalid) ? static_cast<void> (0) : __assert_fail ("!Invalid" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 346, __PRETTY_FUNCTION__)); | ||||||
347 | if (IsOnePastTheEnd) | ||||||
348 | return true; | ||||||
349 | if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && | ||||||
350 | Entries[MostDerivedPathLength - 1].getAsArrayIndex() == | ||||||
351 | MostDerivedArraySize) | ||||||
352 | return true; | ||||||
353 | return false; | ||||||
354 | } | ||||||
355 | |||||||
356 | /// Get the range of valid index adjustments in the form | ||||||
357 | /// {maximum value that can be subtracted from this pointer, | ||||||
358 | /// maximum value that can be added to this pointer} | ||||||
359 | std::pair<uint64_t, uint64_t> validIndexAdjustments() { | ||||||
360 | if (Invalid || isMostDerivedAnUnsizedArray()) | ||||||
361 | return {0, 0}; | ||||||
362 | |||||||
363 | // [expr.add]p4: For the purposes of these operators, a pointer to a | ||||||
364 | // nonarray object behaves the same as a pointer to the first element of | ||||||
365 | // an array of length one with the type of the object as its element type. | ||||||
366 | bool IsArray = MostDerivedPathLength == Entries.size() && | ||||||
367 | MostDerivedIsArrayElement; | ||||||
368 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() | ||||||
369 | : (uint64_t)IsOnePastTheEnd; | ||||||
370 | uint64_t ArraySize = | ||||||
371 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; | ||||||
372 | return {ArrayIndex, ArraySize - ArrayIndex}; | ||||||
373 | } | ||||||
374 | |||||||
375 | /// Check that this refers to a valid subobject. | ||||||
376 | bool isValidSubobject() const { | ||||||
377 | if (Invalid) | ||||||
378 | return false; | ||||||
379 | return !isOnePastTheEnd(); | ||||||
380 | } | ||||||
381 | /// Check that this refers to a valid subobject, and if not, produce a | ||||||
382 | /// relevant diagnostic and set the designator as invalid. | ||||||
383 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); | ||||||
384 | |||||||
385 | /// Get the type of the designated object. | ||||||
386 | QualType getType(ASTContext &Ctx) const { | ||||||
387 | assert(!Invalid && "invalid designator has no subobject type")((!Invalid && "invalid designator has no subobject type" ) ? static_cast<void> (0) : __assert_fail ("!Invalid && \"invalid designator has no subobject type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 387, __PRETTY_FUNCTION__)); | ||||||
388 | return MostDerivedPathLength == Entries.size() | ||||||
389 | ? MostDerivedType | ||||||
390 | : Ctx.getRecordType(getAsBaseClass(Entries.back())); | ||||||
391 | } | ||||||
392 | |||||||
393 | /// Update this designator to refer to the first element within this array. | ||||||
394 | void addArrayUnchecked(const ConstantArrayType *CAT) { | ||||||
395 | Entries.push_back(PathEntry::ArrayIndex(0)); | ||||||
396 | |||||||
397 | // This is a most-derived object. | ||||||
398 | MostDerivedType = CAT->getElementType(); | ||||||
399 | MostDerivedIsArrayElement = true; | ||||||
400 | MostDerivedArraySize = CAT->getSize().getZExtValue(); | ||||||
401 | MostDerivedPathLength = Entries.size(); | ||||||
402 | } | ||||||
403 | /// Update this designator to refer to the first element within the array of | ||||||
404 | /// elements of type T. This is an array of unknown size. | ||||||
405 | void addUnsizedArrayUnchecked(QualType ElemTy) { | ||||||
406 | Entries.push_back(PathEntry::ArrayIndex(0)); | ||||||
407 | |||||||
408 | MostDerivedType = ElemTy; | ||||||
409 | MostDerivedIsArrayElement = true; | ||||||
410 | // The value in MostDerivedArraySize is undefined in this case. So, set it | ||||||
411 | // to an arbitrary value that's likely to loudly break things if it's | ||||||
412 | // used. | ||||||
413 | MostDerivedArraySize = AssumedSizeForUnsizedArray; | ||||||
414 | MostDerivedPathLength = Entries.size(); | ||||||
415 | } | ||||||
416 | /// Update this designator to refer to the given base or member of this | ||||||
417 | /// object. | ||||||
418 | void addDeclUnchecked(const Decl *D, bool Virtual = false) { | ||||||
419 | Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); | ||||||
420 | |||||||
421 | // If this isn't a base class, it's a new most-derived object. | ||||||
422 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { | ||||||
423 | MostDerivedType = FD->getType(); | ||||||
424 | MostDerivedIsArrayElement = false; | ||||||
425 | MostDerivedArraySize = 0; | ||||||
426 | MostDerivedPathLength = Entries.size(); | ||||||
427 | } | ||||||
428 | } | ||||||
429 | /// Update this designator to refer to the given complex component. | ||||||
430 | void addComplexUnchecked(QualType EltTy, bool Imag) { | ||||||
431 | Entries.push_back(PathEntry::ArrayIndex(Imag)); | ||||||
432 | |||||||
433 | // This is technically a most-derived object, though in practice this | ||||||
434 | // is unlikely to matter. | ||||||
435 | MostDerivedType = EltTy; | ||||||
436 | MostDerivedIsArrayElement = true; | ||||||
437 | MostDerivedArraySize = 2; | ||||||
438 | MostDerivedPathLength = Entries.size(); | ||||||
439 | } | ||||||
440 | void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); | ||||||
441 | void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, | ||||||
442 | const APSInt &N); | ||||||
443 | /// Add N to the address of this subobject. | ||||||
444 | void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { | ||||||
445 | if (Invalid || !N) return; | ||||||
446 | uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); | ||||||
447 | if (isMostDerivedAnUnsizedArray()) { | ||||||
448 | diagnoseUnsizedArrayPointerArithmetic(Info, E); | ||||||
449 | // Can't verify -- trust that the user is doing the right thing (or if | ||||||
450 | // not, trust that the caller will catch the bad behavior). | ||||||
451 | // FIXME: Should we reject if this overflows, at least? | ||||||
452 | Entries.back() = PathEntry::ArrayIndex( | ||||||
453 | Entries.back().getAsArrayIndex() + TruncatedN); | ||||||
454 | return; | ||||||
455 | } | ||||||
456 | |||||||
457 | // [expr.add]p4: For the purposes of these operators, a pointer to a | ||||||
458 | // nonarray object behaves the same as a pointer to the first element of | ||||||
459 | // an array of length one with the type of the object as its element type. | ||||||
460 | bool IsArray = MostDerivedPathLength == Entries.size() && | ||||||
461 | MostDerivedIsArrayElement; | ||||||
462 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() | ||||||
463 | : (uint64_t)IsOnePastTheEnd; | ||||||
464 | uint64_t ArraySize = | ||||||
465 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; | ||||||
466 | |||||||
467 | if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { | ||||||
468 | // Calculate the actual index in a wide enough type, so we can include | ||||||
469 | // it in the note. | ||||||
470 | N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); | ||||||
471 | (llvm::APInt&)N += ArrayIndex; | ||||||
472 | assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")((N.ugt(ArraySize) && "bounds check failed for in-bounds index" ) ? static_cast<void> (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 472, __PRETTY_FUNCTION__)); | ||||||
473 | diagnosePointerArithmetic(Info, E, N); | ||||||
474 | setInvalid(); | ||||||
475 | return; | ||||||
476 | } | ||||||
477 | |||||||
478 | ArrayIndex += TruncatedN; | ||||||
479 | assert(ArrayIndex <= ArraySize &&((ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index" ) ? static_cast<void> (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 480, __PRETTY_FUNCTION__)) | ||||||
480 | "bounds check succeeded for out-of-bounds index")((ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index" ) ? static_cast<void> (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 480, __PRETTY_FUNCTION__)); | ||||||
481 | |||||||
482 | if (IsArray) | ||||||
483 | Entries.back() = PathEntry::ArrayIndex(ArrayIndex); | ||||||
484 | else | ||||||
485 | IsOnePastTheEnd = (ArrayIndex != 0); | ||||||
486 | } | ||||||
487 | }; | ||||||
488 | |||||||
489 | /// A stack frame in the constexpr call stack. | ||||||
490 | class CallStackFrame : public interp::Frame { | ||||||
491 | public: | ||||||
492 | EvalInfo &Info; | ||||||
493 | |||||||
494 | /// Parent - The caller of this stack frame. | ||||||
495 | CallStackFrame *Caller; | ||||||
496 | |||||||
497 | /// Callee - The function which was called. | ||||||
498 | const FunctionDecl *Callee; | ||||||
499 | |||||||
500 | /// This - The binding for the this pointer in this call, if any. | ||||||
501 | const LValue *This; | ||||||
502 | |||||||
503 | /// Arguments - Parameter bindings for this function call, indexed by | ||||||
504 | /// parameters' function scope indices. | ||||||
505 | APValue *Arguments; | ||||||
506 | |||||||
507 | /// Source location information about the default argument or default | ||||||
508 | /// initializer expression we're evaluating, if any. | ||||||
509 | CurrentSourceLocExprScope CurSourceLocExprScope; | ||||||
510 | |||||||
511 | // Note that we intentionally use std::map here so that references to | ||||||
512 | // values are stable. | ||||||
513 | typedef std::pair<const void *, unsigned> MapKeyTy; | ||||||
514 | typedef std::map<MapKeyTy, APValue> MapTy; | ||||||
515 | /// Temporaries - Temporary lvalues materialized within this stack frame. | ||||||
516 | MapTy Temporaries; | ||||||
517 | |||||||
518 | /// CallLoc - The location of the call expression for this call. | ||||||
519 | SourceLocation CallLoc; | ||||||
520 | |||||||
521 | /// Index - The call index of this call. | ||||||
522 | unsigned Index; | ||||||
523 | |||||||
524 | /// The stack of integers for tracking version numbers for temporaries. | ||||||
525 | SmallVector<unsigned, 2> TempVersionStack = {1}; | ||||||
526 | unsigned CurTempVersion = TempVersionStack.back(); | ||||||
527 | |||||||
528 | unsigned getTempVersion() const { return TempVersionStack.back(); } | ||||||
529 | |||||||
530 | void pushTempVersion() { | ||||||
531 | TempVersionStack.push_back(++CurTempVersion); | ||||||
532 | } | ||||||
533 | |||||||
534 | void popTempVersion() { | ||||||
535 | TempVersionStack.pop_back(); | ||||||
536 | } | ||||||
537 | |||||||
538 | // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact | ||||||
539 | // on the overall stack usage of deeply-recursing constexpr evaluations. | ||||||
540 | // (We should cache this map rather than recomputing it repeatedly.) | ||||||
541 | // But let's try this and see how it goes; we can look into caching the map | ||||||
542 | // as a later change. | ||||||
543 | |||||||
544 | /// LambdaCaptureFields - Mapping from captured variables/this to | ||||||
545 | /// corresponding data members in the closure class. | ||||||
546 | llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; | ||||||
547 | FieldDecl *LambdaThisCaptureField; | ||||||
548 | |||||||
549 | CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, | ||||||
550 | const FunctionDecl *Callee, const LValue *This, | ||||||
551 | APValue *Arguments); | ||||||
552 | ~CallStackFrame(); | ||||||
553 | |||||||
554 | // Return the temporary for Key whose version number is Version. | ||||||
555 | APValue *getTemporary(const void *Key, unsigned Version) { | ||||||
556 | MapKeyTy KV(Key, Version); | ||||||
557 | auto LB = Temporaries.lower_bound(KV); | ||||||
558 | if (LB != Temporaries.end() && LB->first == KV) | ||||||
559 | return &LB->second; | ||||||
560 | // Pair (Key,Version) wasn't found in the map. Check that no elements | ||||||
561 | // in the map have 'Key' as their key. | ||||||
562 | assert((LB == Temporaries.end() || LB->first.first != Key) &&(((LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && "Element with key 'Key' found in map") ? static_cast <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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 564, __PRETTY_FUNCTION__)) | ||||||
563 | (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&(((LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && "Element with key 'Key' found in map") ? static_cast <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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 564, __PRETTY_FUNCTION__)) | ||||||
564 | "Element with key 'Key' found in map")(((LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && "Element with key 'Key' found in map") ? static_cast <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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 564, __PRETTY_FUNCTION__)); | ||||||
565 | return nullptr; | ||||||
566 | } | ||||||
567 | |||||||
568 | // Return the current temporary for Key in the map. | ||||||
569 | APValue *getCurrentTemporary(const void *Key) { | ||||||
570 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); | ||||||
571 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) | ||||||
572 | return &std::prev(UB)->second; | ||||||
573 | return nullptr; | ||||||
574 | } | ||||||
575 | |||||||
576 | // Return the version number of the current temporary for Key. | ||||||
577 | unsigned getCurrentTemporaryVersion(const void *Key) const { | ||||||
578 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); | ||||||
579 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) | ||||||
580 | return std::prev(UB)->first.second; | ||||||
581 | return 0; | ||||||
582 | } | ||||||
583 | |||||||
584 | /// Allocate storage for an object of type T in this stack frame. | ||||||
585 | /// Populates LV with a handle to the created object. Key identifies | ||||||
586 | /// the temporary within the stack frame, and must not be reused without | ||||||
587 | /// bumping the temporary version number. | ||||||
588 | template<typename KeyT> | ||||||
589 | APValue &createTemporary(const KeyT *Key, QualType T, | ||||||
590 | bool IsLifetimeExtended, LValue &LV); | ||||||
591 | |||||||
592 | void describe(llvm::raw_ostream &OS) override; | ||||||
593 | |||||||
594 | Frame *getCaller() const override { return Caller; } | ||||||
595 | SourceLocation getCallLocation() const override { return CallLoc; } | ||||||
596 | const FunctionDecl *getCallee() const override { return Callee; } | ||||||
597 | }; | ||||||
598 | |||||||
599 | /// Temporarily override 'this'. | ||||||
600 | class ThisOverrideRAII { | ||||||
601 | public: | ||||||
602 | ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) | ||||||
603 | : Frame(Frame), OldThis(Frame.This) { | ||||||
604 | if (Enable) | ||||||
605 | Frame.This = NewThis; | ||||||
606 | } | ||||||
607 | ~ThisOverrideRAII() { | ||||||
608 | Frame.This = OldThis; | ||||||
609 | } | ||||||
610 | private: | ||||||
611 | CallStackFrame &Frame; | ||||||
612 | const LValue *OldThis; | ||||||
613 | }; | ||||||
614 | } | ||||||
615 | |||||||
616 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, | ||||||
617 | const LValue &This, QualType ThisType); | ||||||
618 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, | ||||||
619 | APValue::LValueBase LVBase, APValue &Value, | ||||||
620 | QualType T); | ||||||
621 | |||||||
622 | namespace { | ||||||
623 | /// A cleanup, and a flag indicating whether it is lifetime-extended. | ||||||
624 | class Cleanup { | ||||||
625 | llvm::PointerIntPair<APValue*, 1, bool> Value; | ||||||
626 | APValue::LValueBase Base; | ||||||
627 | QualType T; | ||||||
628 | |||||||
629 | public: | ||||||
630 | Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, | ||||||
631 | bool IsLifetimeExtended) | ||||||
632 | : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} | ||||||
633 | |||||||
634 | bool isLifetimeExtended() const { return Value.getInt(); } | ||||||
635 | bool endLifetime(EvalInfo &Info, bool RunDestructors) { | ||||||
636 | if (RunDestructors) { | ||||||
637 | SourceLocation Loc; | ||||||
638 | if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) | ||||||
639 | Loc = VD->getLocation(); | ||||||
640 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) | ||||||
641 | Loc = E->getExprLoc(); | ||||||
642 | return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); | ||||||
643 | } | ||||||
644 | *Value.getPointer() = APValue(); | ||||||
645 | return true; | ||||||
646 | } | ||||||
647 | |||||||
648 | bool hasSideEffect() { | ||||||
649 | return T.isDestructedType(); | ||||||
650 | } | ||||||
651 | }; | ||||||
652 | |||||||
653 | /// A reference to an object whose construction we are currently evaluating. | ||||||
654 | struct ObjectUnderConstruction { | ||||||
655 | APValue::LValueBase Base; | ||||||
656 | ArrayRef<APValue::LValuePathEntry> Path; | ||||||
657 | friend bool operator==(const ObjectUnderConstruction &LHS, | ||||||
658 | const ObjectUnderConstruction &RHS) { | ||||||
659 | return LHS.Base == RHS.Base && LHS.Path == RHS.Path; | ||||||
660 | } | ||||||
661 | friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { | ||||||
662 | return llvm::hash_combine(Obj.Base, Obj.Path); | ||||||
663 | } | ||||||
664 | }; | ||||||
665 | enum class ConstructionPhase { | ||||||
666 | None, | ||||||
667 | Bases, | ||||||
668 | AfterBases, | ||||||
669 | Destroying, | ||||||
670 | DestroyingBases | ||||||
671 | }; | ||||||
672 | } | ||||||
673 | |||||||
674 | namespace llvm { | ||||||
675 | template<> struct DenseMapInfo<ObjectUnderConstruction> { | ||||||
676 | using Base = DenseMapInfo<APValue::LValueBase>; | ||||||
677 | static ObjectUnderConstruction getEmptyKey() { | ||||||
678 | return {Base::getEmptyKey(), {}}; } | ||||||
679 | static ObjectUnderConstruction getTombstoneKey() { | ||||||
680 | return {Base::getTombstoneKey(), {}}; | ||||||
681 | } | ||||||
682 | static unsigned getHashValue(const ObjectUnderConstruction &Object) { | ||||||
683 | return hash_value(Object); | ||||||
684 | } | ||||||
685 | static bool isEqual(const ObjectUnderConstruction &LHS, | ||||||
686 | const ObjectUnderConstruction &RHS) { | ||||||
687 | return LHS == RHS; | ||||||
688 | } | ||||||
689 | }; | ||||||
690 | } | ||||||
691 | |||||||
692 | namespace { | ||||||
693 | /// EvalInfo - This is a private struct used by the evaluator to capture | ||||||
694 | /// information about a subexpression as it is folded. It retains information | ||||||
695 | /// about the AST context, but also maintains information about the folded | ||||||
696 | /// expression. | ||||||
697 | /// | ||||||
698 | /// If an expression could be evaluated, it is still possible it is not a C | ||||||
699 | /// "integer constant expression" or constant expression. If not, this struct | ||||||
700 | /// captures information about how and why not. | ||||||
701 | /// | ||||||
702 | /// One bit of information passed *into* the request for constant folding | ||||||
703 | /// indicates whether the subexpression is "evaluated" or not according to C | ||||||
704 | /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can | ||||||
705 | /// evaluate the expression regardless of what the RHS is, but C only allows | ||||||
706 | /// certain things in certain situations. | ||||||
707 | class EvalInfo : public interp::State { | ||||||
708 | public: | ||||||
709 | ASTContext &Ctx; | ||||||
710 | |||||||
711 | /// EvalStatus - Contains information about the evaluation. | ||||||
712 | Expr::EvalStatus &EvalStatus; | ||||||
713 | |||||||
714 | /// CurrentCall - The top of the constexpr call stack. | ||||||
715 | CallStackFrame *CurrentCall; | ||||||
716 | |||||||
717 | /// CallStackDepth - The number of calls in the call stack right now. | ||||||
718 | unsigned CallStackDepth; | ||||||
719 | |||||||
720 | /// NextCallIndex - The next call index to assign. | ||||||
721 | unsigned NextCallIndex; | ||||||
722 | |||||||
723 | /// StepsLeft - The remaining number of evaluation steps we're permitted | ||||||
724 | /// to perform. This is essentially a limit for the number of statements | ||||||
725 | /// we will evaluate. | ||||||
726 | unsigned StepsLeft; | ||||||
727 | |||||||
728 | /// Force the use of the experimental new constant interpreter, bailing out | ||||||
729 | /// with an error if a feature is not supported. | ||||||
730 | bool ForceNewConstInterp; | ||||||
731 | |||||||
732 | /// Enable the experimental new constant interpreter. | ||||||
733 | bool EnableNewConstInterp; | ||||||
734 | |||||||
735 | /// BottomFrame - The frame in which evaluation started. This must be | ||||||
736 | /// initialized after CurrentCall and CallStackDepth. | ||||||
737 | CallStackFrame BottomFrame; | ||||||
738 | |||||||
739 | /// A stack of values whose lifetimes end at the end of some surrounding | ||||||
740 | /// evaluation frame. | ||||||
741 | llvm::SmallVector<Cleanup, 16> CleanupStack; | ||||||
742 | |||||||
743 | /// EvaluatingDecl - This is the declaration whose initializer is being | ||||||
744 | /// evaluated, if any. | ||||||
745 | APValue::LValueBase EvaluatingDecl; | ||||||
746 | |||||||
747 | enum class EvaluatingDeclKind { | ||||||
748 | None, | ||||||
749 | /// We're evaluating the construction of EvaluatingDecl. | ||||||
750 | Ctor, | ||||||
751 | /// We're evaluating the destruction of EvaluatingDecl. | ||||||
752 | Dtor, | ||||||
753 | }; | ||||||
754 | EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; | ||||||
755 | |||||||
756 | /// EvaluatingDeclValue - This is the value being constructed for the | ||||||
757 | /// declaration whose initializer is being evaluated, if any. | ||||||
758 | APValue *EvaluatingDeclValue; | ||||||
759 | |||||||
760 | /// Set of objects that are currently being constructed. | ||||||
761 | llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> | ||||||
762 | ObjectsUnderConstruction; | ||||||
763 | |||||||
764 | /// A dynamically-allocated heap object. | ||||||
765 | struct DynAlloc { | ||||||
766 | /// The value of this heap-allocated object. | ||||||
767 | APValue Value; | ||||||
768 | /// The allocating expression; used for diagnostics. | ||||||
769 | const Expr *AllocExpr = nullptr; | ||||||
770 | }; | ||||||
771 | |||||||
772 | struct DynAllocOrder { | ||||||
773 | bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { | ||||||
774 | return L.getIndex() < R.getIndex(); | ||||||
775 | } | ||||||
776 | }; | ||||||
777 | |||||||
778 | /// Current heap allocations, along with the location where each was | ||||||
779 | /// allocated. We use std::map here because we need stable addresses | ||||||
780 | /// for the stored APValues. | ||||||
781 | std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; | ||||||
782 | |||||||
783 | /// The number of heap allocations performed so far in this evaluation. | ||||||
784 | unsigned NumHeapAllocs = 0; | ||||||
785 | |||||||
786 | struct EvaluatingConstructorRAII { | ||||||
787 | EvalInfo &EI; | ||||||
788 | ObjectUnderConstruction Object; | ||||||
789 | bool DidInsert; | ||||||
790 | EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, | ||||||
791 | bool HasBases) | ||||||
792 | : EI(EI), Object(Object) { | ||||||
793 | DidInsert = | ||||||
794 | EI.ObjectsUnderConstruction | ||||||
795 | .insert({Object, HasBases ? ConstructionPhase::Bases | ||||||
796 | : ConstructionPhase::AfterBases}) | ||||||
797 | .second; | ||||||
798 | } | ||||||
799 | void finishedConstructingBases() { | ||||||
800 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; | ||||||
801 | } | ||||||
802 | ~EvaluatingConstructorRAII() { | ||||||
803 | if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); | ||||||
804 | } | ||||||
805 | }; | ||||||
806 | |||||||
807 | struct EvaluatingDestructorRAII { | ||||||
808 | EvalInfo &EI; | ||||||
809 | ObjectUnderConstruction Object; | ||||||
810 | bool DidInsert; | ||||||
811 | EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) | ||||||
812 | : EI(EI), Object(Object) { | ||||||
813 | DidInsert = EI.ObjectsUnderConstruction | ||||||
814 | .insert({Object, ConstructionPhase::Destroying}) | ||||||
815 | .second; | ||||||
816 | } | ||||||
817 | void startedDestroyingBases() { | ||||||
818 | EI.ObjectsUnderConstruction[Object] = | ||||||
819 | ConstructionPhase::DestroyingBases; | ||||||
820 | } | ||||||
821 | ~EvaluatingDestructorRAII() { | ||||||
822 | if (DidInsert) | ||||||
823 | EI.ObjectsUnderConstruction.erase(Object); | ||||||
824 | } | ||||||
825 | }; | ||||||
826 | |||||||
827 | ConstructionPhase | ||||||
828 | isEvaluatingCtorDtor(APValue::LValueBase Base, | ||||||
829 | ArrayRef<APValue::LValuePathEntry> Path) { | ||||||
830 | return ObjectsUnderConstruction.lookup({Base, Path}); | ||||||
831 | } | ||||||
832 | |||||||
833 | /// If we're currently speculatively evaluating, the outermost call stack | ||||||
834 | /// depth at which we can mutate state, otherwise 0. | ||||||
835 | unsigned SpeculativeEvaluationDepth = 0; | ||||||
836 | |||||||
837 | /// The current array initialization index, if we're performing array | ||||||
838 | /// initialization. | ||||||
839 | uint64_t ArrayInitIndex = -1; | ||||||
840 | |||||||
841 | /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further | ||||||
842 | /// notes attached to it will also be stored, otherwise they will not be. | ||||||
843 | bool HasActiveDiagnostic; | ||||||
844 | |||||||
845 | /// Have we emitted a diagnostic explaining why we couldn't constant | ||||||
846 | /// fold (not just why it's not strictly a constant expression)? | ||||||
847 | bool HasFoldFailureDiagnostic; | ||||||
848 | |||||||
849 | /// Whether or not we're in a context where the front end requires a | ||||||
850 | /// constant value. | ||||||
851 | bool InConstantContext; | ||||||
852 | |||||||
853 | /// Whether we're checking that an expression is a potential constant | ||||||
854 | /// expression. If so, do not fail on constructs that could become constant | ||||||
855 | /// later on (such as a use of an undefined global). | ||||||
856 | bool CheckingPotentialConstantExpression = false; | ||||||
857 | |||||||
858 | /// Whether we're checking for an expression that has undefined behavior. | ||||||
859 | /// If so, we will produce warnings if we encounter an operation that is | ||||||
860 | /// always undefined. | ||||||
861 | bool CheckingForUndefinedBehavior = false; | ||||||
862 | |||||||
863 | enum EvaluationMode { | ||||||
864 | /// Evaluate as a constant expression. Stop if we find that the expression | ||||||
865 | /// is not a constant expression. | ||||||
866 | EM_ConstantExpression, | ||||||
867 | |||||||
868 | /// Evaluate as a constant expression. Stop if we find that the expression | ||||||
869 | /// is not a constant expression. Some expressions can be retried in the | ||||||
870 | /// optimizer if we don't constant fold them here, but in an unevaluated | ||||||
871 | /// context we try to fold them immediately since the optimizer never | ||||||
872 | /// gets a chance to look at it. | ||||||
873 | EM_ConstantExpressionUnevaluated, | ||||||
874 | |||||||
875 | /// Fold the expression to a constant. Stop if we hit a side-effect that | ||||||
876 | /// we can't model. | ||||||
877 | EM_ConstantFold, | ||||||
878 | |||||||
879 | /// Evaluate in any way we know how. Don't worry about side-effects that | ||||||
880 | /// can't be modeled. | ||||||
881 | EM_IgnoreSideEffects, | ||||||
882 | } EvalMode; | ||||||
883 | |||||||
884 | /// Are we checking whether the expression is a potential constant | ||||||
885 | /// expression? | ||||||
886 | bool checkingPotentialConstantExpression() const override { | ||||||
887 | return CheckingPotentialConstantExpression; | ||||||
888 | } | ||||||
889 | |||||||
890 | /// Are we checking an expression for overflow? | ||||||
891 | // FIXME: We should check for any kind of undefined or suspicious behavior | ||||||
892 | // in such constructs, not just overflow. | ||||||
893 | bool checkingForUndefinedBehavior() const override { | ||||||
894 | return CheckingForUndefinedBehavior; | ||||||
895 | } | ||||||
896 | |||||||
897 | EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) | ||||||
898 | : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), | ||||||
899 | CallStackDepth(0), NextCallIndex(1), | ||||||
900 | StepsLeft(getLangOpts().ConstexprStepLimit), | ||||||
901 | ForceNewConstInterp(getLangOpts().ForceNewConstInterp), | ||||||
902 | EnableNewConstInterp(ForceNewConstInterp || | ||||||
903 | getLangOpts().EnableNewConstInterp), | ||||||
904 | BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), | ||||||
905 | EvaluatingDecl((const ValueDecl *)nullptr), | ||||||
906 | EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), | ||||||
907 | HasFoldFailureDiagnostic(false), InConstantContext(false), | ||||||
908 | EvalMode(Mode) {} | ||||||
909 | |||||||
910 | ~EvalInfo() { | ||||||
911 | discardCleanups(); | ||||||
912 | } | ||||||
913 | |||||||
914 | void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, | ||||||
915 | EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { | ||||||
916 | EvaluatingDecl = Base; | ||||||
917 | IsEvaluatingDecl = EDK; | ||||||
918 | EvaluatingDeclValue = &Value; | ||||||
919 | } | ||||||
920 | |||||||
921 | bool CheckCallLimit(SourceLocation Loc) { | ||||||
922 | // Don't perform any constexpr calls (other than the call we're checking) | ||||||
923 | // when checking a potential constant expression. | ||||||
924 | if (checkingPotentialConstantExpression() && CallStackDepth > 1) | ||||||
925 | return false; | ||||||
926 | if (NextCallIndex == 0) { | ||||||
927 | // NextCallIndex has wrapped around. | ||||||
928 | FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); | ||||||
929 | return false; | ||||||
930 | } | ||||||
931 | if (CallStackDepth <= getLangOpts().ConstexprCallDepth) | ||||||
932 | return true; | ||||||
933 | FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) | ||||||
934 | << getLangOpts().ConstexprCallDepth; | ||||||
935 | return false; | ||||||
936 | } | ||||||
937 | |||||||
938 | std::pair<CallStackFrame *, unsigned> | ||||||
939 | getCallFrameAndDepth(unsigned CallIndex) { | ||||||
940 | assert(CallIndex && "no call index in getCallFrameAndDepth")((CallIndex && "no call index in getCallFrameAndDepth" ) ? static_cast<void> (0) : __assert_fail ("CallIndex && \"no call index in getCallFrameAndDepth\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 940, __PRETTY_FUNCTION__)); | ||||||
941 | // We will eventually hit BottomFrame, which has Index 1, so Frame can't | ||||||
942 | // be null in this loop. | ||||||
943 | unsigned Depth = CallStackDepth; | ||||||
944 | CallStackFrame *Frame = CurrentCall; | ||||||
945 | while (Frame->Index > CallIndex) { | ||||||
946 | Frame = Frame->Caller; | ||||||
947 | --Depth; | ||||||
948 | } | ||||||
949 | if (Frame->Index == CallIndex) | ||||||
950 | return {Frame, Depth}; | ||||||
951 | return {nullptr, 0}; | ||||||
952 | } | ||||||
953 | |||||||
954 | bool nextStep(const Stmt *S) { | ||||||
955 | if (!StepsLeft) { | ||||||
956 | FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); | ||||||
957 | return false; | ||||||
958 | } | ||||||
959 | --StepsLeft; | ||||||
960 | return true; | ||||||
961 | } | ||||||
962 | |||||||
963 | APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); | ||||||
964 | |||||||
965 | Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { | ||||||
966 | Optional<DynAlloc*> Result; | ||||||
967 | auto It = HeapAllocs.find(DA); | ||||||
968 | if (It != HeapAllocs.end()) | ||||||
969 | Result = &It->second; | ||||||
970 | return Result; | ||||||
971 | } | ||||||
972 | |||||||
973 | void performLifetimeExtension() { | ||||||
974 | // Disable the cleanups for lifetime-extended temporaries. | ||||||
975 | CleanupStack.erase( | ||||||
976 | std::remove_if(CleanupStack.begin(), CleanupStack.end(), | ||||||
977 | [](Cleanup &C) { return C.isLifetimeExtended(); }), | ||||||
978 | CleanupStack.end()); | ||||||
979 | } | ||||||
980 | |||||||
981 | /// Throw away any remaining cleanups at the end of evaluation. If any | ||||||
982 | /// cleanups would have had a side-effect, note that as an unmodeled | ||||||
983 | /// side-effect and return false. Otherwise, return true. | ||||||
984 | bool discardCleanups() { | ||||||
985 | for (Cleanup &C : CleanupStack) | ||||||
986 | if (C.hasSideEffect()) | ||||||
987 | if (!noteSideEffect()) | ||||||
988 | return false; | ||||||
989 | return true; | ||||||
990 | } | ||||||
991 | |||||||
992 | private: | ||||||
993 | interp::Frame *getCurrentFrame() override { return CurrentCall; } | ||||||
994 | const interp::Frame *getBottomFrame() const override { return &BottomFrame; } | ||||||
995 | |||||||
996 | bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } | ||||||
997 | void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } | ||||||
998 | |||||||
999 | void setFoldFailureDiagnostic(bool Flag) override { | ||||||
1000 | HasFoldFailureDiagnostic = Flag; | ||||||
1001 | } | ||||||
1002 | |||||||
1003 | Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } | ||||||
1004 | |||||||
1005 | ASTContext &getCtx() const override { return Ctx; } | ||||||
1006 | |||||||
1007 | // If we have a prior diagnostic, it will be noting that the expression | ||||||
1008 | // isn't a constant expression. This diagnostic is more important, | ||||||
1009 | // unless we require this evaluation to produce a constant expression. | ||||||
1010 | // | ||||||
1011 | // FIXME: We might want to show both diagnostics to the user in | ||||||
1012 | // EM_ConstantFold mode. | ||||||
1013 | bool hasPriorDiagnostic() override { | ||||||
1014 | if (!EvalStatus.Diag->empty()) { | ||||||
1015 | switch (EvalMode) { | ||||||
1016 | case EM_ConstantFold: | ||||||
1017 | case EM_IgnoreSideEffects: | ||||||
1018 | if (!HasFoldFailureDiagnostic) | ||||||
1019 | break; | ||||||
1020 | // We've already failed to fold something. Keep that diagnostic. | ||||||
1021 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
1022 | case EM_ConstantExpression: | ||||||
1023 | case EM_ConstantExpressionUnevaluated: | ||||||
1024 | setActiveDiagnostic(false); | ||||||
1025 | return true; | ||||||
1026 | } | ||||||
1027 | } | ||||||
1028 | return false; | ||||||
1029 | } | ||||||
1030 | |||||||
1031 | unsigned getCallStackDepth() override { return CallStackDepth; } | ||||||
1032 | |||||||
1033 | public: | ||||||
1034 | /// Should we continue evaluation after encountering a side-effect that we | ||||||
1035 | /// couldn't model? | ||||||
1036 | bool keepEvaluatingAfterSideEffect() { | ||||||
1037 | switch (EvalMode) { | ||||||
1038 | case EM_IgnoreSideEffects: | ||||||
1039 | return true; | ||||||
1040 | |||||||
1041 | case EM_ConstantExpression: | ||||||
1042 | case EM_ConstantExpressionUnevaluated: | ||||||
1043 | case EM_ConstantFold: | ||||||
1044 | // By default, assume any side effect might be valid in some other | ||||||
1045 | // evaluation of this expression from a different context. | ||||||
1046 | return checkingPotentialConstantExpression() || | ||||||
1047 | checkingForUndefinedBehavior(); | ||||||
1048 | } | ||||||
1049 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1049); | ||||||
1050 | } | ||||||
1051 | |||||||
1052 | /// Note that we have had a side-effect, and determine whether we should | ||||||
1053 | /// keep evaluating. | ||||||
1054 | bool noteSideEffect() { | ||||||
1055 | EvalStatus.HasSideEffects = true; | ||||||
1056 | return keepEvaluatingAfterSideEffect(); | ||||||
1057 | } | ||||||
1058 | |||||||
1059 | /// Should we continue evaluation after encountering undefined behavior? | ||||||
1060 | bool keepEvaluatingAfterUndefinedBehavior() { | ||||||
1061 | switch (EvalMode) { | ||||||
1062 | case EM_IgnoreSideEffects: | ||||||
1063 | case EM_ConstantFold: | ||||||
1064 | return true; | ||||||
1065 | |||||||
1066 | case EM_ConstantExpression: | ||||||
1067 | case EM_ConstantExpressionUnevaluated: | ||||||
1068 | return checkingForUndefinedBehavior(); | ||||||
1069 | } | ||||||
1070 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1070); | ||||||
1071 | } | ||||||
1072 | |||||||
1073 | /// Note that we hit something that was technically undefined behavior, but | ||||||
1074 | /// that we can evaluate past it (such as signed overflow or floating-point | ||||||
1075 | /// division by zero.) | ||||||
1076 | bool noteUndefinedBehavior() override { | ||||||
1077 | EvalStatus.HasUndefinedBehavior = true; | ||||||
1078 | return keepEvaluatingAfterUndefinedBehavior(); | ||||||
1079 | } | ||||||
1080 | |||||||
1081 | /// Should we continue evaluation as much as possible after encountering a | ||||||
1082 | /// construct which can't be reduced to a value? | ||||||
1083 | bool keepEvaluatingAfterFailure() const override { | ||||||
1084 | if (!StepsLeft) | ||||||
1085 | return false; | ||||||
1086 | |||||||
1087 | switch (EvalMode) { | ||||||
1088 | case EM_ConstantExpression: | ||||||
1089 | case EM_ConstantExpressionUnevaluated: | ||||||
1090 | case EM_ConstantFold: | ||||||
1091 | case EM_IgnoreSideEffects: | ||||||
1092 | return checkingPotentialConstantExpression() || | ||||||
1093 | checkingForUndefinedBehavior(); | ||||||
1094 | } | ||||||
1095 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1095); | ||||||
1096 | } | ||||||
1097 | |||||||
1098 | /// Notes that we failed to evaluate an expression that other expressions | ||||||
1099 | /// directly depend on, and determine if we should keep evaluating. This | ||||||
1100 | /// should only be called if we actually intend to keep evaluating. | ||||||
1101 | /// | ||||||
1102 | /// Call noteSideEffect() instead if we may be able to ignore the value that | ||||||
1103 | /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: | ||||||
1104 | /// | ||||||
1105 | /// (Foo(), 1) // use noteSideEffect | ||||||
1106 | /// (Foo() || true) // use noteSideEffect | ||||||
1107 | /// Foo() + 1 // use noteFailure | ||||||
1108 | LLVM_NODISCARD[[clang::warn_unused_result]] bool noteFailure() { | ||||||
1109 | // Failure when evaluating some expression often means there is some | ||||||
1110 | // subexpression whose evaluation was skipped. Therefore, (because we | ||||||
1111 | // don't track whether we skipped an expression when unwinding after an | ||||||
1112 | // evaluation failure) every evaluation failure that bubbles up from a | ||||||
1113 | // subexpression implies that a side-effect has potentially happened. We | ||||||
1114 | // skip setting the HasSideEffects flag to true until we decide to | ||||||
1115 | // continue evaluating after that point, which happens here. | ||||||
1116 | bool KeepGoing = keepEvaluatingAfterFailure(); | ||||||
1117 | EvalStatus.HasSideEffects |= KeepGoing; | ||||||
1118 | return KeepGoing; | ||||||
1119 | } | ||||||
1120 | |||||||
1121 | class ArrayInitLoopIndex { | ||||||
1122 | EvalInfo &Info; | ||||||
1123 | uint64_t OuterIndex; | ||||||
1124 | |||||||
1125 | public: | ||||||
1126 | ArrayInitLoopIndex(EvalInfo &Info) | ||||||
1127 | : Info(Info), OuterIndex(Info.ArrayInitIndex) { | ||||||
1128 | Info.ArrayInitIndex = 0; | ||||||
1129 | } | ||||||
1130 | ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } | ||||||
1131 | |||||||
1132 | operator uint64_t&() { return Info.ArrayInitIndex; } | ||||||
1133 | }; | ||||||
1134 | }; | ||||||
1135 | |||||||
1136 | /// Object used to treat all foldable expressions as constant expressions. | ||||||
1137 | struct FoldConstant { | ||||||
1138 | EvalInfo &Info; | ||||||
1139 | bool Enabled; | ||||||
1140 | bool HadNoPriorDiags; | ||||||
1141 | EvalInfo::EvaluationMode OldMode; | ||||||
1142 | |||||||
1143 | explicit FoldConstant(EvalInfo &Info, bool Enabled) | ||||||
1144 | : Info(Info), | ||||||
1145 | Enabled(Enabled), | ||||||
1146 | HadNoPriorDiags(Info.EvalStatus.Diag && | ||||||
1147 | Info.EvalStatus.Diag->empty() && | ||||||
1148 | !Info.EvalStatus.HasSideEffects), | ||||||
1149 | OldMode(Info.EvalMode) { | ||||||
1150 | if (Enabled) | ||||||
1151 | Info.EvalMode = EvalInfo::EM_ConstantFold; | ||||||
1152 | } | ||||||
1153 | void keepDiagnostics() { Enabled = false; } | ||||||
1154 | ~FoldConstant() { | ||||||
1155 | if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && | ||||||
1156 | !Info.EvalStatus.HasSideEffects) | ||||||
1157 | Info.EvalStatus.Diag->clear(); | ||||||
1158 | Info.EvalMode = OldMode; | ||||||
1159 | } | ||||||
1160 | }; | ||||||
1161 | |||||||
1162 | /// RAII object used to set the current evaluation mode to ignore | ||||||
1163 | /// side-effects. | ||||||
1164 | struct IgnoreSideEffectsRAII { | ||||||
1165 | EvalInfo &Info; | ||||||
1166 | EvalInfo::EvaluationMode OldMode; | ||||||
1167 | explicit IgnoreSideEffectsRAII(EvalInfo &Info) | ||||||
1168 | : Info(Info), OldMode(Info.EvalMode) { | ||||||
1169 | Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; | ||||||
1170 | } | ||||||
1171 | |||||||
1172 | ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } | ||||||
1173 | }; | ||||||
1174 | |||||||
1175 | /// RAII object used to optionally suppress diagnostics and side-effects from | ||||||
1176 | /// a speculative evaluation. | ||||||
1177 | class SpeculativeEvaluationRAII { | ||||||
1178 | EvalInfo *Info = nullptr; | ||||||
1179 | Expr::EvalStatus OldStatus; | ||||||
1180 | unsigned OldSpeculativeEvaluationDepth; | ||||||
1181 | |||||||
1182 | void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { | ||||||
1183 | Info = Other.Info; | ||||||
1184 | OldStatus = Other.OldStatus; | ||||||
1185 | OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; | ||||||
1186 | Other.Info = nullptr; | ||||||
1187 | } | ||||||
1188 | |||||||
1189 | void maybeRestoreState() { | ||||||
1190 | if (!Info) | ||||||
1191 | return; | ||||||
1192 | |||||||
1193 | Info->EvalStatus = OldStatus; | ||||||
1194 | Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; | ||||||
1195 | } | ||||||
1196 | |||||||
1197 | public: | ||||||
1198 | SpeculativeEvaluationRAII() = default; | ||||||
1199 | |||||||
1200 | SpeculativeEvaluationRAII( | ||||||
1201 | EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) | ||||||
1202 | : Info(&Info), OldStatus(Info.EvalStatus), | ||||||
1203 | OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { | ||||||
1204 | Info.EvalStatus.Diag = NewDiag; | ||||||
1205 | Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; | ||||||
1206 | } | ||||||
1207 | |||||||
1208 | SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; | ||||||
1209 | SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { | ||||||
1210 | moveFromAndCancel(std::move(Other)); | ||||||
1211 | } | ||||||
1212 | |||||||
1213 | SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { | ||||||
1214 | maybeRestoreState(); | ||||||
1215 | moveFromAndCancel(std::move(Other)); | ||||||
1216 | return *this; | ||||||
1217 | } | ||||||
1218 | |||||||
1219 | ~SpeculativeEvaluationRAII() { maybeRestoreState(); } | ||||||
1220 | }; | ||||||
1221 | |||||||
1222 | /// RAII object wrapping a full-expression or block scope, and handling | ||||||
1223 | /// the ending of the lifetime of temporaries created within it. | ||||||
1224 | template<bool IsFullExpression> | ||||||
1225 | class ScopeRAII { | ||||||
1226 | EvalInfo &Info; | ||||||
1227 | unsigned OldStackSize; | ||||||
1228 | public: | ||||||
1229 | ScopeRAII(EvalInfo &Info) | ||||||
1230 | : Info(Info), OldStackSize(Info.CleanupStack.size()) { | ||||||
1231 | // Push a new temporary version. This is needed to distinguish between | ||||||
1232 | // temporaries created in different iterations of a loop. | ||||||
1233 | Info.CurrentCall->pushTempVersion(); | ||||||
1234 | } | ||||||
1235 | bool destroy(bool RunDestructors = true) { | ||||||
1236 | bool OK = cleanup(Info, RunDestructors, OldStackSize); | ||||||
1237 | OldStackSize = -1U; | ||||||
1238 | return OK; | ||||||
1239 | } | ||||||
1240 | ~ScopeRAII() { | ||||||
1241 | if (OldStackSize != -1U) | ||||||
1242 | destroy(false); | ||||||
1243 | // Body moved to a static method to encourage the compiler to inline away | ||||||
1244 | // instances of this class. | ||||||
1245 | Info.CurrentCall->popTempVersion(); | ||||||
1246 | } | ||||||
1247 | private: | ||||||
1248 | static bool cleanup(EvalInfo &Info, bool RunDestructors, | ||||||
1249 | unsigned OldStackSize) { | ||||||
1250 | assert(OldStackSize <= Info.CleanupStack.size() &&((OldStackSize <= Info.CleanupStack.size() && "running cleanups out of order?" ) ? static_cast<void> (0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1251, __PRETTY_FUNCTION__)) | ||||||
1251 | "running cleanups out of order?")((OldStackSize <= Info.CleanupStack.size() && "running cleanups out of order?" ) ? static_cast<void> (0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1251, __PRETTY_FUNCTION__)); | ||||||
1252 | |||||||
1253 | // Run all cleanups for a block scope, and non-lifetime-extended cleanups | ||||||
1254 | // for a full-expression scope. | ||||||
1255 | bool Success = true; | ||||||
1256 | for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { | ||||||
1257 | if (!(IsFullExpression && | ||||||
1258 | Info.CleanupStack[I - 1].isLifetimeExtended())) { | ||||||
1259 | if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { | ||||||
1260 | Success = false; | ||||||
1261 | break; | ||||||
1262 | } | ||||||
1263 | } | ||||||
1264 | } | ||||||
1265 | |||||||
1266 | // Compact lifetime-extended cleanups. | ||||||
1267 | auto NewEnd = Info.CleanupStack.begin() + OldStackSize; | ||||||
1268 | if (IsFullExpression) | ||||||
1269 | NewEnd = | ||||||
1270 | std::remove_if(NewEnd, Info.CleanupStack.end(), | ||||||
1271 | [](Cleanup &C) { return !C.isLifetimeExtended(); }); | ||||||
1272 | Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); | ||||||
1273 | return Success; | ||||||
1274 | } | ||||||
1275 | }; | ||||||
1276 | typedef ScopeRAII<false> BlockScopeRAII; | ||||||
1277 | typedef ScopeRAII<true> FullExpressionRAII; | ||||||
1278 | } | ||||||
1279 | |||||||
1280 | bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, | ||||||
1281 | CheckSubobjectKind CSK) { | ||||||
1282 | if (Invalid) | ||||||
1283 | return false; | ||||||
1284 | if (isOnePastTheEnd()) { | ||||||
1285 | Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) | ||||||
1286 | << CSK; | ||||||
1287 | setInvalid(); | ||||||
1288 | return false; | ||||||
1289 | } | ||||||
1290 | // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there | ||||||
1291 | // must actually be at least one array element; even a VLA cannot have a | ||||||
1292 | // bound of zero. And if our index is nonzero, we already had a CCEDiag. | ||||||
1293 | return true; | ||||||
1294 | } | ||||||
1295 | |||||||
1296 | void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, | ||||||
1297 | const Expr *E) { | ||||||
1298 | Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); | ||||||
1299 | // Do not set the designator as invalid: we can represent this situation, | ||||||
1300 | // and correct handling of __builtin_object_size requires us to do so. | ||||||
1301 | } | ||||||
1302 | |||||||
1303 | void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, | ||||||
1304 | const Expr *E, | ||||||
1305 | const APSInt &N) { | ||||||
1306 | // If we're complaining, we must be able to statically determine the size of | ||||||
1307 | // the most derived array. | ||||||
1308 | if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) | ||||||
1309 | Info.CCEDiag(E, diag::note_constexpr_array_index) | ||||||
1310 | << N << /*array*/ 0 | ||||||
1311 | << static_cast<unsigned>(getMostDerivedArraySize()); | ||||||
1312 | else | ||||||
1313 | Info.CCEDiag(E, diag::note_constexpr_array_index) | ||||||
1314 | << N << /*non-array*/ 1; | ||||||
1315 | setInvalid(); | ||||||
1316 | } | ||||||
1317 | |||||||
1318 | CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, | ||||||
1319 | const FunctionDecl *Callee, const LValue *This, | ||||||
1320 | APValue *Arguments) | ||||||
1321 | : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), | ||||||
1322 | Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { | ||||||
1323 | Info.CurrentCall = this; | ||||||
1324 | ++Info.CallStackDepth; | ||||||
1325 | } | ||||||
1326 | |||||||
1327 | CallStackFrame::~CallStackFrame() { | ||||||
1328 | assert(Info.CurrentCall == this && "calls retired out of order")((Info.CurrentCall == this && "calls retired out of order" ) ? static_cast<void> (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1328, __PRETTY_FUNCTION__)); | ||||||
1329 | --Info.CallStackDepth; | ||||||
1330 | Info.CurrentCall = Caller; | ||||||
1331 | } | ||||||
1332 | |||||||
1333 | static bool isRead(AccessKinds AK) { | ||||||
1334 | return AK == AK_Read || AK == AK_ReadObjectRepresentation; | ||||||
1335 | } | ||||||
1336 | |||||||
1337 | static bool isModification(AccessKinds AK) { | ||||||
1338 | switch (AK) { | ||||||
1339 | case AK_Read: | ||||||
1340 | case AK_ReadObjectRepresentation: | ||||||
1341 | case AK_MemberCall: | ||||||
1342 | case AK_DynamicCast: | ||||||
1343 | case AK_TypeId: | ||||||
1344 | return false; | ||||||
1345 | case AK_Assign: | ||||||
1346 | case AK_Increment: | ||||||
1347 | case AK_Decrement: | ||||||
1348 | case AK_Destroy: | ||||||
1349 | return true; | ||||||
1350 | } | ||||||
1351 | llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1351); | ||||||
1352 | } | ||||||
1353 | |||||||
1354 | static bool isAnyAccess(AccessKinds AK) { | ||||||
1355 | return isRead(AK) || isModification(AK); | ||||||
1356 | } | ||||||
1357 | |||||||
1358 | /// Is this an access per the C++ definition? | ||||||
1359 | static bool isFormalAccess(AccessKinds AK) { | ||||||
1360 | return isAnyAccess(AK) && AK != AK_Destroy; | ||||||
1361 | } | ||||||
1362 | |||||||
1363 | namespace { | ||||||
1364 | struct ComplexValue { | ||||||
1365 | private: | ||||||
1366 | bool IsInt; | ||||||
1367 | |||||||
1368 | public: | ||||||
1369 | APSInt IntReal, IntImag; | ||||||
1370 | APFloat FloatReal, FloatImag; | ||||||
1371 | |||||||
1372 | ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} | ||||||
1373 | |||||||
1374 | void makeComplexFloat() { IsInt = false; } | ||||||
1375 | bool isComplexFloat() const { return !IsInt; } | ||||||
1376 | APFloat &getComplexFloatReal() { return FloatReal; } | ||||||
1377 | APFloat &getComplexFloatImag() { return FloatImag; } | ||||||
1378 | |||||||
1379 | void makeComplexInt() { IsInt = true; } | ||||||
1380 | bool isComplexInt() const { return IsInt; } | ||||||
1381 | APSInt &getComplexIntReal() { return IntReal; } | ||||||
1382 | APSInt &getComplexIntImag() { return IntImag; } | ||||||
1383 | |||||||
1384 | void moveInto(APValue &v) const { | ||||||
1385 | if (isComplexFloat()) | ||||||
1386 | v = APValue(FloatReal, FloatImag); | ||||||
1387 | else | ||||||
1388 | v = APValue(IntReal, IntImag); | ||||||
1389 | } | ||||||
1390 | void setFrom(const APValue &v) { | ||||||
1391 | assert(v.isComplexFloat() || v.isComplexInt())((v.isComplexFloat() || v.isComplexInt()) ? static_cast<void > (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1391, __PRETTY_FUNCTION__)); | ||||||
1392 | if (v.isComplexFloat()) { | ||||||
1393 | makeComplexFloat(); | ||||||
1394 | FloatReal = v.getComplexFloatReal(); | ||||||
1395 | FloatImag = v.getComplexFloatImag(); | ||||||
1396 | } else { | ||||||
1397 | makeComplexInt(); | ||||||
1398 | IntReal = v.getComplexIntReal(); | ||||||
1399 | IntImag = v.getComplexIntImag(); | ||||||
1400 | } | ||||||
1401 | } | ||||||
1402 | }; | ||||||
1403 | |||||||
1404 | struct LValue { | ||||||
1405 | APValue::LValueBase Base; | ||||||
1406 | CharUnits Offset; | ||||||
1407 | SubobjectDesignator Designator; | ||||||
1408 | bool IsNullPtr : 1; | ||||||
1409 | bool InvalidBase : 1; | ||||||
1410 | |||||||
1411 | const APValue::LValueBase getLValueBase() const { return Base; } | ||||||
1412 | CharUnits &getLValueOffset() { return Offset; } | ||||||
1413 | const CharUnits &getLValueOffset() const { return Offset; } | ||||||
1414 | SubobjectDesignator &getLValueDesignator() { return Designator; } | ||||||
1415 | const SubobjectDesignator &getLValueDesignator() const { return Designator;} | ||||||
1416 | bool isNullPointer() const { return IsNullPtr;} | ||||||
1417 | |||||||
1418 | unsigned getLValueCallIndex() const { return Base.getCallIndex(); } | ||||||
1419 | unsigned getLValueVersion() const { return Base.getVersion(); } | ||||||
1420 | |||||||
1421 | void moveInto(APValue &V) const { | ||||||
1422 | if (Designator.Invalid) | ||||||
1423 | V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); | ||||||
1424 | else { | ||||||
1425 | assert(!InvalidBase && "APValues can't handle invalid LValue bases")((!InvalidBase && "APValues can't handle invalid LValue bases" ) ? static_cast<void> (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1425, __PRETTY_FUNCTION__)); | ||||||
1426 | V = APValue(Base, Offset, Designator.Entries, | ||||||
1427 | Designator.IsOnePastTheEnd, IsNullPtr); | ||||||
1428 | } | ||||||
1429 | } | ||||||
1430 | void setFrom(ASTContext &Ctx, const APValue &V) { | ||||||
1431 | assert(V.isLValue() && "Setting LValue from a non-LValue?")((V.isLValue() && "Setting LValue from a non-LValue?" ) ? static_cast<void> (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1431, __PRETTY_FUNCTION__)); | ||||||
1432 | Base = V.getLValueBase(); | ||||||
1433 | Offset = V.getLValueOffset(); | ||||||
1434 | InvalidBase = false; | ||||||
1435 | Designator = SubobjectDesignator(Ctx, V); | ||||||
1436 | IsNullPtr = V.isNullPointer(); | ||||||
1437 | } | ||||||
1438 | |||||||
1439 | void set(APValue::LValueBase B, bool BInvalid = false) { | ||||||
1440 | #ifndef NDEBUG | ||||||
1441 | // We only allow a few types of invalid bases. Enforce that here. | ||||||
1442 | if (BInvalid) { | ||||||
1443 | const auto *E = B.get<const Expr *>(); | ||||||
1444 | assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && "Unexpected type of invalid base") ? static_cast<void> (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1445, __PRETTY_FUNCTION__)) | ||||||
1445 | "Unexpected type of invalid base")(((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && "Unexpected type of invalid base") ? static_cast<void> (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1445, __PRETTY_FUNCTION__)); | ||||||
1446 | } | ||||||
1447 | #endif | ||||||
1448 | |||||||
1449 | Base = B; | ||||||
1450 | Offset = CharUnits::fromQuantity(0); | ||||||
1451 | InvalidBase = BInvalid; | ||||||
1452 | Designator = SubobjectDesignator(getType(B)); | ||||||
1453 | IsNullPtr = false; | ||||||
1454 | } | ||||||
1455 | |||||||
1456 | void setNull(QualType PointerTy, uint64_t TargetVal) { | ||||||
1457 | Base = (Expr *)nullptr; | ||||||
1458 | Offset = CharUnits::fromQuantity(TargetVal); | ||||||
1459 | InvalidBase = false; | ||||||
1460 | Designator = SubobjectDesignator(PointerTy->getPointeeType()); | ||||||
1461 | IsNullPtr = true; | ||||||
1462 | } | ||||||
1463 | |||||||
1464 | void setInvalid(APValue::LValueBase B, unsigned I = 0) { | ||||||
1465 | set(B, true); | ||||||
1466 | } | ||||||
1467 | |||||||
1468 | private: | ||||||
1469 | // Check that this LValue is not based on a null pointer. If it is, produce | ||||||
1470 | // a diagnostic and mark the designator as invalid. | ||||||
1471 | template <typename GenDiagType> | ||||||
1472 | bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { | ||||||
1473 | if (Designator.Invalid) | ||||||
1474 | return false; | ||||||
1475 | if (IsNullPtr) { | ||||||
1476 | GenDiag(); | ||||||
1477 | Designator.setInvalid(); | ||||||
1478 | return false; | ||||||
1479 | } | ||||||
1480 | return true; | ||||||
1481 | } | ||||||
1482 | |||||||
1483 | public: | ||||||
1484 | bool checkNullPointer(EvalInfo &Info, const Expr *E, | ||||||
1485 | CheckSubobjectKind CSK) { | ||||||
1486 | return checkNullPointerDiagnosingWith([&Info, E, CSK] { | ||||||
1487 | Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; | ||||||
1488 | }); | ||||||
1489 | } | ||||||
1490 | |||||||
1491 | bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, | ||||||
1492 | AccessKinds AK) { | ||||||
1493 | return checkNullPointerDiagnosingWith([&Info, E, AK] { | ||||||
1494 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; | ||||||
1495 | }); | ||||||
1496 | } | ||||||
1497 | |||||||
1498 | // Check this LValue refers to an object. If not, set the designator to be | ||||||
1499 | // invalid and emit a diagnostic. | ||||||
1500 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { | ||||||
1501 | return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && | ||||||
1502 | Designator.checkSubobject(Info, E, CSK); | ||||||
1503 | } | ||||||
1504 | |||||||
1505 | void addDecl(EvalInfo &Info, const Expr *E, | ||||||
1506 | const Decl *D, bool Virtual = false) { | ||||||
1507 | if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) | ||||||
1508 | Designator.addDeclUnchecked(D, Virtual); | ||||||
1509 | } | ||||||
1510 | void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { | ||||||
1511 | if (!Designator.Entries.empty()) { | ||||||
1512 | Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); | ||||||
1513 | Designator.setInvalid(); | ||||||
1514 | return; | ||||||
1515 | } | ||||||
1516 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) { | ||||||
1517 | assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())((getType(Base)->isPointerType() || getType(Base)->isArrayType ()) ? static_cast<void> (0) : __assert_fail ("getType(Base)->isPointerType() || getType(Base)->isArrayType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1517, __PRETTY_FUNCTION__)); | ||||||
1518 | Designator.FirstEntryIsAnUnsizedArray = true; | ||||||
1519 | Designator.addUnsizedArrayUnchecked(ElemTy); | ||||||
1520 | } | ||||||
1521 | } | ||||||
1522 | void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { | ||||||
1523 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) | ||||||
1524 | Designator.addArrayUnchecked(CAT); | ||||||
1525 | } | ||||||
1526 | void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { | ||||||
1527 | if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) | ||||||
1528 | Designator.addComplexUnchecked(EltTy, Imag); | ||||||
1529 | } | ||||||
1530 | void clearIsNullPointer() { | ||||||
1531 | IsNullPtr = false; | ||||||
1532 | } | ||||||
1533 | void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, | ||||||
1534 | const APSInt &Index, CharUnits ElementSize) { | ||||||
1535 | // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, | ||||||
1536 | // but we're not required to diagnose it and it's valid in C++.) | ||||||
1537 | if (!Index) | ||||||
1538 | return; | ||||||
1539 | |||||||
1540 | // Compute the new offset in the appropriate width, wrapping at 64 bits. | ||||||
1541 | // FIXME: When compiling for a 32-bit target, we should use 32-bit | ||||||
1542 | // offsets. | ||||||
1543 | uint64_t Offset64 = Offset.getQuantity(); | ||||||
1544 | uint64_t ElemSize64 = ElementSize.getQuantity(); | ||||||
1545 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); | ||||||
1546 | Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); | ||||||
1547 | |||||||
1548 | if (checkNullPointer(Info, E, CSK_ArrayIndex)) | ||||||
1549 | Designator.adjustIndex(Info, E, Index); | ||||||
1550 | clearIsNullPointer(); | ||||||
1551 | } | ||||||
1552 | void adjustOffset(CharUnits N) { | ||||||
1553 | Offset += N; | ||||||
1554 | if (N.getQuantity()) | ||||||
1555 | clearIsNullPointer(); | ||||||
1556 | } | ||||||
1557 | }; | ||||||
1558 | |||||||
1559 | struct MemberPtr { | ||||||
1560 | MemberPtr() {} | ||||||
1561 | explicit MemberPtr(const ValueDecl *Decl) : | ||||||
1562 | DeclAndIsDerivedMember(Decl, false), Path() {} | ||||||
1563 | |||||||
1564 | /// The member or (direct or indirect) field referred to by this member | ||||||
1565 | /// pointer, or 0 if this is a null member pointer. | ||||||
1566 | const ValueDecl *getDecl() const { | ||||||
1567 | return DeclAndIsDerivedMember.getPointer(); | ||||||
1568 | } | ||||||
1569 | /// Is this actually a member of some type derived from the relevant class? | ||||||
1570 | bool isDerivedMember() const { | ||||||
1571 | return DeclAndIsDerivedMember.getInt(); | ||||||
1572 | } | ||||||
1573 | /// Get the class which the declaration actually lives in. | ||||||
1574 | const CXXRecordDecl *getContainingRecord() const { | ||||||
1575 | return cast<CXXRecordDecl>( | ||||||
1576 | DeclAndIsDerivedMember.getPointer()->getDeclContext()); | ||||||
1577 | } | ||||||
1578 | |||||||
1579 | void moveInto(APValue &V) const { | ||||||
1580 | V = APValue(getDecl(), isDerivedMember(), Path); | ||||||
1581 | } | ||||||
1582 | void setFrom(const APValue &V) { | ||||||
1583 | assert(V.isMemberPointer())((V.isMemberPointer()) ? static_cast<void> (0) : __assert_fail ("V.isMemberPointer()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1583, __PRETTY_FUNCTION__)); | ||||||
1584 | DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); | ||||||
1585 | DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); | ||||||
1586 | Path.clear(); | ||||||
1587 | ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); | ||||||
1588 | Path.insert(Path.end(), P.begin(), P.end()); | ||||||
1589 | } | ||||||
1590 | |||||||
1591 | /// DeclAndIsDerivedMember - The member declaration, and a flag indicating | ||||||
1592 | /// whether the member is a member of some class derived from the class type | ||||||
1593 | /// of the member pointer. | ||||||
1594 | llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; | ||||||
1595 | /// Path - The path of base/derived classes from the member declaration's | ||||||
1596 | /// class (exclusive) to the class type of the member pointer (inclusive). | ||||||
1597 | SmallVector<const CXXRecordDecl*, 4> Path; | ||||||
1598 | |||||||
1599 | /// Perform a cast towards the class of the Decl (either up or down the | ||||||
1600 | /// hierarchy). | ||||||
1601 | bool castBack(const CXXRecordDecl *Class) { | ||||||
1602 | assert(!Path.empty())((!Path.empty()) ? static_cast<void> (0) : __assert_fail ("!Path.empty()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1602, __PRETTY_FUNCTION__)); | ||||||
1603 | const CXXRecordDecl *Expected; | ||||||
1604 | if (Path.size() >= 2) | ||||||
1605 | Expected = Path[Path.size() - 2]; | ||||||
1606 | else | ||||||
1607 | Expected = getContainingRecord(); | ||||||
1608 | if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { | ||||||
1609 | // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), | ||||||
1610 | // if B does not contain the original member and is not a base or | ||||||
1611 | // derived class of the class containing the original member, the result | ||||||
1612 | // of the cast is undefined. | ||||||
1613 | // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to | ||||||
1614 | // (D::*). We consider that to be a language defect. | ||||||
1615 | return false; | ||||||
1616 | } | ||||||
1617 | Path.pop_back(); | ||||||
1618 | return true; | ||||||
1619 | } | ||||||
1620 | /// Perform a base-to-derived member pointer cast. | ||||||
1621 | bool castToDerived(const CXXRecordDecl *Derived) { | ||||||
1622 | if (!getDecl()) | ||||||
1623 | return true; | ||||||
1624 | if (!isDerivedMember()) { | ||||||
1625 | Path.push_back(Derived); | ||||||
1626 | return true; | ||||||
1627 | } | ||||||
1628 | if (!castBack(Derived)) | ||||||
1629 | return false; | ||||||
1630 | if (Path.empty()) | ||||||
1631 | DeclAndIsDerivedMember.setInt(false); | ||||||
1632 | return true; | ||||||
1633 | } | ||||||
1634 | /// Perform a derived-to-base member pointer cast. | ||||||
1635 | bool castToBase(const CXXRecordDecl *Base) { | ||||||
1636 | if (!getDecl()) | ||||||
1637 | return true; | ||||||
1638 | if (Path.empty()) | ||||||
1639 | DeclAndIsDerivedMember.setInt(true); | ||||||
1640 | if (isDerivedMember()) { | ||||||
1641 | Path.push_back(Base); | ||||||
1642 | return true; | ||||||
1643 | } | ||||||
1644 | return castBack(Base); | ||||||
1645 | } | ||||||
1646 | }; | ||||||
1647 | |||||||
1648 | /// Compare two member pointers, which are assumed to be of the same type. | ||||||
1649 | static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { | ||||||
1650 | if (!LHS.getDecl() || !RHS.getDecl()) | ||||||
1651 | return !LHS.getDecl() && !RHS.getDecl(); | ||||||
1652 | if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) | ||||||
1653 | return false; | ||||||
1654 | return LHS.Path == RHS.Path; | ||||||
1655 | } | ||||||
1656 | } | ||||||
1657 | |||||||
1658 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); | ||||||
1659 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, | ||||||
1660 | const LValue &This, const Expr *E, | ||||||
1661 | bool AllowNonLiteralTypes = false); | ||||||
1662 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, | ||||||
1663 | bool InvalidBaseOK = false); | ||||||
1664 | static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, | ||||||
1665 | bool InvalidBaseOK = false); | ||||||
1666 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, | ||||||
1667 | EvalInfo &Info); | ||||||
1668 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); | ||||||
1669 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); | ||||||
1670 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, | ||||||
1671 | EvalInfo &Info); | ||||||
1672 | static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); | ||||||
1673 | static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); | ||||||
1674 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, | ||||||
1675 | EvalInfo &Info); | ||||||
1676 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); | ||||||
1677 | |||||||
1678 | /// Evaluate an integer or fixed point expression into an APResult. | ||||||
1679 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, | ||||||
1680 | EvalInfo &Info); | ||||||
1681 | |||||||
1682 | /// Evaluate only a fixed point expression into an APResult. | ||||||
1683 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, | ||||||
1684 | EvalInfo &Info); | ||||||
1685 | |||||||
1686 | //===----------------------------------------------------------------------===// | ||||||
1687 | // Misc utilities | ||||||
1688 | //===----------------------------------------------------------------------===// | ||||||
1689 | |||||||
1690 | /// Negate an APSInt in place, converting it to a signed form if necessary, and | ||||||
1691 | /// preserving its value (by extending by up to one bit as needed). | ||||||
1692 | static void negateAsSigned(APSInt &Int) { | ||||||
1693 | if (Int.isUnsigned() || Int.isMinSignedValue()) { | ||||||
1694 | Int = Int.extend(Int.getBitWidth() + 1); | ||||||
1695 | Int.setIsSigned(true); | ||||||
1696 | } | ||||||
1697 | Int = -Int; | ||||||
1698 | } | ||||||
1699 | |||||||
1700 | template<typename KeyT> | ||||||
1701 | APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, | ||||||
1702 | bool IsLifetimeExtended, LValue &LV) { | ||||||
1703 | unsigned Version = getTempVersion(); | ||||||
1704 | APValue::LValueBase Base(Key, Index, Version); | ||||||
1705 | LV.set(Base); | ||||||
1706 | APValue &Result = Temporaries[MapKeyTy(Key, Version)]; | ||||||
1707 | assert(Result.isAbsent() && "temporary created multiple times")((Result.isAbsent() && "temporary created multiple times" ) ? static_cast<void> (0) : __assert_fail ("Result.isAbsent() && \"temporary created multiple times\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1707, __PRETTY_FUNCTION__)); | ||||||
1708 | |||||||
1709 | // If we're creating a temporary immediately in the operand of a speculative | ||||||
1710 | // evaluation, don't register a cleanup to be run outside the speculative | ||||||
1711 | // evaluation context, since we won't actually be able to initialize this | ||||||
1712 | // object. | ||||||
1713 | if (Index <= Info.SpeculativeEvaluationDepth) { | ||||||
1714 | if (T.isDestructedType()) | ||||||
1715 | Info.noteSideEffect(); | ||||||
1716 | } else { | ||||||
1717 | Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); | ||||||
1718 | } | ||||||
1719 | return Result; | ||||||
1720 | } | ||||||
1721 | |||||||
1722 | APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { | ||||||
1723 | if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { | ||||||
1724 | FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); | ||||||
1725 | return nullptr; | ||||||
1726 | } | ||||||
1727 | |||||||
1728 | DynamicAllocLValue DA(NumHeapAllocs++); | ||||||
1729 | LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); | ||||||
1730 | auto Result = HeapAllocs.emplace(std::piecewise_construct, | ||||||
1731 | std::forward_as_tuple(DA), std::tuple<>()); | ||||||
1732 | assert(Result.second && "reused a heap alloc index?")((Result.second && "reused a heap alloc index?") ? static_cast <void> (0) : __assert_fail ("Result.second && \"reused a heap alloc index?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1732, __PRETTY_FUNCTION__)); | ||||||
1733 | Result.first->second.AllocExpr = E; | ||||||
1734 | return &Result.first->second.Value; | ||||||
1735 | } | ||||||
1736 | |||||||
1737 | /// Produce a string describing the given constexpr call. | ||||||
1738 | void CallStackFrame::describe(raw_ostream &Out) { | ||||||
1739 | unsigned ArgIndex = 0; | ||||||
1740 | bool IsMemberCall = isa<CXXMethodDecl>(Callee) && | ||||||
1741 | !isa<CXXConstructorDecl>(Callee) && | ||||||
1742 | cast<CXXMethodDecl>(Callee)->isInstance(); | ||||||
1743 | |||||||
1744 | if (!IsMemberCall) | ||||||
1745 | Out << *Callee << '('; | ||||||
1746 | |||||||
1747 | if (This && IsMemberCall) { | ||||||
1748 | APValue Val; | ||||||
1749 | This->moveInto(Val); | ||||||
1750 | Val.printPretty(Out, Info.Ctx, | ||||||
1751 | This->Designator.MostDerivedType); | ||||||
1752 | // FIXME: Add parens around Val if needed. | ||||||
1753 | Out << "->" << *Callee << '('; | ||||||
1754 | IsMemberCall = false; | ||||||
1755 | } | ||||||
1756 | |||||||
1757 | for (FunctionDecl::param_const_iterator I = Callee->param_begin(), | ||||||
1758 | E = Callee->param_end(); I != E; ++I, ++ArgIndex) { | ||||||
1759 | if (ArgIndex > (unsigned)IsMemberCall) | ||||||
1760 | Out << ", "; | ||||||
1761 | |||||||
1762 | const ParmVarDecl *Param = *I; | ||||||
1763 | const APValue &Arg = Arguments[ArgIndex]; | ||||||
1764 | Arg.printPretty(Out, Info.Ctx, Param->getType()); | ||||||
1765 | |||||||
1766 | if (ArgIndex == 0 && IsMemberCall) | ||||||
1767 | Out << "->" << *Callee << '('; | ||||||
1768 | } | ||||||
1769 | |||||||
1770 | Out << ')'; | ||||||
1771 | } | ||||||
1772 | |||||||
1773 | /// Evaluate an expression to see if it had side-effects, and discard its | ||||||
1774 | /// result. | ||||||
1775 | /// \return \c true if the caller should keep evaluating. | ||||||
1776 | static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { | ||||||
1777 | APValue Scratch; | ||||||
1778 | if (!Evaluate(Scratch, Info, E)) | ||||||
1779 | // We don't need the value, but we might have skipped a side effect here. | ||||||
1780 | return Info.noteSideEffect(); | ||||||
1781 | return true; | ||||||
1782 | } | ||||||
1783 | |||||||
1784 | /// Should this call expression be treated as a string literal? | ||||||
1785 | static bool IsStringLiteralCall(const CallExpr *E) { | ||||||
1786 | unsigned Builtin = E->getBuiltinCallee(); | ||||||
1787 | return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || | ||||||
1788 | Builtin == Builtin::BI__builtin___NSStringMakeConstantString); | ||||||
1789 | } | ||||||
1790 | |||||||
1791 | static bool IsGlobalLValue(APValue::LValueBase B) { | ||||||
1792 | // C++11 [expr.const]p3 An address constant expression is a prvalue core | ||||||
1793 | // constant expression of pointer type that evaluates to... | ||||||
1794 | |||||||
1795 | // ... a null pointer value, or a prvalue core constant expression of type | ||||||
1796 | // std::nullptr_t. | ||||||
1797 | if (!B) return true; | ||||||
1798 | |||||||
1799 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | ||||||
1800 | // ... the address of an object with static storage duration, | ||||||
1801 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||||
1802 | return VD->hasGlobalStorage(); | ||||||
1803 | // ... the address of a function, | ||||||
1804 | return isa<FunctionDecl>(D); | ||||||
1805 | } | ||||||
1806 | |||||||
1807 | if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) | ||||||
1808 | return true; | ||||||
1809 | |||||||
1810 | const Expr *E = B.get<const Expr*>(); | ||||||
1811 | switch (E->getStmtClass()) { | ||||||
1812 | default: | ||||||
1813 | return false; | ||||||
1814 | case Expr::CompoundLiteralExprClass: { | ||||||
1815 | const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); | ||||||
1816 | return CLE->isFileScope() && CLE->isLValue(); | ||||||
1817 | } | ||||||
1818 | case Expr::MaterializeTemporaryExprClass: | ||||||
1819 | // A materialized temporary might have been lifetime-extended to static | ||||||
1820 | // storage duration. | ||||||
1821 | return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; | ||||||
1822 | // A string literal has static storage duration. | ||||||
1823 | case Expr::StringLiteralClass: | ||||||
1824 | case Expr::PredefinedExprClass: | ||||||
1825 | case Expr::ObjCStringLiteralClass: | ||||||
1826 | case Expr::ObjCEncodeExprClass: | ||||||
1827 | case Expr::CXXUuidofExprClass: | ||||||
1828 | return true; | ||||||
1829 | case Expr::ObjCBoxedExprClass: | ||||||
1830 | return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); | ||||||
1831 | case Expr::CallExprClass: | ||||||
1832 | return IsStringLiteralCall(cast<CallExpr>(E)); | ||||||
1833 | // For GCC compatibility, &&label has static storage duration. | ||||||
1834 | case Expr::AddrLabelExprClass: | ||||||
1835 | return true; | ||||||
1836 | // A Block literal expression may be used as the initialization value for | ||||||
1837 | // Block variables at global or local static scope. | ||||||
1838 | case Expr::BlockExprClass: | ||||||
1839 | return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); | ||||||
1840 | case Expr::ImplicitValueInitExprClass: | ||||||
1841 | // FIXME: | ||||||
1842 | // We can never form an lvalue with an implicit value initialization as its | ||||||
1843 | // base through expression evaluation, so these only appear in one case: the | ||||||
1844 | // implicit variable declaration we invent when checking whether a constexpr | ||||||
1845 | // constructor can produce a constant expression. We must assume that such | ||||||
1846 | // an expression might be a global lvalue. | ||||||
1847 | return true; | ||||||
1848 | } | ||||||
1849 | } | ||||||
1850 | |||||||
1851 | static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { | ||||||
1852 | return LVal.Base.dyn_cast<const ValueDecl*>(); | ||||||
1853 | } | ||||||
1854 | |||||||
1855 | static bool IsLiteralLValue(const LValue &Value) { | ||||||
1856 | if (Value.getLValueCallIndex()) | ||||||
1857 | return false; | ||||||
1858 | const Expr *E = Value.Base.dyn_cast<const Expr*>(); | ||||||
1859 | return E && !isa<MaterializeTemporaryExpr>(E); | ||||||
1860 | } | ||||||
1861 | |||||||
1862 | static bool IsWeakLValue(const LValue &Value) { | ||||||
1863 | const ValueDecl *Decl = GetLValueBaseDecl(Value); | ||||||
1864 | return Decl && Decl->isWeak(); | ||||||
1865 | } | ||||||
1866 | |||||||
1867 | static bool isZeroSized(const LValue &Value) { | ||||||
1868 | const ValueDecl *Decl = GetLValueBaseDecl(Value); | ||||||
1869 | if (Decl && isa<VarDecl>(Decl)) { | ||||||
1870 | QualType Ty = Decl->getType(); | ||||||
1871 | if (Ty->isArrayType()) | ||||||
1872 | return Ty->isIncompleteType() || | ||||||
1873 | Decl->getASTContext().getTypeSize(Ty) == 0; | ||||||
1874 | } | ||||||
1875 | return false; | ||||||
1876 | } | ||||||
1877 | |||||||
1878 | static bool HasSameBase(const LValue &A, const LValue &B) { | ||||||
1879 | if (!A.getLValueBase()) | ||||||
1880 | return !B.getLValueBase(); | ||||||
1881 | if (!B.getLValueBase()) | ||||||
1882 | return false; | ||||||
1883 | |||||||
1884 | if (A.getLValueBase().getOpaqueValue() != | ||||||
1885 | B.getLValueBase().getOpaqueValue()) { | ||||||
1886 | const Decl *ADecl = GetLValueBaseDecl(A); | ||||||
1887 | if (!ADecl) | ||||||
1888 | return false; | ||||||
1889 | const Decl *BDecl = GetLValueBaseDecl(B); | ||||||
1890 | if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) | ||||||
1891 | return false; | ||||||
1892 | } | ||||||
1893 | |||||||
1894 | return IsGlobalLValue(A.getLValueBase()) || | ||||||
1895 | (A.getLValueCallIndex() == B.getLValueCallIndex() && | ||||||
1896 | A.getLValueVersion() == B.getLValueVersion()); | ||||||
1897 | } | ||||||
1898 | |||||||
1899 | static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { | ||||||
1900 | assert(Base && "no location for a null lvalue")((Base && "no location for a null lvalue") ? static_cast <void> (0) : __assert_fail ("Base && \"no location for a null lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1900, __PRETTY_FUNCTION__)); | ||||||
1901 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | ||||||
1902 | if (VD) | ||||||
1903 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||||
1904 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) | ||||||
1905 | Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); | ||||||
1906 | else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { | ||||||
1907 | // FIXME: Produce a note for dangling pointers too. | ||||||
1908 | if (Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) | ||||||
1909 | Info.Note((*Alloc)->AllocExpr->getExprLoc(), | ||||||
1910 | diag::note_constexpr_dynamic_alloc_here); | ||||||
1911 | } | ||||||
1912 | // We have no information to show for a typeid(T) object. | ||||||
1913 | } | ||||||
1914 | |||||||
1915 | enum class CheckEvaluationResultKind { | ||||||
1916 | ConstantExpression, | ||||||
1917 | FullyInitialized, | ||||||
1918 | }; | ||||||
1919 | |||||||
1920 | /// Materialized temporaries that we've already checked to determine if they're | ||||||
1921 | /// initializsed by a constant expression. | ||||||
1922 | using CheckedTemporaries = | ||||||
1923 | llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; | ||||||
1924 | |||||||
1925 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, | ||||||
1926 | EvalInfo &Info, SourceLocation DiagLoc, | ||||||
1927 | QualType Type, const APValue &Value, | ||||||
1928 | Expr::ConstExprUsage Usage, | ||||||
1929 | SourceLocation SubobjectLoc, | ||||||
1930 | CheckedTemporaries &CheckedTemps); | ||||||
1931 | |||||||
1932 | /// Check that this reference or pointer core constant expression is a valid | ||||||
1933 | /// value for an address or reference constant expression. Return true if we | ||||||
1934 | /// can fold this expression, whether or not it's a constant expression. | ||||||
1935 | static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, | ||||||
1936 | QualType Type, const LValue &LVal, | ||||||
1937 | Expr::ConstExprUsage Usage, | ||||||
1938 | CheckedTemporaries &CheckedTemps) { | ||||||
1939 | bool IsReferenceType = Type->isReferenceType(); | ||||||
1940 | |||||||
1941 | APValue::LValueBase Base = LVal.getLValueBase(); | ||||||
1942 | const SubobjectDesignator &Designator = LVal.getLValueDesignator(); | ||||||
1943 | |||||||
1944 | // Check that the object is a global. Note that the fake 'this' object we | ||||||
1945 | // manufacture when checking potential constant expressions is conservatively | ||||||
1946 | // assumed to be global here. | ||||||
1947 | if (!IsGlobalLValue(Base)) { | ||||||
1948 | if (Info.getLangOpts().CPlusPlus11) { | ||||||
1949 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | ||||||
1950 | Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) | ||||||
1951 | << IsReferenceType << !Designator.Entries.empty() | ||||||
1952 | << !!VD << VD; | ||||||
1953 | NoteLValueLocation(Info, Base); | ||||||
1954 | } else { | ||||||
1955 | Info.FFDiag(Loc); | ||||||
1956 | } | ||||||
1957 | // Don't allow references to temporaries to escape. | ||||||
1958 | return false; | ||||||
1959 | } | ||||||
1960 | assert((Info.checkingPotentialConstantExpression() ||(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex () == 0) && "have call index for global lvalue") ? static_cast <void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1962, __PRETTY_FUNCTION__)) | ||||||
1961 | LVal.getLValueCallIndex() == 0) &&(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex () == 0) && "have call index for global lvalue") ? static_cast <void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1962, __PRETTY_FUNCTION__)) | ||||||
1962 | "have call index for global lvalue")(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex () == 0) && "have call index for global lvalue") ? static_cast <void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1962, __PRETTY_FUNCTION__)); | ||||||
1963 | |||||||
1964 | if (Base.is<DynamicAllocLValue>()) { | ||||||
1965 | Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) | ||||||
1966 | << IsReferenceType << !Designator.Entries.empty(); | ||||||
1967 | NoteLValueLocation(Info, Base); | ||||||
1968 | return false; | ||||||
1969 | } | ||||||
1970 | |||||||
1971 | if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { | ||||||
1972 | if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { | ||||||
1973 | // Check if this is a thread-local variable. | ||||||
1974 | if (Var->getTLSKind()) | ||||||
1975 | // FIXME: Diagnostic! | ||||||
1976 | return false; | ||||||
1977 | |||||||
1978 | // A dllimport variable never acts like a constant. | ||||||
1979 | if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) | ||||||
1980 | // FIXME: Diagnostic! | ||||||
1981 | return false; | ||||||
1982 | } | ||||||
1983 | if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { | ||||||
1984 | // __declspec(dllimport) must be handled very carefully: | ||||||
1985 | // We must never initialize an expression with the thunk in C++. | ||||||
1986 | // Doing otherwise would allow the same id-expression to yield | ||||||
1987 | // different addresses for the same function in different translation | ||||||
1988 | // units. However, this means that we must dynamically initialize the | ||||||
1989 | // expression with the contents of the import address table at runtime. | ||||||
1990 | // | ||||||
1991 | // The C language has no notion of ODR; furthermore, it has no notion of | ||||||
1992 | // dynamic initialization. This means that we are permitted to | ||||||
1993 | // perform initialization with the address of the thunk. | ||||||
1994 | if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && | ||||||
1995 | FD->hasAttr<DLLImportAttr>()) | ||||||
1996 | // FIXME: Diagnostic! | ||||||
1997 | return false; | ||||||
1998 | } | ||||||
1999 | } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( | ||||||
2000 | Base.dyn_cast<const Expr *>())) { | ||||||
2001 | if (CheckedTemps.insert(MTE).second) { | ||||||
2002 | QualType TempType = getType(Base); | ||||||
2003 | if (TempType.isDestructedType()) { | ||||||
2004 | Info.FFDiag(MTE->getExprLoc(), | ||||||
2005 | diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) | ||||||
2006 | << TempType; | ||||||
2007 | return false; | ||||||
2008 | } | ||||||
2009 | |||||||
2010 | APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false); | ||||||
2011 | assert(V && "evasluation result refers to uninitialised temporary")((V && "evasluation result refers to uninitialised temporary" ) ? static_cast<void> (0) : __assert_fail ("V && \"evasluation result refers to uninitialised temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2011, __PRETTY_FUNCTION__)); | ||||||
2012 | if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, | ||||||
2013 | Info, MTE->getExprLoc(), TempType, *V, | ||||||
2014 | Usage, SourceLocation(), CheckedTemps)) | ||||||
2015 | return false; | ||||||
2016 | } | ||||||
2017 | } | ||||||
2018 | |||||||
2019 | // Allow address constant expressions to be past-the-end pointers. This is | ||||||
2020 | // an extension: the standard requires them to point to an object. | ||||||
2021 | if (!IsReferenceType) | ||||||
2022 | return true; | ||||||
2023 | |||||||
2024 | // A reference constant expression must refer to an object. | ||||||
2025 | if (!Base) { | ||||||
2026 | // FIXME: diagnostic | ||||||
2027 | Info.CCEDiag(Loc); | ||||||
2028 | return true; | ||||||
2029 | } | ||||||
2030 | |||||||
2031 | // Does this refer one past the end of some object? | ||||||
2032 | if (!Designator.Invalid && Designator.isOnePastTheEnd()) { | ||||||
2033 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | ||||||
2034 | Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) | ||||||
2035 | << !Designator.Entries.empty() << !!VD << VD; | ||||||
2036 | NoteLValueLocation(Info, Base); | ||||||
2037 | } | ||||||
2038 | |||||||
2039 | return true; | ||||||
2040 | } | ||||||
2041 | |||||||
2042 | /// Member pointers are constant expressions unless they point to a | ||||||
2043 | /// non-virtual dllimport member function. | ||||||
2044 | static bool CheckMemberPointerConstantExpression(EvalInfo &Info, | ||||||
2045 | SourceLocation Loc, | ||||||
2046 | QualType Type, | ||||||
2047 | const APValue &Value, | ||||||
2048 | Expr::ConstExprUsage Usage) { | ||||||
2049 | const ValueDecl *Member = Value.getMemberPointerDecl(); | ||||||
2050 | const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); | ||||||
2051 | if (!FD) | ||||||
2052 | return true; | ||||||
2053 | return Usage == Expr::EvaluateForMangling || FD->isVirtual() || | ||||||
2054 | !FD->hasAttr<DLLImportAttr>(); | ||||||
2055 | } | ||||||
2056 | |||||||
2057 | /// Check that this core constant expression is of literal type, and if not, | ||||||
2058 | /// produce an appropriate diagnostic. | ||||||
2059 | static bool CheckLiteralType(EvalInfo &Info, const Expr *E, | ||||||
2060 | const LValue *This = nullptr) { | ||||||
2061 | if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) | ||||||
2062 | return true; | ||||||
2063 | |||||||
2064 | // C++1y: A constant initializer for an object o [...] may also invoke | ||||||
2065 | // constexpr constructors for o and its subobjects even if those objects | ||||||
2066 | // are of non-literal class types. | ||||||
2067 | // | ||||||
2068 | // C++11 missed this detail for aggregates, so classes like this: | ||||||
2069 | // struct foo_t { union { int i; volatile int j; } u; }; | ||||||
2070 | // are not (obviously) initializable like so: | ||||||
2071 | // __attribute__((__require_constant_initialization__)) | ||||||
2072 | // static const foo_t x = {{0}}; | ||||||
2073 | // because "i" is a subobject with non-literal initialization (due to the | ||||||
2074 | // volatile member of the union). See: | ||||||
2075 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 | ||||||
2076 | // Therefore, we use the C++1y behavior. | ||||||
2077 | if (This && Info.EvaluatingDecl == This->getLValueBase()) | ||||||
2078 | return true; | ||||||
2079 | |||||||
2080 | // Prvalue constant expressions must be of literal types. | ||||||
2081 | if (Info.getLangOpts().CPlusPlus11) | ||||||
2082 | Info.FFDiag(E, diag::note_constexpr_nonliteral) | ||||||
2083 | << E->getType(); | ||||||
2084 | else | ||||||
2085 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
2086 | return false; | ||||||
2087 | } | ||||||
2088 | |||||||
2089 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, | ||||||
2090 | EvalInfo &Info, SourceLocation DiagLoc, | ||||||
2091 | QualType Type, const APValue &Value, | ||||||
2092 | Expr::ConstExprUsage Usage, | ||||||
2093 | SourceLocation SubobjectLoc, | ||||||
2094 | CheckedTemporaries &CheckedTemps) { | ||||||
2095 | if (!Value.hasValue()) { | ||||||
2096 | Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) | ||||||
2097 | << true << Type; | ||||||
2098 | if (SubobjectLoc.isValid()) | ||||||
2099 | Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); | ||||||
2100 | return false; | ||||||
2101 | } | ||||||
2102 | |||||||
2103 | // We allow _Atomic(T) to be initialized from anything that T can be | ||||||
2104 | // initialized from. | ||||||
2105 | if (const AtomicType *AT = Type->getAs<AtomicType>()) | ||||||
2106 | Type = AT->getValueType(); | ||||||
2107 | |||||||
2108 | // Core issue 1454: For a literal constant expression of array or class type, | ||||||
2109 | // each subobject of its value shall have been initialized by a constant | ||||||
2110 | // expression. | ||||||
2111 | if (Value.isArray()) { | ||||||
2112 | QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); | ||||||
2113 | for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { | ||||||
2114 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, | ||||||
2115 | Value.getArrayInitializedElt(I), Usage, | ||||||
2116 | SubobjectLoc, CheckedTemps)) | ||||||
2117 | return false; | ||||||
2118 | } | ||||||
2119 | if (!Value.hasArrayFiller()) | ||||||
2120 | return true; | ||||||
2121 | return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, | ||||||
2122 | Value.getArrayFiller(), Usage, SubobjectLoc, | ||||||
2123 | CheckedTemps); | ||||||
2124 | } | ||||||
2125 | if (Value.isUnion() && Value.getUnionField()) { | ||||||
2126 | return CheckEvaluationResult( | ||||||
2127 | CERK, Info, DiagLoc, Value.getUnionField()->getType(), | ||||||
2128 | Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), | ||||||
2129 | CheckedTemps); | ||||||
2130 | } | ||||||
2131 | if (Value.isStruct()) { | ||||||
2132 | RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); | ||||||
2133 | if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { | ||||||
2134 | unsigned BaseIndex = 0; | ||||||
2135 | for (const CXXBaseSpecifier &BS : CD->bases()) { | ||||||
2136 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), | ||||||
2137 | Value.getStructBase(BaseIndex), Usage, | ||||||
2138 | BS.getBeginLoc(), CheckedTemps)) | ||||||
2139 | return false; | ||||||
2140 | ++BaseIndex; | ||||||
2141 | } | ||||||
2142 | } | ||||||
2143 | for (const auto *I : RD->fields()) { | ||||||
2144 | if (I->isUnnamedBitfield()) | ||||||
2145 | continue; | ||||||
2146 | |||||||
2147 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), | ||||||
2148 | Value.getStructField(I->getFieldIndex()), | ||||||
2149 | Usage, I->getLocation(), CheckedTemps)) | ||||||
2150 | return false; | ||||||
2151 | } | ||||||
2152 | } | ||||||
2153 | |||||||
2154 | if (Value.isLValue() && | ||||||
2155 | CERK == CheckEvaluationResultKind::ConstantExpression) { | ||||||
2156 | LValue LVal; | ||||||
2157 | LVal.setFrom(Info.Ctx, Value); | ||||||
2158 | return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, | ||||||
2159 | CheckedTemps); | ||||||
2160 | } | ||||||
2161 | |||||||
2162 | if (Value.isMemberPointer() && | ||||||
2163 | CERK == CheckEvaluationResultKind::ConstantExpression) | ||||||
2164 | return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); | ||||||
2165 | |||||||
2166 | // Everything else is fine. | ||||||
2167 | return true; | ||||||
2168 | } | ||||||
2169 | |||||||
2170 | /// Check that this core constant expression value is a valid value for a | ||||||
2171 | /// constant expression. If not, report an appropriate diagnostic. Does not | ||||||
2172 | /// check that the expression is of literal type. | ||||||
2173 | static bool | ||||||
2174 | CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, | ||||||
2175 | const APValue &Value, | ||||||
2176 | Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { | ||||||
2177 | CheckedTemporaries CheckedTemps; | ||||||
2178 | return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, | ||||||
2179 | Info, DiagLoc, Type, Value, Usage, | ||||||
2180 | SourceLocation(), CheckedTemps); | ||||||
2181 | } | ||||||
2182 | |||||||
2183 | /// Check that this evaluated value is fully-initialized and can be loaded by | ||||||
2184 | /// an lvalue-to-rvalue conversion. | ||||||
2185 | static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, | ||||||
2186 | QualType Type, const APValue &Value) { | ||||||
2187 | CheckedTemporaries CheckedTemps; | ||||||
2188 | return CheckEvaluationResult( | ||||||
2189 | CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, | ||||||
2190 | Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); | ||||||
2191 | } | ||||||
2192 | |||||||
2193 | /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless | ||||||
2194 | /// "the allocated storage is deallocated within the evaluation". | ||||||
2195 | static bool CheckMemoryLeaks(EvalInfo &Info) { | ||||||
2196 | if (!Info.HeapAllocs.empty()) { | ||||||
2197 | // We can still fold to a constant despite a compile-time memory leak, | ||||||
2198 | // so long as the heap allocation isn't referenced in the result (we check | ||||||
2199 | // that in CheckConstantExpression). | ||||||
2200 | Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, | ||||||
2201 | diag::note_constexpr_memory_leak) | ||||||
2202 | << unsigned(Info.HeapAllocs.size() - 1); | ||||||
2203 | } | ||||||
2204 | return true; | ||||||
2205 | } | ||||||
2206 | |||||||
2207 | static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { | ||||||
2208 | // A null base expression indicates a null pointer. These are always | ||||||
2209 | // evaluatable, and they are false unless the offset is zero. | ||||||
2210 | if (!Value.getLValueBase()) { | ||||||
2211 | Result = !Value.getLValueOffset().isZero(); | ||||||
2212 | return true; | ||||||
2213 | } | ||||||
2214 | |||||||
2215 | // We have a non-null base. These are generally known to be true, but if it's | ||||||
2216 | // a weak declaration it can be null at runtime. | ||||||
2217 | Result = true; | ||||||
2218 | const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); | ||||||
2219 | return !Decl || !Decl->isWeak(); | ||||||
2220 | } | ||||||
2221 | |||||||
2222 | static bool HandleConversionToBool(const APValue &Val, bool &Result) { | ||||||
2223 | switch (Val.getKind()) { | ||||||
2224 | case APValue::None: | ||||||
2225 | case APValue::Indeterminate: | ||||||
2226 | return false; | ||||||
2227 | case APValue::Int: | ||||||
2228 | Result = Val.getInt().getBoolValue(); | ||||||
2229 | return true; | ||||||
2230 | case APValue::FixedPoint: | ||||||
2231 | Result = Val.getFixedPoint().getBoolValue(); | ||||||
2232 | return true; | ||||||
2233 | case APValue::Float: | ||||||
2234 | Result = !Val.getFloat().isZero(); | ||||||
2235 | return true; | ||||||
2236 | case APValue::ComplexInt: | ||||||
2237 | Result = Val.getComplexIntReal().getBoolValue() || | ||||||
2238 | Val.getComplexIntImag().getBoolValue(); | ||||||
2239 | return true; | ||||||
2240 | case APValue::ComplexFloat: | ||||||
2241 | Result = !Val.getComplexFloatReal().isZero() || | ||||||
2242 | !Val.getComplexFloatImag().isZero(); | ||||||
2243 | return true; | ||||||
2244 | case APValue::LValue: | ||||||
2245 | return EvalPointerValueAsBool(Val, Result); | ||||||
2246 | case APValue::MemberPointer: | ||||||
2247 | Result = Val.getMemberPointerDecl(); | ||||||
2248 | return true; | ||||||
2249 | case APValue::Vector: | ||||||
2250 | case APValue::Array: | ||||||
2251 | case APValue::Struct: | ||||||
2252 | case APValue::Union: | ||||||
2253 | case APValue::AddrLabelDiff: | ||||||
2254 | return false; | ||||||
2255 | } | ||||||
2256 | |||||||
2257 | llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2257); | ||||||
2258 | } | ||||||
2259 | |||||||
2260 | static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, | ||||||
2261 | EvalInfo &Info) { | ||||||
2262 | assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition")((E->isRValue() && "missing lvalue-to-rvalue conv in bool condition" ) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && \"missing lvalue-to-rvalue conv in bool condition\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2262, __PRETTY_FUNCTION__)); | ||||||
2263 | APValue Val; | ||||||
2264 | if (!Evaluate(Val, Info, E)) | ||||||
2265 | return false; | ||||||
2266 | return HandleConversionToBool(Val, Result); | ||||||
2267 | } | ||||||
2268 | |||||||
2269 | template<typename T> | ||||||
2270 | static bool HandleOverflow(EvalInfo &Info, const Expr *E, | ||||||
2271 | const T &SrcValue, QualType DestType) { | ||||||
2272 | Info.CCEDiag(E, diag::note_constexpr_overflow) | ||||||
2273 | << SrcValue << DestType; | ||||||
2274 | return Info.noteUndefinedBehavior(); | ||||||
2275 | } | ||||||
2276 | |||||||
2277 | static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, | ||||||
2278 | QualType SrcType, const APFloat &Value, | ||||||
2279 | QualType DestType, APSInt &Result) { | ||||||
2280 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); | ||||||
2281 | // Determine whether we are converting to unsigned or signed. | ||||||
2282 | bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); | ||||||
2283 | |||||||
2284 | Result = APSInt(DestWidth, !DestSigned); | ||||||
2285 | bool ignored; | ||||||
2286 | if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) | ||||||
2287 | & APFloat::opInvalidOp) | ||||||
2288 | return HandleOverflow(Info, E, Value, DestType); | ||||||
2289 | return true; | ||||||
2290 | } | ||||||
2291 | |||||||
2292 | static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, | ||||||
2293 | QualType SrcType, QualType DestType, | ||||||
2294 | APFloat &Result) { | ||||||
2295 | APFloat Value = Result; | ||||||
2296 | bool ignored; | ||||||
2297 | Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), | ||||||
2298 | APFloat::rmNearestTiesToEven, &ignored); | ||||||
2299 | return true; | ||||||
2300 | } | ||||||
2301 | |||||||
2302 | static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, | ||||||
2303 | QualType DestType, QualType SrcType, | ||||||
2304 | const APSInt &Value) { | ||||||
2305 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); | ||||||
2306 | // Figure out if this is a truncate, extend or noop cast. | ||||||
2307 | // If the input is signed, do a sign extend, noop, or truncate. | ||||||
2308 | APSInt Result = Value.extOrTrunc(DestWidth); | ||||||
2309 | Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); | ||||||
2310 | if (DestType->isBooleanType()) | ||||||
2311 | Result = Value.getBoolValue(); | ||||||
2312 | return Result; | ||||||
2313 | } | ||||||
2314 | |||||||
2315 | static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, | ||||||
2316 | QualType SrcType, const APSInt &Value, | ||||||
2317 | QualType DestType, APFloat &Result) { | ||||||
2318 | Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); | ||||||
2319 | Result.convertFromAPInt(Value, Value.isSigned(), | ||||||
2320 | APFloat::rmNearestTiesToEven); | ||||||
2321 | return true; | ||||||
2322 | } | ||||||
2323 | |||||||
2324 | static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, | ||||||
2325 | APValue &Value, const FieldDecl *FD) { | ||||||
2326 | assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")((FD->isBitField() && "truncateBitfieldValue on non-bitfield" ) ? static_cast<void> (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2326, __PRETTY_FUNCTION__)); | ||||||
2327 | |||||||
2328 | if (!Value.isInt()) { | ||||||
2329 | // Trying to store a pointer-cast-to-integer into a bitfield. | ||||||
2330 | // FIXME: In this case, we should provide the diagnostic for casting | ||||||
2331 | // a pointer to an integer. | ||||||
2332 | assert(Value.isLValue() && "integral value neither int nor lvalue?")((Value.isLValue() && "integral value neither int nor lvalue?" ) ? static_cast<void> (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2332, __PRETTY_FUNCTION__)); | ||||||
2333 | Info.FFDiag(E); | ||||||
2334 | return false; | ||||||
2335 | } | ||||||
2336 | |||||||
2337 | APSInt &Int = Value.getInt(); | ||||||
2338 | unsigned OldBitWidth = Int.getBitWidth(); | ||||||
2339 | unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); | ||||||
2340 | if (NewBitWidth < OldBitWidth) | ||||||
2341 | Int = Int.trunc(NewBitWidth).extend(OldBitWidth); | ||||||
2342 | return true; | ||||||
2343 | } | ||||||
2344 | |||||||
2345 | static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, | ||||||
2346 | llvm::APInt &Res) { | ||||||
2347 | APValue SVal; | ||||||
2348 | if (!Evaluate(SVal, Info, E)) | ||||||
2349 | return false; | ||||||
2350 | if (SVal.isInt()) { | ||||||
2351 | Res = SVal.getInt(); | ||||||
2352 | return true; | ||||||
2353 | } | ||||||
2354 | if (SVal.isFloat()) { | ||||||
2355 | Res = SVal.getFloat().bitcastToAPInt(); | ||||||
2356 | return true; | ||||||
2357 | } | ||||||
2358 | if (SVal.isVector()) { | ||||||
2359 | QualType VecTy = E->getType(); | ||||||
2360 | unsigned VecSize = Info.Ctx.getTypeSize(VecTy); | ||||||
2361 | QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); | ||||||
2362 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); | ||||||
2363 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); | ||||||
2364 | Res = llvm::APInt::getNullValue(VecSize); | ||||||
2365 | for (unsigned i = 0; i < SVal.getVectorLength(); i++) { | ||||||
2366 | APValue &Elt = SVal.getVectorElt(i); | ||||||
2367 | llvm::APInt EltAsInt; | ||||||
2368 | if (Elt.isInt()) { | ||||||
2369 | EltAsInt = Elt.getInt(); | ||||||
2370 | } else if (Elt.isFloat()) { | ||||||
2371 | EltAsInt = Elt.getFloat().bitcastToAPInt(); | ||||||
2372 | } else { | ||||||
2373 | // Don't try to handle vectors of anything other than int or float | ||||||
2374 | // (not sure if it's possible to hit this case). | ||||||
2375 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
2376 | return false; | ||||||
2377 | } | ||||||
2378 | unsigned BaseEltSize = EltAsInt.getBitWidth(); | ||||||
2379 | if (BigEndian) | ||||||
2380 | Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); | ||||||
2381 | else | ||||||
2382 | Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); | ||||||
2383 | } | ||||||
2384 | return true; | ||||||
2385 | } | ||||||
2386 | // Give up if the input isn't an int, float, or vector. For example, we | ||||||
2387 | // reject "(v4i16)(intptr_t)&a". | ||||||
2388 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
2389 | return false; | ||||||
2390 | } | ||||||
2391 | |||||||
2392 | /// Perform the given integer operation, which is known to need at most BitWidth | ||||||
2393 | /// bits, and check for overflow in the original type (if that type was not an | ||||||
2394 | /// unsigned type). | ||||||
2395 | template<typename Operation> | ||||||
2396 | static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, | ||||||
2397 | const APSInt &LHS, const APSInt &RHS, | ||||||
2398 | unsigned BitWidth, Operation Op, | ||||||
2399 | APSInt &Result) { | ||||||
2400 | if (LHS.isUnsigned()) { | ||||||
2401 | Result = Op(LHS, RHS); | ||||||
2402 | return true; | ||||||
2403 | } | ||||||
2404 | |||||||
2405 | APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); | ||||||
2406 | Result = Value.trunc(LHS.getBitWidth()); | ||||||
2407 | if (Result.extend(BitWidth) != Value) { | ||||||
2408 | if (Info.checkingForUndefinedBehavior()) | ||||||
2409 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | ||||||
2410 | diag::warn_integer_constant_overflow) | ||||||
2411 | << Result.toString(10) << E->getType(); | ||||||
2412 | else | ||||||
2413 | return HandleOverflow(Info, E, Value, E->getType()); | ||||||
2414 | } | ||||||
2415 | return true; | ||||||
2416 | } | ||||||
2417 | |||||||
2418 | /// Perform the given binary integer operation. | ||||||
2419 | static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, | ||||||
2420 | BinaryOperatorKind Opcode, APSInt RHS, | ||||||
2421 | APSInt &Result) { | ||||||
2422 | switch (Opcode) { | ||||||
2423 | default: | ||||||
2424 | Info.FFDiag(E); | ||||||
2425 | return false; | ||||||
2426 | case BO_Mul: | ||||||
2427 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, | ||||||
2428 | std::multiplies<APSInt>(), Result); | ||||||
2429 | case BO_Add: | ||||||
2430 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, | ||||||
2431 | std::plus<APSInt>(), Result); | ||||||
2432 | case BO_Sub: | ||||||
2433 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, | ||||||
2434 | std::minus<APSInt>(), Result); | ||||||
2435 | case BO_And: Result = LHS & RHS; return true; | ||||||
2436 | case BO_Xor: Result = LHS ^ RHS; return true; | ||||||
2437 | case BO_Or: Result = LHS | RHS; return true; | ||||||
2438 | case BO_Div: | ||||||
2439 | case BO_Rem: | ||||||
2440 | if (RHS == 0) { | ||||||
2441 | Info.FFDiag(E, diag::note_expr_divide_by_zero); | ||||||
2442 | return false; | ||||||
2443 | } | ||||||
2444 | Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); | ||||||
2445 | // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports | ||||||
2446 | // this operation and gives the two's complement result. | ||||||
2447 | if (RHS.isNegative() && RHS.isAllOnesValue() && | ||||||
2448 | LHS.isSigned() && LHS.isMinSignedValue()) | ||||||
2449 | return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), | ||||||
2450 | E->getType()); | ||||||
2451 | return true; | ||||||
2452 | case BO_Shl: { | ||||||
2453 | if (Info.getLangOpts().OpenCL) | ||||||
2454 | // OpenCL 6.3j: shift values are effectively % word size of LHS. | ||||||
2455 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), | ||||||
2456 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), | ||||||
2457 | RHS.isUnsigned()); | ||||||
2458 | else if (RHS.isSigned() && RHS.isNegative()) { | ||||||
2459 | // During constant-folding, a negative shift is an opposite shift. Such | ||||||
2460 | // a shift is not a constant expression. | ||||||
2461 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; | ||||||
2462 | RHS = -RHS; | ||||||
2463 | goto shift_right; | ||||||
2464 | } | ||||||
2465 | shift_left: | ||||||
2466 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of | ||||||
2467 | // the shifted type. | ||||||
2468 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); | ||||||
2469 | if (SA != RHS) { | ||||||
2470 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | ||||||
2471 | << RHS << E->getType() << LHS.getBitWidth(); | ||||||
2472 | } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) { | ||||||
2473 | // C++11 [expr.shift]p2: A signed left shift must have a non-negative | ||||||
2474 | // operand, and must not overflow the corresponding unsigned type. | ||||||
2475 | // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to | ||||||
2476 | // E1 x 2^E2 module 2^N. | ||||||
2477 | if (LHS.isNegative()) | ||||||
2478 | Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; | ||||||
2479 | else if (LHS.countLeadingZeros() < SA) | ||||||
2480 | Info.CCEDiag(E, diag::note_constexpr_lshift_discards); | ||||||
2481 | } | ||||||
2482 | Result = LHS << SA; | ||||||
2483 | return true; | ||||||
2484 | } | ||||||
2485 | case BO_Shr: { | ||||||
2486 | if (Info.getLangOpts().OpenCL) | ||||||
2487 | // OpenCL 6.3j: shift values are effectively % word size of LHS. | ||||||
2488 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), | ||||||
2489 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), | ||||||
2490 | RHS.isUnsigned()); | ||||||
2491 | else if (RHS.isSigned() && RHS.isNegative()) { | ||||||
2492 | // During constant-folding, a negative shift is an opposite shift. Such a | ||||||
2493 | // shift is not a constant expression. | ||||||
2494 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; | ||||||
2495 | RHS = -RHS; | ||||||
2496 | goto shift_left; | ||||||
2497 | } | ||||||
2498 | shift_right: | ||||||
2499 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of the | ||||||
2500 | // shifted type. | ||||||
2501 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); | ||||||
2502 | if (SA != RHS) | ||||||
2503 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | ||||||
2504 | << RHS << E->getType() << LHS.getBitWidth(); | ||||||
2505 | Result = LHS >> SA; | ||||||
2506 | return true; | ||||||
2507 | } | ||||||
2508 | |||||||
2509 | case BO_LT: Result = LHS < RHS; return true; | ||||||
2510 | case BO_GT: Result = LHS > RHS; return true; | ||||||
2511 | case BO_LE: Result = LHS <= RHS; return true; | ||||||
2512 | case BO_GE: Result = LHS >= RHS; return true; | ||||||
2513 | case BO_EQ: Result = LHS == RHS; return true; | ||||||
2514 | case BO_NE: Result = LHS != RHS; return true; | ||||||
2515 | case BO_Cmp: | ||||||
2516 | llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2516); | ||||||
2517 | } | ||||||
2518 | } | ||||||
2519 | |||||||
2520 | /// Perform the given binary floating-point operation, in-place, on LHS. | ||||||
2521 | static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, | ||||||
2522 | APFloat &LHS, BinaryOperatorKind Opcode, | ||||||
2523 | const APFloat &RHS) { | ||||||
2524 | switch (Opcode) { | ||||||
2525 | default: | ||||||
2526 | Info.FFDiag(E); | ||||||
2527 | return false; | ||||||
2528 | case BO_Mul: | ||||||
2529 | LHS.multiply(RHS, APFloat::rmNearestTiesToEven); | ||||||
2530 | break; | ||||||
2531 | case BO_Add: | ||||||
2532 | LHS.add(RHS, APFloat::rmNearestTiesToEven); | ||||||
2533 | break; | ||||||
2534 | case BO_Sub: | ||||||
2535 | LHS.subtract(RHS, APFloat::rmNearestTiesToEven); | ||||||
2536 | break; | ||||||
2537 | case BO_Div: | ||||||
2538 | // [expr.mul]p4: | ||||||
2539 | // If the second operand of / or % is zero the behavior is undefined. | ||||||
2540 | if (RHS.isZero()) | ||||||
2541 | Info.CCEDiag(E, diag::note_expr_divide_by_zero); | ||||||
2542 | LHS.divide(RHS, APFloat::rmNearestTiesToEven); | ||||||
2543 | break; | ||||||
2544 | } | ||||||
2545 | |||||||
2546 | // [expr.pre]p4: | ||||||
2547 | // If during the evaluation of an expression, the result is not | ||||||
2548 | // mathematically defined [...], the behavior is undefined. | ||||||
2549 | // FIXME: C++ rules require us to not conform to IEEE 754 here. | ||||||
2550 | if (LHS.isNaN()) { | ||||||
2551 | Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); | ||||||
2552 | return Info.noteUndefinedBehavior(); | ||||||
2553 | } | ||||||
2554 | return true; | ||||||
2555 | } | ||||||
2556 | |||||||
2557 | /// Cast an lvalue referring to a base subobject to a derived class, by | ||||||
2558 | /// truncating the lvalue's path to the given length. | ||||||
2559 | static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, | ||||||
2560 | const RecordDecl *TruncatedType, | ||||||
2561 | unsigned TruncatedElements) { | ||||||
2562 | SubobjectDesignator &D = Result.Designator; | ||||||
2563 | |||||||
2564 | // Check we actually point to a derived class object. | ||||||
2565 | if (TruncatedElements == D.Entries.size()) | ||||||
2566 | return true; | ||||||
2567 | assert(TruncatedElements >= D.MostDerivedPathLength &&((TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class" ) ? static_cast<void> (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2568, __PRETTY_FUNCTION__)) | ||||||
2568 | "not casting to a derived class")((TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class" ) ? static_cast<void> (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2568, __PRETTY_FUNCTION__)); | ||||||
2569 | if (!Result.checkSubobject(Info, E, CSK_Derived)) | ||||||
2570 | return false; | ||||||
2571 | |||||||
2572 | // Truncate the path to the subobject, and remove any derived-to-base offsets. | ||||||
2573 | const RecordDecl *RD = TruncatedType; | ||||||
2574 | for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { | ||||||
2575 | if (RD->isInvalidDecl()) return false; | ||||||
2576 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||||
2577 | const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); | ||||||
2578 | if (isVirtualBaseClass(D.Entries[I])) | ||||||
2579 | Result.Offset -= Layout.getVBaseClassOffset(Base); | ||||||
2580 | else | ||||||
2581 | Result.Offset -= Layout.getBaseClassOffset(Base); | ||||||
2582 | RD = Base; | ||||||
2583 | } | ||||||
2584 | D.Entries.resize(TruncatedElements); | ||||||
2585 | return true; | ||||||
2586 | } | ||||||
2587 | |||||||
2588 | static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, | ||||||
2589 | const CXXRecordDecl *Derived, | ||||||
2590 | const CXXRecordDecl *Base, | ||||||
2591 | const ASTRecordLayout *RL = nullptr) { | ||||||
2592 | if (!RL) { | ||||||
2593 | if (Derived->isInvalidDecl()) return false; | ||||||
2594 | RL = &Info.Ctx.getASTRecordLayout(Derived); | ||||||
2595 | } | ||||||
2596 | |||||||
2597 | Obj.getLValueOffset() += RL->getBaseClassOffset(Base); | ||||||
2598 | Obj.addDecl(Info, E, Base, /*Virtual*/ false); | ||||||
2599 | return true; | ||||||
2600 | } | ||||||
2601 | |||||||
2602 | static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, | ||||||
2603 | const CXXRecordDecl *DerivedDecl, | ||||||
2604 | const CXXBaseSpecifier *Base) { | ||||||
2605 | const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); | ||||||
2606 | |||||||
2607 | if (!Base->isVirtual()) | ||||||
2608 | return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); | ||||||
2609 | |||||||
2610 | SubobjectDesignator &D = Obj.Designator; | ||||||
2611 | if (D.Invalid) | ||||||
2612 | return false; | ||||||
2613 | |||||||
2614 | // Extract most-derived object and corresponding type. | ||||||
2615 | DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); | ||||||
2616 | if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) | ||||||
2617 | return false; | ||||||
2618 | |||||||
2619 | // Find the virtual base class. | ||||||
2620 | if (DerivedDecl->isInvalidDecl()) return false; | ||||||
2621 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); | ||||||
2622 | Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); | ||||||
2623 | Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); | ||||||
2624 | return true; | ||||||
2625 | } | ||||||
2626 | |||||||
2627 | static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, | ||||||
2628 | QualType Type, LValue &Result) { | ||||||
2629 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||||
2630 | PathE = E->path_end(); | ||||||
2631 | PathI != PathE; ++PathI) { | ||||||
2632 | if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), | ||||||
2633 | *PathI)) | ||||||
2634 | return false; | ||||||
2635 | Type = (*PathI)->getType(); | ||||||
2636 | } | ||||||
2637 | return true; | ||||||
2638 | } | ||||||
2639 | |||||||
2640 | /// Cast an lvalue referring to a derived class to a known base subobject. | ||||||
2641 | static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, | ||||||
2642 | const CXXRecordDecl *DerivedRD, | ||||||
2643 | const CXXRecordDecl *BaseRD) { | ||||||
2644 | CXXBasePaths Paths(/*FindAmbiguities=*/false, | ||||||
2645 | /*RecordPaths=*/true, /*DetectVirtual=*/false); | ||||||
2646 | if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) | ||||||
2647 | 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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2647); | ||||||
2648 | |||||||
2649 | for (CXXBasePathElement &Elem : Paths.front()) | ||||||
2650 | if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) | ||||||
2651 | return false; | ||||||
2652 | return true; | ||||||
2653 | } | ||||||
2654 | |||||||
2655 | /// Update LVal to refer to the given field, which must be a member of the type | ||||||
2656 | /// currently described by LVal. | ||||||
2657 | static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, | ||||||
2658 | const FieldDecl *FD, | ||||||
2659 | const ASTRecordLayout *RL = nullptr) { | ||||||
2660 | if (!RL) { | ||||||
2661 | if (FD->getParent()->isInvalidDecl()) return false; | ||||||
2662 | RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); | ||||||
2663 | } | ||||||
2664 | |||||||
2665 | unsigned I = FD->getFieldIndex(); | ||||||
2666 | LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); | ||||||
2667 | LVal.addDecl(Info, E, FD); | ||||||
2668 | return true; | ||||||
2669 | } | ||||||
2670 | |||||||
2671 | /// Update LVal to refer to the given indirect field. | ||||||
2672 | static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, | ||||||
2673 | LValue &LVal, | ||||||
2674 | const IndirectFieldDecl *IFD) { | ||||||
2675 | for (const auto *C : IFD->chain()) | ||||||
2676 | if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) | ||||||
2677 | return false; | ||||||
2678 | return true; | ||||||
2679 | } | ||||||
2680 | |||||||
2681 | /// Get the size of the given type in char units. | ||||||
2682 | static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, | ||||||
2683 | QualType Type, CharUnits &Size) { | ||||||
2684 | // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc | ||||||
2685 | // extension. | ||||||
2686 | if (Type->isVoidType() || Type->isFunctionType()) { | ||||||
2687 | Size = CharUnits::One(); | ||||||
2688 | return true; | ||||||
2689 | } | ||||||
2690 | |||||||
2691 | if (Type->isDependentType()) { | ||||||
2692 | Info.FFDiag(Loc); | ||||||
2693 | return false; | ||||||
2694 | } | ||||||
2695 | |||||||
2696 | if (!Type->isConstantSizeType()) { | ||||||
2697 | // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. | ||||||
2698 | // FIXME: Better diagnostic. | ||||||
2699 | Info.FFDiag(Loc); | ||||||
2700 | return false; | ||||||
2701 | } | ||||||
2702 | |||||||
2703 | Size = Info.Ctx.getTypeSizeInChars(Type); | ||||||
2704 | return true; | ||||||
2705 | } | ||||||
2706 | |||||||
2707 | /// Update a pointer value to model pointer arithmetic. | ||||||
2708 | /// \param Info - Information about the ongoing evaluation. | ||||||
2709 | /// \param E - The expression being evaluated, for diagnostic purposes. | ||||||
2710 | /// \param LVal - The pointer value to be updated. | ||||||
2711 | /// \param EltTy - The pointee type represented by LVal. | ||||||
2712 | /// \param Adjustment - The adjustment, in objects of type EltTy, to add. | ||||||
2713 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, | ||||||
2714 | LValue &LVal, QualType EltTy, | ||||||
2715 | APSInt Adjustment) { | ||||||
2716 | CharUnits SizeOfPointee; | ||||||
2717 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) | ||||||
2718 | return false; | ||||||
2719 | |||||||
2720 | LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); | ||||||
2721 | return true; | ||||||
2722 | } | ||||||
2723 | |||||||
2724 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, | ||||||
2725 | LValue &LVal, QualType EltTy, | ||||||
2726 | int64_t Adjustment) { | ||||||
2727 | return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, | ||||||
2728 | APSInt::get(Adjustment)); | ||||||
2729 | } | ||||||
2730 | |||||||
2731 | /// Update an lvalue to refer to a component of a complex number. | ||||||
2732 | /// \param Info - Information about the ongoing evaluation. | ||||||
2733 | /// \param LVal - The lvalue to be updated. | ||||||
2734 | /// \param EltTy - The complex number's component type. | ||||||
2735 | /// \param Imag - False for the real component, true for the imaginary. | ||||||
2736 | static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, | ||||||
2737 | LValue &LVal, QualType EltTy, | ||||||
2738 | bool Imag) { | ||||||
2739 | if (Imag) { | ||||||
2740 | CharUnits SizeOfComponent; | ||||||
2741 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) | ||||||
2742 | return false; | ||||||
2743 | LVal.Offset += SizeOfComponent; | ||||||
2744 | } | ||||||
2745 | LVal.addComplex(Info, E, EltTy, Imag); | ||||||
2746 | return true; | ||||||
2747 | } | ||||||
2748 | |||||||
2749 | /// Try to evaluate the initializer for a variable declaration. | ||||||
2750 | /// | ||||||
2751 | /// \param Info Information about the ongoing evaluation. | ||||||
2752 | /// \param E An expression to be used when printing diagnostics. | ||||||
2753 | /// \param VD The variable whose initializer should be obtained. | ||||||
2754 | /// \param Frame The frame in which the variable was created. Must be null | ||||||
2755 | /// if this variable is not local to the evaluation. | ||||||
2756 | /// \param Result Filled in with a pointer to the value of the variable. | ||||||
2757 | static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, | ||||||
2758 | const VarDecl *VD, CallStackFrame *Frame, | ||||||
2759 | APValue *&Result, const LValue *LVal) { | ||||||
2760 | |||||||
2761 | // If this is a parameter to an active constexpr function call, perform | ||||||
2762 | // argument substitution. | ||||||
2763 | if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { | ||||||
2764 | // Assume arguments of a potential constant expression are unknown | ||||||
2765 | // constant expressions. | ||||||
2766 | if (Info.checkingPotentialConstantExpression()) | ||||||
2767 | return false; | ||||||
2768 | if (!Frame || !Frame->Arguments) { | ||||||
2769 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
2770 | return false; | ||||||
2771 | } | ||||||
2772 | Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; | ||||||
2773 | return true; | ||||||
2774 | } | ||||||
2775 | |||||||
2776 | // If this is a local variable, dig out its value. | ||||||
2777 | if (Frame) { | ||||||
2778 | Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) | ||||||
2779 | : Frame->getCurrentTemporary(VD); | ||||||
2780 | if (!Result) { | ||||||
2781 | // Assume variables referenced within a lambda's call operator that were | ||||||
2782 | // not declared within the call operator are captures and during checking | ||||||
2783 | // of a potential constant expression, assume they are unknown constant | ||||||
2784 | // expressions. | ||||||
2785 | assert(isLambdaCallOperator(Frame->Callee) &&((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext () != Frame->Callee || VD->isInitCapture()) && "missing value for local variable" ) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2787, __PRETTY_FUNCTION__)) | ||||||
2786 | (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext () != Frame->Callee || VD->isInitCapture()) && "missing value for local variable" ) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2787, __PRETTY_FUNCTION__)) | ||||||
2787 | "missing value for local variable")((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext () != Frame->Callee || VD->isInitCapture()) && "missing value for local variable" ) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2787, __PRETTY_FUNCTION__)); | ||||||
2788 | if (Info.checkingPotentialConstantExpression()) | ||||||
2789 | return false; | ||||||
2790 | // FIXME: implement capture evaluation during constant expr evaluation. | ||||||
2791 | Info.FFDiag(E->getBeginLoc(), | ||||||
2792 | diag::note_unimplemented_constexpr_lambda_feature_ast) | ||||||
2793 | << "captures not currently allowed"; | ||||||
2794 | return false; | ||||||
2795 | } | ||||||
2796 | return true; | ||||||
2797 | } | ||||||
2798 | |||||||
2799 | // Dig out the initializer, and use the declaration which it's attached to. | ||||||
2800 | const Expr *Init = VD->getAnyInitializer(VD); | ||||||
2801 | if (!Init || Init->isValueDependent()) { | ||||||
2802 | // If we're checking a potential constant expression, the variable could be | ||||||
2803 | // initialized later. | ||||||
2804 | if (!Info.checkingPotentialConstantExpression()) | ||||||
2805 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
2806 | return false; | ||||||
2807 | } | ||||||
2808 | |||||||
2809 | // If we're currently evaluating the initializer of this declaration, use that | ||||||
2810 | // in-flight value. | ||||||
2811 | if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { | ||||||
2812 | Result = Info.EvaluatingDeclValue; | ||||||
2813 | return true; | ||||||
2814 | } | ||||||
2815 | |||||||
2816 | // Never evaluate the initializer of a weak variable. We can't be sure that | ||||||
2817 | // this is the definition which will be used. | ||||||
2818 | if (VD->isWeak()) { | ||||||
2819 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
2820 | return false; | ||||||
2821 | } | ||||||
2822 | |||||||
2823 | // Check that we can fold the initializer. In C++, we will have already done | ||||||
2824 | // this in the cases where it matters for conformance. | ||||||
2825 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||
2826 | if (!VD->evaluateValue(Notes)) { | ||||||
2827 | Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, | ||||||
2828 | Notes.size() + 1) << VD; | ||||||
2829 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||||
2830 | Info.addNotes(Notes); | ||||||
2831 | return false; | ||||||
2832 | } else if (!VD->checkInitIsICE()) { | ||||||
2833 | Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, | ||||||
2834 | Notes.size() + 1) << VD; | ||||||
2835 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||||
2836 | Info.addNotes(Notes); | ||||||
2837 | } | ||||||
2838 | |||||||
2839 | Result = VD->getEvaluatedValue(); | ||||||
2840 | return true; | ||||||
2841 | } | ||||||
2842 | |||||||
2843 | static bool IsConstNonVolatile(QualType T) { | ||||||
2844 | Qualifiers Quals = T.getQualifiers(); | ||||||
2845 | return Quals.hasConst() && !Quals.hasVolatile(); | ||||||
2846 | } | ||||||
2847 | |||||||
2848 | /// Get the base index of the given base class within an APValue representing | ||||||
2849 | /// the given derived class. | ||||||
2850 | static unsigned getBaseIndex(const CXXRecordDecl *Derived, | ||||||
2851 | const CXXRecordDecl *Base) { | ||||||
2852 | Base = Base->getCanonicalDecl(); | ||||||
2853 | unsigned Index = 0; | ||||||
2854 | for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), | ||||||
2855 | E = Derived->bases_end(); I != E; ++I, ++Index) { | ||||||
2856 | if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) | ||||||
2857 | return Index; | ||||||
2858 | } | ||||||
2859 | |||||||
2860 | 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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2860); | ||||||
2861 | } | ||||||
2862 | |||||||
2863 | /// Extract the value of a character from a string literal. | ||||||
2864 | static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, | ||||||
2865 | uint64_t Index) { | ||||||
2866 | assert(!isa<SourceLocExpr>(Lit) &&((!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? static_cast<void> (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2867, __PRETTY_FUNCTION__)) | ||||||
2867 | "SourceLocExpr should have already been converted to a StringLiteral")((!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? static_cast<void> (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2867, __PRETTY_FUNCTION__)); | ||||||
2868 | |||||||
2869 | // FIXME: Support MakeStringConstant | ||||||
2870 | if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { | ||||||
2871 | std::string Str; | ||||||
2872 | Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); | ||||||
2873 | assert(Index <= Str.size() && "Index too large")((Index <= Str.size() && "Index too large") ? static_cast <void> (0) : __assert_fail ("Index <= Str.size() && \"Index too large\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2873, __PRETTY_FUNCTION__)); | ||||||
2874 | return APSInt::getUnsigned(Str.c_str()[Index]); | ||||||
2875 | } | ||||||
2876 | |||||||
2877 | if (auto PE = dyn_cast<PredefinedExpr>(Lit)) | ||||||
2878 | Lit = PE->getFunctionName(); | ||||||
2879 | const StringLiteral *S = cast<StringLiteral>(Lit); | ||||||
2880 | const ConstantArrayType *CAT = | ||||||
2881 | Info.Ctx.getAsConstantArrayType(S->getType()); | ||||||
2882 | assert(CAT && "string literal isn't an array")((CAT && "string literal isn't an array") ? static_cast <void> (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2882, __PRETTY_FUNCTION__)); | ||||||
2883 | QualType CharType = CAT->getElementType(); | ||||||
2884 | assert(CharType->isIntegerType() && "unexpected character type")((CharType->isIntegerType() && "unexpected character type" ) ? static_cast<void> (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2884, __PRETTY_FUNCTION__)); | ||||||
2885 | |||||||
2886 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), | ||||||
2887 | CharType->isUnsignedIntegerType()); | ||||||
2888 | if (Index < S->getLength()) | ||||||
2889 | Value = S->getCodeUnit(Index); | ||||||
2890 | return Value; | ||||||
2891 | } | ||||||
2892 | |||||||
2893 | // Expand a string literal into an array of characters. | ||||||
2894 | // | ||||||
2895 | // FIXME: This is inefficient; we should probably introduce something similar | ||||||
2896 | // to the LLVM ConstantDataArray to make this cheaper. | ||||||
2897 | static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, | ||||||
2898 | APValue &Result, | ||||||
2899 | QualType AllocType = QualType()) { | ||||||
2900 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( | ||||||
2901 | AllocType.isNull() ? S->getType() : AllocType); | ||||||
2902 | assert(CAT && "string literal isn't an array")((CAT && "string literal isn't an array") ? static_cast <void> (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2902, __PRETTY_FUNCTION__)); | ||||||
2903 | QualType CharType = CAT->getElementType(); | ||||||
2904 | assert(CharType->isIntegerType() && "unexpected character type")((CharType->isIntegerType() && "unexpected character type" ) ? static_cast<void> (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2904, __PRETTY_FUNCTION__)); | ||||||
2905 | |||||||
2906 | unsigned Elts = CAT->getSize().getZExtValue(); | ||||||
2907 | Result = APValue(APValue::UninitArray(), | ||||||
2908 | std::min(S->getLength(), Elts), Elts); | ||||||
2909 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), | ||||||
2910 | CharType->isUnsignedIntegerType()); | ||||||
2911 | if (Result.hasArrayFiller()) | ||||||
2912 | Result.getArrayFiller() = APValue(Value); | ||||||
2913 | for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { | ||||||
2914 | Value = S->getCodeUnit(I); | ||||||
2915 | Result.getArrayInitializedElt(I) = APValue(Value); | ||||||
2916 | } | ||||||
2917 | } | ||||||
2918 | |||||||
2919 | // Expand an array so that it has more than Index filled elements. | ||||||
2920 | static void expandArray(APValue &Array, unsigned Index) { | ||||||
2921 | unsigned Size = Array.getArraySize(); | ||||||
2922 | assert(Index < Size)((Index < Size) ? static_cast<void> (0) : __assert_fail ("Index < Size", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2922, __PRETTY_FUNCTION__)); | ||||||
2923 | |||||||
2924 | // Always at least double the number of elements for which we store a value. | ||||||
2925 | unsigned OldElts = Array.getArrayInitializedElts(); | ||||||
2926 | unsigned NewElts = std::max(Index+1, OldElts * 2); | ||||||
2927 | NewElts = std::min(Size, std::max(NewElts, 8u)); | ||||||
2928 | |||||||
2929 | // Copy the data across. | ||||||
2930 | APValue NewValue(APValue::UninitArray(), NewElts, Size); | ||||||
2931 | for (unsigned I = 0; I != OldElts; ++I) | ||||||
2932 | NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); | ||||||
2933 | for (unsigned I = OldElts; I != NewElts; ++I) | ||||||
2934 | NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); | ||||||
2935 | if (NewValue.hasArrayFiller()) | ||||||
2936 | NewValue.getArrayFiller() = Array.getArrayFiller(); | ||||||
2937 | Array.swap(NewValue); | ||||||
2938 | } | ||||||
2939 | |||||||
2940 | /// Determine whether a type would actually be read by an lvalue-to-rvalue | ||||||
2941 | /// conversion. If it's of class type, we may assume that the copy operation | ||||||
2942 | /// is trivial. Note that this is never true for a union type with fields | ||||||
2943 | /// (because the copy always "reads" the active member) and always true for | ||||||
2944 | /// a non-class type. | ||||||
2945 | static bool isReadByLvalueToRvalueConversion(QualType T) { | ||||||
2946 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||||
2947 | if (!RD || (RD->isUnion() && !RD->field_empty())) | ||||||
2948 | return true; | ||||||
2949 | if (RD->isEmpty()) | ||||||
2950 | return false; | ||||||
2951 | |||||||
2952 | for (auto *Field : RD->fields()) | ||||||
2953 | if (isReadByLvalueToRvalueConversion(Field->getType())) | ||||||
2954 | return true; | ||||||
2955 | |||||||
2956 | for (auto &BaseSpec : RD->bases()) | ||||||
2957 | if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) | ||||||
2958 | return true; | ||||||
2959 | |||||||
2960 | return false; | ||||||
2961 | } | ||||||
2962 | |||||||
2963 | /// Diagnose an attempt to read from any unreadable field within the specified | ||||||
2964 | /// type, which might be a class type. | ||||||
2965 | static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, | ||||||
2966 | QualType T) { | ||||||
2967 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||||
2968 | if (!RD) | ||||||
2969 | return false; | ||||||
2970 | |||||||
2971 | if (!RD->hasMutableFields()) | ||||||
2972 | return false; | ||||||
2973 | |||||||
2974 | for (auto *Field : RD->fields()) { | ||||||
2975 | // If we're actually going to read this field in some way, then it can't | ||||||
2976 | // be mutable. If we're in a union, then assigning to a mutable field | ||||||
2977 | // (even an empty one) can change the active member, so that's not OK. | ||||||
2978 | // FIXME: Add core issue number for the union case. | ||||||
2979 | if (Field->isMutable() && | ||||||
2980 | (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { | ||||||
2981 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; | ||||||
2982 | Info.Note(Field->getLocation(), diag::note_declared_at); | ||||||
2983 | return true; | ||||||
2984 | } | ||||||
2985 | |||||||
2986 | if (diagnoseMutableFields(Info, E, AK, Field->getType())) | ||||||
2987 | return true; | ||||||
2988 | } | ||||||
2989 | |||||||
2990 | for (auto &BaseSpec : RD->bases()) | ||||||
2991 | if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) | ||||||
2992 | return true; | ||||||
2993 | |||||||
2994 | // All mutable fields were empty, and thus not actually read. | ||||||
2995 | return false; | ||||||
2996 | } | ||||||
2997 | |||||||
2998 | static bool lifetimeStartedInEvaluation(EvalInfo &Info, | ||||||
2999 | APValue::LValueBase Base, | ||||||
3000 | bool MutableSubobject = false) { | ||||||
3001 | // A temporary we created. | ||||||
3002 | if (Base.getCallIndex()) | ||||||
3003 | return true; | ||||||
3004 | |||||||
3005 | auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); | ||||||
3006 | if (!Evaluating) | ||||||
3007 | return false; | ||||||
3008 | |||||||
3009 | auto *BaseD = Base.dyn_cast<const ValueDecl*>(); | ||||||
3010 | |||||||
3011 | switch (Info.IsEvaluatingDecl) { | ||||||
3012 | case EvalInfo::EvaluatingDeclKind::None: | ||||||
3013 | return false; | ||||||
3014 | |||||||
3015 | case EvalInfo::EvaluatingDeclKind::Ctor: | ||||||
3016 | // The variable whose initializer we're evaluating. | ||||||
3017 | if (BaseD) | ||||||
3018 | return declaresSameEntity(Evaluating, BaseD); | ||||||
3019 | |||||||
3020 | // A temporary lifetime-extended by the variable whose initializer we're | ||||||
3021 | // evaluating. | ||||||
3022 | if (auto *BaseE = Base.dyn_cast<const Expr *>()) | ||||||
3023 | if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) | ||||||
3024 | return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); | ||||||
3025 | return false; | ||||||
3026 | |||||||
3027 | case EvalInfo::EvaluatingDeclKind::Dtor: | ||||||
3028 | // C++2a [expr.const]p6: | ||||||
3029 | // [during constant destruction] the lifetime of a and its non-mutable | ||||||
3030 | // subobjects (but not its mutable subobjects) [are] considered to start | ||||||
3031 | // within e. | ||||||
3032 | // | ||||||
3033 | // FIXME: We can meaningfully extend this to cover non-const objects, but | ||||||
3034 | // we will need special handling: we should be able to access only | ||||||
3035 | // subobjects of such objects that are themselves declared const. | ||||||
3036 | if (!BaseD || | ||||||
3037 | !(BaseD->getType().isConstQualified() || | ||||||
3038 | BaseD->getType()->isReferenceType()) || | ||||||
3039 | MutableSubobject) | ||||||
3040 | return false; | ||||||
3041 | return declaresSameEntity(Evaluating, BaseD); | ||||||
3042 | } | ||||||
3043 | |||||||
3044 | llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3044); | ||||||
3045 | } | ||||||
3046 | |||||||
3047 | namespace { | ||||||
3048 | /// A handle to a complete object (an object that is not a subobject of | ||||||
3049 | /// another object). | ||||||
3050 | struct CompleteObject { | ||||||
3051 | /// The identity of the object. | ||||||
3052 | APValue::LValueBase Base; | ||||||
3053 | /// The value of the complete object. | ||||||
3054 | APValue *Value; | ||||||
3055 | /// The type of the complete object. | ||||||
3056 | QualType Type; | ||||||
3057 | |||||||
3058 | CompleteObject() : Value(nullptr) {} | ||||||
3059 | CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) | ||||||
3060 | : Base(Base), Value(Value), Type(Type) {} | ||||||
3061 | |||||||
3062 | bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { | ||||||
3063 | // In C++14 onwards, it is permitted to read a mutable member whose | ||||||
3064 | // lifetime began within the evaluation. | ||||||
3065 | // FIXME: Should we also allow this in C++11? | ||||||
3066 | if (!Info.getLangOpts().CPlusPlus14) | ||||||
3067 | return false; | ||||||
3068 | return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); | ||||||
3069 | } | ||||||
3070 | |||||||
3071 | explicit operator bool() const { return !Type.isNull(); } | ||||||
3072 | }; | ||||||
3073 | } // end anonymous namespace | ||||||
3074 | |||||||
3075 | static QualType getSubobjectType(QualType ObjType, QualType SubobjType, | ||||||
3076 | bool IsMutable = false) { | ||||||
3077 | // C++ [basic.type.qualifier]p1: | ||||||
3078 | // - A const object is an object of type const T or a non-mutable subobject | ||||||
3079 | // of a const object. | ||||||
3080 | if (ObjType.isConstQualified() && !IsMutable) | ||||||
3081 | SubobjType.addConst(); | ||||||
3082 | // - A volatile object is an object of type const T or a subobject of a | ||||||
3083 | // volatile object. | ||||||
3084 | if (ObjType.isVolatileQualified()) | ||||||
3085 | SubobjType.addVolatile(); | ||||||
3086 | return SubobjType; | ||||||
3087 | } | ||||||
3088 | |||||||
3089 | /// Find the designated sub-object of an rvalue. | ||||||
3090 | template<typename SubobjectHandler> | ||||||
3091 | typename SubobjectHandler::result_type | ||||||
3092 | findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, | ||||||
3093 | const SubobjectDesignator &Sub, SubobjectHandler &handler) { | ||||||
3094 | if (Sub.Invalid) | ||||||
3095 | // A diagnostic will have already been produced. | ||||||
3096 | return handler.failed(); | ||||||
3097 | if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { | ||||||
3098 | if (Info.getLangOpts().CPlusPlus11) | ||||||
3099 | Info.FFDiag(E, Sub.isOnePastTheEnd() | ||||||
3100 | ? diag::note_constexpr_access_past_end | ||||||
3101 | : diag::note_constexpr_access_unsized_array) | ||||||
3102 | << handler.AccessKind; | ||||||
3103 | else | ||||||
3104 | Info.FFDiag(E); | ||||||
3105 | return handler.failed(); | ||||||
3106 | } | ||||||
3107 | |||||||
3108 | APValue *O = Obj.Value; | ||||||
3109 | QualType ObjType = Obj.Type; | ||||||
3110 | const FieldDecl *LastField = nullptr; | ||||||
3111 | const FieldDecl *VolatileField = nullptr; | ||||||
3112 | |||||||
3113 | // Walk the designator's path to find the subobject. | ||||||
3114 | for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { | ||||||
3115 | // Reading an indeterminate value is undefined, but assigning over one is OK. | ||||||
3116 | if (O->isAbsent() || | ||||||
3117 | (O->isIndeterminate() && handler.AccessKind != AK_Assign && | ||||||
3118 | handler.AccessKind != AK_ReadObjectRepresentation)) { | ||||||
3119 | if (!Info.checkingPotentialConstantExpression()) | ||||||
3120 | Info.FFDiag(E, diag::note_constexpr_access_uninit) | ||||||
3121 | << handler.AccessKind << O->isIndeterminate(); | ||||||
3122 | return handler.failed(); | ||||||
3123 | } | ||||||
3124 | |||||||
3125 | // C++ [class.ctor]p5, C++ [class.dtor]p5: | ||||||
3126 | // const and volatile semantics are not applied on an object under | ||||||
3127 | // {con,de}struction. | ||||||
3128 | if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && | ||||||
3129 | ObjType->isRecordType() && | ||||||
3130 | Info.isEvaluatingCtorDtor( | ||||||
3131 | Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), | ||||||
3132 | Sub.Entries.begin() + I)) != | ||||||
3133 | ConstructionPhase::None) { | ||||||
3134 | ObjType = Info.Ctx.getCanonicalType(ObjType); | ||||||
3135 | ObjType.removeLocalConst(); | ||||||
3136 | ObjType.removeLocalVolatile(); | ||||||
3137 | } | ||||||
3138 | |||||||
3139 | // If this is our last pass, check that the final object type is OK. | ||||||
3140 | if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { | ||||||
3141 | // Accesses to volatile objects are prohibited. | ||||||
3142 | if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { | ||||||
3143 | if (Info.getLangOpts().CPlusPlus) { | ||||||
3144 | int DiagKind; | ||||||
3145 | SourceLocation Loc; | ||||||
3146 | const NamedDecl *Decl = nullptr; | ||||||
3147 | if (VolatileField) { | ||||||
3148 | DiagKind = 2; | ||||||
3149 | Loc = VolatileField->getLocation(); | ||||||
3150 | Decl = VolatileField; | ||||||
3151 | } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { | ||||||
3152 | DiagKind = 1; | ||||||
3153 | Loc = VD->getLocation(); | ||||||
3154 | Decl = VD; | ||||||
3155 | } else { | ||||||
3156 | DiagKind = 0; | ||||||
3157 | if (auto *E = Obj.Base.dyn_cast<const Expr *>()) | ||||||
3158 | Loc = E->getExprLoc(); | ||||||
3159 | } | ||||||
3160 | Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) | ||||||
3161 | << handler.AccessKind << DiagKind << Decl; | ||||||
3162 | Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; | ||||||
3163 | } else { | ||||||
3164 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
3165 | } | ||||||
3166 | return handler.failed(); | ||||||
3167 | } | ||||||
3168 | |||||||
3169 | // If we are reading an object of class type, there may still be more | ||||||
3170 | // things we need to check: if there are any mutable subobjects, we | ||||||
3171 | // cannot perform this read. (This only happens when performing a trivial | ||||||
3172 | // copy or assignment.) | ||||||
3173 | if (ObjType->isRecordType() && | ||||||
3174 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && | ||||||
3175 | diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) | ||||||
3176 | return handler.failed(); | ||||||
3177 | } | ||||||
3178 | |||||||
3179 | if (I == N) { | ||||||
3180 | if (!handler.found(*O, ObjType)) | ||||||
3181 | return false; | ||||||
3182 | |||||||
3183 | // If we modified a bit-field, truncate it to the right width. | ||||||
3184 | if (isModification(handler.AccessKind) && | ||||||
3185 | LastField && LastField->isBitField() && | ||||||
3186 | !truncateBitfieldValue(Info, E, *O, LastField)) | ||||||
3187 | return false; | ||||||
3188 | |||||||
3189 | return true; | ||||||
3190 | } | ||||||
3191 | |||||||
3192 | LastField = nullptr; | ||||||
3193 | if (ObjType->isArrayType()) { | ||||||
3194 | // Next subobject is an array element. | ||||||
3195 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); | ||||||
3196 | assert(CAT && "vla in literal type?")((CAT && "vla in literal type?") ? static_cast<void > (0) : __assert_fail ("CAT && \"vla in literal type?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3196, __PRETTY_FUNCTION__)); | ||||||
3197 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); | ||||||
3198 | if (CAT->getSize().ule(Index)) { | ||||||
3199 | // Note, it should not be possible to form a pointer with a valid | ||||||
3200 | // designator which points more than one past the end of the array. | ||||||
3201 | if (Info.getLangOpts().CPlusPlus11) | ||||||
3202 | Info.FFDiag(E, diag::note_constexpr_access_past_end) | ||||||
3203 | << handler.AccessKind; | ||||||
3204 | else | ||||||
3205 | Info.FFDiag(E); | ||||||
3206 | return handler.failed(); | ||||||
3207 | } | ||||||
3208 | |||||||
3209 | ObjType = CAT->getElementType(); | ||||||
3210 | |||||||
3211 | if (O->getArrayInitializedElts() > Index) | ||||||
3212 | O = &O->getArrayInitializedElt(Index); | ||||||
3213 | else if (!isRead(handler.AccessKind)) { | ||||||
3214 | expandArray(*O, Index); | ||||||
3215 | O = &O->getArrayInitializedElt(Index); | ||||||
3216 | } else | ||||||
3217 | O = &O->getArrayFiller(); | ||||||
3218 | } else if (ObjType->isAnyComplexType()) { | ||||||
3219 | // Next subobject is a complex number. | ||||||
3220 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); | ||||||
3221 | if (Index > 1) { | ||||||
3222 | if (Info.getLangOpts().CPlusPlus11) | ||||||
3223 | Info.FFDiag(E, diag::note_constexpr_access_past_end) | ||||||
3224 | << handler.AccessKind; | ||||||
3225 | else | ||||||
3226 | Info.FFDiag(E); | ||||||
3227 | return handler.failed(); | ||||||
3228 | } | ||||||
3229 | |||||||
3230 | ObjType = getSubobjectType( | ||||||
3231 | ObjType, ObjType->castAs<ComplexType>()->getElementType()); | ||||||
3232 | |||||||
3233 | assert(I == N - 1 && "extracting subobject of scalar?")((I == N - 1 && "extracting subobject of scalar?") ? static_cast <void> (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3233, __PRETTY_FUNCTION__)); | ||||||
3234 | if (O->isComplexInt()) { | ||||||
3235 | return handler.found(Index ? O->getComplexIntImag() | ||||||
3236 | : O->getComplexIntReal(), ObjType); | ||||||
3237 | } else { | ||||||
3238 | assert(O->isComplexFloat())((O->isComplexFloat()) ? static_cast<void> (0) : __assert_fail ("O->isComplexFloat()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3238, __PRETTY_FUNCTION__)); | ||||||
3239 | return handler.found(Index ? O->getComplexFloatImag() | ||||||
3240 | : O->getComplexFloatReal(), ObjType); | ||||||
3241 | } | ||||||
3242 | } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { | ||||||
3243 | if (Field->isMutable() && | ||||||
3244 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { | ||||||
3245 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) | ||||||
3246 | << handler.AccessKind << Field; | ||||||
3247 | Info.Note(Field->getLocation(), diag::note_declared_at); | ||||||
3248 | return handler.failed(); | ||||||
3249 | } | ||||||
3250 | |||||||
3251 | // Next subobject is a class, struct or union field. | ||||||
3252 | RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); | ||||||
3253 | if (RD->isUnion()) { | ||||||
3254 | const FieldDecl *UnionField = O->getUnionField(); | ||||||
3255 | if (!UnionField || | ||||||
3256 | UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { | ||||||
3257 | // FIXME: If O->getUnionValue() is absent, report that there's no | ||||||
3258 | // active union member rather than reporting the prior active union | ||||||
3259 | // member. We'll need to fix nullptr_t to not use APValue() as its | ||||||
3260 | // representation first. | ||||||
3261 | Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) | ||||||
3262 | << handler.AccessKind << Field << !UnionField << UnionField; | ||||||
3263 | return handler.failed(); | ||||||
3264 | } | ||||||
3265 | O = &O->getUnionValue(); | ||||||
3266 | } else | ||||||
3267 | O = &O->getStructField(Field->getFieldIndex()); | ||||||
3268 | |||||||
3269 | ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); | ||||||
3270 | LastField = Field; | ||||||
3271 | if (Field->getType().isVolatileQualified()) | ||||||
3272 | VolatileField = Field; | ||||||
3273 | } else { | ||||||
3274 | // Next subobject is a base class. | ||||||
3275 | const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); | ||||||
3276 | const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); | ||||||
3277 | O = &O->getStructBase(getBaseIndex(Derived, Base)); | ||||||
3278 | |||||||
3279 | ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); | ||||||
3280 | } | ||||||
3281 | } | ||||||
3282 | } | ||||||
3283 | |||||||
3284 | namespace { | ||||||
3285 | struct ExtractSubobjectHandler { | ||||||
3286 | EvalInfo &Info; | ||||||
3287 | const Expr *E; | ||||||
3288 | APValue &Result; | ||||||
3289 | const AccessKinds AccessKind; | ||||||
3290 | |||||||
3291 | typedef bool result_type; | ||||||
3292 | bool failed() { return false; } | ||||||
3293 | bool found(APValue &Subobj, QualType SubobjType) { | ||||||
3294 | Result = Subobj; | ||||||
3295 | if (AccessKind == AK_ReadObjectRepresentation) | ||||||
3296 | return true; | ||||||
3297 | return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); | ||||||
3298 | } | ||||||
3299 | bool found(APSInt &Value, QualType SubobjType) { | ||||||
3300 | Result = APValue(Value); | ||||||
3301 | return true; | ||||||
3302 | } | ||||||
3303 | bool found(APFloat &Value, QualType SubobjType) { | ||||||
3304 | Result = APValue(Value); | ||||||
3305 | return true; | ||||||
3306 | } | ||||||
3307 | }; | ||||||
3308 | } // end anonymous namespace | ||||||
3309 | |||||||
3310 | /// Extract the designated sub-object of an rvalue. | ||||||
3311 | static bool extractSubobject(EvalInfo &Info, const Expr *E, | ||||||
3312 | const CompleteObject &Obj, | ||||||
3313 | const SubobjectDesignator &Sub, APValue &Result, | ||||||
3314 | AccessKinds AK = AK_Read) { | ||||||
3315 | assert(AK == AK_Read || AK == AK_ReadObjectRepresentation)((AK == AK_Read || AK == AK_ReadObjectRepresentation) ? static_cast <void> (0) : __assert_fail ("AK == AK_Read || AK == AK_ReadObjectRepresentation" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3315, __PRETTY_FUNCTION__)); | ||||||
3316 | ExtractSubobjectHandler Handler = {Info, E, Result, AK}; | ||||||
3317 | return findSubobject(Info, E, Obj, Sub, Handler); | ||||||
3318 | } | ||||||
3319 | |||||||
3320 | namespace { | ||||||
3321 | struct ModifySubobjectHandler { | ||||||
3322 | EvalInfo &Info; | ||||||
3323 | APValue &NewVal; | ||||||
3324 | const Expr *E; | ||||||
3325 | |||||||
3326 | typedef bool result_type; | ||||||
3327 | static const AccessKinds AccessKind = AK_Assign; | ||||||
3328 | |||||||
3329 | bool checkConst(QualType QT) { | ||||||
3330 | // Assigning to a const object has undefined behavior. | ||||||
3331 | if (QT.isConstQualified()) { | ||||||
3332 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||||
3333 | return false; | ||||||
3334 | } | ||||||
3335 | return true; | ||||||
3336 | } | ||||||
3337 | |||||||
3338 | bool failed() { return false; } | ||||||
3339 | bool found(APValue &Subobj, QualType SubobjType) { | ||||||
3340 | if (!checkConst(SubobjType)) | ||||||
3341 | return false; | ||||||
3342 | // We've been given ownership of NewVal, so just swap it in. | ||||||
3343 | Subobj.swap(NewVal); | ||||||
3344 | return true; | ||||||
3345 | } | ||||||
3346 | bool found(APSInt &Value, QualType SubobjType) { | ||||||
3347 | if (!checkConst(SubobjType)) | ||||||
3348 | return false; | ||||||
3349 | if (!NewVal.isInt()) { | ||||||
3350 | // Maybe trying to write a cast pointer value into a complex? | ||||||
3351 | Info.FFDiag(E); | ||||||
3352 | return false; | ||||||
3353 | } | ||||||
3354 | Value = NewVal.getInt(); | ||||||
3355 | return true; | ||||||
3356 | } | ||||||
3357 | bool found(APFloat &Value, QualType SubobjType) { | ||||||
3358 | if (!checkConst(SubobjType)) | ||||||
3359 | return false; | ||||||
3360 | Value = NewVal.getFloat(); | ||||||
3361 | return true; | ||||||
3362 | } | ||||||
3363 | }; | ||||||
3364 | } // end anonymous namespace | ||||||
3365 | |||||||
3366 | const AccessKinds ModifySubobjectHandler::AccessKind; | ||||||
3367 | |||||||
3368 | /// Update the designated sub-object of an rvalue to the given value. | ||||||
3369 | static bool modifySubobject(EvalInfo &Info, const Expr *E, | ||||||
3370 | const CompleteObject &Obj, | ||||||
3371 | const SubobjectDesignator &Sub, | ||||||
3372 | APValue &NewVal) { | ||||||
3373 | ModifySubobjectHandler Handler = { Info, NewVal, E }; | ||||||
3374 | return findSubobject(Info, E, Obj, Sub, Handler); | ||||||
3375 | } | ||||||
3376 | |||||||
3377 | /// Find the position where two subobject designators diverge, or equivalently | ||||||
3378 | /// the length of the common initial subsequence. | ||||||
3379 | static unsigned FindDesignatorMismatch(QualType ObjType, | ||||||
3380 | const SubobjectDesignator &A, | ||||||
3381 | const SubobjectDesignator &B, | ||||||
3382 | bool &WasArrayIndex) { | ||||||
3383 | unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); | ||||||
3384 | for (/**/; I != N; ++I) { | ||||||
3385 | if (!ObjType.isNull() && | ||||||
3386 | (ObjType->isArrayType() || ObjType->isAnyComplexType())) { | ||||||
3387 | // Next subobject is an array element. | ||||||
3388 | if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { | ||||||
3389 | WasArrayIndex = true; | ||||||
3390 | return I; | ||||||
3391 | } | ||||||
3392 | if (ObjType->isAnyComplexType()) | ||||||
3393 | ObjType = ObjType->castAs<ComplexType>()->getElementType(); | ||||||
3394 | else | ||||||
3395 | ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); | ||||||
3396 | } else { | ||||||
3397 | if (A.Entries[I].getAsBaseOrMember() != | ||||||
3398 | B.Entries[I].getAsBaseOrMember()) { | ||||||
3399 | WasArrayIndex = false; | ||||||
3400 | return I; | ||||||
3401 | } | ||||||
3402 | if (const FieldDecl *FD = getAsField(A.Entries[I])) | ||||||
3403 | // Next subobject is a field. | ||||||
3404 | ObjType = FD->getType(); | ||||||
3405 | else | ||||||
3406 | // Next subobject is a base class. | ||||||
3407 | ObjType = QualType(); | ||||||
3408 | } | ||||||
3409 | } | ||||||
3410 | WasArrayIndex = false; | ||||||
3411 | return I; | ||||||
3412 | } | ||||||
3413 | |||||||
3414 | /// Determine whether the given subobject designators refer to elements of the | ||||||
3415 | /// same array object. | ||||||
3416 | static bool AreElementsOfSameArray(QualType ObjType, | ||||||
3417 | const SubobjectDesignator &A, | ||||||
3418 | const SubobjectDesignator &B) { | ||||||
3419 | if (A.Entries.size() != B.Entries.size()) | ||||||
3420 | return false; | ||||||
3421 | |||||||
3422 | bool IsArray = A.MostDerivedIsArrayElement; | ||||||
3423 | if (IsArray && A.MostDerivedPathLength != A.Entries.size()) | ||||||
3424 | // A is a subobject of the array element. | ||||||
3425 | return false; | ||||||
3426 | |||||||
3427 | // If A (and B) designates an array element, the last entry will be the array | ||||||
3428 | // index. That doesn't have to match. Otherwise, we're in the 'implicit array | ||||||
3429 | // of length 1' case, and the entire path must match. | ||||||
3430 | bool WasArrayIndex; | ||||||
3431 | unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); | ||||||
3432 | return CommonLength >= A.Entries.size() - IsArray; | ||||||
3433 | } | ||||||
3434 | |||||||
3435 | /// Find the complete object to which an LValue refers. | ||||||
3436 | static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, | ||||||
3437 | AccessKinds AK, const LValue &LVal, | ||||||
3438 | QualType LValType) { | ||||||
3439 | if (LVal.InvalidBase) { | ||||||
3440 | Info.FFDiag(E); | ||||||
3441 | return CompleteObject(); | ||||||
3442 | } | ||||||
3443 | |||||||
3444 | if (!LVal.Base) { | ||||||
3445 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; | ||||||
3446 | return CompleteObject(); | ||||||
3447 | } | ||||||
3448 | |||||||
3449 | CallStackFrame *Frame = nullptr; | ||||||
3450 | unsigned Depth = 0; | ||||||
3451 | if (LVal.getLValueCallIndex()) { | ||||||
3452 | std::tie(Frame, Depth) = | ||||||
3453 | Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); | ||||||
3454 | if (!Frame) { | ||||||
3455 | Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) | ||||||
3456 | << AK << LVal.Base.is<const ValueDecl*>(); | ||||||
3457 | NoteLValueLocation(Info, LVal.Base); | ||||||
3458 | return CompleteObject(); | ||||||
3459 | } | ||||||
3460 | } | ||||||
3461 | |||||||
3462 | bool IsAccess = isAnyAccess(AK); | ||||||
3463 | |||||||
3464 | // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type | ||||||
3465 | // is not a constant expression (even if the object is non-volatile). We also | ||||||
3466 | // apply this rule to C++98, in order to conform to the expected 'volatile' | ||||||
3467 | // semantics. | ||||||
3468 | if (isFormalAccess(AK) && LValType.isVolatileQualified()) { | ||||||
3469 | if (Info.getLangOpts().CPlusPlus) | ||||||
3470 | Info.FFDiag(E, diag::note_constexpr_access_volatile_type) | ||||||
3471 | << AK << LValType; | ||||||
3472 | else | ||||||
3473 | Info.FFDiag(E); | ||||||
3474 | return CompleteObject(); | ||||||
3475 | } | ||||||
3476 | |||||||
3477 | // Compute value storage location and type of base object. | ||||||
3478 | APValue *BaseVal = nullptr; | ||||||
3479 | QualType BaseType = getType(LVal.Base); | ||||||
3480 | |||||||
3481 | if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { | ||||||
3482 | // In C++98, const, non-volatile integers initialized with ICEs are ICEs. | ||||||
3483 | // In C++11, constexpr, non-volatile variables initialized with constant | ||||||
3484 | // expressions are constant expressions too. Inside constexpr functions, | ||||||
3485 | // parameters are constant expressions even if they're non-const. | ||||||
3486 | // In C++1y, objects local to a constant expression (those with a Frame) are | ||||||
3487 | // both readable and writable inside constant expressions. | ||||||
3488 | // In C, such things can also be folded, although they are not ICEs. | ||||||
3489 | const VarDecl *VD = dyn_cast<VarDecl>(D); | ||||||
3490 | if (VD) { | ||||||
3491 | if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) | ||||||
3492 | VD = VDef; | ||||||
3493 | } | ||||||
3494 | if (!VD || VD->isInvalidDecl()) { | ||||||
3495 | Info.FFDiag(E); | ||||||
3496 | return CompleteObject(); | ||||||
3497 | } | ||||||
3498 | |||||||
3499 | // Unless we're looking at a local variable or argument in a constexpr call, | ||||||
3500 | // the variable we're reading must be const. | ||||||
3501 | if (!Frame) { | ||||||
3502 | if (Info.getLangOpts().CPlusPlus14 && | ||||||
3503 | lifetimeStartedInEvaluation(Info, LVal.Base)) { | ||||||
3504 | // OK, we can read and modify an object if we're in the process of | ||||||
3505 | // evaluating its initializer, because its lifetime began in this | ||||||
3506 | // evaluation. | ||||||
3507 | } else if (isModification(AK)) { | ||||||
3508 | // All the remaining cases do not permit modification of the object. | ||||||
3509 | Info.FFDiag(E, diag::note_constexpr_modify_global); | ||||||
3510 | return CompleteObject(); | ||||||
3511 | } else if (VD->isConstexpr()) { | ||||||
3512 | // OK, we can read this variable. | ||||||
3513 | } else if (BaseType->isIntegralOrEnumerationType()) { | ||||||
3514 | // In OpenCL if a variable is in constant address space it is a const | ||||||
3515 | // value. | ||||||
3516 | if (!(BaseType.isConstQualified() || | ||||||
3517 | (Info.getLangOpts().OpenCL && | ||||||
3518 | BaseType.getAddressSpace() == LangAS::opencl_constant))) { | ||||||
3519 | if (!IsAccess) | ||||||
3520 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||||
3521 | if (Info.getLangOpts().CPlusPlus) { | ||||||
3522 | Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; | ||||||
3523 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||||
3524 | } else { | ||||||
3525 | Info.FFDiag(E); | ||||||
3526 | } | ||||||
3527 | return CompleteObject(); | ||||||
3528 | } | ||||||
3529 | } else if (!IsAccess) { | ||||||
3530 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||||
3531 | } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { | ||||||
3532 | // We support folding of const floating-point types, in order to make | ||||||
3533 | // static const data members of such types (supported as an extension) | ||||||
3534 | // more useful. | ||||||
3535 | if (Info.getLangOpts().CPlusPlus11) { | ||||||
3536 | Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; | ||||||
3537 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||||
3538 | } else { | ||||||
3539 | Info.CCEDiag(E); | ||||||
3540 | } | ||||||
3541 | } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { | ||||||
3542 | Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; | ||||||
3543 | // Keep evaluating to see what we can do. | ||||||
3544 | } else { | ||||||
3545 | // FIXME: Allow folding of values of any literal type in all languages. | ||||||
3546 | if (Info.checkingPotentialConstantExpression() && | ||||||
3547 | VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { | ||||||
3548 | // The definition of this variable could be constexpr. We can't | ||||||
3549 | // access it right now, but may be able to in future. | ||||||
3550 | } else if (Info.getLangOpts().CPlusPlus11) { | ||||||
3551 | Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; | ||||||
3552 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||||
3553 | } else { | ||||||
3554 | Info.FFDiag(E); | ||||||
3555 | } | ||||||
3556 | return CompleteObject(); | ||||||
3557 | } | ||||||
3558 | } | ||||||
3559 | |||||||
3560 | if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) | ||||||
3561 | return CompleteObject(); | ||||||
3562 | } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { | ||||||
3563 | Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); | ||||||
3564 | if (!Alloc) { | ||||||
3565 | Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; | ||||||
3566 | return CompleteObject(); | ||||||
3567 | } | ||||||
3568 | return CompleteObject(LVal.Base, &(*Alloc)->Value, | ||||||
3569 | LVal.Base.getDynamicAllocType()); | ||||||
3570 | } else { | ||||||
3571 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); | ||||||
3572 | |||||||
3573 | if (!Frame) { | ||||||
3574 | if (const MaterializeTemporaryExpr *MTE = | ||||||
3575 | dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { | ||||||
3576 | assert(MTE->getStorageDuration() == SD_Static &&((MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? static_cast<void> (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3577, __PRETTY_FUNCTION__)) | ||||||
3577 | "should have a frame for a non-global materialized temporary")((MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? static_cast<void> (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3577, __PRETTY_FUNCTION__)); | ||||||
3578 | |||||||
3579 | // Per C++1y [expr.const]p2: | ||||||
3580 | // an lvalue-to-rvalue conversion [is not allowed unless it applies to] | ||||||
3581 | // - a [...] glvalue of integral or enumeration type that refers to | ||||||
3582 | // a non-volatile const object [...] | ||||||
3583 | // [...] | ||||||
3584 | // - a [...] glvalue of literal type that refers to a non-volatile | ||||||
3585 | // object whose lifetime began within the evaluation of e. | ||||||
3586 | // | ||||||
3587 | // C++11 misses the 'began within the evaluation of e' check and | ||||||
3588 | // instead allows all temporaries, including things like: | ||||||
3589 | // int &&r = 1; | ||||||
3590 | // int x = ++r; | ||||||
3591 | // constexpr int k = r; | ||||||
3592 | // Therefore we use the C++14 rules in C++11 too. | ||||||
3593 | // | ||||||
3594 | // Note that temporaries whose lifetimes began while evaluating a | ||||||
3595 | // variable's constructor are not usable while evaluating the | ||||||
3596 | // corresponding destructor, not even if they're of const-qualified | ||||||
3597 | // types. | ||||||
3598 | if (!(BaseType.isConstQualified() && | ||||||
3599 | BaseType->isIntegralOrEnumerationType()) && | ||||||
3600 | !lifetimeStartedInEvaluation(Info, LVal.Base)) { | ||||||
3601 | if (!IsAccess) | ||||||
3602 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||||
3603 | Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; | ||||||
3604 | Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); | ||||||
3605 | return CompleteObject(); | ||||||
3606 | } | ||||||
3607 | |||||||
3608 | BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); | ||||||
3609 | assert(BaseVal && "got reference to unevaluated temporary")((BaseVal && "got reference to unevaluated temporary" ) ? static_cast<void> (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3609, __PRETTY_FUNCTION__)); | ||||||
3610 | } else { | ||||||
3611 | if (!IsAccess) | ||||||
3612 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||||
3613 | APValue Val; | ||||||
3614 | LVal.moveInto(Val); | ||||||
3615 | Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) | ||||||
3616 | << AK | ||||||
3617 | << Val.getAsString(Info.Ctx, | ||||||
3618 | Info.Ctx.getLValueReferenceType(LValType)); | ||||||
3619 | NoteLValueLocation(Info, LVal.Base); | ||||||
3620 | return CompleteObject(); | ||||||
3621 | } | ||||||
3622 | } else { | ||||||
3623 | BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); | ||||||
3624 | assert(BaseVal && "missing value for temporary")((BaseVal && "missing value for temporary") ? static_cast <void> (0) : __assert_fail ("BaseVal && \"missing value for temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3624, __PRETTY_FUNCTION__)); | ||||||
3625 | } | ||||||
3626 | } | ||||||
3627 | |||||||
3628 | // In C++14, we can't safely access any mutable state when we might be | ||||||
3629 | // evaluating after an unmodeled side effect. | ||||||
3630 | // | ||||||
3631 | // FIXME: Not all local state is mutable. Allow local constant subobjects | ||||||
3632 | // to be read here (but take care with 'mutable' fields). | ||||||
3633 | if ((Frame && Info.getLangOpts().CPlusPlus14 && | ||||||
3634 | Info.EvalStatus.HasSideEffects) || | ||||||
3635 | (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) | ||||||
3636 | return CompleteObject(); | ||||||
3637 | |||||||
3638 | return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); | ||||||
3639 | } | ||||||
3640 | |||||||
3641 | /// Perform an lvalue-to-rvalue conversion on the given glvalue. This | ||||||
3642 | /// can also be used for 'lvalue-to-lvalue' conversions for looking up the | ||||||
3643 | /// glvalue referred to by an entity of reference type. | ||||||
3644 | /// | ||||||
3645 | /// \param Info - Information about the ongoing evaluation. | ||||||
3646 | /// \param Conv - The expression for which we are performing the conversion. | ||||||
3647 | /// Used for diagnostics. | ||||||
3648 | /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the | ||||||
3649 | /// case of a non-class type). | ||||||
3650 | /// \param LVal - The glvalue on which we are attempting to perform this action. | ||||||
3651 | /// \param RVal - The produced value will be placed here. | ||||||
3652 | /// \param WantObjectRepresentation - If true, we're looking for the object | ||||||
3653 | /// representation rather than the value, and in particular, | ||||||
3654 | /// there is no requirement that the result be fully initialized. | ||||||
3655 | static bool | ||||||
3656 | handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, | ||||||
3657 | const LValue &LVal, APValue &RVal, | ||||||
3658 | bool WantObjectRepresentation = false) { | ||||||
3659 | if (LVal.Designator.Invalid) | ||||||
3660 | return false; | ||||||
3661 | |||||||
3662 | // Check for special cases where there is no existing APValue to look at. | ||||||
3663 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); | ||||||
3664 | |||||||
3665 | AccessKinds AK = | ||||||
3666 | WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; | ||||||
3667 | |||||||
3668 | if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { | ||||||
3669 | if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { | ||||||
3670 | // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the | ||||||
3671 | // initializer until now for such expressions. Such an expression can't be | ||||||
3672 | // an ICE in C, so this only matters for fold. | ||||||
3673 | if (Type.isVolatileQualified()) { | ||||||
3674 | Info.FFDiag(Conv); | ||||||
3675 | return false; | ||||||
3676 | } | ||||||
3677 | APValue Lit; | ||||||
3678 | if (!Evaluate(Lit, Info, CLE->getInitializer())) | ||||||
3679 | return false; | ||||||
3680 | CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); | ||||||
3681 | return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); | ||||||
3682 | } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { | ||||||
3683 | // Special-case character extraction so we don't have to construct an | ||||||
3684 | // APValue for the whole string. | ||||||
3685 | assert(LVal.Designator.Entries.size() <= 1 &&((LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? static_cast<void> (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3686, __PRETTY_FUNCTION__)) | ||||||
3686 | "Can only read characters from string literals")((LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? static_cast<void> (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3686, __PRETTY_FUNCTION__)); | ||||||
3687 | if (LVal.Designator.Entries.empty()) { | ||||||
3688 | // Fail for now for LValue to RValue conversion of an array. | ||||||
3689 | // (This shouldn't show up in C/C++, but it could be triggered by a | ||||||
3690 | // weird EvaluateAsRValue call from a tool.) | ||||||
3691 | Info.FFDiag(Conv); | ||||||
3692 | return false; | ||||||
3693 | } | ||||||
3694 | if (LVal.Designator.isOnePastTheEnd()) { | ||||||
3695 | if (Info.getLangOpts().CPlusPlus11) | ||||||
3696 | Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; | ||||||
3697 | else | ||||||
3698 | Info.FFDiag(Conv); | ||||||
3699 | return false; | ||||||
3700 | } | ||||||
3701 | uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); | ||||||
3702 | RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); | ||||||
3703 | return true; | ||||||
3704 | } | ||||||
3705 | } | ||||||
3706 | |||||||
3707 | CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); | ||||||
3708 | return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); | ||||||
3709 | } | ||||||
3710 | |||||||
3711 | /// Perform an assignment of Val to LVal. Takes ownership of Val. | ||||||
3712 | static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, | ||||||
3713 | QualType LValType, APValue &Val) { | ||||||
3714 | if (LVal.Designator.Invalid) | ||||||
3715 | return false; | ||||||
3716 | |||||||
3717 | if (!Info.getLangOpts().CPlusPlus14) { | ||||||
3718 | Info.FFDiag(E); | ||||||
3719 | return false; | ||||||
3720 | } | ||||||
3721 | |||||||
3722 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); | ||||||
3723 | return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); | ||||||
3724 | } | ||||||
3725 | |||||||
3726 | namespace { | ||||||
3727 | struct CompoundAssignSubobjectHandler { | ||||||
3728 | EvalInfo &Info; | ||||||
3729 | const Expr *E; | ||||||
3730 | QualType PromotedLHSType; | ||||||
3731 | BinaryOperatorKind Opcode; | ||||||
3732 | const APValue &RHS; | ||||||
3733 | |||||||
3734 | static const AccessKinds AccessKind = AK_Assign; | ||||||
3735 | |||||||
3736 | typedef bool result_type; | ||||||
3737 | |||||||
3738 | bool checkConst(QualType QT) { | ||||||
3739 | // Assigning to a const object has undefined behavior. | ||||||
3740 | if (QT.isConstQualified()) { | ||||||
3741 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||||
3742 | return false; | ||||||
3743 | } | ||||||
3744 | return true; | ||||||
3745 | } | ||||||
3746 | |||||||
3747 | bool failed() { return false; } | ||||||
3748 | bool found(APValue &Subobj, QualType SubobjType) { | ||||||
3749 | switch (Subobj.getKind()) { | ||||||
3750 | case APValue::Int: | ||||||
3751 | return found(Subobj.getInt(), SubobjType); | ||||||
3752 | case APValue::Float: | ||||||
3753 | return found(Subobj.getFloat(), SubobjType); | ||||||
3754 | case APValue::ComplexInt: | ||||||
3755 | case APValue::ComplexFloat: | ||||||
3756 | // FIXME: Implement complex compound assignment. | ||||||
3757 | Info.FFDiag(E); | ||||||
3758 | return false; | ||||||
3759 | case APValue::LValue: | ||||||
3760 | return foundPointer(Subobj, SubobjType); | ||||||
3761 | default: | ||||||
3762 | // FIXME: can this happen? | ||||||
3763 | Info.FFDiag(E); | ||||||
3764 | return false; | ||||||
3765 | } | ||||||
3766 | } | ||||||
3767 | bool found(APSInt &Value, QualType SubobjType) { | ||||||
3768 | if (!checkConst(SubobjType)) | ||||||
3769 | return false; | ||||||
3770 | |||||||
3771 | if (!SubobjType->isIntegerType()) { | ||||||
3772 | // We don't support compound assignment on integer-cast-to-pointer | ||||||
3773 | // values. | ||||||
3774 | Info.FFDiag(E); | ||||||
3775 | return false; | ||||||
3776 | } | ||||||
3777 | |||||||
3778 | if (RHS.isInt()) { | ||||||
3779 | APSInt LHS = | ||||||
3780 | HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); | ||||||
3781 | if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) | ||||||
3782 | return false; | ||||||
3783 | Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); | ||||||
3784 | return true; | ||||||
3785 | } else if (RHS.isFloat()) { | ||||||
3786 | APFloat FValue(0.0); | ||||||
3787 | return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, | ||||||
3788 | FValue) && | ||||||
3789 | handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && | ||||||
3790 | HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, | ||||||
3791 | Value); | ||||||
3792 | } | ||||||
3793 | |||||||
3794 | Info.FFDiag(E); | ||||||
3795 | return false; | ||||||
3796 | } | ||||||
3797 | bool found(APFloat &Value, QualType SubobjType) { | ||||||
3798 | return checkConst(SubobjType) && | ||||||
3799 | HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, | ||||||
3800 | Value) && | ||||||
3801 | handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && | ||||||
3802 | HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); | ||||||
3803 | } | ||||||
3804 | bool foundPointer(APValue &Subobj, QualType SubobjType) { | ||||||
3805 | if (!checkConst(SubobjType)) | ||||||
3806 | return false; | ||||||
3807 | |||||||
3808 | QualType PointeeType; | ||||||
3809 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) | ||||||
3810 | PointeeType = PT->getPointeeType(); | ||||||
3811 | |||||||
3812 | if (PointeeType.isNull() || !RHS.isInt() || | ||||||
3813 | (Opcode != BO_Add && Opcode != BO_Sub)) { | ||||||
3814 | Info.FFDiag(E); | ||||||
3815 | return false; | ||||||
3816 | } | ||||||
3817 | |||||||
3818 | APSInt Offset = RHS.getInt(); | ||||||
3819 | if (Opcode == BO_Sub) | ||||||
3820 | negateAsSigned(Offset); | ||||||
3821 | |||||||
3822 | LValue LVal; | ||||||
3823 | LVal.setFrom(Info.Ctx, Subobj); | ||||||
3824 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) | ||||||
3825 | return false; | ||||||
3826 | LVal.moveInto(Subobj); | ||||||
3827 | return true; | ||||||
3828 | } | ||||||
3829 | }; | ||||||
3830 | } // end anonymous namespace | ||||||
3831 | |||||||
3832 | const AccessKinds CompoundAssignSubobjectHandler::AccessKind; | ||||||
3833 | |||||||
3834 | /// Perform a compound assignment of LVal <op>= RVal. | ||||||
3835 | static bool handleCompoundAssignment( | ||||||
3836 | EvalInfo &Info, const Expr *E, | ||||||
3837 | const LValue &LVal, QualType LValType, QualType PromotedLValType, | ||||||
3838 | BinaryOperatorKind Opcode, const APValue &RVal) { | ||||||
3839 | if (LVal.Designator.Invalid) | ||||||
3840 | return false; | ||||||
3841 | |||||||
3842 | if (!Info.getLangOpts().CPlusPlus14) { | ||||||
3843 | Info.FFDiag(E); | ||||||
3844 | return false; | ||||||
3845 | } | ||||||
3846 | |||||||
3847 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); | ||||||
3848 | CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, | ||||||
3849 | RVal }; | ||||||
3850 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); | ||||||
3851 | } | ||||||
3852 | |||||||
3853 | namespace { | ||||||
3854 | struct IncDecSubobjectHandler { | ||||||
3855 | EvalInfo &Info; | ||||||
3856 | const UnaryOperator *E; | ||||||
3857 | AccessKinds AccessKind; | ||||||
3858 | APValue *Old; | ||||||
3859 | |||||||
3860 | typedef bool result_type; | ||||||
3861 | |||||||
3862 | bool checkConst(QualType QT) { | ||||||
3863 | // Assigning to a const object has undefined behavior. | ||||||
3864 | if (QT.isConstQualified()) { | ||||||
3865 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||||
3866 | return false; | ||||||
3867 | } | ||||||
3868 | return true; | ||||||
3869 | } | ||||||
3870 | |||||||
3871 | bool failed() { return false; } | ||||||
3872 | bool found(APValue &Subobj, QualType SubobjType) { | ||||||
3873 | // Stash the old value. Also clear Old, so we don't clobber it later | ||||||
3874 | // if we're post-incrementing a complex. | ||||||
3875 | if (Old) { | ||||||
3876 | *Old = Subobj; | ||||||
3877 | Old = nullptr; | ||||||
3878 | } | ||||||
3879 | |||||||
3880 | switch (Subobj.getKind()) { | ||||||
3881 | case APValue::Int: | ||||||
3882 | return found(Subobj.getInt(), SubobjType); | ||||||
3883 | case APValue::Float: | ||||||
3884 | return found(Subobj.getFloat(), SubobjType); | ||||||
3885 | case APValue::ComplexInt: | ||||||
3886 | return found(Subobj.getComplexIntReal(), | ||||||
3887 | SubobjType->castAs<ComplexType>()->getElementType() | ||||||
3888 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); | ||||||
3889 | case APValue::ComplexFloat: | ||||||
3890 | return found(Subobj.getComplexFloatReal(), | ||||||
3891 | SubobjType->castAs<ComplexType>()->getElementType() | ||||||
3892 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); | ||||||
3893 | case APValue::LValue: | ||||||
3894 | return foundPointer(Subobj, SubobjType); | ||||||
3895 | default: | ||||||
3896 | // FIXME: can this happen? | ||||||
3897 | Info.FFDiag(E); | ||||||
3898 | return false; | ||||||
3899 | } | ||||||
3900 | } | ||||||
3901 | bool found(APSInt &Value, QualType SubobjType) { | ||||||
3902 | if (!checkConst(SubobjType)) | ||||||
3903 | return false; | ||||||
3904 | |||||||
3905 | if (!SubobjType->isIntegerType()) { | ||||||
3906 | // We don't support increment / decrement on integer-cast-to-pointer | ||||||
3907 | // values. | ||||||
3908 | Info.FFDiag(E); | ||||||
3909 | return false; | ||||||
3910 | } | ||||||
3911 | |||||||
3912 | if (Old) *Old = APValue(Value); | ||||||
3913 | |||||||
3914 | // bool arithmetic promotes to int, and the conversion back to bool | ||||||
3915 | // doesn't reduce mod 2^n, so special-case it. | ||||||
3916 | if (SubobjType->isBooleanType()) { | ||||||
3917 | if (AccessKind == AK_Increment) | ||||||
3918 | Value = 1; | ||||||
3919 | else | ||||||
3920 | Value = !Value; | ||||||
3921 | return true; | ||||||
3922 | } | ||||||
3923 | |||||||
3924 | bool WasNegative = Value.isNegative(); | ||||||
3925 | if (AccessKind == AK_Increment) { | ||||||
3926 | ++Value; | ||||||
3927 | |||||||
3928 | if (!WasNegative && Value.isNegative() && E->canOverflow()) { | ||||||
3929 | APSInt ActualValue(Value, /*IsUnsigned*/true); | ||||||
3930 | return HandleOverflow(Info, E, ActualValue, SubobjType); | ||||||
3931 | } | ||||||
3932 | } else { | ||||||
3933 | --Value; | ||||||
3934 | |||||||
3935 | if (WasNegative && !Value.isNegative() && E->canOverflow()) { | ||||||
3936 | unsigned BitWidth = Value.getBitWidth(); | ||||||
3937 | APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); | ||||||
3938 | ActualValue.setBit(BitWidth); | ||||||
3939 | return HandleOverflow(Info, E, ActualValue, SubobjType); | ||||||
3940 | } | ||||||
3941 | } | ||||||
3942 | return true; | ||||||
3943 | } | ||||||
3944 | bool found(APFloat &Value, QualType SubobjType) { | ||||||
3945 | if (!checkConst(SubobjType)) | ||||||
3946 | return false; | ||||||
3947 | |||||||
3948 | if (Old) *Old = APValue(Value); | ||||||
3949 | |||||||
3950 | APFloat One(Value.getSemantics(), 1); | ||||||
3951 | if (AccessKind == AK_Increment) | ||||||
3952 | Value.add(One, APFloat::rmNearestTiesToEven); | ||||||
3953 | else | ||||||
3954 | Value.subtract(One, APFloat::rmNearestTiesToEven); | ||||||
3955 | return true; | ||||||
3956 | } | ||||||
3957 | bool foundPointer(APValue &Subobj, QualType SubobjType) { | ||||||
3958 | if (!checkConst(SubobjType)) | ||||||
3959 | return false; | ||||||
3960 | |||||||
3961 | QualType PointeeType; | ||||||
3962 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) | ||||||
3963 | PointeeType = PT->getPointeeType(); | ||||||
3964 | else { | ||||||
3965 | Info.FFDiag(E); | ||||||
3966 | return false; | ||||||
3967 | } | ||||||
3968 | |||||||
3969 | LValue LVal; | ||||||
3970 | LVal.setFrom(Info.Ctx, Subobj); | ||||||
3971 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, | ||||||
3972 | AccessKind == AK_Increment ? 1 : -1)) | ||||||
3973 | return false; | ||||||
3974 | LVal.moveInto(Subobj); | ||||||
3975 | return true; | ||||||
3976 | } | ||||||
3977 | }; | ||||||
3978 | } // end anonymous namespace | ||||||
3979 | |||||||
3980 | /// Perform an increment or decrement on LVal. | ||||||
3981 | static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, | ||||||
3982 | QualType LValType, bool IsIncrement, APValue *Old) { | ||||||
3983 | if (LVal.Designator.Invalid) | ||||||
3984 | return false; | ||||||
3985 | |||||||
3986 | if (!Info.getLangOpts().CPlusPlus14) { | ||||||
3987 | Info.FFDiag(E); | ||||||
3988 | return false; | ||||||
3989 | } | ||||||
3990 | |||||||
3991 | AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; | ||||||
3992 | CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); | ||||||
3993 | IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; | ||||||
3994 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); | ||||||
3995 | } | ||||||
3996 | |||||||
3997 | /// Build an lvalue for the object argument of a member function call. | ||||||
3998 | static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, | ||||||
3999 | LValue &This) { | ||||||
4000 | if (Object->getType()->isPointerType() && Object->isRValue()) | ||||||
4001 | return EvaluatePointer(Object, This, Info); | ||||||
4002 | |||||||
4003 | if (Object->isGLValue()) | ||||||
4004 | return EvaluateLValue(Object, This, Info); | ||||||
4005 | |||||||
4006 | if (Object->getType()->isLiteralType(Info.Ctx)) | ||||||
4007 | return EvaluateTemporary(Object, This, Info); | ||||||
4008 | |||||||
4009 | Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); | ||||||
4010 | return false; | ||||||
4011 | } | ||||||
4012 | |||||||
4013 | /// HandleMemberPointerAccess - Evaluate a member access operation and build an | ||||||
4014 | /// lvalue referring to the result. | ||||||
4015 | /// | ||||||
4016 | /// \param Info - Information about the ongoing evaluation. | ||||||
4017 | /// \param LV - An lvalue referring to the base of the member pointer. | ||||||
4018 | /// \param RHS - The member pointer expression. | ||||||
4019 | /// \param IncludeMember - Specifies whether the member itself is included in | ||||||
4020 | /// the resulting LValue subobject designator. This is not possible when | ||||||
4021 | /// creating a bound member function. | ||||||
4022 | /// \return The field or method declaration to which the member pointer refers, | ||||||
4023 | /// or 0 if evaluation fails. | ||||||
4024 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, | ||||||
4025 | QualType LVType, | ||||||
4026 | LValue &LV, | ||||||
4027 | const Expr *RHS, | ||||||
4028 | bool IncludeMember = true) { | ||||||
4029 | MemberPtr MemPtr; | ||||||
4030 | if (!EvaluateMemberPointer(RHS, MemPtr, Info)) | ||||||
4031 | return nullptr; | ||||||
4032 | |||||||
4033 | // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to | ||||||
4034 | // member value, the behavior is undefined. | ||||||
4035 | if (!MemPtr.getDecl()) { | ||||||
4036 | // FIXME: Specific diagnostic. | ||||||
4037 | Info.FFDiag(RHS); | ||||||
4038 | return nullptr; | ||||||
4039 | } | ||||||
4040 | |||||||
4041 | if (MemPtr.isDerivedMember()) { | ||||||
4042 | // This is a member of some derived class. Truncate LV appropriately. | ||||||
4043 | // The end of the derived-to-base path for the base object must match the | ||||||
4044 | // derived-to-base path for the member pointer. | ||||||
4045 | if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > | ||||||
4046 | LV.Designator.Entries.size()) { | ||||||
4047 | Info.FFDiag(RHS); | ||||||
4048 | return nullptr; | ||||||
4049 | } | ||||||
4050 | unsigned PathLengthToMember = | ||||||
4051 | LV.Designator.Entries.size() - MemPtr.Path.size(); | ||||||
4052 | for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { | ||||||
4053 | const CXXRecordDecl *LVDecl = getAsBaseClass( | ||||||
4054 | LV.Designator.Entries[PathLengthToMember + I]); | ||||||
4055 | const CXXRecordDecl *MPDecl = MemPtr.Path[I]; | ||||||
4056 | if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { | ||||||
4057 | Info.FFDiag(RHS); | ||||||
4058 | return nullptr; | ||||||
4059 | } | ||||||
4060 | } | ||||||
4061 | |||||||
4062 | // Truncate the lvalue to the appropriate derived class. | ||||||
4063 | if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), | ||||||
4064 | PathLengthToMember)) | ||||||
4065 | return nullptr; | ||||||
4066 | } else if (!MemPtr.Path.empty()) { | ||||||
4067 | // Extend the LValue path with the member pointer's path. | ||||||
4068 | LV.Designator.Entries.reserve(LV.Designator.Entries.size() + | ||||||
4069 | MemPtr.Path.size() + IncludeMember); | ||||||
4070 | |||||||
4071 | // Walk down to the appropriate base class. | ||||||
4072 | if (const PointerType *PT = LVType->getAs<PointerType>()) | ||||||
4073 | LVType = PT->getPointeeType(); | ||||||
4074 | const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); | ||||||
4075 | assert(RD && "member pointer access on non-class-type expression")((RD && "member pointer access on non-class-type expression" ) ? static_cast<void> (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4075, __PRETTY_FUNCTION__)); | ||||||
4076 | // The first class in the path is that of the lvalue. | ||||||
4077 | for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { | ||||||
4078 | const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; | ||||||
4079 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) | ||||||
4080 | return nullptr; | ||||||
4081 | RD = Base; | ||||||
4082 | } | ||||||
4083 | // Finally cast to the class containing the member. | ||||||
4084 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, | ||||||
4085 | MemPtr.getContainingRecord())) | ||||||
4086 | return nullptr; | ||||||
4087 | } | ||||||
4088 | |||||||
4089 | // Add the member. Note that we cannot build bound member functions here. | ||||||
4090 | if (IncludeMember) { | ||||||
4091 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { | ||||||
4092 | if (!HandleLValueMember(Info, RHS, LV, FD)) | ||||||
4093 | return nullptr; | ||||||
4094 | } else if (const IndirectFieldDecl *IFD = | ||||||
4095 | dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { | ||||||
4096 | if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) | ||||||
4097 | return nullptr; | ||||||
4098 | } else { | ||||||
4099 | 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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4099); | ||||||
4100 | } | ||||||
4101 | } | ||||||
4102 | |||||||
4103 | return MemPtr.getDecl(); | ||||||
4104 | } | ||||||
4105 | |||||||
4106 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, | ||||||
4107 | const BinaryOperator *BO, | ||||||
4108 | LValue &LV, | ||||||
4109 | bool IncludeMember = true) { | ||||||
4110 | assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)((BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI ) ? static_cast<void> (0) : __assert_fail ("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4110, __PRETTY_FUNCTION__)); | ||||||
4111 | |||||||
4112 | if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { | ||||||
4113 | if (Info.noteFailure()) { | ||||||
4114 | MemberPtr MemPtr; | ||||||
4115 | EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); | ||||||
4116 | } | ||||||
4117 | return nullptr; | ||||||
4118 | } | ||||||
4119 | |||||||
4120 | return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, | ||||||
4121 | BO->getRHS(), IncludeMember); | ||||||
4122 | } | ||||||
4123 | |||||||
4124 | /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on | ||||||
4125 | /// the provided lvalue, which currently refers to the base object. | ||||||
4126 | static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, | ||||||
4127 | LValue &Result) { | ||||||
4128 | SubobjectDesignator &D = Result.Designator; | ||||||
4129 | if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) | ||||||
4130 | return false; | ||||||
4131 | |||||||
4132 | QualType TargetQT = E->getType(); | ||||||
4133 | if (const PointerType *PT = TargetQT->getAs<PointerType>()) | ||||||
4134 | TargetQT = PT->getPointeeType(); | ||||||
4135 | |||||||
4136 | // Check this cast lands within the final derived-to-base subobject path. | ||||||
4137 | if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { | ||||||
4138 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) | ||||||
4139 | << D.MostDerivedType << TargetQT; | ||||||
4140 | return false; | ||||||
4141 | } | ||||||
4142 | |||||||
4143 | // Check the type of the final cast. We don't need to check the path, | ||||||
4144 | // since a cast can only be formed if the path is unique. | ||||||
4145 | unsigned NewEntriesSize = D.Entries.size() - E->path_size(); | ||||||
4146 | const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); | ||||||
4147 | const CXXRecordDecl *FinalType; | ||||||
4148 | if (NewEntriesSize == D.MostDerivedPathLength) | ||||||
4149 | FinalType = D.MostDerivedType->getAsCXXRecordDecl(); | ||||||
4150 | else | ||||||
4151 | FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); | ||||||
4152 | if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { | ||||||
4153 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) | ||||||
4154 | << D.MostDerivedType << TargetQT; | ||||||
4155 | return false; | ||||||
4156 | } | ||||||
4157 | |||||||
4158 | // Truncate the lvalue to the appropriate derived class. | ||||||
4159 | return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); | ||||||
4160 | } | ||||||
4161 | |||||||
4162 | /// Get the value to use for a default-initialized object of type T. | ||||||
4163 | static APValue getDefaultInitValue(QualType T) { | ||||||
4164 | if (auto *RD = T->getAsCXXRecordDecl()) { | ||||||
4165 | if (RD->isUnion()) | ||||||
4166 | return APValue((const FieldDecl*)nullptr); | ||||||
4167 | |||||||
4168 | APValue Struct(APValue::UninitStruct(), RD->getNumBases(), | ||||||
4169 | std::distance(RD->field_begin(), RD->field_end())); | ||||||
4170 | |||||||
4171 | unsigned Index = 0; | ||||||
4172 | for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), | ||||||
4173 | End = RD->bases_end(); I != End; ++I, ++Index) | ||||||
4174 | Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); | ||||||
4175 | |||||||
4176 | for (const auto *I : RD->fields()) { | ||||||
4177 | if (I->isUnnamedBitfield()) | ||||||
4178 | continue; | ||||||
4179 | Struct.getStructField(I->getFieldIndex()) = | ||||||
4180 | getDefaultInitValue(I->getType()); | ||||||
4181 | } | ||||||
4182 | return Struct; | ||||||
4183 | } | ||||||
4184 | |||||||
4185 | if (auto *AT = | ||||||
4186 | dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { | ||||||
4187 | APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); | ||||||
4188 | if (Array.hasArrayFiller()) | ||||||
4189 | Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); | ||||||
4190 | return Array; | ||||||
4191 | } | ||||||
4192 | |||||||
4193 | return APValue::IndeterminateValue(); | ||||||
4194 | } | ||||||
4195 | |||||||
4196 | namespace { | ||||||
4197 | enum EvalStmtResult { | ||||||
4198 | /// Evaluation failed. | ||||||
4199 | ESR_Failed, | ||||||
4200 | /// Hit a 'return' statement. | ||||||
4201 | ESR_Returned, | ||||||
4202 | /// Evaluation succeeded. | ||||||
4203 | ESR_Succeeded, | ||||||
4204 | /// Hit a 'continue' statement. | ||||||
4205 | ESR_Continue, | ||||||
4206 | /// Hit a 'break' statement. | ||||||
4207 | ESR_Break, | ||||||
4208 | /// Still scanning for 'case' or 'default' statement. | ||||||
4209 | ESR_CaseNotFound | ||||||
4210 | }; | ||||||
4211 | } | ||||||
4212 | |||||||
4213 | static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { | ||||||
4214 | // We don't need to evaluate the initializer for a static local. | ||||||
4215 | if (!VD->hasLocalStorage()) | ||||||
4216 | return true; | ||||||
4217 | |||||||
4218 | LValue Result; | ||||||
4219 | APValue &Val = | ||||||
4220 | Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); | ||||||
4221 | |||||||
4222 | const Expr *InitE = VD->getInit(); | ||||||
4223 | if (!InitE) { | ||||||
4224 | Val = getDefaultInitValue(VD->getType()); | ||||||
4225 | return true; | ||||||
4226 | } | ||||||
4227 | |||||||
4228 | if (InitE->isValueDependent()) | ||||||
4229 | return false; | ||||||
4230 | |||||||
4231 | if (!EvaluateInPlace(Val, Info, Result, InitE)) { | ||||||
4232 | // Wipe out any partially-computed value, to allow tracking that this | ||||||
4233 | // evaluation failed. | ||||||
4234 | Val = APValue(); | ||||||
4235 | return false; | ||||||
4236 | } | ||||||
4237 | |||||||
4238 | return true; | ||||||
4239 | } | ||||||
4240 | |||||||
4241 | static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { | ||||||
4242 | bool OK = true; | ||||||
4243 | |||||||
4244 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||||
4245 | OK &= EvaluateVarDecl(Info, VD); | ||||||
4246 | |||||||
4247 | if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) | ||||||
4248 | for (auto *BD : DD->bindings()) | ||||||
4249 | if (auto *VD = BD->getHoldingVar()) | ||||||
4250 | OK &= EvaluateDecl(Info, VD); | ||||||
4251 | |||||||
4252 | return OK; | ||||||
4253 | } | ||||||
4254 | |||||||
4255 | |||||||
4256 | /// Evaluate a condition (either a variable declaration or an expression). | ||||||
4257 | static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, | ||||||
4258 | const Expr *Cond, bool &Result) { | ||||||
4259 | FullExpressionRAII Scope(Info); | ||||||
4260 | if (CondDecl && !EvaluateDecl(Info, CondDecl)) | ||||||
4261 | return false; | ||||||
4262 | if (!EvaluateAsBooleanCondition(Cond, Result, Info)) | ||||||
4263 | return false; | ||||||
4264 | return Scope.destroy(); | ||||||
4265 | } | ||||||
4266 | |||||||
4267 | namespace { | ||||||
4268 | /// A location where the result (returned value) of evaluating a | ||||||
4269 | /// statement should be stored. | ||||||
4270 | struct StmtResult { | ||||||
4271 | /// The APValue that should be filled in with the returned value. | ||||||
4272 | APValue &Value; | ||||||
4273 | /// The location containing the result, if any (used to support RVO). | ||||||
4274 | const LValue *Slot; | ||||||
4275 | }; | ||||||
4276 | |||||||
4277 | struct TempVersionRAII { | ||||||
4278 | CallStackFrame &Frame; | ||||||
4279 | |||||||
4280 | TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { | ||||||
4281 | Frame.pushTempVersion(); | ||||||
4282 | } | ||||||
4283 | |||||||
4284 | ~TempVersionRAII() { | ||||||
4285 | Frame.popTempVersion(); | ||||||
4286 | } | ||||||
4287 | }; | ||||||
4288 | |||||||
4289 | } | ||||||
4290 | |||||||
4291 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, | ||||||
4292 | const Stmt *S, | ||||||
4293 | const SwitchCase *SC = nullptr); | ||||||
4294 | |||||||
4295 | /// Evaluate the body of a loop, and translate the result as appropriate. | ||||||
4296 | static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, | ||||||
4297 | const Stmt *Body, | ||||||
4298 | const SwitchCase *Case = nullptr) { | ||||||
4299 | BlockScopeRAII Scope(Info); | ||||||
4300 | |||||||
4301 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); | ||||||
4302 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) | ||||||
4303 | ESR = ESR_Failed; | ||||||
4304 | |||||||
4305 | switch (ESR) { | ||||||
4306 | case ESR_Break: | ||||||
4307 | return ESR_Succeeded; | ||||||
4308 | case ESR_Succeeded: | ||||||
4309 | case ESR_Continue: | ||||||
4310 | return ESR_Continue; | ||||||
4311 | case ESR_Failed: | ||||||
4312 | case ESR_Returned: | ||||||
4313 | case ESR_CaseNotFound: | ||||||
4314 | return ESR; | ||||||
4315 | } | ||||||
4316 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4316); | ||||||
4317 | } | ||||||
4318 | |||||||
4319 | /// Evaluate a switch statement. | ||||||
4320 | static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, | ||||||
4321 | const SwitchStmt *SS) { | ||||||
4322 | BlockScopeRAII Scope(Info); | ||||||
4323 | |||||||
4324 | // Evaluate the switch condition. | ||||||
4325 | APSInt Value; | ||||||
4326 | { | ||||||
4327 | if (const Stmt *Init = SS->getInit()) { | ||||||
4328 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); | ||||||
4329 | if (ESR != ESR_Succeeded) { | ||||||
4330 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4331 | ESR = ESR_Failed; | ||||||
4332 | return ESR; | ||||||
4333 | } | ||||||
4334 | } | ||||||
4335 | |||||||
4336 | FullExpressionRAII CondScope(Info); | ||||||
4337 | if (SS->getConditionVariable() && | ||||||
4338 | !EvaluateDecl(Info, SS->getConditionVariable())) | ||||||
4339 | return ESR_Failed; | ||||||
4340 | if (!EvaluateInteger(SS->getCond(), Value, Info)) | ||||||
4341 | return ESR_Failed; | ||||||
4342 | if (!CondScope.destroy()) | ||||||
4343 | return ESR_Failed; | ||||||
4344 | } | ||||||
4345 | |||||||
4346 | // Find the switch case corresponding to the value of the condition. | ||||||
4347 | // FIXME: Cache this lookup. | ||||||
4348 | const SwitchCase *Found = nullptr; | ||||||
4349 | for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; | ||||||
4350 | SC = SC->getNextSwitchCase()) { | ||||||
4351 | if (isa<DefaultStmt>(SC)) { | ||||||
4352 | Found = SC; | ||||||
4353 | continue; | ||||||
4354 | } | ||||||
4355 | |||||||
4356 | const CaseStmt *CS = cast<CaseStmt>(SC); | ||||||
4357 | APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); | ||||||
4358 | APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) | ||||||
4359 | : LHS; | ||||||
4360 | if (LHS <= Value && Value <= RHS) { | ||||||
4361 | Found = SC; | ||||||
4362 | break; | ||||||
4363 | } | ||||||
4364 | } | ||||||
4365 | |||||||
4366 | if (!Found) | ||||||
4367 | return Scope.destroy() ? ESR_Failed : ESR_Succeeded; | ||||||
4368 | |||||||
4369 | // Search the switch body for the switch case and evaluate it from there. | ||||||
4370 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); | ||||||
4371 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) | ||||||
4372 | return ESR_Failed; | ||||||
4373 | |||||||
4374 | switch (ESR) { | ||||||
4375 | case ESR_Break: | ||||||
4376 | return ESR_Succeeded; | ||||||
4377 | case ESR_Succeeded: | ||||||
4378 | case ESR_Continue: | ||||||
4379 | case ESR_Failed: | ||||||
4380 | case ESR_Returned: | ||||||
4381 | return ESR; | ||||||
4382 | case ESR_CaseNotFound: | ||||||
4383 | // This can only happen if the switch case is nested within a statement | ||||||
4384 | // expression. We have no intention of supporting that. | ||||||
4385 | Info.FFDiag(Found->getBeginLoc(), | ||||||
4386 | diag::note_constexpr_stmt_expr_unsupported); | ||||||
4387 | return ESR_Failed; | ||||||
4388 | } | ||||||
4389 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4389); | ||||||
4390 | } | ||||||
4391 | |||||||
4392 | // Evaluate a statement. | ||||||
4393 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, | ||||||
4394 | const Stmt *S, const SwitchCase *Case) { | ||||||
4395 | if (!Info.nextStep(S)) | ||||||
4396 | return ESR_Failed; | ||||||
4397 | |||||||
4398 | // If we're hunting down a 'case' or 'default' label, recurse through | ||||||
4399 | // substatements until we hit the label. | ||||||
4400 | if (Case) { | ||||||
4401 | switch (S->getStmtClass()) { | ||||||
4402 | case Stmt::CompoundStmtClass: | ||||||
4403 | // FIXME: Precompute which substatement of a compound statement we | ||||||
4404 | // would jump to, and go straight there rather than performing a | ||||||
4405 | // linear scan each time. | ||||||
4406 | case Stmt::LabelStmtClass: | ||||||
4407 | case Stmt::AttributedStmtClass: | ||||||
4408 | case Stmt::DoStmtClass: | ||||||
4409 | break; | ||||||
4410 | |||||||
4411 | case Stmt::CaseStmtClass: | ||||||
4412 | case Stmt::DefaultStmtClass: | ||||||
4413 | if (Case == S) | ||||||
4414 | Case = nullptr; | ||||||
4415 | break; | ||||||
4416 | |||||||
4417 | case Stmt::IfStmtClass: { | ||||||
4418 | // FIXME: Precompute which side of an 'if' we would jump to, and go | ||||||
4419 | // straight there rather than scanning both sides. | ||||||
4420 | const IfStmt *IS = cast<IfStmt>(S); | ||||||
4421 | |||||||
4422 | // Wrap the evaluation in a block scope, in case it's a DeclStmt | ||||||
4423 | // preceded by our switch label. | ||||||
4424 | BlockScopeRAII Scope(Info); | ||||||
4425 | |||||||
4426 | // Step into the init statement in case it brings an (uninitialized) | ||||||
4427 | // variable into scope. | ||||||
4428 | if (const Stmt *Init = IS->getInit()) { | ||||||
4429 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); | ||||||
4430 | if (ESR != ESR_CaseNotFound) { | ||||||
4431 | assert(ESR != ESR_Succeeded)((ESR != ESR_Succeeded) ? static_cast<void> (0) : __assert_fail ("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4431, __PRETTY_FUNCTION__)); | ||||||
4432 | return ESR; | ||||||
4433 | } | ||||||
4434 | } | ||||||
4435 | |||||||
4436 | // Condition variable must be initialized if it exists. | ||||||
4437 | // FIXME: We can skip evaluating the body if there's a condition | ||||||
4438 | // variable, as there can't be any case labels within it. | ||||||
4439 | // (The same is true for 'for' statements.) | ||||||
4440 | |||||||
4441 | EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); | ||||||
4442 | if (ESR == ESR_Failed) | ||||||
4443 | return ESR; | ||||||
4444 | if (ESR != ESR_CaseNotFound) | ||||||
4445 | return Scope.destroy() ? ESR : ESR_Failed; | ||||||
4446 | if (!IS->getElse()) | ||||||
4447 | return ESR_CaseNotFound; | ||||||
4448 | |||||||
4449 | ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); | ||||||
4450 | if (ESR == ESR_Failed) | ||||||
4451 | return ESR; | ||||||
4452 | if (ESR != ESR_CaseNotFound) | ||||||
4453 | return Scope.destroy() ? ESR : ESR_Failed; | ||||||
4454 | return ESR_CaseNotFound; | ||||||
4455 | } | ||||||
4456 | |||||||
4457 | case Stmt::WhileStmtClass: { | ||||||
4458 | EvalStmtResult ESR = | ||||||
4459 | EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); | ||||||
4460 | if (ESR != ESR_Continue) | ||||||
4461 | return ESR; | ||||||
4462 | break; | ||||||
4463 | } | ||||||
4464 | |||||||
4465 | case Stmt::ForStmtClass: { | ||||||
4466 | const ForStmt *FS = cast<ForStmt>(S); | ||||||
4467 | BlockScopeRAII Scope(Info); | ||||||
4468 | |||||||
4469 | // Step into the init statement in case it brings an (uninitialized) | ||||||
4470 | // variable into scope. | ||||||
4471 | if (const Stmt *Init = FS->getInit()) { | ||||||
4472 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); | ||||||
4473 | if (ESR != ESR_CaseNotFound) { | ||||||
4474 | assert(ESR != ESR_Succeeded)((ESR != ESR_Succeeded) ? static_cast<void> (0) : __assert_fail ("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4474, __PRETTY_FUNCTION__)); | ||||||
4475 | return ESR; | ||||||
4476 | } | ||||||
4477 | } | ||||||
4478 | |||||||
4479 | EvalStmtResult ESR = | ||||||
4480 | EvaluateLoopBody(Result, Info, FS->getBody(), Case); | ||||||
4481 | if (ESR != ESR_Continue) | ||||||
4482 | return ESR; | ||||||
4483 | if (FS->getInc()) { | ||||||
4484 | FullExpressionRAII IncScope(Info); | ||||||
4485 | if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) | ||||||
4486 | return ESR_Failed; | ||||||
4487 | } | ||||||
4488 | break; | ||||||
4489 | } | ||||||
4490 | |||||||
4491 | case Stmt::DeclStmtClass: { | ||||||
4492 | // Start the lifetime of any uninitialized variables we encounter. They | ||||||
4493 | // might be used by the selected branch of the switch. | ||||||
4494 | const DeclStmt *DS = cast<DeclStmt>(S); | ||||||
4495 | for (const auto *D : DS->decls()) { | ||||||
4496 | if (const auto *VD = dyn_cast<VarDecl>(D)) { | ||||||
4497 | if (VD->hasLocalStorage() && !VD->getInit()) | ||||||
4498 | if (!EvaluateVarDecl(Info, VD)) | ||||||
4499 | return ESR_Failed; | ||||||
4500 | // FIXME: If the variable has initialization that can't be jumped | ||||||
4501 | // over, bail out of any immediately-surrounding compound-statement | ||||||
4502 | // too. There can't be any case labels here. | ||||||
4503 | } | ||||||
4504 | } | ||||||
4505 | return ESR_CaseNotFound; | ||||||
4506 | } | ||||||
4507 | |||||||
4508 | default: | ||||||
4509 | return ESR_CaseNotFound; | ||||||
4510 | } | ||||||
4511 | } | ||||||
4512 | |||||||
4513 | switch (S->getStmtClass()) { | ||||||
4514 | default: | ||||||
4515 | if (const Expr *E = dyn_cast<Expr>(S)) { | ||||||
4516 | // Don't bother evaluating beyond an expression-statement which couldn't | ||||||
4517 | // be evaluated. | ||||||
4518 | // FIXME: Do we need the FullExpressionRAII object here? | ||||||
4519 | // VisitExprWithCleanups should create one when necessary. | ||||||
4520 | FullExpressionRAII Scope(Info); | ||||||
4521 | if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) | ||||||
4522 | return ESR_Failed; | ||||||
4523 | return ESR_Succeeded; | ||||||
4524 | } | ||||||
4525 | |||||||
4526 | Info.FFDiag(S->getBeginLoc()); | ||||||
4527 | return ESR_Failed; | ||||||
4528 | |||||||
4529 | case Stmt::NullStmtClass: | ||||||
4530 | return ESR_Succeeded; | ||||||
4531 | |||||||
4532 | case Stmt::DeclStmtClass: { | ||||||
4533 | const DeclStmt *DS = cast<DeclStmt>(S); | ||||||
4534 | for (const auto *D : DS->decls()) { | ||||||
4535 | // Each declaration initialization is its own full-expression. | ||||||
4536 | FullExpressionRAII Scope(Info); | ||||||
4537 | if (!EvaluateDecl(Info, D) && !Info.noteFailure()) | ||||||
4538 | return ESR_Failed; | ||||||
4539 | if (!Scope.destroy()) | ||||||
4540 | return ESR_Failed; | ||||||
4541 | } | ||||||
4542 | return ESR_Succeeded; | ||||||
4543 | } | ||||||
4544 | |||||||
4545 | case Stmt::ReturnStmtClass: { | ||||||
4546 | const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); | ||||||
4547 | FullExpressionRAII Scope(Info); | ||||||
4548 | if (RetExpr && | ||||||
4549 | !(Result.Slot | ||||||
4550 | ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) | ||||||
4551 | : Evaluate(Result.Value, Info, RetExpr))) | ||||||
4552 | return ESR_Failed; | ||||||
4553 | return Scope.destroy() ? ESR_Returned : ESR_Failed; | ||||||
4554 | } | ||||||
4555 | |||||||
4556 | case Stmt::CompoundStmtClass: { | ||||||
4557 | BlockScopeRAII Scope(Info); | ||||||
4558 | |||||||
4559 | const CompoundStmt *CS = cast<CompoundStmt>(S); | ||||||
4560 | for (const auto *BI : CS->body()) { | ||||||
4561 | EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); | ||||||
4562 | if (ESR == ESR_Succeeded) | ||||||
4563 | Case = nullptr; | ||||||
4564 | else if (ESR != ESR_CaseNotFound) { | ||||||
4565 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4566 | return ESR_Failed; | ||||||
4567 | return ESR; | ||||||
4568 | } | ||||||
4569 | } | ||||||
4570 | if (Case) | ||||||
4571 | return ESR_CaseNotFound; | ||||||
4572 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||||
4573 | } | ||||||
4574 | |||||||
4575 | case Stmt::IfStmtClass: { | ||||||
4576 | const IfStmt *IS = cast<IfStmt>(S); | ||||||
4577 | |||||||
4578 | // Evaluate the condition, as either a var decl or as an expression. | ||||||
4579 | BlockScopeRAII Scope(Info); | ||||||
4580 | if (const Stmt *Init = IS->getInit()) { | ||||||
4581 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); | ||||||
4582 | if (ESR != ESR_Succeeded) { | ||||||
4583 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4584 | return ESR_Failed; | ||||||
4585 | return ESR; | ||||||
4586 | } | ||||||
4587 | } | ||||||
4588 | bool Cond; | ||||||
4589 | if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) | ||||||
4590 | return ESR_Failed; | ||||||
4591 | |||||||
4592 | if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { | ||||||
4593 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); | ||||||
4594 | if (ESR != ESR_Succeeded) { | ||||||
4595 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4596 | return ESR_Failed; | ||||||
4597 | return ESR; | ||||||
4598 | } | ||||||
4599 | } | ||||||
4600 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||||
4601 | } | ||||||
4602 | |||||||
4603 | case Stmt::WhileStmtClass: { | ||||||
4604 | const WhileStmt *WS = cast<WhileStmt>(S); | ||||||
4605 | while (true) { | ||||||
4606 | BlockScopeRAII Scope(Info); | ||||||
4607 | bool Continue; | ||||||
4608 | if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), | ||||||
4609 | Continue)) | ||||||
4610 | return ESR_Failed; | ||||||
4611 | if (!Continue) | ||||||
4612 | break; | ||||||
4613 | |||||||
4614 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); | ||||||
4615 | if (ESR != ESR_Continue) { | ||||||
4616 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4617 | return ESR_Failed; | ||||||
4618 | return ESR; | ||||||
4619 | } | ||||||
4620 | if (!Scope.destroy()) | ||||||
4621 | return ESR_Failed; | ||||||
4622 | } | ||||||
4623 | return ESR_Succeeded; | ||||||
4624 | } | ||||||
4625 | |||||||
4626 | case Stmt::DoStmtClass: { | ||||||
4627 | const DoStmt *DS = cast<DoStmt>(S); | ||||||
4628 | bool Continue; | ||||||
4629 | do { | ||||||
4630 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); | ||||||
4631 | if (ESR != ESR_Continue) | ||||||
4632 | return ESR; | ||||||
4633 | Case = nullptr; | ||||||
4634 | |||||||
4635 | FullExpressionRAII CondScope(Info); | ||||||
4636 | if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || | ||||||
4637 | !CondScope.destroy()) | ||||||
4638 | return ESR_Failed; | ||||||
4639 | } while (Continue); | ||||||
4640 | return ESR_Succeeded; | ||||||
4641 | } | ||||||
4642 | |||||||
4643 | case Stmt::ForStmtClass: { | ||||||
4644 | const ForStmt *FS = cast<ForStmt>(S); | ||||||
4645 | BlockScopeRAII ForScope(Info); | ||||||
4646 | if (FS->getInit()) { | ||||||
4647 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); | ||||||
4648 | if (ESR != ESR_Succeeded) { | ||||||
4649 | if (ESR != ESR_Failed && !ForScope.destroy()) | ||||||
4650 | return ESR_Failed; | ||||||
4651 | return ESR; | ||||||
4652 | } | ||||||
4653 | } | ||||||
4654 | while (true) { | ||||||
4655 | BlockScopeRAII IterScope(Info); | ||||||
4656 | bool Continue = true; | ||||||
4657 | if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), | ||||||
4658 | FS->getCond(), Continue)) | ||||||
4659 | return ESR_Failed; | ||||||
4660 | if (!Continue) | ||||||
4661 | break; | ||||||
4662 | |||||||
4663 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); | ||||||
4664 | if (ESR != ESR_Continue) { | ||||||
4665 | if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) | ||||||
4666 | return ESR_Failed; | ||||||
4667 | return ESR; | ||||||
4668 | } | ||||||
4669 | |||||||
4670 | if (FS->getInc()) { | ||||||
4671 | FullExpressionRAII IncScope(Info); | ||||||
4672 | if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) | ||||||
4673 | return ESR_Failed; | ||||||
4674 | } | ||||||
4675 | |||||||
4676 | if (!IterScope.destroy()) | ||||||
4677 | return ESR_Failed; | ||||||
4678 | } | ||||||
4679 | return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||||
4680 | } | ||||||
4681 | |||||||
4682 | case Stmt::CXXForRangeStmtClass: { | ||||||
4683 | const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); | ||||||
4684 | BlockScopeRAII Scope(Info); | ||||||
4685 | |||||||
4686 | // Evaluate the init-statement if present. | ||||||
4687 | if (FS->getInit()) { | ||||||
4688 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); | ||||||
4689 | if (ESR != ESR_Succeeded) { | ||||||
4690 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4691 | return ESR_Failed; | ||||||
4692 | return ESR; | ||||||
4693 | } | ||||||
4694 | } | ||||||
4695 | |||||||
4696 | // Initialize the __range variable. | ||||||
4697 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); | ||||||
4698 | if (ESR != ESR_Succeeded) { | ||||||
4699 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4700 | return ESR_Failed; | ||||||
4701 | return ESR; | ||||||
4702 | } | ||||||
4703 | |||||||
4704 | // Create the __begin and __end iterators. | ||||||
4705 | ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); | ||||||
4706 | if (ESR != ESR_Succeeded) { | ||||||
4707 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4708 | return ESR_Failed; | ||||||
4709 | return ESR; | ||||||
4710 | } | ||||||
4711 | ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); | ||||||
4712 | if (ESR != ESR_Succeeded) { | ||||||
4713 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||||
4714 | return ESR_Failed; | ||||||
4715 | return ESR; | ||||||
4716 | } | ||||||
4717 | |||||||
4718 | while (true) { | ||||||
4719 | // Condition: __begin != __end. | ||||||
4720 | { | ||||||
4721 | bool Continue = true; | ||||||
4722 | FullExpressionRAII CondExpr(Info); | ||||||
4723 | if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) | ||||||
4724 | return ESR_Failed; | ||||||
4725 | if (!Continue) | ||||||
4726 | break; | ||||||
4727 | } | ||||||
4728 | |||||||
4729 | // User's variable declaration, initialized by *__begin. | ||||||
4730 | BlockScopeRAII InnerScope(Info); | ||||||
4731 | ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); | ||||||
4732 | if (ESR != ESR_Succeeded) { | ||||||
4733 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) | ||||||
4734 | return ESR_Failed; | ||||||
4735 | return ESR; | ||||||
4736 | } | ||||||
4737 | |||||||
4738 | // Loop body. | ||||||
4739 | ESR = EvaluateLoopBody(Result, Info, FS->getBody()); | ||||||
4740 | if (ESR != ESR_Continue) { | ||||||
4741 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) | ||||||
4742 | return ESR_Failed; | ||||||
4743 | return ESR; | ||||||
4744 | } | ||||||
4745 | |||||||
4746 | // Increment: ++__begin | ||||||
4747 | if (!EvaluateIgnoredValue(Info, FS->getInc())) | ||||||
4748 | return ESR_Failed; | ||||||
4749 | |||||||
4750 | if (!InnerScope.destroy()) | ||||||
4751 | return ESR_Failed; | ||||||
4752 | } | ||||||
4753 | |||||||
4754 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||||
4755 | } | ||||||
4756 | |||||||
4757 | case Stmt::SwitchStmtClass: | ||||||
4758 | return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); | ||||||
4759 | |||||||
4760 | case Stmt::ContinueStmtClass: | ||||||
4761 | return ESR_Continue; | ||||||
4762 | |||||||
4763 | case Stmt::BreakStmtClass: | ||||||
4764 | return ESR_Break; | ||||||
4765 | |||||||
4766 | case Stmt::LabelStmtClass: | ||||||
4767 | return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); | ||||||
4768 | |||||||
4769 | case Stmt::AttributedStmtClass: | ||||||
4770 | // As a general principle, C++11 attributes can be ignored without | ||||||
4771 | // any semantic impact. | ||||||
4772 | return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), | ||||||
4773 | Case); | ||||||
4774 | |||||||
4775 | case Stmt::CaseStmtClass: | ||||||
4776 | case Stmt::DefaultStmtClass: | ||||||
4777 | return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); | ||||||
4778 | case Stmt::CXXTryStmtClass: | ||||||
4779 | // Evaluate try blocks by evaluating all sub statements. | ||||||
4780 | return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); | ||||||
4781 | } | ||||||
4782 | } | ||||||
4783 | |||||||
4784 | /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial | ||||||
4785 | /// default constructor. If so, we'll fold it whether or not it's marked as | ||||||
4786 | /// constexpr. If it is marked as constexpr, we will never implicitly define it, | ||||||
4787 | /// so we need special handling. | ||||||
4788 | static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, | ||||||
4789 | const CXXConstructorDecl *CD, | ||||||
4790 | bool IsValueInitialization) { | ||||||
4791 | if (!CD->isTrivial() || !CD->isDefaultConstructor()) | ||||||
4792 | return false; | ||||||
4793 | |||||||
4794 | // Value-initialization does not call a trivial default constructor, so such a | ||||||
4795 | // call is a core constant expression whether or not the constructor is | ||||||
4796 | // constexpr. | ||||||
4797 | if (!CD->isConstexpr() && !IsValueInitialization) { | ||||||
4798 | if (Info.getLangOpts().CPlusPlus11) { | ||||||
4799 | // FIXME: If DiagDecl is an implicitly-declared special member function, | ||||||
4800 | // we should be much more explicit about why it's not constexpr. | ||||||
4801 | Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) | ||||||
4802 | << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; | ||||||
4803 | Info.Note(CD->getLocation(), diag::note_declared_at); | ||||||
4804 | } else { | ||||||
4805 | Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); | ||||||
4806 | } | ||||||
4807 | } | ||||||
4808 | return true; | ||||||
4809 | } | ||||||
4810 | |||||||
4811 | /// CheckConstexprFunction - Check that a function can be called in a constant | ||||||
4812 | /// expression. | ||||||
4813 | static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, | ||||||
4814 | const FunctionDecl *Declaration, | ||||||
4815 | const FunctionDecl *Definition, | ||||||
4816 | const Stmt *Body) { | ||||||
4817 | // Potential constant expressions can contain calls to declared, but not yet | ||||||
4818 | // defined, constexpr functions. | ||||||
4819 | if (Info.checkingPotentialConstantExpression() && !Definition && | ||||||
4820 | Declaration->isConstexpr()) | ||||||
4821 | return false; | ||||||
4822 | |||||||
4823 | // Bail out if the function declaration itself is invalid. We will | ||||||
4824 | // have produced a relevant diagnostic while parsing it, so just | ||||||
4825 | // note the problematic sub-expression. | ||||||
4826 | if (Declaration->isInvalidDecl()) { | ||||||
4827 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||||
4828 | return false; | ||||||
4829 | } | ||||||
4830 | |||||||
4831 | // DR1872: An instantiated virtual constexpr function can't be called in a | ||||||
4832 | // constant expression (prior to C++20). We can still constant-fold such a | ||||||
4833 | // call. | ||||||
4834 | if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && | ||||||
4835 | cast<CXXMethodDecl>(Declaration)->isVirtual()) | ||||||
4836 | Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); | ||||||
4837 | |||||||
4838 | if (Definition && Definition->isInvalidDecl()) { | ||||||
4839 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||||
4840 | return false; | ||||||
4841 | } | ||||||
4842 | |||||||
4843 | // Can we evaluate this function call? | ||||||
4844 | if (Definition && Definition->isConstexpr() && Body) | ||||||
4845 | return true; | ||||||
4846 | |||||||
4847 | if (Info.getLangOpts().CPlusPlus11) { | ||||||
4848 | const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; | ||||||
4849 | |||||||
4850 | // If this function is not constexpr because it is an inherited | ||||||
4851 | // non-constexpr constructor, diagnose that directly. | ||||||
4852 | auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); | ||||||
4853 | if (CD && CD->isInheritingConstructor()) { | ||||||
4854 | auto *Inherited = CD->getInheritedConstructor().getConstructor(); | ||||||
4855 | if (!Inherited->isConstexpr()) | ||||||
4856 | DiagDecl = CD = Inherited; | ||||||
4857 | } | ||||||
4858 | |||||||
4859 | // FIXME: If DiagDecl is an implicitly-declared special member function | ||||||
4860 | // or an inheriting constructor, we should be much more explicit about why | ||||||
4861 | // it's not constexpr. | ||||||
4862 | if (CD && CD->isInheritingConstructor()) | ||||||
4863 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) | ||||||
4864 | << CD->getInheritedConstructor().getConstructor()->getParent(); | ||||||
4865 | else | ||||||
4866 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) | ||||||
4867 | << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; | ||||||
4868 | Info.Note(DiagDecl->getLocation(), diag::note_declared_at); | ||||||
4869 | } else { | ||||||
4870 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||||
4871 | } | ||||||
4872 | return false; | ||||||
4873 | } | ||||||
4874 | |||||||
4875 | namespace { | ||||||
4876 | struct CheckDynamicTypeHandler { | ||||||
4877 | AccessKinds AccessKind; | ||||||
4878 | typedef bool result_type; | ||||||
4879 | bool failed() { return false; } | ||||||
4880 | bool found(APValue &Subobj, QualType SubobjType) { return true; } | ||||||
4881 | bool found(APSInt &Value, QualType SubobjType) { return true; } | ||||||
4882 | bool found(APFloat &Value, QualType SubobjType) { return true; } | ||||||
4883 | }; | ||||||
4884 | } // end anonymous namespace | ||||||
4885 | |||||||
4886 | /// Check that we can access the notional vptr of an object / determine its | ||||||
4887 | /// dynamic type. | ||||||
4888 | static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, | ||||||
4889 | AccessKinds AK, bool Polymorphic) { | ||||||
4890 | if (This.Designator.Invalid) | ||||||
4891 | return false; | ||||||
4892 | |||||||
4893 | CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); | ||||||
4894 | |||||||
4895 | if (!Obj) | ||||||
4896 | return false; | ||||||
4897 | |||||||
4898 | if (!Obj.Value) { | ||||||
4899 | // The object is not usable in constant expressions, so we can't inspect | ||||||
4900 | // its value to see if it's in-lifetime or what the active union members | ||||||
4901 | // are. We can still check for a one-past-the-end lvalue. | ||||||
4902 | if (This.Designator.isOnePastTheEnd() || | ||||||
4903 | This.Designator.isMostDerivedAnUnsizedArray()) { | ||||||
4904 | Info.FFDiag(E, This.Designator.isOnePastTheEnd() | ||||||
4905 | ? diag::note_constexpr_access_past_end | ||||||
4906 | : diag::note_constexpr_access_unsized_array) | ||||||
4907 | << AK; | ||||||
4908 | return false; | ||||||
4909 | } else if (Polymorphic) { | ||||||
4910 | // Conservatively refuse to perform a polymorphic operation if we would | ||||||
4911 | // not be able to read a notional 'vptr' value. | ||||||
4912 | APValue Val; | ||||||
4913 | This.moveInto(Val); | ||||||
4914 | QualType StarThisType = | ||||||
4915 | Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); | ||||||
4916 | Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) | ||||||
4917 | << AK << Val.getAsString(Info.Ctx, StarThisType); | ||||||
4918 | return false; | ||||||
4919 | } | ||||||
4920 | return true; | ||||||
4921 | } | ||||||
4922 | |||||||
4923 | CheckDynamicTypeHandler Handler{AK}; | ||||||
4924 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); | ||||||
4925 | } | ||||||
4926 | |||||||
4927 | /// Check that the pointee of the 'this' pointer in a member function call is | ||||||
4928 | /// either within its lifetime or in its period of construction or destruction. | ||||||
4929 | static bool | ||||||
4930 | checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, | ||||||
4931 | const LValue &This, | ||||||
4932 | const CXXMethodDecl *NamedMember) { | ||||||
4933 | return checkDynamicType( | ||||||
4934 | Info, E, This, | ||||||
4935 | isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); | ||||||
4936 | } | ||||||
4937 | |||||||
4938 | struct DynamicType { | ||||||
4939 | /// The dynamic class type of the object. | ||||||
4940 | const CXXRecordDecl *Type; | ||||||
4941 | /// The corresponding path length in the lvalue. | ||||||
4942 | unsigned PathLength; | ||||||
4943 | }; | ||||||
4944 | |||||||
4945 | static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, | ||||||
4946 | unsigned PathLength) { | ||||||
4947 | assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=((PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length" ) ? static_cast<void> (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4948, __PRETTY_FUNCTION__)) | ||||||
4948 | Designator.Entries.size() && "invalid path length")((PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length" ) ? static_cast<void> (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4948, __PRETTY_FUNCTION__)); | ||||||
4949 | return (PathLength == Designator.MostDerivedPathLength) | ||||||
4950 | ? Designator.MostDerivedType->getAsCXXRecordDecl() | ||||||
4951 | : getAsBaseClass(Designator.Entries[PathLength - 1]); | ||||||
4952 | } | ||||||
4953 | |||||||
4954 | /// Determine the dynamic type of an object. | ||||||
4955 | static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, | ||||||
4956 | LValue &This, AccessKinds AK) { | ||||||
4957 | // If we don't have an lvalue denoting an object of class type, there is no | ||||||
4958 | // meaningful dynamic type. (We consider objects of non-class type to have no | ||||||
4959 | // dynamic type.) | ||||||
4960 | if (!checkDynamicType(Info, E, This, AK, true)) | ||||||
4961 | return None; | ||||||
4962 | |||||||
4963 | // Refuse to compute a dynamic type in the presence of virtual bases. This | ||||||
4964 | // shouldn't happen other than in constant-folding situations, since literal | ||||||
4965 | // types can't have virtual bases. | ||||||
4966 | // | ||||||
4967 | // Note that consumers of DynamicType assume that the type has no virtual | ||||||
4968 | // bases, and will need modifications if this restriction is relaxed. | ||||||
4969 | const CXXRecordDecl *Class = | ||||||
4970 | This.Designator.MostDerivedType->getAsCXXRecordDecl(); | ||||||
4971 | if (!Class || Class->getNumVBases()) { | ||||||
4972 | Info.FFDiag(E); | ||||||
4973 | return None; | ||||||
4974 | } | ||||||
4975 | |||||||
4976 | // FIXME: For very deep class hierarchies, it might be beneficial to use a | ||||||
4977 | // binary search here instead. But the overwhelmingly common case is that | ||||||
4978 | // we're not in the middle of a constructor, so it probably doesn't matter | ||||||
4979 | // in practice. | ||||||
4980 | ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; | ||||||
4981 | for (unsigned PathLength = This.Designator.MostDerivedPathLength; | ||||||
4982 | PathLength <= Path.size(); ++PathLength) { | ||||||
4983 | switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), | ||||||
4984 | Path.slice(0, PathLength))) { | ||||||
4985 | case ConstructionPhase::Bases: | ||||||
4986 | case ConstructionPhase::DestroyingBases: | ||||||
4987 | // We're constructing or destroying a base class. This is not the dynamic | ||||||
4988 | // type. | ||||||
4989 | break; | ||||||
4990 | |||||||
4991 | case ConstructionPhase::None: | ||||||
4992 | case ConstructionPhase::AfterBases: | ||||||
4993 | case ConstructionPhase::Destroying: | ||||||
4994 | // We've finished constructing the base classes and not yet started | ||||||
4995 | // destroying them again, so this is the dynamic type. | ||||||
4996 | return DynamicType{getBaseClassType(This.Designator, PathLength), | ||||||
4997 | PathLength}; | ||||||
4998 | } | ||||||
4999 | } | ||||||
5000 | |||||||
5001 | // CWG issue 1517: we're constructing a base class of the object described by | ||||||
5002 | // 'This', so that object has not yet begun its period of construction and | ||||||
5003 | // any polymorphic operation on it results in undefined behavior. | ||||||
5004 | Info.FFDiag(E); | ||||||
5005 | return None; | ||||||
5006 | } | ||||||
5007 | |||||||
5008 | /// Perform virtual dispatch. | ||||||
5009 | static const CXXMethodDecl *HandleVirtualDispatch( | ||||||
5010 | EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, | ||||||
5011 | llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { | ||||||
5012 | Optional<DynamicType> DynType = ComputeDynamicType( | ||||||
5013 | Info, E, This, | ||||||
5014 | isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); | ||||||
5015 | if (!DynType) | ||||||
5016 | return nullptr; | ||||||
5017 | |||||||
5018 | // Find the final overrider. It must be declared in one of the classes on the | ||||||
5019 | // path from the dynamic type to the static type. | ||||||
5020 | // FIXME: If we ever allow literal types to have virtual base classes, that | ||||||
5021 | // won't be true. | ||||||
5022 | const CXXMethodDecl *Callee = Found; | ||||||
5023 | unsigned PathLength = DynType->PathLength; | ||||||
5024 | for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { | ||||||
5025 | const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); | ||||||
5026 | const CXXMethodDecl *Overrider = | ||||||
5027 | Found->getCorrespondingMethodDeclaredInClass(Class, false); | ||||||
5028 | if (Overrider) { | ||||||
5029 | Callee = Overrider; | ||||||
5030 | break; | ||||||
5031 | } | ||||||
5032 | } | ||||||
5033 | |||||||
5034 | // C++2a [class.abstract]p6: | ||||||
5035 | // the effect of making a virtual call to a pure virtual function [...] is | ||||||
5036 | // undefined | ||||||
5037 | if (Callee->isPure()) { | ||||||
5038 | Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; | ||||||
5039 | Info.Note(Callee->getLocation(), diag::note_declared_at); | ||||||
5040 | return nullptr; | ||||||
5041 | } | ||||||
5042 | |||||||
5043 | // If necessary, walk the rest of the path to determine the sequence of | ||||||
5044 | // covariant adjustment steps to apply. | ||||||
5045 | if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), | ||||||
5046 | Found->getReturnType())) { | ||||||
5047 | CovariantAdjustmentPath.push_back(Callee->getReturnType()); | ||||||
5048 | for (unsigned CovariantPathLength = PathLength + 1; | ||||||
5049 | CovariantPathLength != This.Designator.Entries.size(); | ||||||
5050 | ++CovariantPathLength) { | ||||||
5051 | const CXXRecordDecl *NextClass = | ||||||
5052 | getBaseClassType(This.Designator, CovariantPathLength); | ||||||
5053 | const CXXMethodDecl *Next = | ||||||
5054 | Found->getCorrespondingMethodDeclaredInClass(NextClass, false); | ||||||
5055 | if (Next && !Info.Ctx.hasSameUnqualifiedType( | ||||||
5056 | Next->getReturnType(), CovariantAdjustmentPath.back())) | ||||||
5057 | CovariantAdjustmentPath.push_back(Next->getReturnType()); | ||||||
5058 | } | ||||||
5059 | if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), | ||||||
5060 | CovariantAdjustmentPath.back())) | ||||||
5061 | CovariantAdjustmentPath.push_back(Found->getReturnType()); | ||||||
5062 | } | ||||||
5063 | |||||||
5064 | // Perform 'this' adjustment. | ||||||
5065 | if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) | ||||||
5066 | return nullptr; | ||||||
5067 | |||||||
5068 | return Callee; | ||||||
5069 | } | ||||||
5070 | |||||||
5071 | /// Perform the adjustment from a value returned by a virtual function to | ||||||
5072 | /// a value of the statically expected type, which may be a pointer or | ||||||
5073 | /// reference to a base class of the returned type. | ||||||
5074 | static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, | ||||||
5075 | APValue &Result, | ||||||
5076 | ArrayRef<QualType> Path) { | ||||||
5077 | assert(Result.isLValue() &&((Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? static_cast<void> (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5078, __PRETTY_FUNCTION__)) | ||||||
5078 | "unexpected kind of APValue for covariant return")((Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? static_cast<void> (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5078, __PRETTY_FUNCTION__)); | ||||||
5079 | if (Result.isNullPointer()) | ||||||
5080 | return true; | ||||||
5081 | |||||||
5082 | LValue LVal; | ||||||
5083 | LVal.setFrom(Info.Ctx, Result); | ||||||
5084 | |||||||
5085 | const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); | ||||||
5086 | for (unsigned I = 1; I != Path.size(); ++I) { | ||||||
5087 | const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); | ||||||
5088 | assert(OldClass && NewClass && "unexpected kind of covariant return")((OldClass && NewClass && "unexpected kind of covariant return" ) ? static_cast<void> (0) : __assert_fail ("OldClass && NewClass && \"unexpected kind of covariant return\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5088, __PRETTY_FUNCTION__)); | ||||||
5089 | if (OldClass != NewClass && | ||||||
5090 | !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) | ||||||
5091 | return false; | ||||||
5092 | OldClass = NewClass; | ||||||
5093 | } | ||||||
5094 | |||||||
5095 | LVal.moveInto(Result); | ||||||
5096 | return true; | ||||||
5097 | } | ||||||
5098 | |||||||
5099 | /// Determine whether \p Base, which is known to be a direct base class of | ||||||
5100 | /// \p Derived, is a public base class. | ||||||
5101 | static bool isBaseClassPublic(const CXXRecordDecl *Derived, | ||||||
5102 | const CXXRecordDecl *Base) { | ||||||
5103 | for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { | ||||||
5104 | auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); | ||||||
5105 | if (BaseClass && declaresSameEntity(BaseClass, Base)) | ||||||
5106 | return BaseSpec.getAccessSpecifier() == AS_public; | ||||||
5107 | } | ||||||
5108 | 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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5108); | ||||||
5109 | } | ||||||
5110 | |||||||
5111 | /// Apply the given dynamic cast operation on the provided lvalue. | ||||||
5112 | /// | ||||||
5113 | /// This implements the hard case of dynamic_cast, requiring a "runtime check" | ||||||
5114 | /// to find a suitable target subobject. | ||||||
5115 | static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, | ||||||
5116 | LValue &Ptr) { | ||||||
5117 | // We can't do anything with a non-symbolic pointer value. | ||||||
5118 | SubobjectDesignator &D = Ptr.Designator; | ||||||
5119 | if (D.Invalid) | ||||||
5120 | return false; | ||||||
5121 | |||||||
5122 | // C++ [expr.dynamic.cast]p6: | ||||||
5123 | // If v is a null pointer value, the result is a null pointer value. | ||||||
5124 | if (Ptr.isNullPointer() && !E->isGLValue()) | ||||||
5125 | return true; | ||||||
5126 | |||||||
5127 | // For all the other cases, we need the pointer to point to an object within | ||||||
5128 | // its lifetime / period of construction / destruction, and we need to know | ||||||
5129 | // its dynamic type. | ||||||
5130 | Optional<DynamicType> DynType = | ||||||
5131 | ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); | ||||||
5132 | if (!DynType) | ||||||
5133 | return false; | ||||||
5134 | |||||||
5135 | // C++ [expr.dynamic.cast]p7: | ||||||
5136 | // If T is "pointer to cv void", then the result is a pointer to the most | ||||||
5137 | // derived object | ||||||
5138 | if (E->getType()->isVoidPointerType()) | ||||||
5139 | return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); | ||||||
5140 | |||||||
5141 | const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); | ||||||
5142 | assert(C && "dynamic_cast target is not void pointer nor class")((C && "dynamic_cast target is not void pointer nor class" ) ? static_cast<void> (0) : __assert_fail ("C && \"dynamic_cast target is not void pointer nor class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5142, __PRETTY_FUNCTION__)); | ||||||
5143 | CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); | ||||||
5144 | |||||||
5145 | auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { | ||||||
5146 | // C++ [expr.dynamic.cast]p9: | ||||||
5147 | if (!E->isGLValue()) { | ||||||
5148 | // The value of a failed cast to pointer type is the null pointer value | ||||||
5149 | // of the required result type. | ||||||
5150 | auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); | ||||||
5151 | Ptr.setNull(E->getType(), TargetVal); | ||||||
5152 | return true; | ||||||
5153 | } | ||||||
5154 | |||||||
5155 | // A failed cast to reference type throws [...] std::bad_cast. | ||||||
5156 | unsigned DiagKind; | ||||||
5157 | if (!Paths && (declaresSameEntity(DynType->Type, C) || | ||||||
5158 | DynType->Type->isDerivedFrom(C))) | ||||||
5159 | DiagKind = 0; | ||||||
5160 | else if (!Paths || Paths->begin() == Paths->end()) | ||||||
5161 | DiagKind = 1; | ||||||
5162 | else if (Paths->isAmbiguous(CQT)) | ||||||
5163 | DiagKind = 2; | ||||||
5164 | else { | ||||||
5165 | assert(Paths->front().Access != AS_public && "why did the cast fail?")((Paths->front().Access != AS_public && "why did the cast fail?" ) ? static_cast<void> (0) : __assert_fail ("Paths->front().Access != AS_public && \"why did the cast fail?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5165, __PRETTY_FUNCTION__)); | ||||||
5166 | DiagKind = 3; | ||||||
5167 | } | ||||||
5168 | Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) | ||||||
5169 | << DiagKind << Ptr.Designator.getType(Info.Ctx) | ||||||
5170 | << Info.Ctx.getRecordType(DynType->Type) | ||||||
5171 | << E->getType().getUnqualifiedType(); | ||||||
5172 | return false; | ||||||
5173 | }; | ||||||
5174 | |||||||
5175 | // Runtime check, phase 1: | ||||||
5176 | // Walk from the base subobject towards the derived object looking for the | ||||||
5177 | // target type. | ||||||
5178 | for (int PathLength = Ptr.Designator.Entries.size(); | ||||||
5179 | PathLength >= (int)DynType->PathLength; --PathLength) { | ||||||
5180 | const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); | ||||||
5181 | if (declaresSameEntity(Class, C)) | ||||||
5182 | return CastToDerivedClass(Info, E, Ptr, Class, PathLength); | ||||||
5183 | // We can only walk across public inheritance edges. | ||||||
5184 | if (PathLength > (int)DynType->PathLength && | ||||||
5185 | !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), | ||||||
5186 | Class)) | ||||||
5187 | return RuntimeCheckFailed(nullptr); | ||||||
5188 | } | ||||||
5189 | |||||||
5190 | // Runtime check, phase 2: | ||||||
5191 | // Search the dynamic type for an unambiguous public base of type C. | ||||||
5192 | CXXBasePaths Paths(/*FindAmbiguities=*/true, | ||||||
5193 | /*RecordPaths=*/true, /*DetectVirtual=*/false); | ||||||
5194 | if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && | ||||||
5195 | Paths.front().Access == AS_public) { | ||||||
5196 | // Downcast to the dynamic type... | ||||||
5197 | if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) | ||||||
5198 | return false; | ||||||
5199 | // ... then upcast to the chosen base class subobject. | ||||||
5200 | for (CXXBasePathElement &Elem : Paths.front()) | ||||||
5201 | if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) | ||||||
5202 | return false; | ||||||
5203 | return true; | ||||||
5204 | } | ||||||
5205 | |||||||
5206 | // Otherwise, the runtime check fails. | ||||||
5207 | return RuntimeCheckFailed(&Paths); | ||||||
5208 | } | ||||||
5209 | |||||||
5210 | namespace { | ||||||
5211 | struct StartLifetimeOfUnionMemberHandler { | ||||||
5212 | const FieldDecl *Field; | ||||||
5213 | |||||||
5214 | static const AccessKinds AccessKind = AK_Assign; | ||||||
5215 | |||||||
5216 | typedef bool result_type; | ||||||
5217 | bool failed() { return false; } | ||||||
5218 | bool found(APValue &Subobj, QualType SubobjType) { | ||||||
5219 | // We are supposed to perform no initialization but begin the lifetime of | ||||||
5220 | // the object. We interpret that as meaning to do what default | ||||||
5221 | // initialization of the object would do if all constructors involved were | ||||||
5222 | // trivial: | ||||||
5223 | // * All base, non-variant member, and array element subobjects' lifetimes | ||||||
5224 | // begin | ||||||
5225 | // * No variant members' lifetimes begin | ||||||
5226 | // * All scalar subobjects whose lifetimes begin have indeterminate values | ||||||
5227 | assert(SubobjType->isUnionType())((SubobjType->isUnionType()) ? static_cast<void> (0) : __assert_fail ("SubobjType->isUnionType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5227, __PRETTY_FUNCTION__)); | ||||||
5228 | if (!declaresSameEntity(Subobj.getUnionField(), Field) || | ||||||
5229 | !Subobj.getUnionValue().hasValue()) | ||||||
5230 | Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); | ||||||
5231 | return true; | ||||||
5232 | } | ||||||
5233 | bool found(APSInt &Value, QualType SubobjType) { | ||||||
5234 | llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5234); | ||||||
5235 | } | ||||||
5236 | bool found(APFloat &Value, QualType SubobjType) { | ||||||
5237 | llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5237); | ||||||
5238 | } | ||||||
5239 | }; | ||||||
5240 | } // end anonymous namespace | ||||||
5241 | |||||||
5242 | const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; | ||||||
5243 | |||||||
5244 | /// Handle a builtin simple-assignment or a call to a trivial assignment | ||||||
5245 | /// operator whose left-hand side might involve a union member access. If it | ||||||
5246 | /// does, implicitly start the lifetime of any accessed union elements per | ||||||
5247 | /// C++20 [class.union]5. | ||||||
5248 | static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, | ||||||
5249 | const LValue &LHS) { | ||||||
5250 | if (LHS.InvalidBase || LHS.Designator.Invalid) | ||||||
5251 | return false; | ||||||
5252 | |||||||
5253 | llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; | ||||||
5254 | // C++ [class.union]p5: | ||||||
5255 | // define the set S(E) of subexpressions of E as follows: | ||||||
5256 | unsigned PathLength = LHS.Designator.Entries.size(); | ||||||
5257 | for (const Expr *E = LHSExpr; E != nullptr;) { | ||||||
5258 | // -- If E is of the form A.B, S(E) contains the elements of S(A)... | ||||||
5259 | if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||||
5260 | auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | ||||||
5261 | // Note that we can't implicitly start the lifetime of a reference, | ||||||
5262 | // so we don't need to proceed any further if we reach one. | ||||||
5263 | if (!FD || FD->getType()->isReferenceType()) | ||||||
5264 | break; | ||||||
5265 | |||||||
5266 | // ... and also contains A.B if B names a union member | ||||||
5267 | if (FD->getParent()->isUnion()) | ||||||
5268 | UnionPathLengths.push_back({PathLength - 1, FD}); | ||||||
5269 | |||||||
5270 | E = ME->getBase(); | ||||||
5271 | --PathLength; | ||||||
5272 | assert(declaresSameEntity(FD,((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] . getAsBaseOrMember().getPointer())) ? static_cast<void> ( 0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5274, __PRETTY_FUNCTION__)) | ||||||
5273 | LHS.Designator.Entries[PathLength]((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] . getAsBaseOrMember().getPointer())) ? static_cast<void> ( 0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5274, __PRETTY_FUNCTION__)) | ||||||
5274 | .getAsBaseOrMember().getPointer()))((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] . getAsBaseOrMember().getPointer())) ? static_cast<void> ( 0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5274, __PRETTY_FUNCTION__)); | ||||||
5275 | |||||||
5276 | // -- If E is of the form A[B] and is interpreted as a built-in array | ||||||
5277 | // subscripting operator, S(E) is [S(the array operand, if any)]. | ||||||
5278 | } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { | ||||||
5279 | // Step over an ArrayToPointerDecay implicit cast. | ||||||
5280 | auto *Base = ASE->getBase()->IgnoreImplicit(); | ||||||
5281 | if (!Base->getType()->isArrayType()) | ||||||
5282 | break; | ||||||
5283 | |||||||
5284 | E = Base; | ||||||
5285 | --PathLength; | ||||||
5286 | |||||||
5287 | } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { | ||||||
5288 | // Step over a derived-to-base conversion. | ||||||
5289 | E = ICE->getSubExpr(); | ||||||
5290 | if (ICE->getCastKind() == CK_NoOp) | ||||||
5291 | continue; | ||||||
5292 | if (ICE->getCastKind() != CK_DerivedToBase && | ||||||
5293 | ICE->getCastKind() != CK_UncheckedDerivedToBase) | ||||||
5294 | break; | ||||||
5295 | // Walk path backwards as we walk up from the base to the derived class. | ||||||
5296 | for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { | ||||||
5297 | --PathLength; | ||||||
5298 | (void)Elt; | ||||||
5299 | assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl (), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer ())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5301, __PRETTY_FUNCTION__)) | ||||||
5300 | LHS.Designator.Entries[PathLength]((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl (), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer ())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5301, __PRETTY_FUNCTION__)) | ||||||
5301 | .getAsBaseOrMember().getPointer()))((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl (), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer ())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5301, __PRETTY_FUNCTION__)); | ||||||
5302 | } | ||||||
5303 | |||||||
5304 | // -- Otherwise, S(E) is empty. | ||||||
5305 | } else { | ||||||
5306 | break; | ||||||
5307 | } | ||||||
5308 | } | ||||||
5309 | |||||||
5310 | // Common case: no unions' lifetimes are started. | ||||||
5311 | if (UnionPathLengths.empty()) | ||||||
5312 | return true; | ||||||
5313 | |||||||
5314 | // if modification of X [would access an inactive union member], an object | ||||||
5315 | // of the type of X is implicitly created | ||||||
5316 | CompleteObject Obj = | ||||||
5317 | findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); | ||||||
5318 | if (!Obj) | ||||||
5319 | return false; | ||||||
5320 | for (std::pair<unsigned, const FieldDecl *> LengthAndField : | ||||||
5321 | llvm::reverse(UnionPathLengths)) { | ||||||
5322 | // Form a designator for the union object. | ||||||
5323 | SubobjectDesignator D = LHS.Designator; | ||||||
5324 | D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); | ||||||
5325 | |||||||
5326 | StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; | ||||||
5327 | if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) | ||||||
5328 | return false; | ||||||
5329 | } | ||||||
5330 | |||||||
5331 | return true; | ||||||
5332 | } | ||||||
5333 | |||||||
5334 | /// Determine if a class has any fields that might need to be copied by a | ||||||
5335 | /// trivial copy or move operation. | ||||||
5336 | static bool hasFields(const CXXRecordDecl *RD) { | ||||||
5337 | if (!RD || RD->isEmpty()) | ||||||
5338 | return false; | ||||||
5339 | for (auto *FD : RD->fields()) { | ||||||
5340 | if (FD->isUnnamedBitfield()) | ||||||
5341 | continue; | ||||||
5342 | return true; | ||||||
5343 | } | ||||||
5344 | for (auto &Base : RD->bases()) | ||||||
5345 | if (hasFields(Base.getType()->getAsCXXRecordDecl())) | ||||||
5346 | return true; | ||||||
5347 | return false; | ||||||
5348 | } | ||||||
5349 | |||||||
5350 | namespace { | ||||||
5351 | typedef SmallVector<APValue, 8> ArgVector; | ||||||
5352 | } | ||||||
5353 | |||||||
5354 | /// EvaluateArgs - Evaluate the arguments to a function call. | ||||||
5355 | static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, | ||||||
5356 | EvalInfo &Info, const FunctionDecl *Callee) { | ||||||
5357 | bool Success = true; | ||||||
5358 | llvm::SmallBitVector ForbiddenNullArgs; | ||||||
5359 | if (Callee->hasAttr<NonNullAttr>()) { | ||||||
5360 | ForbiddenNullArgs.resize(Args.size()); | ||||||
5361 | for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { | ||||||
5362 | if (!Attr->args_size()) { | ||||||
5363 | ForbiddenNullArgs.set(); | ||||||
5364 | break; | ||||||
5365 | } else | ||||||
5366 | for (auto Idx : Attr->args()) { | ||||||
5367 | unsigned ASTIdx = Idx.getASTIndex(); | ||||||
5368 | if (ASTIdx >= Args.size()) | ||||||
5369 | continue; | ||||||
5370 | ForbiddenNullArgs[ASTIdx] = 1; | ||||||
5371 | } | ||||||
5372 | } | ||||||
5373 | } | ||||||
5374 | for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); | ||||||
5375 | I != E; ++I) { | ||||||
5376 | if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { | ||||||
5377 | // If we're checking for a potential constant expression, evaluate all | ||||||
5378 | // initializers even if some of them fail. | ||||||
5379 | if (!Info.noteFailure()) | ||||||
5380 | return false; | ||||||
5381 | Success = false; | ||||||
5382 | } else if (!ForbiddenNullArgs.empty() && | ||||||
5383 | ForbiddenNullArgs[I - Args.begin()] && | ||||||
5384 | ArgValues[I - Args.begin()].isNullPointer()) { | ||||||
5385 | Info.CCEDiag(*I, diag::note_non_null_attribute_failed); | ||||||
5386 | if (!Info.noteFailure()) | ||||||
5387 | return false; | ||||||
5388 | Success = false; | ||||||
5389 | } | ||||||
5390 | } | ||||||
5391 | return Success; | ||||||
5392 | } | ||||||
5393 | |||||||
5394 | /// Evaluate a function call. | ||||||
5395 | static bool HandleFunctionCall(SourceLocation CallLoc, | ||||||
5396 | const FunctionDecl *Callee, const LValue *This, | ||||||
5397 | ArrayRef<const Expr*> Args, const Stmt *Body, | ||||||
5398 | EvalInfo &Info, APValue &Result, | ||||||
5399 | const LValue *ResultSlot) { | ||||||
5400 | ArgVector ArgValues(Args.size()); | ||||||
5401 | if (!EvaluateArgs(Args, ArgValues, Info, Callee)) | ||||||
5402 | return false; | ||||||
5403 | |||||||
5404 | if (!Info.CheckCallLimit(CallLoc)) | ||||||
5405 | return false; | ||||||
5406 | |||||||
5407 | CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); | ||||||
5408 | |||||||
5409 | // For a trivial copy or move assignment, perform an APValue copy. This is | ||||||
5410 | // essential for unions, where the operations performed by the assignment | ||||||
5411 | // operator cannot be represented as statements. | ||||||
5412 | // | ||||||
5413 | // Skip this for non-union classes with no fields; in that case, the defaulted | ||||||
5414 | // copy/move does not actually read the object. | ||||||
5415 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); | ||||||
5416 | if (MD && MD->isDefaulted() && | ||||||
5417 | (MD->getParent()->isUnion() || | ||||||
5418 | (MD->isTrivial() && hasFields(MD->getParent())))) { | ||||||
5419 | assert(This &&((This && (MD->isCopyAssignmentOperator() || MD-> isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail ("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5420, __PRETTY_FUNCTION__)) | ||||||
5420 | (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))((This && (MD->isCopyAssignmentOperator() || MD-> isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail ("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5420, __PRETTY_FUNCTION__)); | ||||||
5421 | LValue RHS; | ||||||
5422 | RHS.setFrom(Info.Ctx, ArgValues[0]); | ||||||
5423 | APValue RHSValue; | ||||||
5424 | if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, | ||||||
5425 | RHSValue, MD->getParent()->isUnion())) | ||||||
5426 | return false; | ||||||
5427 | if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && | ||||||
5428 | !HandleUnionActiveMemberChange(Info, Args[0], *This)) | ||||||
5429 | return false; | ||||||
5430 | if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), | ||||||
5431 | RHSValue)) | ||||||
5432 | return false; | ||||||
5433 | This->moveInto(Result); | ||||||
5434 | return true; | ||||||
5435 | } else if (MD && isLambdaCallOperator(MD)) { | ||||||
5436 | // We're in a lambda; determine the lambda capture field maps unless we're | ||||||
5437 | // just constexpr checking a lambda's call operator. constexpr checking is | ||||||
5438 | // done before the captures have been added to the closure object (unless | ||||||
5439 | // we're inferring constexpr-ness), so we don't have access to them in this | ||||||
5440 | // case. But since we don't need the captures to constexpr check, we can | ||||||
5441 | // just ignore them. | ||||||
5442 | if (!Info.checkingPotentialConstantExpression()) | ||||||
5443 | MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, | ||||||
5444 | Frame.LambdaThisCaptureField); | ||||||
5445 | } | ||||||
5446 | |||||||
5447 | StmtResult Ret = {Result, ResultSlot}; | ||||||
5448 | EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); | ||||||
5449 | if (ESR == ESR_Succeeded) { | ||||||
5450 | if (Callee->getReturnType()->isVoidType()) | ||||||
5451 | return true; | ||||||
5452 | Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); | ||||||
5453 | } | ||||||
5454 | return ESR == ESR_Returned; | ||||||
5455 | } | ||||||
5456 | |||||||
5457 | /// Evaluate a constructor call. | ||||||
5458 | static bool HandleConstructorCall(const Expr *E, const LValue &This, | ||||||
5459 | APValue *ArgValues, | ||||||
5460 | const CXXConstructorDecl *Definition, | ||||||
5461 | EvalInfo &Info, APValue &Result) { | ||||||
5462 | SourceLocation CallLoc = E->getExprLoc(); | ||||||
5463 | if (!Info.CheckCallLimit(CallLoc)) | ||||||
5464 | return false; | ||||||
5465 | |||||||
5466 | const CXXRecordDecl *RD = Definition->getParent(); | ||||||
5467 | if (RD->getNumVBases()) { | ||||||
5468 | Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; | ||||||
5469 | return false; | ||||||
5470 | } | ||||||
5471 | |||||||
5472 | EvalInfo::EvaluatingConstructorRAII EvalObj( | ||||||
5473 | Info, | ||||||
5474 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, | ||||||
5475 | RD->getNumBases()); | ||||||
5476 | CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); | ||||||
5477 | |||||||
5478 | // FIXME: Creating an APValue just to hold a nonexistent return value is | ||||||
5479 | // wasteful. | ||||||
5480 | APValue RetVal; | ||||||
5481 | StmtResult Ret = {RetVal, nullptr}; | ||||||
5482 | |||||||
5483 | // If it's a delegating constructor, delegate. | ||||||
5484 | if (Definition->isDelegatingConstructor()) { | ||||||
5485 | CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); | ||||||
5486 | { | ||||||
5487 | FullExpressionRAII InitScope(Info); | ||||||
5488 | if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || | ||||||
5489 | !InitScope.destroy()) | ||||||
5490 | return false; | ||||||
5491 | } | ||||||
5492 | return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; | ||||||
5493 | } | ||||||
5494 | |||||||
5495 | // For a trivial copy or move constructor, perform an APValue copy. This is | ||||||
5496 | // essential for unions (or classes with anonymous union members), where the | ||||||
5497 | // operations performed by the constructor cannot be represented by | ||||||
5498 | // ctor-initializers. | ||||||
5499 | // | ||||||
5500 | // Skip this for empty non-union classes; we should not perform an | ||||||
5501 | // lvalue-to-rvalue conversion on them because their copy constructor does not | ||||||
5502 | // actually read them. | ||||||
5503 | if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && | ||||||
5504 | (Definition->getParent()->isUnion() || | ||||||
5505 | (Definition->isTrivial() && hasFields(Definition->getParent())))) { | ||||||
5506 | LValue RHS; | ||||||
5507 | RHS.setFrom(Info.Ctx, ArgValues[0]); | ||||||
5508 | return handleLValueToRValueConversion( | ||||||
5509 | Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), | ||||||
5510 | RHS, Result, Definition->getParent()->isUnion()); | ||||||
5511 | } | ||||||
5512 | |||||||
5513 | // Reserve space for the struct members. | ||||||
5514 | if (!RD->isUnion() && !Result.hasValue()) | ||||||
5515 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), | ||||||
5516 | std::distance(RD->field_begin(), RD->field_end())); | ||||||
5517 | |||||||
5518 | if (RD->isInvalidDecl()) return false; | ||||||
5519 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||||
5520 | |||||||
5521 | // A scope for temporaries lifetime-extended by reference members. | ||||||
5522 | BlockScopeRAII LifetimeExtendedScope(Info); | ||||||
5523 | |||||||
5524 | bool Success = true; | ||||||
5525 | unsigned BasesSeen = 0; | ||||||
5526 | #ifndef NDEBUG | ||||||
5527 | CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); | ||||||
5528 | #endif | ||||||
5529 | CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); | ||||||
5530 | auto SkipToField = [&](FieldDecl *FD, bool Indirect) { | ||||||
5531 | // We might be initializing the same field again if this is an indirect | ||||||
5532 | // field initialization. | ||||||
5533 | if (FieldIt == RD->field_end() || | ||||||
5534 | FieldIt->getFieldIndex() > FD->getFieldIndex()) { | ||||||
5535 | assert(Indirect && "fields out of order?")((Indirect && "fields out of order?") ? static_cast< void> (0) : __assert_fail ("Indirect && \"fields out of order?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5535, __PRETTY_FUNCTION__)); | ||||||
5536 | return; | ||||||
5537 | } | ||||||
5538 | |||||||
5539 | // Default-initialize any fields with no explicit initializer. | ||||||
5540 | for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { | ||||||
5541 | assert(FieldIt != RD->field_end() && "missing field?")((FieldIt != RD->field_end() && "missing field?") ? static_cast<void> (0) : __assert_fail ("FieldIt != RD->field_end() && \"missing field?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5541, __PRETTY_FUNCTION__)); | ||||||
5542 | if (!FieldIt->isUnnamedBitfield()) | ||||||
5543 | Result.getStructField(FieldIt->getFieldIndex()) = | ||||||
5544 | getDefaultInitValue(FieldIt->getType()); | ||||||
5545 | } | ||||||
5546 | ++FieldIt; | ||||||
5547 | }; | ||||||
5548 | for (const auto *I : Definition->inits()) { | ||||||
5549 | LValue Subobject = This; | ||||||
5550 | LValue SubobjectParent = This; | ||||||
5551 | APValue *Value = &Result; | ||||||
5552 | |||||||
5553 | // Determine the subobject to initialize. | ||||||
5554 | FieldDecl *FD = nullptr; | ||||||
5555 | if (I->isBaseInitializer()) { | ||||||
5556 | QualType BaseType(I->getBaseClass(), 0); | ||||||
5557 | #ifndef NDEBUG | ||||||
5558 | // Non-virtual base classes are initialized in the order in the class | ||||||
5559 | // definition. We have already checked for virtual base classes. | ||||||
5560 | assert(!BaseIt->isVirtual() && "virtual base for literal type")((!BaseIt->isVirtual() && "virtual base for literal type" ) ? static_cast<void> (0) : __assert_fail ("!BaseIt->isVirtual() && \"virtual base for literal type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5560, __PRETTY_FUNCTION__)); | ||||||
5561 | assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&((Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && "base class initializers not in expected order") ? static_cast <void> (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5562, __PRETTY_FUNCTION__)) | ||||||
5562 | "base class initializers not in expected order")((Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && "base class initializers not in expected order") ? static_cast <void> (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5562, __PRETTY_FUNCTION__)); | ||||||
5563 | ++BaseIt; | ||||||
5564 | #endif | ||||||
5565 | if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, | ||||||
5566 | BaseType->getAsCXXRecordDecl(), &Layout)) | ||||||
5567 | return false; | ||||||
5568 | Value = &Result.getStructBase(BasesSeen++); | ||||||
5569 | } else if ((FD = I->getMember())) { | ||||||
5570 | if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) | ||||||
5571 | return false; | ||||||
5572 | if (RD->isUnion()) { | ||||||
5573 | Result = APValue(FD); | ||||||
5574 | Value = &Result.getUnionValue(); | ||||||
5575 | } else { | ||||||
5576 | SkipToField(FD, false); | ||||||
5577 | Value = &Result.getStructField(FD->getFieldIndex()); | ||||||
5578 | } | ||||||
5579 | } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { | ||||||
5580 | // Walk the indirect field decl's chain to find the object to initialize, | ||||||
5581 | // and make sure we've initialized every step along it. | ||||||
5582 | auto IndirectFieldChain = IFD->chain(); | ||||||
5583 | for (auto *C : IndirectFieldChain) { | ||||||
5584 | FD = cast<FieldDecl>(C); | ||||||
5585 | CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); | ||||||
5586 | // Switch the union field if it differs. This happens if we had | ||||||
5587 | // preceding zero-initialization, and we're now initializing a union | ||||||
5588 | // subobject other than the first. | ||||||
5589 | // FIXME: In this case, the values of the other subobjects are | ||||||
5590 | // specified, since zero-initialization sets all padding bits to zero. | ||||||
5591 | if (!Value->hasValue() || | ||||||
5592 | (Value->isUnion() && Value->getUnionField() != FD)) { | ||||||
5593 | if (CD->isUnion()) | ||||||
5594 | *Value = APValue(FD); | ||||||
5595 | else | ||||||
5596 | // FIXME: This immediately starts the lifetime of all members of an | ||||||
5597 | // anonymous struct. It would be preferable to strictly start member | ||||||
5598 | // lifetime in initialization order. | ||||||
5599 | *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD)); | ||||||
5600 | } | ||||||
5601 | // Store Subobject as its parent before updating it for the last element | ||||||
5602 | // in the chain. | ||||||
5603 | if (C == IndirectFieldChain.back()) | ||||||
5604 | SubobjectParent = Subobject; | ||||||
5605 | if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) | ||||||
5606 | return false; | ||||||
5607 | if (CD->isUnion()) | ||||||
5608 | Value = &Value->getUnionValue(); | ||||||
5609 | else { | ||||||
5610 | if (C == IndirectFieldChain.front() && !RD->isUnion()) | ||||||
5611 | SkipToField(FD, true); | ||||||
5612 | Value = &Value->getStructField(FD->getFieldIndex()); | ||||||
5613 | } | ||||||
5614 | } | ||||||
5615 | } else { | ||||||
5616 | llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5616); | ||||||
5617 | } | ||||||
5618 | |||||||
5619 | // Need to override This for implicit field initializers as in this case | ||||||
5620 | // This refers to innermost anonymous struct/union containing initializer, | ||||||
5621 | // not to currently constructed class. | ||||||
5622 | const Expr *Init = I->getInit(); | ||||||
5623 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, | ||||||
5624 | isa<CXXDefaultInitExpr>(Init)); | ||||||
5625 | FullExpressionRAII InitScope(Info); | ||||||
5626 | if (!EvaluateInPlace(*Value, Info, Subobject, Init) || | ||||||
5627 | (FD && FD->isBitField() && | ||||||
5628 | !truncateBitfieldValue(Info, Init, *Value, FD))) { | ||||||
5629 | // If we're checking for a potential constant expression, evaluate all | ||||||
5630 | // initializers even if some of them fail. | ||||||
5631 | if (!Info.noteFailure()) | ||||||
5632 | return false; | ||||||
5633 | Success = false; | ||||||
5634 | } | ||||||
5635 | |||||||
5636 | // This is the point at which the dynamic type of the object becomes this | ||||||
5637 | // class type. | ||||||
5638 | if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) | ||||||
5639 | EvalObj.finishedConstructingBases(); | ||||||
5640 | } | ||||||
5641 | |||||||
5642 | // Default-initialize any remaining fields. | ||||||
5643 | if (!RD->isUnion()) { | ||||||
5644 | for (; FieldIt != RD->field_end(); ++FieldIt) { | ||||||
5645 | if (!FieldIt->isUnnamedBitfield()) | ||||||
5646 | Result.getStructField(FieldIt->getFieldIndex()) = | ||||||
5647 | getDefaultInitValue(FieldIt->getType()); | ||||||
5648 | } | ||||||
5649 | } | ||||||
5650 | |||||||
5651 | return Success && | ||||||
5652 | EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && | ||||||
5653 | LifetimeExtendedScope.destroy(); | ||||||
5654 | } | ||||||
5655 | |||||||
5656 | static bool HandleConstructorCall(const Expr *E, const LValue &This, | ||||||
5657 | ArrayRef<const Expr*> Args, | ||||||
5658 | const CXXConstructorDecl *Definition, | ||||||
5659 | EvalInfo &Info, APValue &Result) { | ||||||
5660 | ArgVector ArgValues(Args.size()); | ||||||
5661 | if (!EvaluateArgs(Args, ArgValues, Info, Definition)) | ||||||
5662 | return false; | ||||||
5663 | |||||||
5664 | return HandleConstructorCall(E, This, ArgValues.data(), Definition, | ||||||
5665 | Info, Result); | ||||||
5666 | } | ||||||
5667 | |||||||
5668 | static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, | ||||||
5669 | const LValue &This, APValue &Value, | ||||||
5670 | QualType T) { | ||||||
5671 | // Objects can only be destroyed while they're within their lifetimes. | ||||||
5672 | // FIXME: We have no representation for whether an object of type nullptr_t | ||||||
5673 | // is in its lifetime; it usually doesn't matter. Perhaps we should model it | ||||||
5674 | // as indeterminate instead? | ||||||
5675 | if (Value.isAbsent() && !T->isNullPtrType()) { | ||||||
5676 | APValue Printable; | ||||||
5677 | This.moveInto(Printable); | ||||||
5678 | Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) | ||||||
5679 | << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); | ||||||
5680 | return false; | ||||||
5681 | } | ||||||
5682 | |||||||
5683 | // Invent an expression for location purposes. | ||||||
5684 | // FIXME: We shouldn't need to do this. | ||||||
5685 | OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); | ||||||
5686 | |||||||
5687 | // For arrays, destroy elements right-to-left. | ||||||
5688 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { | ||||||
5689 | uint64_t Size = CAT->getSize().getZExtValue(); | ||||||
5690 | QualType ElemT = CAT->getElementType(); | ||||||
5691 | |||||||
5692 | LValue ElemLV = This; | ||||||
5693 | ElemLV.addArray(Info, &LocE, CAT); | ||||||
5694 | if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) | ||||||
5695 | return false; | ||||||
5696 | |||||||
5697 | // Ensure that we have actual array elements available to destroy; the | ||||||
5698 | // destructors might mutate the value, so we can't run them on the array | ||||||
5699 | // filler. | ||||||
5700 | if (Size && Size > Value.getArrayInitializedElts()) | ||||||
5701 | expandArray(Value, Value.getArraySize() - 1); | ||||||
5702 | |||||||
5703 | for (; Size != 0; --Size) { | ||||||
5704 | APValue &Elem = Value.getArrayInitializedElt(Size - 1); | ||||||
5705 | if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || | ||||||
5706 | !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) | ||||||
5707 | return false; | ||||||
5708 | } | ||||||
5709 | |||||||
5710 | // End the lifetime of this array now. | ||||||
5711 | Value = APValue(); | ||||||
5712 | return true; | ||||||
5713 | } | ||||||
5714 | |||||||
5715 | const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); | ||||||
5716 | if (!RD) { | ||||||
5717 | if (T.isDestructedType()) { | ||||||
5718 | Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; | ||||||
5719 | return false; | ||||||
5720 | } | ||||||
5721 | |||||||
5722 | Value = APValue(); | ||||||
5723 | return true; | ||||||
5724 | } | ||||||
5725 | |||||||
5726 | if (RD->getNumVBases()) { | ||||||
5727 | Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; | ||||||
5728 | return false; | ||||||
5729 | } | ||||||
5730 | |||||||
5731 | const CXXDestructorDecl *DD = RD->getDestructor(); | ||||||
5732 | if (!DD && !RD->hasTrivialDestructor()) { | ||||||
5733 | Info.FFDiag(CallLoc); | ||||||
5734 | return false; | ||||||
5735 | } | ||||||
5736 | |||||||
5737 | if (!DD || DD->isTrivial() || | ||||||
5738 | (RD->isAnonymousStructOrUnion() && RD->isUnion())) { | ||||||
5739 | // A trivial destructor just ends the lifetime of the object. Check for | ||||||
5740 | // this case before checking for a body, because we might not bother | ||||||
5741 | // building a body for a trivial destructor. Note that it doesn't matter | ||||||
5742 | // whether the destructor is constexpr in this case; all trivial | ||||||
5743 | // destructors are constexpr. | ||||||
5744 | // | ||||||
5745 | // If an anonymous union would be destroyed, some enclosing destructor must | ||||||
5746 | // have been explicitly defined, and the anonymous union destruction should | ||||||
5747 | // have no effect. | ||||||
5748 | Value = APValue(); | ||||||
5749 | return true; | ||||||
5750 | } | ||||||
5751 | |||||||
5752 | if (!Info.CheckCallLimit(CallLoc)) | ||||||
5753 | return false; | ||||||
5754 | |||||||
5755 | const FunctionDecl *Definition = nullptr; | ||||||
5756 | const Stmt *Body = DD->getBody(Definition); | ||||||
5757 | |||||||
5758 | if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) | ||||||
5759 | return false; | ||||||
5760 | |||||||
5761 | CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); | ||||||
5762 | |||||||
5763 | // We're now in the period of destruction of this object. | ||||||
5764 | unsigned BasesLeft = RD->getNumBases(); | ||||||
5765 | EvalInfo::EvaluatingDestructorRAII EvalObj( | ||||||
5766 | Info, | ||||||
5767 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); | ||||||
5768 | if (!EvalObj.DidInsert) { | ||||||
5769 | // C++2a [class.dtor]p19: | ||||||
5770 | // the behavior is undefined if the destructor is invoked for an object | ||||||
5771 | // whose lifetime has ended | ||||||
5772 | // (Note that formally the lifetime ends when the period of destruction | ||||||
5773 | // begins, even though certain uses of the object remain valid until the | ||||||
5774 | // period of destruction ends.) | ||||||
5775 | Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); | ||||||
5776 | return false; | ||||||
5777 | } | ||||||
5778 | |||||||
5779 | // FIXME: Creating an APValue just to hold a nonexistent return value is | ||||||
5780 | // wasteful. | ||||||
5781 | APValue RetVal; | ||||||
5782 | StmtResult Ret = {RetVal, nullptr}; | ||||||
5783 | if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) | ||||||
5784 | return false; | ||||||
5785 | |||||||
5786 | // A union destructor does not implicitly destroy its members. | ||||||
5787 | if (RD->isUnion()) | ||||||
5788 | return true; | ||||||
5789 | |||||||
5790 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||||
5791 | |||||||
5792 | // We don't have a good way to iterate fields in reverse, so collect all the | ||||||
5793 | // fields first and then walk them backwards. | ||||||
5794 | SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); | ||||||
5795 | for (const FieldDecl *FD : llvm::reverse(Fields)) { | ||||||
5796 | if (FD->isUnnamedBitfield()) | ||||||
5797 | continue; | ||||||
5798 | |||||||
5799 | LValue Subobject = This; | ||||||
5800 | if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) | ||||||
5801 | return false; | ||||||
5802 | |||||||
5803 | APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); | ||||||
5804 | if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, | ||||||
5805 | FD->getType())) | ||||||
5806 | return false; | ||||||
5807 | } | ||||||
5808 | |||||||
5809 | if (BasesLeft != 0) | ||||||
5810 | EvalObj.startedDestroyingBases(); | ||||||
5811 | |||||||
5812 | // Destroy base classes in reverse order. | ||||||
5813 | for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { | ||||||
5814 | --BasesLeft; | ||||||
5815 | |||||||
5816 | QualType BaseType = Base.getType(); | ||||||
5817 | LValue Subobject = This; | ||||||
5818 | if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, | ||||||
5819 | BaseType->getAsCXXRecordDecl(), &Layout)) | ||||||
5820 | return false; | ||||||
5821 | |||||||
5822 | APValue *SubobjectValue = &Value.getStructBase(BasesLeft); | ||||||
5823 | if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, | ||||||
5824 | BaseType)) | ||||||
5825 | return false; | ||||||
5826 | } | ||||||
5827 | assert(BasesLeft == 0 && "NumBases was wrong?")((BasesLeft == 0 && "NumBases was wrong?") ? static_cast <void> (0) : __assert_fail ("BasesLeft == 0 && \"NumBases was wrong?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5827, __PRETTY_FUNCTION__)); | ||||||
5828 | |||||||
5829 | // The period of destruction ends now. The object is gone. | ||||||
5830 | Value = APValue(); | ||||||
5831 | return true; | ||||||
5832 | } | ||||||
5833 | |||||||
5834 | namespace { | ||||||
5835 | struct DestroyObjectHandler { | ||||||
5836 | EvalInfo &Info; | ||||||
5837 | const Expr *E; | ||||||
5838 | const LValue &This; | ||||||
5839 | const AccessKinds AccessKind; | ||||||
5840 | |||||||
5841 | typedef bool result_type; | ||||||
5842 | bool failed() { return false; } | ||||||
5843 | bool found(APValue &Subobj, QualType SubobjType) { | ||||||
5844 | return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, | ||||||
5845 | SubobjType); | ||||||
5846 | } | ||||||
5847 | bool found(APSInt &Value, QualType SubobjType) { | ||||||
5848 | Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); | ||||||
5849 | return false; | ||||||
5850 | } | ||||||
5851 | bool found(APFloat &Value, QualType SubobjType) { | ||||||
5852 | Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); | ||||||
5853 | return false; | ||||||
5854 | } | ||||||
5855 | }; | ||||||
5856 | } | ||||||
5857 | |||||||
5858 | /// Perform a destructor or pseudo-destructor call on the given object, which | ||||||
5859 | /// might in general not be a complete object. | ||||||
5860 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, | ||||||
5861 | const LValue &This, QualType ThisType) { | ||||||
5862 | CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); | ||||||
5863 | DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; | ||||||
5864 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); | ||||||
5865 | } | ||||||
5866 | |||||||
5867 | /// Destroy and end the lifetime of the given complete object. | ||||||
5868 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, | ||||||
5869 | APValue::LValueBase LVBase, APValue &Value, | ||||||
5870 | QualType T) { | ||||||
5871 | // If we've had an unmodeled side-effect, we can't rely on mutable state | ||||||
5872 | // (such as the object we're about to destroy) being correct. | ||||||
5873 | if (Info.EvalStatus.HasSideEffects) | ||||||
5874 | return false; | ||||||
5875 | |||||||
5876 | LValue LV; | ||||||
5877 | LV.set({LVBase}); | ||||||
5878 | return HandleDestructionImpl(Info, Loc, LV, Value, T); | ||||||
5879 | } | ||||||
5880 | |||||||
5881 | //===----------------------------------------------------------------------===// | ||||||
5882 | // Generic Evaluation | ||||||
5883 | //===----------------------------------------------------------------------===// | ||||||
5884 | namespace { | ||||||
5885 | |||||||
5886 | class BitCastBuffer { | ||||||
5887 | // FIXME: We're going to need bit-level granularity when we support | ||||||
5888 | // bit-fields. | ||||||
5889 | // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but | ||||||
5890 | // we don't support a host or target where that is the case. Still, we should | ||||||
5891 | // use a more generic type in case we ever do. | ||||||
5892 | SmallVector<Optional<unsigned char>, 32> Bytes; | ||||||
5893 | |||||||
5894 | static_assert(std::numeric_limits<unsigned char>::digits >= 8, | ||||||
5895 | "Need at least 8 bit unsigned char"); | ||||||
5896 | |||||||
5897 | bool TargetIsLittleEndian; | ||||||
5898 | |||||||
5899 | public: | ||||||
5900 | BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) | ||||||
5901 | : Bytes(Width.getQuantity()), | ||||||
5902 | TargetIsLittleEndian(TargetIsLittleEndian) {} | ||||||
5903 | |||||||
5904 | LLVM_NODISCARD[[clang::warn_unused_result]] | ||||||
5905 | bool readObject(CharUnits Offset, CharUnits Width, | ||||||
5906 | SmallVectorImpl<unsigned char> &Output) const { | ||||||
5907 | for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { | ||||||
5908 | // If a byte of an integer is uninitialized, then the whole integer is | ||||||
5909 | // uninitalized. | ||||||
5910 | if (!Bytes[I.getQuantity()]) | ||||||
5911 | return false; | ||||||
5912 | Output.push_back(*Bytes[I.getQuantity()]); | ||||||
5913 | } | ||||||
5914 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) | ||||||
5915 | std::reverse(Output.begin(), Output.end()); | ||||||
5916 | return true; | ||||||
5917 | } | ||||||
5918 | |||||||
5919 | void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { | ||||||
5920 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) | ||||||
5921 | std::reverse(Input.begin(), Input.end()); | ||||||
5922 | |||||||
5923 | size_t Index = 0; | ||||||
5924 | for (unsigned char Byte : Input) { | ||||||
5925 | assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?")((!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?" ) ? static_cast<void> (0) : __assert_fail ("!Bytes[Offset.getQuantity() + Index] && \"overwriting a byte?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5925, __PRETTY_FUNCTION__)); | ||||||
5926 | Bytes[Offset.getQuantity() + Index] = Byte; | ||||||
5927 | ++Index; | ||||||
5928 | } | ||||||
5929 | } | ||||||
5930 | |||||||
5931 | size_t size() { return Bytes.size(); } | ||||||
5932 | }; | ||||||
5933 | |||||||
5934 | /// Traverse an APValue to produce an BitCastBuffer, emulating how the current | ||||||
5935 | /// target would represent the value at runtime. | ||||||
5936 | class APValueToBufferConverter { | ||||||
5937 | EvalInfo &Info; | ||||||
5938 | BitCastBuffer Buffer; | ||||||
5939 | const CastExpr *BCE; | ||||||
5940 | |||||||
5941 | APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, | ||||||
5942 | const CastExpr *BCE) | ||||||
5943 | : Info(Info), | ||||||
5944 | Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), | ||||||
5945 | BCE(BCE) {} | ||||||
5946 | |||||||
5947 | bool visit(const APValue &Val, QualType Ty) { | ||||||
5948 | return visit(Val, Ty, CharUnits::fromQuantity(0)); | ||||||
5949 | } | ||||||
5950 | |||||||
5951 | // Write out Val with type Ty into Buffer starting at Offset. | ||||||
5952 | bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||||
5953 | assert((size_t)Offset.getQuantity() <= Buffer.size())(((size_t)Offset.getQuantity() <= Buffer.size()) ? static_cast <void> (0) : __assert_fail ("(size_t)Offset.getQuantity() <= Buffer.size()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5953, __PRETTY_FUNCTION__)); | ||||||
5954 | |||||||
5955 | // As a special case, nullptr_t has an indeterminate value. | ||||||
5956 | if (Ty->isNullPtrType()) | ||||||
5957 | return true; | ||||||
5958 | |||||||
5959 | // Dig through Src to find the byte at SrcOffset. | ||||||
5960 | switch (Val.getKind()) { | ||||||
5961 | case APValue::Indeterminate: | ||||||
5962 | case APValue::None: | ||||||
5963 | return true; | ||||||
5964 | |||||||
5965 | case APValue::Int: | ||||||
5966 | return visitInt(Val.getInt(), Ty, Offset); | ||||||
5967 | case APValue::Float: | ||||||
5968 | return visitFloat(Val.getFloat(), Ty, Offset); | ||||||
5969 | case APValue::Array: | ||||||
5970 | return visitArray(Val, Ty, Offset); | ||||||
5971 | case APValue::Struct: | ||||||
5972 | return visitRecord(Val, Ty, Offset); | ||||||
5973 | |||||||
5974 | case APValue::ComplexInt: | ||||||
5975 | case APValue::ComplexFloat: | ||||||
5976 | case APValue::Vector: | ||||||
5977 | case APValue::FixedPoint: | ||||||
5978 | // FIXME: We should support these. | ||||||
5979 | |||||||
5980 | case APValue::Union: | ||||||
5981 | case APValue::MemberPointer: | ||||||
5982 | case APValue::AddrLabelDiff: { | ||||||
5983 | Info.FFDiag(BCE->getBeginLoc(), | ||||||
5984 | diag::note_constexpr_bit_cast_unsupported_type) | ||||||
5985 | << Ty; | ||||||
5986 | return false; | ||||||
5987 | } | ||||||
5988 | |||||||
5989 | case APValue::LValue: | ||||||
5990 | llvm_unreachable("LValue subobject in bit_cast?")::llvm::llvm_unreachable_internal("LValue subobject in bit_cast?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5990); | ||||||
5991 | } | ||||||
5992 | llvm_unreachable("Unhandled APValue::ValueKind")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5992); | ||||||
5993 | } | ||||||
5994 | |||||||
5995 | bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||||
5996 | const RecordDecl *RD = Ty->getAsRecordDecl(); | ||||||
5997 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||||
5998 | |||||||
5999 | // Visit the base classes. | ||||||
6000 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||||
6001 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { | ||||||
6002 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; | ||||||
6003 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | ||||||
6004 | |||||||
6005 | if (!visitRecord(Val.getStructBase(I), BS.getType(), | ||||||
6006 | Layout.getBaseClassOffset(BaseDecl) + Offset)) | ||||||
6007 | return false; | ||||||
6008 | } | ||||||
6009 | } | ||||||
6010 | |||||||
6011 | // Visit the fields. | ||||||
6012 | unsigned FieldIdx = 0; | ||||||
6013 | for (FieldDecl *FD : RD->fields()) { | ||||||
6014 | if (FD->isBitField()) { | ||||||
6015 | Info.FFDiag(BCE->getBeginLoc(), | ||||||
6016 | diag::note_constexpr_bit_cast_unsupported_bitfield); | ||||||
6017 | return false; | ||||||
6018 | } | ||||||
6019 | |||||||
6020 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); | ||||||
6021 | |||||||
6022 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&((FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && "only bit-fields can have sub-char alignment" ) ? static_cast<void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6023, __PRETTY_FUNCTION__)) | ||||||
6023 | "only bit-fields can have sub-char alignment")((FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && "only bit-fields can have sub-char alignment" ) ? static_cast<void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6023, __PRETTY_FUNCTION__)); | ||||||
6024 | CharUnits FieldOffset = | ||||||
6025 | Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; | ||||||
6026 | QualType FieldTy = FD->getType(); | ||||||
6027 | if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) | ||||||
6028 | return false; | ||||||
6029 | ++FieldIdx; | ||||||
6030 | } | ||||||
6031 | |||||||
6032 | return true; | ||||||
6033 | } | ||||||
6034 | |||||||
6035 | bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||||
6036 | const auto *CAT = | ||||||
6037 | dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); | ||||||
6038 | if (!CAT) | ||||||
6039 | return false; | ||||||
6040 | |||||||
6041 | CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); | ||||||
6042 | unsigned NumInitializedElts = Val.getArrayInitializedElts(); | ||||||
6043 | unsigned ArraySize = Val.getArraySize(); | ||||||
6044 | // First, initialize the initialized elements. | ||||||
6045 | for (unsigned I = 0; I != NumInitializedElts; ++I) { | ||||||
6046 | const APValue &SubObj = Val.getArrayInitializedElt(I); | ||||||
6047 | if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) | ||||||
6048 | return false; | ||||||
6049 | } | ||||||
6050 | |||||||
6051 | // Next, initialize the rest of the array using the filler. | ||||||
6052 | if (Val.hasArrayFiller()) { | ||||||
6053 | const APValue &Filler = Val.getArrayFiller(); | ||||||
6054 | for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { | ||||||
6055 | if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) | ||||||
6056 | return false; | ||||||
6057 | } | ||||||
6058 | } | ||||||
6059 | |||||||
6060 | return true; | ||||||
6061 | } | ||||||
6062 | |||||||
6063 | bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { | ||||||
6064 | CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); | ||||||
6065 | SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); | ||||||
6066 | llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); | ||||||
6067 | Buffer.writeObject(Offset, Bytes); | ||||||
6068 | return true; | ||||||
6069 | } | ||||||
6070 | |||||||
6071 | bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { | ||||||
6072 | APSInt AsInt(Val.bitcastToAPInt()); | ||||||
6073 | return visitInt(AsInt, Ty, Offset); | ||||||
6074 | } | ||||||
6075 | |||||||
6076 | public: | ||||||
6077 | static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, | ||||||
6078 | const CastExpr *BCE) { | ||||||
6079 | CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); | ||||||
6080 | APValueToBufferConverter Converter(Info, DstSize, BCE); | ||||||
6081 | if (!Converter.visit(Src, BCE->getSubExpr()->getType())) | ||||||
6082 | return None; | ||||||
6083 | return Converter.Buffer; | ||||||
6084 | } | ||||||
6085 | }; | ||||||
6086 | |||||||
6087 | /// Write an BitCastBuffer into an APValue. | ||||||
6088 | class BufferToAPValueConverter { | ||||||
6089 | EvalInfo &Info; | ||||||
6090 | const BitCastBuffer &Buffer; | ||||||
6091 | const CastExpr *BCE; | ||||||
6092 | |||||||
6093 | BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, | ||||||
6094 | const CastExpr *BCE) | ||||||
6095 | : Info(Info), Buffer(Buffer), BCE(BCE) {} | ||||||
6096 | |||||||
6097 | // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast | ||||||
6098 | // with an invalid type, so anything left is a deficiency on our part (FIXME). | ||||||
6099 | // Ideally this will be unreachable. | ||||||
6100 | llvm::NoneType unsupportedType(QualType Ty) { | ||||||
6101 | Info.FFDiag(BCE->getBeginLoc(), | ||||||
6102 | diag::note_constexpr_bit_cast_unsupported_type) | ||||||
6103 | << Ty; | ||||||
6104 | return None; | ||||||
6105 | } | ||||||
6106 | |||||||
6107 | Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, | ||||||
6108 | const EnumType *EnumSugar = nullptr) { | ||||||
6109 | if (T->isNullPtrType()) { | ||||||
6110 | uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); | ||||||
6111 | return APValue((Expr *)nullptr, | ||||||
6112 | /*Offset=*/CharUnits::fromQuantity(NullValue), | ||||||
6113 | APValue::NoLValuePath{}, /*IsNullPtr=*/true); | ||||||
6114 | } | ||||||
6115 | |||||||
6116 | CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); | ||||||
6117 | SmallVector<uint8_t, 8> Bytes; | ||||||
6118 | if (!Buffer.readObject(Offset, SizeOf, Bytes)) { | ||||||
6119 | // If this is std::byte or unsigned char, then its okay to store an | ||||||
6120 | // indeterminate value. | ||||||
6121 | bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); | ||||||
6122 | bool IsUChar = | ||||||
6123 | !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || | ||||||
6124 | T->isSpecificBuiltinType(BuiltinType::Char_U)); | ||||||
6125 | if (!IsStdByte && !IsUChar) { | ||||||
6126 | QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); | ||||||
6127 | Info.FFDiag(BCE->getExprLoc(), | ||||||
6128 | diag::note_constexpr_bit_cast_indet_dest) | ||||||
6129 | << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; | ||||||
6130 | return None; | ||||||
6131 | } | ||||||
6132 | |||||||
6133 | return APValue::IndeterminateValue(); | ||||||
6134 | } | ||||||
6135 | |||||||
6136 | APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); | ||||||
6137 | llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); | ||||||
6138 | |||||||
6139 | if (T->isIntegralOrEnumerationType()) { | ||||||
6140 | Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); | ||||||
6141 | return APValue(Val); | ||||||
6142 | } | ||||||
6143 | |||||||
6144 | if (T->isRealFloatingType()) { | ||||||
6145 | const llvm::fltSemantics &Semantics = | ||||||
6146 | Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); | ||||||
6147 | return APValue(APFloat(Semantics, Val)); | ||||||
6148 | } | ||||||
6149 | |||||||
6150 | return unsupportedType(QualType(T, 0)); | ||||||
6151 | } | ||||||
6152 | |||||||
6153 | Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { | ||||||
6154 | const RecordDecl *RD = RTy->getAsRecordDecl(); | ||||||
6155 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||||
6156 | |||||||
6157 | unsigned NumBases = 0; | ||||||
6158 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) | ||||||
6159 | NumBases = CXXRD->getNumBases(); | ||||||
6160 | |||||||
6161 | APValue ResultVal(APValue::UninitStruct(), NumBases, | ||||||
6162 | std::distance(RD->field_begin(), RD->field_end())); | ||||||
6163 | |||||||
6164 | // Visit the base classes. | ||||||
6165 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||||
6166 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { | ||||||
6167 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; | ||||||
6168 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | ||||||
6169 | if (BaseDecl->isEmpty() || | ||||||
6170 | Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) | ||||||
6171 | continue; | ||||||
6172 | |||||||
6173 | Optional<APValue> SubObj = visitType( | ||||||
6174 | BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); | ||||||
6175 | if (!SubObj) | ||||||
6176 | return None; | ||||||
6177 | ResultVal.getStructBase(I) = *SubObj; | ||||||
6178 | } | ||||||
6179 | } | ||||||
6180 | |||||||
6181 | // Visit the fields. | ||||||
6182 | unsigned FieldIdx = 0; | ||||||
6183 | for (FieldDecl *FD : RD->fields()) { | ||||||
6184 | // FIXME: We don't currently support bit-fields. A lot of the logic for | ||||||
6185 | // this is in CodeGen, so we need to factor it around. | ||||||
6186 | if (FD->isBitField()) { | ||||||
6187 | Info.FFDiag(BCE->getBeginLoc(), | ||||||
6188 | diag::note_constexpr_bit_cast_unsupported_bitfield); | ||||||
6189 | return None; | ||||||
6190 | } | ||||||
6191 | |||||||
6192 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); | ||||||
6193 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0)((FieldOffsetBits % Info.Ctx.getCharWidth() == 0) ? static_cast <void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6193, __PRETTY_FUNCTION__)); | ||||||
6194 | |||||||
6195 | CharUnits FieldOffset = | ||||||
6196 | CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + | ||||||
6197 | Offset; | ||||||
6198 | QualType FieldTy = FD->getType(); | ||||||
6199 | Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); | ||||||
6200 | if (!SubObj) | ||||||
6201 | return None; | ||||||
6202 | ResultVal.getStructField(FieldIdx) = *SubObj; | ||||||
6203 | ++FieldIdx; | ||||||
6204 | } | ||||||
6205 | |||||||
6206 | return ResultVal; | ||||||
6207 | } | ||||||
6208 | |||||||
6209 | Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { | ||||||
6210 | QualType RepresentationType = Ty->getDecl()->getIntegerType(); | ||||||
6211 | assert(!RepresentationType.isNull() &&((!RepresentationType.isNull() && "enum forward decl should be caught by Sema" ) ? static_cast<void> (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6212, __PRETTY_FUNCTION__)) | ||||||
6212 | "enum forward decl should be caught by Sema")((!RepresentationType.isNull() && "enum forward decl should be caught by Sema" ) ? static_cast<void> (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6212, __PRETTY_FUNCTION__)); | ||||||
6213 | const BuiltinType *AsBuiltin = | ||||||
6214 | RepresentationType.getCanonicalType()->getAs<BuiltinType>(); | ||||||
6215 | assert(AsBuiltin && "non-integral enum underlying type?")((AsBuiltin && "non-integral enum underlying type?") ? static_cast<void> (0) : __assert_fail ("AsBuiltin && \"non-integral enum underlying type?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6215, __PRETTY_FUNCTION__)); | ||||||
6216 | // Recurse into the underlying type. Treat std::byte transparently as | ||||||
6217 | // unsigned char. | ||||||
6218 | return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); | ||||||
6219 | } | ||||||
6220 | |||||||
6221 | Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { | ||||||
6222 | size_t Size = Ty->getSize().getLimitedValue(); | ||||||
6223 | CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); | ||||||
6224 | |||||||
6225 | APValue ArrayValue(APValue::UninitArray(), Size, Size); | ||||||
6226 | for (size_t I = 0; I != Size; ++I) { | ||||||
6227 | Optional<APValue> ElementValue = | ||||||
6228 | visitType(Ty->getElementType(), Offset + I * ElementWidth); | ||||||
6229 | if (!ElementValue) | ||||||
6230 | return None; | ||||||
6231 | ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); | ||||||
6232 | } | ||||||
6233 | |||||||
6234 | return ArrayValue; | ||||||
6235 | } | ||||||
6236 | |||||||
6237 | Optional<APValue> visit(const Type *Ty, CharUnits Offset) { | ||||||
6238 | return unsupportedType(QualType(Ty, 0)); | ||||||
6239 | } | ||||||
6240 | |||||||
6241 | Optional<APValue> visitType(QualType Ty, CharUnits Offset) { | ||||||
6242 | QualType Can = Ty.getCanonicalType(); | ||||||
6243 | |||||||
6244 | switch (Can->getTypeClass()) { | ||||||
6245 | #define TYPE(Class, Base) \ | ||||||
6246 | case Type::Class: \ | ||||||
6247 | return visit(cast<Class##Type>(Can.getTypePtr()), Offset); | ||||||
6248 | #define ABSTRACT_TYPE(Class, Base) | ||||||
6249 | #define NON_CANONICAL_TYPE(Class, Base) \ | ||||||
6250 | case Type::Class: \ | ||||||
6251 | llvm_unreachable("non-canonical type should be impossible!")::llvm::llvm_unreachable_internal("non-canonical type should be impossible!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6251); | ||||||
6252 | #define DEPENDENT_TYPE(Class, Base) \ | ||||||
6253 | case Type::Class: \ | ||||||
6254 | llvm_unreachable( \::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6255) | ||||||
6255 | "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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6255); | ||||||
6256 | #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)case Type::Class: ::llvm::llvm_unreachable_internal("either dependent or not canonical!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6256); \ | ||||||
6257 | case Type::Class: \ | ||||||
6258 | llvm_unreachable("either dependent or not canonical!")::llvm::llvm_unreachable_internal("either dependent or not canonical!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6258); | ||||||
6259 | #include "clang/AST/TypeNodes.inc" | ||||||
6260 | } | ||||||
6261 | llvm_unreachable("Unhandled Type::TypeClass")::llvm::llvm_unreachable_internal("Unhandled Type::TypeClass" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6261); | ||||||
6262 | } | ||||||
6263 | |||||||
6264 | public: | ||||||
6265 | // Pull out a full value of type DstType. | ||||||
6266 | static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, | ||||||
6267 | const CastExpr *BCE) { | ||||||
6268 | BufferToAPValueConverter Converter(Info, Buffer, BCE); | ||||||
6269 | return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); | ||||||
6270 | } | ||||||
6271 | }; | ||||||
6272 | |||||||
6273 | static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, | ||||||
6274 | QualType Ty, EvalInfo *Info, | ||||||
6275 | const ASTContext &Ctx, | ||||||
6276 | bool CheckingDest) { | ||||||
6277 | Ty = Ty.getCanonicalType(); | ||||||
6278 | |||||||
6279 | auto diag = [&](int Reason) { | ||||||
6280 | if (Info) | ||||||
6281 | Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) | ||||||
6282 | << CheckingDest << (Reason == 4) << Reason; | ||||||
6283 | return false; | ||||||
6284 | }; | ||||||
6285 | auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { | ||||||
6286 | if (Info) | ||||||
6287 | Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) | ||||||
6288 | << NoteTy << Construct << Ty; | ||||||
6289 | return false; | ||||||
6290 | }; | ||||||
6291 | |||||||
6292 | if (Ty->isUnionType()) | ||||||
6293 | return diag(0); | ||||||
6294 | if (Ty->isPointerType()) | ||||||
6295 | return diag(1); | ||||||
6296 | if (Ty->isMemberPointerType()) | ||||||
6297 | return diag(2); | ||||||
6298 | if (Ty.isVolatileQualified()) | ||||||
6299 | return diag(3); | ||||||
6300 | |||||||
6301 | if (RecordDecl *Record = Ty->getAsRecordDecl()) { | ||||||
6302 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { | ||||||
6303 | for (CXXBaseSpecifier &BS : CXXRD->bases()) | ||||||
6304 | if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, | ||||||
6305 | CheckingDest)) | ||||||
6306 | return note(1, BS.getType(), BS.getBeginLoc()); | ||||||
6307 | } | ||||||
6308 | for (FieldDecl *FD : Record->fields()) { | ||||||
6309 | if (FD->getType()->isReferenceType()) | ||||||
6310 | return diag(4); | ||||||
6311 | if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, | ||||||
6312 | CheckingDest)) | ||||||
6313 | return note(0, FD->getType(), FD->getBeginLoc()); | ||||||
6314 | } | ||||||
6315 | } | ||||||
6316 | |||||||
6317 | if (Ty->isArrayType() && | ||||||
6318 | !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), | ||||||
6319 | Info, Ctx, CheckingDest)) | ||||||
6320 | return false; | ||||||
6321 | |||||||
6322 | return true; | ||||||
6323 | } | ||||||
6324 | |||||||
6325 | static bool checkBitCastConstexprEligibility(EvalInfo *Info, | ||||||
6326 | const ASTContext &Ctx, | ||||||
6327 | const CastExpr *BCE) { | ||||||
6328 | bool DestOK = checkBitCastConstexprEligibilityType( | ||||||
6329 | BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); | ||||||
6330 | bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( | ||||||
6331 | BCE->getBeginLoc(), | ||||||
6332 | BCE->getSubExpr()->getType(), Info, Ctx, false); | ||||||
6333 | return SourceOK; | ||||||
6334 | } | ||||||
6335 | |||||||
6336 | static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, | ||||||
6337 | APValue &SourceValue, | ||||||
6338 | const CastExpr *BCE) { | ||||||
6339 | assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&((8 == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && "no host or target supports non 8-bit chars") ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6340, __PRETTY_FUNCTION__)) | ||||||
6340 | "no host or target supports non 8-bit chars")((8 == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && "no host or target supports non 8-bit chars") ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6340, __PRETTY_FUNCTION__)); | ||||||
6341 | assert(SourceValue.isLValue() &&((SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!" ) ? static_cast<void> (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6342, __PRETTY_FUNCTION__)) | ||||||
6342 | "LValueToRValueBitcast requires an lvalue operand!")((SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!" ) ? static_cast<void> (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6342, __PRETTY_FUNCTION__)); | ||||||
6343 | |||||||
6344 | if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) | ||||||
6345 | return false; | ||||||
6346 | |||||||
6347 | LValue SourceLValue; | ||||||
6348 | APValue SourceRValue; | ||||||
6349 | SourceLValue.setFrom(Info.Ctx, SourceValue); | ||||||
6350 | if (!handleLValueToRValueConversion( | ||||||
6351 | Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, | ||||||
6352 | SourceRValue, /*WantObjectRepresentation=*/true)) | ||||||
6353 | return false; | ||||||
6354 | |||||||
6355 | // Read out SourceValue into a char buffer. | ||||||
6356 | Optional<BitCastBuffer> Buffer = | ||||||
6357 | APValueToBufferConverter::convert(Info, SourceRValue, BCE); | ||||||
6358 | if (!Buffer) | ||||||
6359 | return false; | ||||||
6360 | |||||||
6361 | // Write out the buffer into a new APValue. | ||||||
6362 | Optional<APValue> MaybeDestValue = | ||||||
6363 | BufferToAPValueConverter::convert(Info, *Buffer, BCE); | ||||||
6364 | if (!MaybeDestValue) | ||||||
6365 | return false; | ||||||
6366 | |||||||
6367 | DestValue = std::move(*MaybeDestValue); | ||||||
6368 | return true; | ||||||
6369 | } | ||||||
6370 | |||||||
6371 | template <class Derived> | ||||||
6372 | class ExprEvaluatorBase | ||||||
6373 | : public ConstStmtVisitor<Derived, bool> { | ||||||
6374 | private: | ||||||
6375 | Derived &getDerived() { return static_cast<Derived&>(*this); } | ||||||
6376 | bool DerivedSuccess(const APValue &V, const Expr *E) { | ||||||
6377 | return getDerived().Success(V, E); | ||||||
6378 | } | ||||||
6379 | bool DerivedZeroInitialization(const Expr *E) { | ||||||
6380 | return getDerived().ZeroInitialization(E); | ||||||
6381 | } | ||||||
6382 | |||||||
6383 | // Check whether a conditional operator with a non-constant condition is a | ||||||
6384 | // potential constant expression. If neither arm is a potential constant | ||||||
6385 | // expression, then the conditional operator is not either. | ||||||
6386 | template<typename ConditionalOperator> | ||||||
6387 | void CheckPotentialConstantConditional(const ConditionalOperator *E) { | ||||||
6388 | assert(Info.checkingPotentialConstantExpression())((Info.checkingPotentialConstantExpression()) ? static_cast< void> (0) : __assert_fail ("Info.checkingPotentialConstantExpression()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6388, __PRETTY_FUNCTION__)); | ||||||
6389 | |||||||
6390 | // Speculatively evaluate both arms. | ||||||
6391 | SmallVector<PartialDiagnosticAt, 8> Diag; | ||||||
6392 | { | ||||||
6393 | SpeculativeEvaluationRAII Speculate(Info, &Diag); | ||||||
6394 | StmtVisitorTy::Visit(E->getFalseExpr()); | ||||||
6395 | if (Diag.empty()) | ||||||
6396 | return; | ||||||
6397 | } | ||||||
6398 | |||||||
6399 | { | ||||||
6400 | SpeculativeEvaluationRAII Speculate(Info, &Diag); | ||||||
6401 | Diag.clear(); | ||||||
6402 | StmtVisitorTy::Visit(E->getTrueExpr()); | ||||||
6403 | if (Diag.empty()) | ||||||
6404 | return; | ||||||
6405 | } | ||||||
6406 | |||||||
6407 | Error(E, diag::note_constexpr_conditional_never_const); | ||||||
6408 | } | ||||||
6409 | |||||||
6410 | |||||||
6411 | template<typename ConditionalOperator> | ||||||
6412 | bool HandleConditionalOperator(const ConditionalOperator *E) { | ||||||
6413 | bool BoolResult; | ||||||
6414 | if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { | ||||||
6415 | if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { | ||||||
6416 | CheckPotentialConstantConditional(E); | ||||||
6417 | return false; | ||||||
6418 | } | ||||||
6419 | if (Info.noteFailure()) { | ||||||
6420 | StmtVisitorTy::Visit(E->getTrueExpr()); | ||||||
6421 | StmtVisitorTy::Visit(E->getFalseExpr()); | ||||||
6422 | } | ||||||
6423 | return false; | ||||||
6424 | } | ||||||
6425 | |||||||
6426 | Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); | ||||||
6427 | return StmtVisitorTy::Visit(EvalExpr); | ||||||
6428 | } | ||||||
6429 | |||||||
6430 | protected: | ||||||
6431 | EvalInfo &Info; | ||||||
6432 | typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; | ||||||
6433 | typedef ExprEvaluatorBase ExprEvaluatorBaseTy; | ||||||
6434 | |||||||
6435 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { | ||||||
6436 | return Info.CCEDiag(E, D); | ||||||
6437 | } | ||||||
6438 | |||||||
6439 | bool ZeroInitialization(const Expr *E) { return Error(E); } | ||||||
6440 | |||||||
6441 | public: | ||||||
6442 | ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} | ||||||
6443 | |||||||
6444 | EvalInfo &getEvalInfo() { return Info; } | ||||||
6445 | |||||||
6446 | /// Report an evaluation error. This should only be called when an error is | ||||||
6447 | /// first discovered. When propagating an error, just return false. | ||||||
6448 | bool Error(const Expr *E, diag::kind D) { | ||||||
6449 | Info.FFDiag(E, D); | ||||||
6450 | return false; | ||||||
6451 | } | ||||||
6452 | bool Error(const Expr *E) { | ||||||
6453 | return Error(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
6454 | } | ||||||
6455 | |||||||
6456 | bool VisitStmt(const Stmt *) { | ||||||
6457 | 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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6457); | ||||||
6458 | } | ||||||
6459 | bool VisitExpr(const Expr *E) { | ||||||
6460 | return Error(E); | ||||||
6461 | } | ||||||
6462 | |||||||
6463 | bool VisitConstantExpr(const ConstantExpr *E) | ||||||
6464 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||||
6465 | bool VisitParenExpr(const ParenExpr *E) | ||||||
6466 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||||
6467 | bool VisitUnaryExtension(const UnaryOperator *E) | ||||||
6468 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||||
6469 | bool VisitUnaryPlus(const UnaryOperator *E) | ||||||
6470 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||||
6471 | bool VisitChooseExpr(const ChooseExpr *E) | ||||||
6472 | { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } | ||||||
6473 | bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) | ||||||
6474 | { return StmtVisitorTy::Visit(E->getResultExpr()); } | ||||||
6475 | bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) | ||||||
6476 | { return StmtVisitorTy::Visit(E->getReplacement()); } | ||||||
6477 | bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { | ||||||
6478 | TempVersionRAII RAII(*Info.CurrentCall); | ||||||
6479 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); | ||||||
6480 | return StmtVisitorTy::Visit(E->getExpr()); | ||||||
6481 | } | ||||||
6482 | bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { | ||||||
6483 | TempVersionRAII RAII(*Info.CurrentCall); | ||||||
6484 | // The initializer may not have been parsed yet, or might be erroneous. | ||||||
6485 | if (!E->getExpr()) | ||||||
6486 | return Error(E); | ||||||
6487 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); | ||||||
6488 | return StmtVisitorTy::Visit(E->getExpr()); | ||||||
6489 | } | ||||||
6490 | |||||||
6491 | bool VisitExprWithCleanups(const ExprWithCleanups *E) { | ||||||
6492 | FullExpressionRAII Scope(Info); | ||||||
6493 | return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); | ||||||
6494 | } | ||||||
6495 | |||||||
6496 | // Temporaries are registered when created, so we don't care about | ||||||
6497 | // CXXBindTemporaryExpr. | ||||||
6498 | bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { | ||||||
6499 | return StmtVisitorTy::Visit(E->getSubExpr()); | ||||||
6500 | } | ||||||
6501 | |||||||
6502 | bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { | ||||||
6503 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; | ||||||
6504 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||||
6505 | } | ||||||
6506 | bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { | ||||||
6507 | if (!Info.Ctx.getLangOpts().CPlusPlus2a) | ||||||
6508 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; | ||||||
6509 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||||
6510 | } | ||||||
6511 | bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { | ||||||
6512 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||||
6513 | } | ||||||
6514 | |||||||
6515 | bool VisitBinaryOperator(const BinaryOperator *E) { | ||||||
6516 | switch (E->getOpcode()) { | ||||||
6517 | default: | ||||||
6518 | return Error(E); | ||||||
6519 | |||||||
6520 | case BO_Comma: | ||||||
6521 | VisitIgnoredValue(E->getLHS()); | ||||||
6522 | return StmtVisitorTy::Visit(E->getRHS()); | ||||||
6523 | |||||||
6524 | case BO_PtrMemD: | ||||||
6525 | case BO_PtrMemI: { | ||||||
6526 | LValue Obj; | ||||||
6527 | if (!HandleMemberPointerAccess(Info, E, Obj)) | ||||||
6528 | return false; | ||||||
6529 | APValue Result; | ||||||
6530 | if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) | ||||||
6531 | return false; | ||||||
6532 | return DerivedSuccess(Result, E); | ||||||
6533 | } | ||||||
6534 | } | ||||||
6535 | } | ||||||
6536 | |||||||
6537 | bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { | ||||||
6538 | // Evaluate and cache the common expression. We treat it as a temporary, | ||||||
6539 | // even though it's not quite the same thing. | ||||||
6540 | LValue CommonLV; | ||||||
6541 | if (!Evaluate(Info.CurrentCall->createTemporary( | ||||||
6542 | E->getOpaqueValue(), | ||||||
6543 | getStorageType(Info.Ctx, E->getOpaqueValue()), false, | ||||||
6544 | CommonLV), | ||||||
6545 | Info, E->getCommon())) | ||||||
6546 | return false; | ||||||
6547 | |||||||
6548 | return HandleConditionalOperator(E); | ||||||
6549 | } | ||||||
6550 | |||||||
6551 | bool VisitConditionalOperator(const ConditionalOperator *E) { | ||||||
6552 | bool IsBcpCall = false; | ||||||
6553 | // If the condition (ignoring parens) is a __builtin_constant_p call, | ||||||
6554 | // the result is a constant expression if it can be folded without | ||||||
6555 | // side-effects. This is an important GNU extension. See GCC PR38377 | ||||||
6556 | // for discussion. | ||||||
6557 | if (const CallExpr *CallCE = | ||||||
6558 | dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) | ||||||
6559 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) | ||||||
6560 | IsBcpCall = true; | ||||||
6561 | |||||||
6562 | // Always assume __builtin_constant_p(...) ? ... : ... is a potential | ||||||
6563 | // constant expression; we can't check whether it's potentially foldable. | ||||||
6564 | // FIXME: We should instead treat __builtin_constant_p as non-constant if | ||||||
6565 | // it would return 'false' in this mode. | ||||||
6566 | if (Info.checkingPotentialConstantExpression() && IsBcpCall) | ||||||
6567 | return false; | ||||||
6568 | |||||||
6569 | FoldConstant Fold(Info, IsBcpCall); | ||||||
6570 | if (!HandleConditionalOperator(E)) { | ||||||
6571 | Fold.keepDiagnostics(); | ||||||
6572 | return false; | ||||||
6573 | } | ||||||
6574 | |||||||
6575 | return true; | ||||||
6576 | } | ||||||
6577 | |||||||
6578 | bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { | ||||||
6579 | if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) | ||||||
6580 | return DerivedSuccess(*Value, E); | ||||||
6581 | |||||||
6582 | const Expr *Source = E->getSourceExpr(); | ||||||
6583 | if (!Source) | ||||||
6584 | return Error(E); | ||||||
6585 | if (Source == E) { // sanity checking. | ||||||
6586 | assert(0 && "OpaqueValueExpr recursively refers to itself")((0 && "OpaqueValueExpr recursively refers to itself" ) ? static_cast<void> (0) : __assert_fail ("0 && \"OpaqueValueExpr recursively refers to itself\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6586, __PRETTY_FUNCTION__)); | ||||||
6587 | return Error(E); | ||||||
6588 | } | ||||||
6589 | return StmtVisitorTy::Visit(Source); | ||||||
6590 | } | ||||||
6591 | |||||||
6592 | bool VisitCallExpr(const CallExpr *E) { | ||||||
6593 | APValue Result; | ||||||
6594 | if (!handleCallExpr(E, Result, nullptr)) | ||||||
6595 | return false; | ||||||
6596 | return DerivedSuccess(Result, E); | ||||||
6597 | } | ||||||
6598 | |||||||
6599 | bool handleCallExpr(const CallExpr *E, APValue &Result, | ||||||
6600 | const LValue *ResultSlot) { | ||||||
6601 | const Expr *Callee = E->getCallee()->IgnoreParens(); | ||||||
6602 | QualType CalleeType = Callee->getType(); | ||||||
6603 | |||||||
6604 | const FunctionDecl *FD = nullptr; | ||||||
6605 | LValue *This = nullptr, ThisVal; | ||||||
6606 | auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); | ||||||
6607 | bool HasQualifier = false; | ||||||
6608 | |||||||
6609 | // Extract function decl and 'this' pointer from the callee. | ||||||
6610 | if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { | ||||||
6611 | const CXXMethodDecl *Member = nullptr; | ||||||
6612 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { | ||||||
6613 | // Explicit bound member calls, such as x.f() or p->g(); | ||||||
6614 | if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) | ||||||
6615 | return false; | ||||||
6616 | Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||||
6617 | if (!Member) | ||||||
6618 | return Error(Callee); | ||||||
6619 | This = &ThisVal; | ||||||
6620 | HasQualifier = ME->hasQualifier(); | ||||||
6621 | } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { | ||||||
6622 | // Indirect bound member calls ('.*' or '->*'). | ||||||
6623 | Member = dyn_cast_or_null<CXXMethodDecl>( | ||||||
6624 | HandleMemberPointerAccess(Info, BE, ThisVal, false)); | ||||||
6625 | if (!Member) | ||||||
6626 | return Error(Callee); | ||||||
6627 | This = &ThisVal; | ||||||
6628 | } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { | ||||||
6629 | if (!Info.getLangOpts().CPlusPlus2a) | ||||||
6630 | Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); | ||||||
6631 | // FIXME: If pseudo-destructor calls ever start ending the lifetime of | ||||||
6632 | // their callee, we should start calling HandleDestruction here. | ||||||
6633 | // For now, we just evaluate the object argument and discard it. | ||||||
6634 | return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal); | ||||||
6635 | } else | ||||||
6636 | return Error(Callee); | ||||||
6637 | FD = Member; | ||||||
6638 | } else if (CalleeType->isFunctionPointerType()) { | ||||||
6639 | LValue Call; | ||||||
6640 | if (!EvaluatePointer(Callee, Call, Info)) | ||||||
6641 | return false; | ||||||
6642 | |||||||
6643 | if (!Call.getLValueOffset().isZero()) | ||||||
6644 | return Error(Callee); | ||||||
6645 | FD = dyn_cast_or_null<FunctionDecl>( | ||||||
6646 | Call.getLValueBase().dyn_cast<const ValueDecl*>()); | ||||||
6647 | if (!FD) | ||||||
6648 | return Error(Callee); | ||||||
6649 | // Don't call function pointers which have been cast to some other type. | ||||||
6650 | // Per DR (no number yet), the caller and callee can differ in noexcept. | ||||||
6651 | if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( | ||||||
6652 | CalleeType->getPointeeType(), FD->getType())) { | ||||||
6653 | return Error(E); | ||||||
6654 | } | ||||||
6655 | |||||||
6656 | // Overloaded operator calls to member functions are represented as normal | ||||||
6657 | // calls with '*this' as the first argument. | ||||||
6658 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||||
6659 | if (MD && !MD->isStatic()) { | ||||||
6660 | // FIXME: When selecting an implicit conversion for an overloaded | ||||||
6661 | // operator delete, we sometimes try to evaluate calls to conversion | ||||||
6662 | // operators without a 'this' parameter! | ||||||
6663 | if (Args.empty()) | ||||||
6664 | return Error(E); | ||||||
6665 | |||||||
6666 | if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) | ||||||
6667 | return false; | ||||||
6668 | This = &ThisVal; | ||||||
6669 | Args = Args.slice(1); | ||||||
6670 | } else if (MD && MD->isLambdaStaticInvoker()) { | ||||||
6671 | // Map the static invoker for the lambda back to the call operator. | ||||||
6672 | // Conveniently, we don't have to slice out the 'this' argument (as is | ||||||
6673 | // being done for the non-static case), since a static member function | ||||||
6674 | // doesn't have an implicit argument passed in. | ||||||
6675 | const CXXRecordDecl *ClosureClass = MD->getParent(); | ||||||
6676 | assert(((ClosureClass->captures_begin() == ClosureClass->captures_end () && "Number of captures must be zero for conversion to function-ptr" ) ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6678, __PRETTY_FUNCTION__)) | ||||||
6677 | ClosureClass->captures_begin() == ClosureClass->captures_end() &&((ClosureClass->captures_begin() == ClosureClass->captures_end () && "Number of captures must be zero for conversion to function-ptr" ) ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6678, __PRETTY_FUNCTION__)) | ||||||
6678 | "Number of captures must be zero for conversion to function-ptr")((ClosureClass->captures_begin() == ClosureClass->captures_end () && "Number of captures must be zero for conversion to function-ptr" ) ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6678, __PRETTY_FUNCTION__)); | ||||||
6679 | |||||||
6680 | const CXXMethodDecl *LambdaCallOp = | ||||||
6681 | ClosureClass->getLambdaCallOperator(); | ||||||
6682 | |||||||
6683 | // Set 'FD', the function that will be called below, to the call | ||||||
6684 | // operator. If the closure object represents a generic lambda, find | ||||||
6685 | // the corresponding specialization of the call operator. | ||||||
6686 | |||||||
6687 | if (ClosureClass->isGenericLambda()) { | ||||||
6688 | assert(MD->isFunctionTemplateSpecialization() &&((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a " "template specialization") ? static_cast<void> (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6690, __PRETTY_FUNCTION__)) | ||||||
6689 | "A generic lambda's static-invoker function must be a "((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a " "template specialization") ? static_cast<void> (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6690, __PRETTY_FUNCTION__)) | ||||||
6690 | "template specialization")((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a " "template specialization") ? static_cast<void> (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6690, __PRETTY_FUNCTION__)); | ||||||
6691 | const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); | ||||||
6692 | FunctionTemplateDecl *CallOpTemplate = | ||||||
6693 | LambdaCallOp->getDescribedFunctionTemplate(); | ||||||
6694 | void *InsertPos = nullptr; | ||||||
6695 | FunctionDecl *CorrespondingCallOpSpecialization = | ||||||
6696 | CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); | ||||||
6697 | assert(CorrespondingCallOpSpecialization &&((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? static_cast <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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6699, __PRETTY_FUNCTION__)) | ||||||
6698 | "We must always have a function call operator specialization "((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? static_cast <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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6699, __PRETTY_FUNCTION__)) | ||||||
6699 | "that corresponds to our static invoker specialization")((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? static_cast <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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6699, __PRETTY_FUNCTION__)); | ||||||
6700 | FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); | ||||||
6701 | } else | ||||||
6702 | FD = LambdaCallOp; | ||||||
6703 | } | ||||||
6704 | } else | ||||||
6705 | return Error(E); | ||||||
6706 | |||||||
6707 | SmallVector<QualType, 4> CovariantAdjustmentPath; | ||||||
6708 | if (This) { | ||||||
6709 | auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); | ||||||
6710 | if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { | ||||||
6711 | // Perform virtual dispatch, if necessary. | ||||||
6712 | FD = HandleVirtualDispatch(Info, E, *This, NamedMember, | ||||||
6713 | CovariantAdjustmentPath); | ||||||
6714 | if (!FD) | ||||||
6715 | return false; | ||||||
6716 | } else { | ||||||
6717 | // Check that the 'this' pointer points to an object of the right type. | ||||||
6718 | // FIXME: If this is an assignment operator call, we may need to change | ||||||
6719 | // the active union member before we check this. | ||||||
6720 | if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) | ||||||
6721 | return false; | ||||||
6722 | } | ||||||
6723 | } | ||||||
6724 | |||||||
6725 | // Destructor calls are different enough that they have their own codepath. | ||||||
6726 | if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { | ||||||
6727 | assert(This && "no 'this' pointer for destructor call")((This && "no 'this' pointer for destructor call") ? static_cast <void> (0) : __assert_fail ("This && \"no 'this' pointer for destructor call\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6727, __PRETTY_FUNCTION__)); | ||||||
6728 | return HandleDestruction(Info, E, *This, | ||||||
6729 | Info.Ctx.getRecordType(DD->getParent())); | ||||||
6730 | } | ||||||
6731 | |||||||
6732 | const FunctionDecl *Definition = nullptr; | ||||||
6733 | Stmt *Body = FD->getBody(Definition); | ||||||
6734 | |||||||
6735 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || | ||||||
6736 | !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, | ||||||
6737 | Result, ResultSlot)) | ||||||
6738 | return false; | ||||||
6739 | |||||||
6740 | if (!CovariantAdjustmentPath.empty() && | ||||||
6741 | !HandleCovariantReturnAdjustment(Info, E, Result, | ||||||
6742 | CovariantAdjustmentPath)) | ||||||
6743 | return false; | ||||||
6744 | |||||||
6745 | return true; | ||||||
6746 | } | ||||||
6747 | |||||||
6748 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { | ||||||
6749 | return StmtVisitorTy::Visit(E->getInitializer()); | ||||||
6750 | } | ||||||
6751 | bool VisitInitListExpr(const InitListExpr *E) { | ||||||
6752 | if (E->getNumInits() == 0) | ||||||
6753 | return DerivedZeroInitialization(E); | ||||||
6754 | if (E->getNumInits() == 1) | ||||||
6755 | return StmtVisitorTy::Visit(E->getInit(0)); | ||||||
6756 | return Error(E); | ||||||
6757 | } | ||||||
6758 | bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { | ||||||
6759 | return DerivedZeroInitialization(E); | ||||||
6760 | } | ||||||
6761 | bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { | ||||||
6762 | return DerivedZeroInitialization(E); | ||||||
6763 | } | ||||||
6764 | bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { | ||||||
6765 | return DerivedZeroInitialization(E); | ||||||
6766 | } | ||||||
6767 | |||||||
6768 | /// A member expression where the object is a prvalue is itself a prvalue. | ||||||
6769 | bool VisitMemberExpr(const MemberExpr *E) { | ||||||
6770 | assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&((!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion" ) ? static_cast<void> (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6771, __PRETTY_FUNCTION__)) | ||||||
6771 | "missing temporary materialization conversion")((!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion" ) ? static_cast<void> (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6771, __PRETTY_FUNCTION__)); | ||||||
6772 | assert(!E->isArrow() && "missing call to bound member function?")((!E->isArrow() && "missing call to bound member function?" ) ? static_cast<void> (0) : __assert_fail ("!E->isArrow() && \"missing call to bound member function?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6772, __PRETTY_FUNCTION__)); | ||||||
6773 | |||||||
6774 | APValue Val; | ||||||
6775 | if (!Evaluate(Val, Info, E->getBase())) | ||||||
6776 | return false; | ||||||
6777 | |||||||
6778 | QualType BaseTy = E->getBase()->getType(); | ||||||
6779 | |||||||
6780 | const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); | ||||||
6781 | if (!FD) return Error(E); | ||||||
6782 | assert(!FD->getType()->isReferenceType() && "prvalue reference?")((!FD->getType()->isReferenceType() && "prvalue reference?" ) ? static_cast<void> (0) : __assert_fail ("!FD->getType()->isReferenceType() && \"prvalue reference?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6782, __PRETTY_FUNCTION__)); | ||||||
6783 | assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==((BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl () == FD->getParent()->getCanonicalDecl() && "record / field mismatch" ) ? static_cast<void> (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6784, __PRETTY_FUNCTION__)) | ||||||
6784 | FD->getParent()->getCanonicalDecl() && "record / field mismatch")((BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl () == FD->getParent()->getCanonicalDecl() && "record / field mismatch" ) ? static_cast<void> (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6784, __PRETTY_FUNCTION__)); | ||||||
6785 | |||||||
6786 | // Note: there is no lvalue base here. But this case should only ever | ||||||
6787 | // happen in C or in C++98, where we cannot be evaluating a constexpr | ||||||
6788 | // constructor, which is the only case the base matters. | ||||||
6789 | CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); | ||||||
6790 | SubobjectDesignator Designator(BaseTy); | ||||||
6791 | Designator.addDeclUnchecked(FD); | ||||||
6792 | |||||||
6793 | APValue Result; | ||||||
6794 | return extractSubobject(Info, E, Obj, Designator, Result) && | ||||||
6795 | DerivedSuccess(Result, E); | ||||||
6796 | } | ||||||
6797 | |||||||
6798 | bool VisitCastExpr(const CastExpr *E) { | ||||||
6799 | switch (E->getCastKind()) { | ||||||
6800 | default: | ||||||
6801 | break; | ||||||
6802 | |||||||
6803 | case CK_AtomicToNonAtomic: { | ||||||
6804 | APValue AtomicVal; | ||||||
6805 | // This does not need to be done in place even for class/array types: | ||||||
6806 | // atomic-to-non-atomic conversion implies copying the object | ||||||
6807 | // representation. | ||||||
6808 | if (!Evaluate(AtomicVal, Info, E->getSubExpr())) | ||||||
6809 | return false; | ||||||
6810 | return DerivedSuccess(AtomicVal, E); | ||||||
6811 | } | ||||||
6812 | |||||||
6813 | case CK_NoOp: | ||||||
6814 | case CK_UserDefinedConversion: | ||||||
6815 | return StmtVisitorTy::Visit(E->getSubExpr()); | ||||||
6816 | |||||||
6817 | case CK_LValueToRValue: { | ||||||
6818 | LValue LVal; | ||||||
6819 | if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) | ||||||
6820 | return false; | ||||||
6821 | APValue RVal; | ||||||
6822 | // Note, we use the subexpression's type in order to retain cv-qualifiers. | ||||||
6823 | if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), | ||||||
6824 | LVal, RVal)) | ||||||
6825 | return false; | ||||||
6826 | return DerivedSuccess(RVal, E); | ||||||
6827 | } | ||||||
6828 | case CK_LValueToRValueBitCast: { | ||||||
6829 | APValue DestValue, SourceValue; | ||||||
6830 | if (!Evaluate(SourceValue, Info, E->getSubExpr())) | ||||||
6831 | return false; | ||||||
6832 | if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) | ||||||
6833 | return false; | ||||||
6834 | return DerivedSuccess(DestValue, E); | ||||||
6835 | } | ||||||
6836 | } | ||||||
6837 | |||||||
6838 | return Error(E); | ||||||
6839 | } | ||||||
6840 | |||||||
6841 | bool VisitUnaryPostInc(const UnaryOperator *UO) { | ||||||
6842 | return VisitUnaryPostIncDec(UO); | ||||||
6843 | } | ||||||
6844 | bool VisitUnaryPostDec(const UnaryOperator *UO) { | ||||||
6845 | return VisitUnaryPostIncDec(UO); | ||||||
6846 | } | ||||||
6847 | bool VisitUnaryPostIncDec(const UnaryOperator *UO) { | ||||||
6848 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||||
6849 | return Error(UO); | ||||||
6850 | |||||||
6851 | LValue LVal; | ||||||
6852 | if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) | ||||||
6853 | return false; | ||||||
6854 | APValue RVal; | ||||||
6855 | if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), | ||||||
6856 | UO->isIncrementOp(), &RVal)) | ||||||
6857 | return false; | ||||||
6858 | return DerivedSuccess(RVal, UO); | ||||||
6859 | } | ||||||
6860 | |||||||
6861 | bool VisitStmtExpr(const StmtExpr *E) { | ||||||
6862 | // We will have checked the full-expressions inside the statement expression | ||||||
6863 | // when they were completed, and don't need to check them again now. | ||||||
6864 | if (Info.checkingForUndefinedBehavior()) | ||||||
6865 | return Error(E); | ||||||
6866 | |||||||
6867 | const CompoundStmt *CS = E->getSubStmt(); | ||||||
6868 | if (CS->body_empty()) | ||||||
6869 | return true; | ||||||
6870 | |||||||
6871 | BlockScopeRAII Scope(Info); | ||||||
6872 | for (CompoundStmt::const_body_iterator BI = CS->body_begin(), | ||||||
6873 | BE = CS->body_end(); | ||||||
6874 | /**/; ++BI) { | ||||||
6875 | if (BI + 1 == BE) { | ||||||
6876 | const Expr *FinalExpr = dyn_cast<Expr>(*BI); | ||||||
6877 | if (!FinalExpr) { | ||||||
6878 | Info.FFDiag((*BI)->getBeginLoc(), | ||||||
6879 | diag::note_constexpr_stmt_expr_unsupported); | ||||||
6880 | return false; | ||||||
6881 | } | ||||||
6882 | return this->Visit(FinalExpr) && Scope.destroy(); | ||||||
6883 | } | ||||||
6884 | |||||||
6885 | APValue ReturnValue; | ||||||
6886 | StmtResult Result = { ReturnValue, nullptr }; | ||||||
6887 | EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); | ||||||
6888 | if (ESR != ESR_Succeeded) { | ||||||
6889 | // FIXME: If the statement-expression terminated due to 'return', | ||||||
6890 | // 'break', or 'continue', it would be nice to propagate that to | ||||||
6891 | // the outer statement evaluation rather than bailing out. | ||||||
6892 | if (ESR != ESR_Failed) | ||||||
6893 | Info.FFDiag((*BI)->getBeginLoc(), | ||||||
6894 | diag::note_constexpr_stmt_expr_unsupported); | ||||||
6895 | return false; | ||||||
6896 | } | ||||||
6897 | } | ||||||
6898 | |||||||
6899 | llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6899); | ||||||
6900 | } | ||||||
6901 | |||||||
6902 | /// Visit a value which is evaluated, but whose value is ignored. | ||||||
6903 | void VisitIgnoredValue(const Expr *E) { | ||||||
6904 | EvaluateIgnoredValue(Info, E); | ||||||
6905 | } | ||||||
6906 | |||||||
6907 | /// Potentially visit a MemberExpr's base expression. | ||||||
6908 | void VisitIgnoredBaseExpression(const Expr *E) { | ||||||
6909 | // While MSVC doesn't evaluate the base expression, it does diagnose the | ||||||
6910 | // presence of side-effecting behavior. | ||||||
6911 | if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) | ||||||
6912 | return; | ||||||
6913 | VisitIgnoredValue(E); | ||||||
6914 | } | ||||||
6915 | }; | ||||||
6916 | |||||||
6917 | } // namespace | ||||||
6918 | |||||||
6919 | //===----------------------------------------------------------------------===// | ||||||
6920 | // Common base class for lvalue and temporary evaluation. | ||||||
6921 | //===----------------------------------------------------------------------===// | ||||||
6922 | namespace { | ||||||
6923 | template<class Derived> | ||||||
6924 | class LValueExprEvaluatorBase | ||||||
6925 | : public ExprEvaluatorBase<Derived> { | ||||||
6926 | protected: | ||||||
6927 | LValue &Result; | ||||||
6928 | bool InvalidBaseOK; | ||||||
6929 | typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; | ||||||
6930 | typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; | ||||||
6931 | |||||||
6932 | bool Success(APValue::LValueBase B) { | ||||||
6933 | Result.set(B); | ||||||
6934 | return true; | ||||||
6935 | } | ||||||
6936 | |||||||
6937 | bool evaluatePointer(const Expr *E, LValue &Result) { | ||||||
6938 | return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); | ||||||
6939 | } | ||||||
6940 | |||||||
6941 | public: | ||||||
6942 | LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) | ||||||
6943 | : ExprEvaluatorBaseTy(Info), Result(Result), | ||||||
6944 | InvalidBaseOK(InvalidBaseOK) {} | ||||||
6945 | |||||||
6946 | bool Success(const APValue &V, const Expr *E) { | ||||||
6947 | Result.setFrom(this->Info.Ctx, V); | ||||||
6948 | return true; | ||||||
6949 | } | ||||||
6950 | |||||||
6951 | bool VisitMemberExpr(const MemberExpr *E) { | ||||||
6952 | // Handle non-static data members. | ||||||
6953 | QualType BaseTy; | ||||||
6954 | bool EvalOK; | ||||||
6955 | if (E->isArrow()) { | ||||||
6956 | EvalOK = evaluatePointer(E->getBase(), Result); | ||||||
6957 | BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); | ||||||
6958 | } else if (E->getBase()->isRValue()) { | ||||||
6959 | assert(E->getBase()->getType()->isRecordType())((E->getBase()->getType()->isRecordType()) ? static_cast <void> (0) : __assert_fail ("E->getBase()->getType()->isRecordType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6959, __PRETTY_FUNCTION__)); | ||||||
6960 | EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); | ||||||
6961 | BaseTy = E->getBase()->getType(); | ||||||
6962 | } else { | ||||||
6963 | EvalOK = this->Visit(E->getBase()); | ||||||
6964 | BaseTy = E->getBase()->getType(); | ||||||
6965 | } | ||||||
6966 | if (!EvalOK) { | ||||||
6967 | if (!InvalidBaseOK) | ||||||
6968 | return false; | ||||||
6969 | Result.setInvalid(E); | ||||||
6970 | return true; | ||||||
6971 | } | ||||||
6972 | |||||||
6973 | const ValueDecl *MD = E->getMemberDecl(); | ||||||
6974 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { | ||||||
6975 | assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==((BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl () == FD->getParent()->getCanonicalDecl() && "record / field mismatch" ) ? static_cast<void> (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6976, __PRETTY_FUNCTION__)) | ||||||
6976 | FD->getParent()->getCanonicalDecl() && "record / field mismatch")((BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl () == FD->getParent()->getCanonicalDecl() && "record / field mismatch" ) ? static_cast<void> (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6976, __PRETTY_FUNCTION__)); | ||||||
6977 | (void)BaseTy; | ||||||
6978 | if (!HandleLValueMember(this->Info, E, Result, FD)) | ||||||
6979 | return false; | ||||||
6980 | } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { | ||||||
6981 | if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) | ||||||
6982 | return false; | ||||||
6983 | } else | ||||||
6984 | return this->Error(E); | ||||||
6985 | |||||||
6986 | if (MD->getType()->isReferenceType()) { | ||||||
6987 | APValue RefValue; | ||||||
6988 | if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, | ||||||
6989 | RefValue)) | ||||||
6990 | return false; | ||||||
6991 | return Success(RefValue, E); | ||||||
6992 | } | ||||||
6993 | return true; | ||||||
6994 | } | ||||||
6995 | |||||||
6996 | bool VisitBinaryOperator(const BinaryOperator *E) { | ||||||
6997 | switch (E->getOpcode()) { | ||||||
6998 | default: | ||||||
6999 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||||
7000 | |||||||
7001 | case BO_PtrMemD: | ||||||
7002 | case BO_PtrMemI: | ||||||
7003 | return HandleMemberPointerAccess(this->Info, E, Result); | ||||||
7004 | } | ||||||
7005 | } | ||||||
7006 | |||||||
7007 | bool VisitCastExpr(const CastExpr *E) { | ||||||
7008 | switch (E->getCastKind()) { | ||||||
7009 | default: | ||||||
7010 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
7011 | |||||||
7012 | case CK_DerivedToBase: | ||||||
7013 | case CK_UncheckedDerivedToBase: | ||||||
7014 | if (!this->Visit(E->getSubExpr())) | ||||||
7015 | return false; | ||||||
7016 | |||||||
7017 | // Now figure out the necessary offset to add to the base LV to get from | ||||||
7018 | // the derived class to the base class. | ||||||
7019 | return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), | ||||||
7020 | Result); | ||||||
7021 | } | ||||||
7022 | } | ||||||
7023 | }; | ||||||
7024 | } | ||||||
7025 | |||||||
7026 | //===----------------------------------------------------------------------===// | ||||||
7027 | // LValue Evaluation | ||||||
7028 | // | ||||||
7029 | // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), | ||||||
7030 | // function designators (in C), decl references to void objects (in C), and | ||||||
7031 | // temporaries (if building with -Wno-address-of-temporary). | ||||||
7032 | // | ||||||
7033 | // LValue evaluation produces values comprising a base expression of one of the | ||||||
7034 | // following types: | ||||||
7035 | // - Declarations | ||||||
7036 | // * VarDecl | ||||||
7037 | // * FunctionDecl | ||||||
7038 | // - Literals | ||||||
7039 | // * CompoundLiteralExpr in C (and in global scope in C++) | ||||||
7040 | // * StringLiteral | ||||||
7041 | // * PredefinedExpr | ||||||
7042 | // * ObjCStringLiteralExpr | ||||||
7043 | // * ObjCEncodeExpr | ||||||
7044 | // * AddrLabelExpr | ||||||
7045 | // * BlockExpr | ||||||
7046 | // * CallExpr for a MakeStringConstant builtin | ||||||
7047 | // - typeid(T) expressions, as TypeInfoLValues | ||||||
7048 | // - Locals and temporaries | ||||||
7049 | // * MaterializeTemporaryExpr | ||||||
7050 | // * Any Expr, with a CallIndex indicating the function in which the temporary | ||||||
7051 | // was evaluated, for cases where the MaterializeTemporaryExpr is missing | ||||||
7052 | // from the AST (FIXME). | ||||||
7053 | // * A MaterializeTemporaryExpr that has static storage duration, with no | ||||||
7054 | // CallIndex, for a lifetime-extended temporary. | ||||||
7055 | // plus an offset in bytes. | ||||||
7056 | //===----------------------------------------------------------------------===// | ||||||
7057 | namespace { | ||||||
7058 | class LValueExprEvaluator | ||||||
7059 | : public LValueExprEvaluatorBase<LValueExprEvaluator> { | ||||||
7060 | public: | ||||||
7061 | LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : | ||||||
7062 | LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} | ||||||
7063 | |||||||
7064 | bool VisitVarDecl(const Expr *E, const VarDecl *VD); | ||||||
7065 | bool VisitUnaryPreIncDec(const UnaryOperator *UO); | ||||||
7066 | |||||||
7067 | bool VisitDeclRefExpr(const DeclRefExpr *E); | ||||||
7068 | bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } | ||||||
7069 | bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); | ||||||
7070 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); | ||||||
7071 | bool VisitMemberExpr(const MemberExpr *E); | ||||||
7072 | bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } | ||||||
7073 | bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } | ||||||
7074 | bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); | ||||||
7075 | bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); | ||||||
7076 | bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); | ||||||
7077 | bool VisitUnaryDeref(const UnaryOperator *E); | ||||||
7078 | bool VisitUnaryReal(const UnaryOperator *E); | ||||||
7079 | bool VisitUnaryImag(const UnaryOperator *E); | ||||||
7080 | bool VisitUnaryPreInc(const UnaryOperator *UO) { | ||||||
7081 | return VisitUnaryPreIncDec(UO); | ||||||
7082 | } | ||||||
7083 | bool VisitUnaryPreDec(const UnaryOperator *UO) { | ||||||
7084 | return VisitUnaryPreIncDec(UO); | ||||||
7085 | } | ||||||
7086 | bool VisitBinAssign(const BinaryOperator *BO); | ||||||
7087 | bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); | ||||||
7088 | |||||||
7089 | bool VisitCastExpr(const CastExpr *E) { | ||||||
7090 | switch (E->getCastKind()) { | ||||||
7091 | default: | ||||||
7092 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
7093 | |||||||
7094 | case CK_LValueBitCast: | ||||||
7095 | this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||||
7096 | if (!Visit(E->getSubExpr())) | ||||||
7097 | return false; | ||||||
7098 | Result.Designator.setInvalid(); | ||||||
7099 | return true; | ||||||
7100 | |||||||
7101 | case CK_BaseToDerived: | ||||||
7102 | if (!Visit(E->getSubExpr())) | ||||||
7103 | return false; | ||||||
7104 | return HandleBaseToDerivedCast(Info, E, Result); | ||||||
7105 | |||||||
7106 | case CK_Dynamic: | ||||||
7107 | if (!Visit(E->getSubExpr())) | ||||||
7108 | return false; | ||||||
7109 | return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); | ||||||
7110 | } | ||||||
7111 | } | ||||||
7112 | }; | ||||||
7113 | } // end anonymous namespace | ||||||
7114 | |||||||
7115 | /// Evaluate an expression as an lvalue. This can be legitimately called on | ||||||
7116 | /// expressions which are not glvalues, in three cases: | ||||||
7117 | /// * function designators in C, and | ||||||
7118 | /// * "extern void" objects | ||||||
7119 | /// * @selector() expressions in Objective-C | ||||||
7120 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, | ||||||
7121 | bool InvalidBaseOK) { | ||||||
7122 | assert(E->isGLValue() || E->getType()->isFunctionType() ||((E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr> (E)) ? static_cast<void> (0) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7123, __PRETTY_FUNCTION__)) | ||||||
7123 | E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E))((E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr> (E)) ? static_cast<void> (0) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7123, __PRETTY_FUNCTION__)); | ||||||
7124 | return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); | ||||||
7125 | } | ||||||
7126 | |||||||
7127 | bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { | ||||||
7128 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) | ||||||
7129 | return Success(FD); | ||||||
7130 | if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | ||||||
7131 | return VisitVarDecl(E, VD); | ||||||
7132 | if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) | ||||||
7133 | return Visit(BD->getBinding()); | ||||||
7134 | return Error(E); | ||||||
7135 | } | ||||||
7136 | |||||||
7137 | |||||||
7138 | bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { | ||||||
7139 | |||||||
7140 | // If we are within a lambda's call operator, check whether the 'VD' referred | ||||||
7141 | // to within 'E' actually represents a lambda-capture that maps to a | ||||||
7142 | // data-member/field within the closure object, and if so, evaluate to the | ||||||
7143 | // field or what the field refers to. | ||||||
7144 | if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && | ||||||
7145 | isa<DeclRefExpr>(E) && | ||||||
7146 | cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { | ||||||
7147 | // We don't always have a complete capture-map when checking or inferring if | ||||||
7148 | // the function call operator meets the requirements of a constexpr function | ||||||
7149 | // - but we don't need to evaluate the captures to determine constexprness | ||||||
7150 | // (dcl.constexpr C++17). | ||||||
7151 | if (Info.checkingPotentialConstantExpression()) | ||||||
7152 | return false; | ||||||
7153 | |||||||
7154 | if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { | ||||||
7155 | // Start with 'Result' referring to the complete closure object... | ||||||
7156 | Result = *Info.CurrentCall->This; | ||||||
7157 | // ... then update it to refer to the field of the closure object | ||||||
7158 | // that represents the capture. | ||||||
7159 | if (!HandleLValueMember(Info, E, Result, FD)) | ||||||
7160 | return false; | ||||||
7161 | // And if the field is of reference type, update 'Result' to refer to what | ||||||
7162 | // the field refers to. | ||||||
7163 | if (FD->getType()->isReferenceType()) { | ||||||
7164 | APValue RVal; | ||||||
7165 | if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, | ||||||
7166 | RVal)) | ||||||
7167 | return false; | ||||||
7168 | Result.setFrom(Info.Ctx, RVal); | ||||||
7169 | } | ||||||
7170 | return true; | ||||||
7171 | } | ||||||
7172 | } | ||||||
7173 | CallStackFrame *Frame = nullptr; | ||||||
7174 | if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { | ||||||
7175 | // Only if a local variable was declared in the function currently being | ||||||
7176 | // evaluated, do we expect to be able to find its value in the current | ||||||
7177 | // frame. (Otherwise it was likely declared in an enclosing context and | ||||||
7178 | // could either have a valid evaluatable value (for e.g. a constexpr | ||||||
7179 | // variable) or be ill-formed (and trigger an appropriate evaluation | ||||||
7180 | // diagnostic)). | ||||||
7181 | if (Info.CurrentCall->Callee && | ||||||
7182 | Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { | ||||||
7183 | Frame = Info.CurrentCall; | ||||||
7184 | } | ||||||
7185 | } | ||||||
7186 | |||||||
7187 | if (!VD->getType()->isReferenceType()) { | ||||||
7188 | if (Frame) { | ||||||
7189 | Result.set({VD, Frame->Index, | ||||||
7190 | Info.CurrentCall->getCurrentTemporaryVersion(VD)}); | ||||||
7191 | return true; | ||||||
7192 | } | ||||||
7193 | return Success(VD); | ||||||
7194 | } | ||||||
7195 | |||||||
7196 | APValue *V; | ||||||
7197 | if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) | ||||||
7198 | return false; | ||||||
7199 | if (!V->hasValue()) { | ||||||
7200 | // FIXME: Is it possible for V to be indeterminate here? If so, we should | ||||||
7201 | // adjust the diagnostic to say that. | ||||||
7202 | if (!Info.checkingPotentialConstantExpression()) | ||||||
7203 | Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); | ||||||
7204 | return false; | ||||||
7205 | } | ||||||
7206 | return Success(*V, E); | ||||||
7207 | } | ||||||
7208 | |||||||
7209 | bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( | ||||||
7210 | const MaterializeTemporaryExpr *E) { | ||||||
7211 | // Walk through the expression to find the materialized temporary itself. | ||||||
7212 | SmallVector<const Expr *, 2> CommaLHSs; | ||||||
7213 | SmallVector<SubobjectAdjustment, 2> Adjustments; | ||||||
7214 | const Expr *Inner = E->GetTemporaryExpr()-> | ||||||
7215 | skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); | ||||||
7216 | |||||||
7217 | // If we passed any comma operators, evaluate their LHSs. | ||||||
7218 | for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) | ||||||
7219 | if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) | ||||||
7220 | return false; | ||||||
7221 | |||||||
7222 | // A materialized temporary with static storage duration can appear within the | ||||||
7223 | // result of a constant expression evaluation, so we need to preserve its | ||||||
7224 | // value for use outside this evaluation. | ||||||
7225 | APValue *Value; | ||||||
7226 | if (E->getStorageDuration() == SD_Static) { | ||||||
7227 | Value = Info.Ctx.getMaterializedTemporaryValue(E, true); | ||||||
7228 | *Value = APValue(); | ||||||
7229 | Result.set(E); | ||||||
7230 | } else { | ||||||
7231 | Value = &Info.CurrentCall->createTemporary( | ||||||
7232 | E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); | ||||||
7233 | } | ||||||
7234 | |||||||
7235 | QualType Type = Inner->getType(); | ||||||
7236 | |||||||
7237 | // Materialize the temporary itself. | ||||||
7238 | if (!EvaluateInPlace(*Value, Info, Result, Inner)) { | ||||||
7239 | *Value = APValue(); | ||||||
7240 | return false; | ||||||
7241 | } | ||||||
7242 | |||||||
7243 | // Adjust our lvalue to refer to the desired subobject. | ||||||
7244 | for (unsigned I = Adjustments.size(); I != 0; /**/) { | ||||||
7245 | --I; | ||||||
7246 | switch (Adjustments[I].Kind) { | ||||||
7247 | case SubobjectAdjustment::DerivedToBaseAdjustment: | ||||||
7248 | if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, | ||||||
7249 | Type, Result)) | ||||||
7250 | return false; | ||||||
7251 | Type = Adjustments[I].DerivedToBase.BasePath->getType(); | ||||||
7252 | break; | ||||||
7253 | |||||||
7254 | case SubobjectAdjustment::FieldAdjustment: | ||||||
7255 | if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) | ||||||
7256 | return false; | ||||||
7257 | Type = Adjustments[I].Field->getType(); | ||||||
7258 | break; | ||||||
7259 | |||||||
7260 | case SubobjectAdjustment::MemberPointerAdjustment: | ||||||
7261 | if (!HandleMemberPointerAccess(this->Info, Type, Result, | ||||||
7262 | Adjustments[I].Ptr.RHS)) | ||||||
7263 | return false; | ||||||
7264 | Type = Adjustments[I].Ptr.MPT->getPointeeType(); | ||||||
7265 | break; | ||||||
7266 | } | ||||||
7267 | } | ||||||
7268 | |||||||
7269 | return true; | ||||||
7270 | } | ||||||
7271 | |||||||
7272 | bool | ||||||
7273 | LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { | ||||||
7274 | assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&(((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && "lvalue compound literal in c++?") ? static_cast<void> (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7275, __PRETTY_FUNCTION__)) | ||||||
7275 | "lvalue compound literal in c++?")(((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && "lvalue compound literal in c++?") ? static_cast<void> (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7275, __PRETTY_FUNCTION__)); | ||||||
7276 | // Defer visiting the literal until the lvalue-to-rvalue conversion. We can | ||||||
7277 | // only see this when folding in C, so there's no standard to follow here. | ||||||
7278 | return Success(E); | ||||||
7279 | } | ||||||
7280 | |||||||
7281 | bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { | ||||||
7282 | TypeInfoLValue TypeInfo; | ||||||
7283 | |||||||
7284 | if (!E->isPotentiallyEvaluated()) { | ||||||
7285 | if (E->isTypeOperand()) | ||||||
7286 | TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); | ||||||
7287 | else | ||||||
7288 | TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); | ||||||
7289 | } else { | ||||||
7290 | if (!Info.Ctx.getLangOpts().CPlusPlus2a) { | ||||||
7291 | Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) | ||||||
7292 | << E->getExprOperand()->getType() | ||||||
7293 | << E->getExprOperand()->getSourceRange(); | ||||||
7294 | } | ||||||
7295 | |||||||
7296 | if (!Visit(E->getExprOperand())) | ||||||
7297 | return false; | ||||||
7298 | |||||||
7299 | Optional<DynamicType> DynType = | ||||||
7300 | ComputeDynamicType(Info, E, Result, AK_TypeId); | ||||||
7301 | if (!DynType) | ||||||
7302 | return false; | ||||||
7303 | |||||||
7304 | TypeInfo = | ||||||
7305 | TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); | ||||||
7306 | } | ||||||
7307 | |||||||
7308 | return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); | ||||||
7309 | } | ||||||
7310 | |||||||
7311 | bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { | ||||||
7312 | return Success(E); | ||||||
7313 | } | ||||||
7314 | |||||||
7315 | bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { | ||||||
7316 | // Handle static data members. | ||||||
7317 | if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { | ||||||
7318 | VisitIgnoredBaseExpression(E->getBase()); | ||||||
7319 | return VisitVarDecl(E, VD); | ||||||
7320 | } | ||||||
7321 | |||||||
7322 | // Handle static member functions. | ||||||
7323 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { | ||||||
7324 | if (MD->isStatic()) { | ||||||
7325 | VisitIgnoredBaseExpression(E->getBase()); | ||||||
7326 | return Success(MD); | ||||||
7327 | } | ||||||
7328 | } | ||||||
7329 | |||||||
7330 | // Handle non-static data members. | ||||||
7331 | return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); | ||||||
7332 | } | ||||||
7333 | |||||||
7334 | bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { | ||||||
7335 | // FIXME: Deal with vectors as array subscript bases. | ||||||
7336 | if (E->getBase()->getType()->isVectorType()) | ||||||
7337 | return Error(E); | ||||||
7338 | |||||||
7339 | bool Success = true; | ||||||
7340 | if (!evaluatePointer(E->getBase(), Result)) { | ||||||
7341 | if (!Info.noteFailure()) | ||||||
7342 | return false; | ||||||
7343 | Success = false; | ||||||
7344 | } | ||||||
7345 | |||||||
7346 | APSInt Index; | ||||||
7347 | if (!EvaluateInteger(E->getIdx(), Index, Info)) | ||||||
7348 | return false; | ||||||
7349 | |||||||
7350 | return Success && | ||||||
7351 | HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); | ||||||
7352 | } | ||||||
7353 | |||||||
7354 | bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { | ||||||
7355 | return evaluatePointer(E->getSubExpr(), Result); | ||||||
7356 | } | ||||||
7357 | |||||||
7358 | bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||||
7359 | if (!Visit(E->getSubExpr())) | ||||||
7360 | return false; | ||||||
7361 | // __real is a no-op on scalar lvalues. | ||||||
7362 | if (E->getSubExpr()->getType()->isAnyComplexType()) | ||||||
7363 | HandleLValueComplexElement(Info, E, Result, E->getType(), false); | ||||||
7364 | return true; | ||||||
7365 | } | ||||||
7366 | |||||||
7367 | bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||||
7368 | assert(E->getSubExpr()->getType()->isAnyComplexType() &&((E->getSubExpr()->getType()->isAnyComplexType() && "lvalue __imag__ on scalar?") ? static_cast<void> (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7369, __PRETTY_FUNCTION__)) | ||||||
7369 | "lvalue __imag__ on scalar?")((E->getSubExpr()->getType()->isAnyComplexType() && "lvalue __imag__ on scalar?") ? static_cast<void> (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7369, __PRETTY_FUNCTION__)); | ||||||
7370 | if (!Visit(E->getSubExpr())) | ||||||
7371 | return false; | ||||||
7372 | HandleLValueComplexElement(Info, E, Result, E->getType(), true); | ||||||
7373 | return true; | ||||||
7374 | } | ||||||
7375 | |||||||
7376 | bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { | ||||||
7377 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||||
7378 | return Error(UO); | ||||||
7379 | |||||||
7380 | if (!this->Visit(UO->getSubExpr())) | ||||||
7381 | return false; | ||||||
7382 | |||||||
7383 | return handleIncDec( | ||||||
7384 | this->Info, UO, Result, UO->getSubExpr()->getType(), | ||||||
7385 | UO->isIncrementOp(), nullptr); | ||||||
7386 | } | ||||||
7387 | |||||||
7388 | bool LValueExprEvaluator::VisitCompoundAssignOperator( | ||||||
7389 | const CompoundAssignOperator *CAO) { | ||||||
7390 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||||
7391 | return Error(CAO); | ||||||
7392 | |||||||
7393 | APValue RHS; | ||||||
7394 | |||||||
7395 | // The overall lvalue result is the result of evaluating the LHS. | ||||||
7396 | if (!this->Visit(CAO->getLHS())) { | ||||||
7397 | if (Info.noteFailure()) | ||||||
7398 | Evaluate(RHS, this->Info, CAO->getRHS()); | ||||||
7399 | return false; | ||||||
7400 | } | ||||||
7401 | |||||||
7402 | if (!Evaluate(RHS, this->Info, CAO->getRHS())) | ||||||
7403 | return false; | ||||||
7404 | |||||||
7405 | return handleCompoundAssignment( | ||||||
7406 | this->Info, CAO, | ||||||
7407 | Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), | ||||||
7408 | CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); | ||||||
7409 | } | ||||||
7410 | |||||||
7411 | bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { | ||||||
7412 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||||
7413 | return Error(E); | ||||||
7414 | |||||||
7415 | APValue NewVal; | ||||||
7416 | |||||||
7417 | if (!this->Visit(E->getLHS())) { | ||||||
7418 | if (Info.noteFailure()) | ||||||
7419 | Evaluate(NewVal, this->Info, E->getRHS()); | ||||||
7420 | return false; | ||||||
7421 | } | ||||||
7422 | |||||||
7423 | if (!Evaluate(NewVal, this->Info, E->getRHS())) | ||||||
7424 | return false; | ||||||
7425 | |||||||
7426 | if (Info.getLangOpts().CPlusPlus2a && | ||||||
7427 | !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) | ||||||
7428 | return false; | ||||||
7429 | |||||||
7430 | return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), | ||||||
7431 | NewVal); | ||||||
7432 | } | ||||||
7433 | |||||||
7434 | //===----------------------------------------------------------------------===// | ||||||
7435 | // Pointer Evaluation | ||||||
7436 | //===----------------------------------------------------------------------===// | ||||||
7437 | |||||||
7438 | /// Attempts to compute the number of bytes available at the pointer | ||||||
7439 | /// returned by a function with the alloc_size attribute. Returns true if we | ||||||
7440 | /// were successful. Places an unsigned number into `Result`. | ||||||
7441 | /// | ||||||
7442 | /// This expects the given CallExpr to be a call to a function with an | ||||||
7443 | /// alloc_size attribute. | ||||||
7444 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, | ||||||
7445 | const CallExpr *Call, | ||||||
7446 | llvm::APInt &Result) { | ||||||
7447 | const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); | ||||||
7448 | |||||||
7449 | assert(AllocSize && AllocSize->getElemSizeParam().isValid())((AllocSize && AllocSize->getElemSizeParam().isValid ()) ? static_cast<void> (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam().isValid()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7449, __PRETTY_FUNCTION__)); | ||||||
7450 | unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); | ||||||
7451 | unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); | ||||||
7452 | if (Call->getNumArgs() <= SizeArgNo) | ||||||
7453 | return false; | ||||||
7454 | |||||||
7455 | auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { | ||||||
7456 | Expr::EvalResult ExprResult; | ||||||
7457 | if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) | ||||||
7458 | return false; | ||||||
7459 | Into = ExprResult.Val.getInt(); | ||||||
7460 | if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) | ||||||
7461 | return false; | ||||||
7462 | Into = Into.zextOrSelf(BitsInSizeT); | ||||||
7463 | return true; | ||||||
7464 | }; | ||||||
7465 | |||||||
7466 | APSInt SizeOfElem; | ||||||
7467 | if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) | ||||||
7468 | return false; | ||||||
7469 | |||||||
7470 | if (!AllocSize->getNumElemsParam().isValid()) { | ||||||
7471 | Result = std::move(SizeOfElem); | ||||||
7472 | return true; | ||||||
7473 | } | ||||||
7474 | |||||||
7475 | APSInt NumberOfElems; | ||||||
7476 | unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); | ||||||
7477 | if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) | ||||||
7478 | return false; | ||||||
7479 | |||||||
7480 | bool Overflow; | ||||||
7481 | llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); | ||||||
7482 | if (Overflow) | ||||||
7483 | return false; | ||||||
7484 | |||||||
7485 | Result = std::move(BytesAvailable); | ||||||
7486 | return true; | ||||||
7487 | } | ||||||
7488 | |||||||
7489 | /// Convenience function. LVal's base must be a call to an alloc_size | ||||||
7490 | /// function. | ||||||
7491 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, | ||||||
7492 | const LValue &LVal, | ||||||
7493 | llvm::APInt &Result) { | ||||||
7494 | assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&((isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function" ) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7495, __PRETTY_FUNCTION__)) | ||||||
7495 | "Can't get the size of a non alloc_size function")((isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function" ) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7495, __PRETTY_FUNCTION__)); | ||||||
7496 | const auto *Base = LVal.getLValueBase().get<const Expr *>(); | ||||||
7497 | const CallExpr *CE = tryUnwrapAllocSizeCall(Base); | ||||||
7498 | return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); | ||||||
7499 | } | ||||||
7500 | |||||||
7501 | /// Attempts to evaluate the given LValueBase as the result of a call to | ||||||
7502 | /// a function with the alloc_size attribute. If it was possible to do so, this | ||||||
7503 | /// function will return true, make Result's Base point to said function call, | ||||||
7504 | /// and mark Result's Base as invalid. | ||||||
7505 | static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, | ||||||
7506 | LValue &Result) { | ||||||
7507 | if (Base.isNull()) | ||||||
7508 | return false; | ||||||
7509 | |||||||
7510 | // Because we do no form of static analysis, we only support const variables. | ||||||
7511 | // | ||||||
7512 | // Additionally, we can't support parameters, nor can we support static | ||||||
7513 | // variables (in the latter case, use-before-assign isn't UB; in the former, | ||||||
7514 | // we have no clue what they'll be assigned to). | ||||||
7515 | const auto *VD = | ||||||
7516 | dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); | ||||||
7517 | if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) | ||||||
7518 | return false; | ||||||
7519 | |||||||
7520 | const Expr *Init = VD->getAnyInitializer(); | ||||||
7521 | if (!Init) | ||||||
7522 | return false; | ||||||
7523 | |||||||
7524 | const Expr *E = Init->IgnoreParens(); | ||||||
7525 | if (!tryUnwrapAllocSizeCall(E)) | ||||||
7526 | return false; | ||||||
7527 | |||||||
7528 | // Store E instead of E unwrapped so that the type of the LValue's base is | ||||||
7529 | // what the user wanted. | ||||||
7530 | Result.setInvalid(E); | ||||||
7531 | |||||||
7532 | QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); | ||||||
7533 | Result.addUnsizedArray(Info, E, Pointee); | ||||||
7534 | return true; | ||||||
7535 | } | ||||||
7536 | |||||||
7537 | namespace { | ||||||
7538 | class PointerExprEvaluator | ||||||
7539 | : public ExprEvaluatorBase<PointerExprEvaluator> { | ||||||
7540 | LValue &Result; | ||||||
7541 | bool InvalidBaseOK; | ||||||
7542 | |||||||
7543 | bool Success(const Expr *E) { | ||||||
7544 | Result.set(E); | ||||||
7545 | return true; | ||||||
7546 | } | ||||||
7547 | |||||||
7548 | bool evaluateLValue(const Expr *E, LValue &Result) { | ||||||
7549 | return EvaluateLValue(E, Result, Info, InvalidBaseOK); | ||||||
7550 | } | ||||||
7551 | |||||||
7552 | bool evaluatePointer(const Expr *E, LValue &Result) { | ||||||
7553 | return EvaluatePointer(E, Result, Info, InvalidBaseOK); | ||||||
7554 | } | ||||||
7555 | |||||||
7556 | bool visitNonBuiltinCallExpr(const CallExpr *E); | ||||||
7557 | public: | ||||||
7558 | |||||||
7559 | PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) | ||||||
7560 | : ExprEvaluatorBaseTy(info), Result(Result), | ||||||
7561 | InvalidBaseOK(InvalidBaseOK) {} | ||||||
7562 | |||||||
7563 | bool Success(const APValue &V, const Expr *E) { | ||||||
7564 | Result.setFrom(Info.Ctx, V); | ||||||
7565 | return true; | ||||||
7566 | } | ||||||
7567 | bool ZeroInitialization(const Expr *E) { | ||||||
7568 | auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); | ||||||
7569 | Result.setNull(E->getType(), TargetVal); | ||||||
7570 | return true; | ||||||
7571 | } | ||||||
7572 | |||||||
7573 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||||
7574 | bool VisitCastExpr(const CastExpr* E); | ||||||
7575 | bool VisitUnaryAddrOf(const UnaryOperator *E); | ||||||
7576 | bool VisitObjCStringLiteral(const ObjCStringLiteral *E) | ||||||
7577 | { return Success(E); } | ||||||
7578 | bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { | ||||||
7579 | if (E->isExpressibleAsConstantInitializer()) | ||||||
7580 | return Success(E); | ||||||
7581 | if (Info.noteFailure()) | ||||||
7582 | EvaluateIgnoredValue(Info, E->getSubExpr()); | ||||||
7583 | return Error(E); | ||||||
7584 | } | ||||||
7585 | bool VisitAddrLabelExpr(const AddrLabelExpr *E) | ||||||
7586 | { return Success(E); } | ||||||
7587 | bool VisitCallExpr(const CallExpr *E); | ||||||
7588 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); | ||||||
7589 | bool VisitBlockExpr(const BlockExpr *E) { | ||||||
7590 | if (!E->getBlockDecl()->hasCaptures()) | ||||||
7591 | return Success(E); | ||||||
7592 | return Error(E); | ||||||
7593 | } | ||||||
7594 | bool VisitCXXThisExpr(const CXXThisExpr *E) { | ||||||
7595 | // Can't look at 'this' when checking a potential constant expression. | ||||||
7596 | if (Info.checkingPotentialConstantExpression()) | ||||||
7597 | return false; | ||||||
7598 | if (!Info.CurrentCall->This) { | ||||||
7599 | if (Info.getLangOpts().CPlusPlus11) | ||||||
7600 | Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); | ||||||
7601 | else | ||||||
7602 | Info.FFDiag(E); | ||||||
7603 | return false; | ||||||
7604 | } | ||||||
7605 | Result = *Info.CurrentCall->This; | ||||||
7606 | // If we are inside a lambda's call operator, the 'this' expression refers | ||||||
7607 | // to the enclosing '*this' object (either by value or reference) which is | ||||||
7608 | // either copied into the closure object's field that represents the '*this' | ||||||
7609 | // or refers to '*this'. | ||||||
7610 | if (isLambdaCallOperator(Info.CurrentCall->Callee)) { | ||||||
7611 | // Update 'Result' to refer to the data member/field of the closure object | ||||||
7612 | // that represents the '*this' capture. | ||||||
7613 | if (!HandleLValueMember(Info, E, Result, | ||||||
7614 | Info.CurrentCall->LambdaThisCaptureField)) | ||||||
7615 | return false; | ||||||
7616 | // If we captured '*this' by reference, replace the field with its referent. | ||||||
7617 | if (Info.CurrentCall->LambdaThisCaptureField->getType() | ||||||
7618 | ->isPointerType()) { | ||||||
7619 | APValue RVal; | ||||||
7620 | if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, | ||||||
7621 | RVal)) | ||||||
7622 | return false; | ||||||
7623 | |||||||
7624 | Result.setFrom(Info.Ctx, RVal); | ||||||
7625 | } | ||||||
7626 | } | ||||||
7627 | return true; | ||||||
7628 | } | ||||||
7629 | |||||||
7630 | bool VisitCXXNewExpr(const CXXNewExpr *E); | ||||||
7631 | |||||||
7632 | bool VisitSourceLocExpr(const SourceLocExpr *E) { | ||||||
7633 | assert(E->isStringType() && "SourceLocExpr isn't a pointer type?")((E->isStringType() && "SourceLocExpr isn't a pointer type?" ) ? static_cast<void> (0) : __assert_fail ("E->isStringType() && \"SourceLocExpr isn't a pointer type?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7633, __PRETTY_FUNCTION__)); | ||||||
7634 | APValue LValResult = E->EvaluateInContext( | ||||||
7635 | Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); | ||||||
7636 | Result.setFrom(Info.Ctx, LValResult); | ||||||
7637 | return true; | ||||||
7638 | } | ||||||
7639 | |||||||
7640 | // FIXME: Missing: @protocol, @selector | ||||||
7641 | }; | ||||||
7642 | } // end anonymous namespace | ||||||
7643 | |||||||
7644 | static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, | ||||||
7645 | bool InvalidBaseOK) { | ||||||
7646 | assert(E->isRValue() && E->getType()->hasPointerRepresentation())((E->isRValue() && E->getType()->hasPointerRepresentation ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->hasPointerRepresentation()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7646, __PRETTY_FUNCTION__)); | ||||||
7647 | return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); | ||||||
7648 | } | ||||||
7649 | |||||||
7650 | bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||||
7651 | if (E->getOpcode() != BO_Add && | ||||||
7652 | E->getOpcode() != BO_Sub) | ||||||
7653 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||||
7654 | |||||||
7655 | const Expr *PExp = E->getLHS(); | ||||||
7656 | const Expr *IExp = E->getRHS(); | ||||||
7657 | if (IExp->getType()->isPointerType()) | ||||||
7658 | std::swap(PExp, IExp); | ||||||
7659 | |||||||
7660 | bool EvalPtrOK = evaluatePointer(PExp, Result); | ||||||
7661 | if (!EvalPtrOK && !Info.noteFailure()) | ||||||
7662 | return false; | ||||||
7663 | |||||||
7664 | llvm::APSInt Offset; | ||||||
7665 | if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) | ||||||
7666 | return false; | ||||||
7667 | |||||||
7668 | if (E->getOpcode() == BO_Sub) | ||||||
7669 | negateAsSigned(Offset); | ||||||
7670 | |||||||
7671 | QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); | ||||||
7672 | return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); | ||||||
7673 | } | ||||||
7674 | |||||||
7675 | bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { | ||||||
7676 | return evaluateLValue(E->getSubExpr(), Result); | ||||||
7677 | } | ||||||
7678 | |||||||
7679 | bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||||
7680 | const Expr *SubExpr = E->getSubExpr(); | ||||||
7681 | |||||||
7682 | switch (E->getCastKind()) { | ||||||
7683 | default: | ||||||
7684 | break; | ||||||
7685 | case CK_BitCast: | ||||||
7686 | case CK_CPointerToObjCPointerCast: | ||||||
7687 | case CK_BlockPointerToObjCPointerCast: | ||||||
7688 | case CK_AnyPointerToBlockPointerCast: | ||||||
7689 | case CK_AddressSpaceConversion: | ||||||
7690 | if (!Visit(SubExpr)) | ||||||
7691 | return false; | ||||||
7692 | // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are | ||||||
7693 | // permitted in constant expressions in C++11. Bitcasts from cv void* are | ||||||
7694 | // also static_casts, but we disallow them as a resolution to DR1312. | ||||||
7695 | if (!E->getType()->isVoidPointerType()) { | ||||||
7696 | Result.Designator.setInvalid(); | ||||||
7697 | if (SubExpr->getType()->isVoidPointerType()) | ||||||
7698 | CCEDiag(E, diag::note_constexpr_invalid_cast) | ||||||
7699 | << 3 << SubExpr->getType(); | ||||||
7700 | else | ||||||
7701 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||||
7702 | } | ||||||
7703 | if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) | ||||||
7704 | ZeroInitialization(E); | ||||||
7705 | return true; | ||||||
7706 | |||||||
7707 | case CK_DerivedToBase: | ||||||
7708 | case CK_UncheckedDerivedToBase: | ||||||
7709 | if (!evaluatePointer(E->getSubExpr(), Result)) | ||||||
7710 | return false; | ||||||
7711 | if (!Result.Base && Result.Offset.isZero()) | ||||||
7712 | return true; | ||||||
7713 | |||||||
7714 | // Now figure out the necessary offset to add to the base LV to get from | ||||||
7715 | // the derived class to the base class. | ||||||
7716 | return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> | ||||||
7717 | castAs<PointerType>()->getPointeeType(), | ||||||
7718 | Result); | ||||||
7719 | |||||||
7720 | case CK_BaseToDerived: | ||||||
7721 | if (!Visit(E->getSubExpr())) | ||||||
7722 | return false; | ||||||
7723 | if (!Result.Base && Result.Offset.isZero()) | ||||||
7724 | return true; | ||||||
7725 | return HandleBaseToDerivedCast(Info, E, Result); | ||||||
7726 | |||||||
7727 | case CK_Dynamic: | ||||||
7728 | if (!Visit(E->getSubExpr())) | ||||||
7729 | return false; | ||||||
7730 | return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); | ||||||
7731 | |||||||
7732 | case CK_NullToPointer: | ||||||
7733 | VisitIgnoredValue(E->getSubExpr()); | ||||||
7734 | return ZeroInitialization(E); | ||||||
7735 | |||||||
7736 | case CK_IntegralToPointer: { | ||||||
7737 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||||
7738 | |||||||
7739 | APValue Value; | ||||||
7740 | if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) | ||||||
7741 | break; | ||||||
7742 | |||||||
7743 | if (Value.isInt()) { | ||||||
7744 | unsigned Size = Info.Ctx.getTypeSize(E->getType()); | ||||||
7745 | uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); | ||||||
7746 | Result.Base = (Expr*)nullptr; | ||||||
7747 | Result.InvalidBase = false; | ||||||
7748 | Result.Offset = CharUnits::fromQuantity(N); | ||||||
7749 | Result.Designator.setInvalid(); | ||||||
7750 | Result.IsNullPtr = false; | ||||||
7751 | return true; | ||||||
7752 | } else { | ||||||
7753 | // Cast is of an lvalue, no need to change value. | ||||||
7754 | Result.setFrom(Info.Ctx, Value); | ||||||
7755 | return true; | ||||||
7756 | } | ||||||
7757 | } | ||||||
7758 | |||||||
7759 | case CK_ArrayToPointerDecay: { | ||||||
7760 | if (SubExpr->isGLValue()) { | ||||||
7761 | if (!evaluateLValue(SubExpr, Result)) | ||||||
7762 | return false; | ||||||
7763 | } else { | ||||||
7764 | APValue &Value = Info.CurrentCall->createTemporary( | ||||||
7765 | SubExpr, SubExpr->getType(), false, Result); | ||||||
7766 | if (!EvaluateInPlace(Value, Info, Result, SubExpr)) | ||||||
7767 | return false; | ||||||
7768 | } | ||||||
7769 | // The result is a pointer to the first element of the array. | ||||||
7770 | auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); | ||||||
7771 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) | ||||||
7772 | Result.addArray(Info, E, CAT); | ||||||
7773 | else | ||||||
7774 | Result.addUnsizedArray(Info, E, AT->getElementType()); | ||||||
7775 | return true; | ||||||
7776 | } | ||||||
7777 | |||||||
7778 | case CK_FunctionToPointerDecay: | ||||||
7779 | return evaluateLValue(SubExpr, Result); | ||||||
7780 | |||||||
7781 | case CK_LValueToRValue: { | ||||||
7782 | LValue LVal; | ||||||
7783 | if (!evaluateLValue(E->getSubExpr(), LVal)) | ||||||
7784 | return false; | ||||||
7785 | |||||||
7786 | APValue RVal; | ||||||
7787 | // Note, we use the subexpression's type in order to retain cv-qualifiers. | ||||||
7788 | if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), | ||||||
7789 | LVal, RVal)) | ||||||
7790 | return InvalidBaseOK && | ||||||
7791 | evaluateLValueAsAllocSize(Info, LVal.Base, Result); | ||||||
7792 | return Success(RVal, E); | ||||||
7793 | } | ||||||
7794 | } | ||||||
7795 | |||||||
7796 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
7797 | } | ||||||
7798 | |||||||
7799 | static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, | ||||||
7800 | UnaryExprOrTypeTrait ExprKind) { | ||||||
7801 | // C++ [expr.alignof]p3: | ||||||
7802 | // When alignof is applied to a reference type, the result is the | ||||||
7803 | // alignment of the referenced type. | ||||||
7804 | if (const ReferenceType *Ref = T->getAs<ReferenceType>()) | ||||||
7805 | T = Ref->getPointeeType(); | ||||||
7806 | |||||||
7807 | if (T.getQualifiers().hasUnaligned()) | ||||||
7808 | return CharUnits::One(); | ||||||
7809 | |||||||
7810 | const bool AlignOfReturnsPreferred = | ||||||
7811 | Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; | ||||||
7812 | |||||||
7813 | // __alignof is defined to return the preferred alignment. | ||||||
7814 | // Before 8, clang returned the preferred alignment for alignof and _Alignof | ||||||
7815 | // as well. | ||||||
7816 | if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) | ||||||
7817 | return Info.Ctx.toCharUnitsFromBits( | ||||||
7818 | Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); | ||||||
7819 | // alignof and _Alignof are defined to return the ABI alignment. | ||||||
7820 | else if (ExprKind == UETT_AlignOf) | ||||||
7821 | return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); | ||||||
7822 | else | ||||||
7823 | llvm_unreachable("GetAlignOfType on a non-alignment ExprKind")::llvm::llvm_unreachable_internal("GetAlignOfType on a non-alignment ExprKind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7823); | ||||||
7824 | } | ||||||
7825 | |||||||
7826 | static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, | ||||||
7827 | UnaryExprOrTypeTrait ExprKind) { | ||||||
7828 | E = E->IgnoreParens(); | ||||||
7829 | |||||||
7830 | // The kinds of expressions that we have special-case logic here for | ||||||
7831 | // should be kept up to date with the special checks for those | ||||||
7832 | // expressions in Sema. | ||||||
7833 | |||||||
7834 | // alignof decl is always accepted, even if it doesn't make sense: we default | ||||||
7835 | // to 1 in those cases. | ||||||
7836 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||||
7837 | return Info.Ctx.getDeclAlign(DRE->getDecl(), | ||||||
7838 | /*RefAsPointee*/true); | ||||||
7839 | |||||||
7840 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||||
7841 | return Info.Ctx.getDeclAlign(ME->getMemberDecl(), | ||||||
7842 | /*RefAsPointee*/true); | ||||||
7843 | |||||||
7844 | return GetAlignOfType(Info, E->getType(), ExprKind); | ||||||
7845 | } | ||||||
7846 | |||||||
7847 | // To be clear: this happily visits unsupported builtins. Better name welcomed. | ||||||
7848 | bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { | ||||||
7849 | if (ExprEvaluatorBaseTy::VisitCallExpr(E)) | ||||||
7850 | return true; | ||||||
7851 | |||||||
7852 | if (!(InvalidBaseOK && getAllocSizeAttr(E))) | ||||||
7853 | return false; | ||||||
7854 | |||||||
7855 | Result.setInvalid(E); | ||||||
7856 | QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); | ||||||
7857 | Result.addUnsizedArray(Info, E, PointeeTy); | ||||||
7858 | return true; | ||||||
7859 | } | ||||||
7860 | |||||||
7861 | bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||||
7862 | if (IsStringLiteralCall(E)) | ||||||
7863 | return Success(E); | ||||||
7864 | |||||||
7865 | if (unsigned BuiltinOp = E->getBuiltinCallee()) | ||||||
7866 | return VisitBuiltinCallExpr(E, BuiltinOp); | ||||||
7867 | |||||||
7868 | return visitNonBuiltinCallExpr(E); | ||||||
7869 | } | ||||||
7870 | |||||||
7871 | bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, | ||||||
7872 | unsigned BuiltinOp) { | ||||||
7873 | switch (BuiltinOp) { | ||||||
7874 | case Builtin::BI__builtin_addressof: | ||||||
7875 | return evaluateLValue(E->getArg(0), Result); | ||||||
7876 | case Builtin::BI__builtin_assume_aligned: { | ||||||
7877 | // We need to be very careful here because: if the pointer does not have the | ||||||
7878 | // asserted alignment, then the behavior is undefined, and undefined | ||||||
7879 | // behavior is non-constant. | ||||||
7880 | if (!evaluatePointer(E->getArg(0), Result)) | ||||||
7881 | return false; | ||||||
7882 | |||||||
7883 | LValue OffsetResult(Result); | ||||||
7884 | APSInt Alignment; | ||||||
7885 | if (!EvaluateInteger(E->getArg(1), Alignment, Info)) | ||||||
7886 | return false; | ||||||
7887 | CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); | ||||||
7888 | |||||||
7889 | if (E->getNumArgs() > 2) { | ||||||
7890 | APSInt Offset; | ||||||
7891 | if (!EvaluateInteger(E->getArg(2), Offset, Info)) | ||||||
7892 | return false; | ||||||
7893 | |||||||
7894 | int64_t AdditionalOffset = -Offset.getZExtValue(); | ||||||
7895 | OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); | ||||||
7896 | } | ||||||
7897 | |||||||
7898 | // If there is a base object, then it must have the correct alignment. | ||||||
7899 | if (OffsetResult.Base) { | ||||||
7900 | CharUnits BaseAlignment; | ||||||
7901 | if (const ValueDecl *VD = | ||||||
7902 | OffsetResult.Base.dyn_cast<const ValueDecl*>()) { | ||||||
7903 | BaseAlignment = Info.Ctx.getDeclAlign(VD); | ||||||
7904 | } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) { | ||||||
7905 | BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf); | ||||||
7906 | } else { | ||||||
7907 | BaseAlignment = GetAlignOfType( | ||||||
7908 | Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf); | ||||||
7909 | } | ||||||
7910 | |||||||
7911 | if (BaseAlignment < Align) { | ||||||
7912 | Result.Designator.setInvalid(); | ||||||
7913 | // FIXME: Add support to Diagnostic for long / long long. | ||||||
7914 | CCEDiag(E->getArg(0), | ||||||
7915 | diag::note_constexpr_baa_insufficient_alignment) << 0 | ||||||
7916 | << (unsigned)BaseAlignment.getQuantity() | ||||||
7917 | << (unsigned)Align.getQuantity(); | ||||||
7918 | return false; | ||||||
7919 | } | ||||||
7920 | } | ||||||
7921 | |||||||
7922 | // The offset must also have the correct alignment. | ||||||
7923 | if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { | ||||||
7924 | Result.Designator.setInvalid(); | ||||||
7925 | |||||||
7926 | (OffsetResult.Base | ||||||
7927 | ? CCEDiag(E->getArg(0), | ||||||
7928 | diag::note_constexpr_baa_insufficient_alignment) << 1 | ||||||
7929 | : CCEDiag(E->getArg(0), | ||||||
7930 | diag::note_constexpr_baa_value_insufficient_alignment)) | ||||||
7931 | << (int)OffsetResult.Offset.getQuantity() | ||||||
7932 | << (unsigned)Align.getQuantity(); | ||||||
7933 | return false; | ||||||
7934 | } | ||||||
7935 | |||||||
7936 | return true; | ||||||
7937 | } | ||||||
7938 | case Builtin::BI__builtin_launder: | ||||||
7939 | return evaluatePointer(E->getArg(0), Result); | ||||||
7940 | case Builtin::BIstrchr: | ||||||
7941 | case Builtin::BIwcschr: | ||||||
7942 | case Builtin::BImemchr: | ||||||
7943 | case Builtin::BIwmemchr: | ||||||
7944 | if (Info.getLangOpts().CPlusPlus11) | ||||||
7945 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||||
7946 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||||
7947 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||||
7948 | else | ||||||
7949 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
7950 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
7951 | case Builtin::BI__builtin_strchr: | ||||||
7952 | case Builtin::BI__builtin_wcschr: | ||||||
7953 | case Builtin::BI__builtin_memchr: | ||||||
7954 | case Builtin::BI__builtin_char_memchr: | ||||||
7955 | case Builtin::BI__builtin_wmemchr: { | ||||||
7956 | if (!Visit(E->getArg(0))) | ||||||
7957 | return false; | ||||||
7958 | APSInt Desired; | ||||||
7959 | if (!EvaluateInteger(E->getArg(1), Desired, Info)) | ||||||
7960 | return false; | ||||||
7961 | uint64_t MaxLength = uint64_t(-1); | ||||||
7962 | if (BuiltinOp != Builtin::BIstrchr && | ||||||
7963 | BuiltinOp != Builtin::BIwcschr && | ||||||
7964 | BuiltinOp != Builtin::BI__builtin_strchr && | ||||||
7965 | BuiltinOp != Builtin::BI__builtin_wcschr) { | ||||||
7966 | APSInt N; | ||||||
7967 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||||
7968 | return false; | ||||||
7969 | MaxLength = N.getExtValue(); | ||||||
7970 | } | ||||||
7971 | // We cannot find the value if there are no candidates to match against. | ||||||
7972 | if (MaxLength == 0u) | ||||||
7973 | return ZeroInitialization(E); | ||||||
7974 | if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||||
7975 | Result.Designator.Invalid) | ||||||
7976 | return false; | ||||||
7977 | QualType CharTy = Result.Designator.getType(Info.Ctx); | ||||||
7978 | bool IsRawByte = BuiltinOp == Builtin::BImemchr || | ||||||
7979 | BuiltinOp == Builtin::BI__builtin_memchr; | ||||||
7980 | assert(IsRawByte ||((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E-> getArg(0)->getType()->getPointeeType())) ? static_cast< void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7982, __PRETTY_FUNCTION__)) | ||||||
7981 | Info.Ctx.hasSameUnqualifiedType(((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E-> getArg(0)->getType()->getPointeeType())) ? static_cast< void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7982, __PRETTY_FUNCTION__)) | ||||||
7982 | CharTy, E->getArg(0)->getType()->getPointeeType()))((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E-> getArg(0)->getType()->getPointeeType())) ? static_cast< void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7982, __PRETTY_FUNCTION__)); | ||||||
7983 | // Pointers to const void may point to objects of incomplete type. | ||||||
7984 | if (IsRawByte && CharTy->isIncompleteType()) { | ||||||
7985 | Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; | ||||||
7986 | return false; | ||||||
7987 | } | ||||||
7988 | // Give up on byte-oriented matching against multibyte elements. | ||||||
7989 | // FIXME: We can compare the bytes in the correct order. | ||||||
7990 | if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) | ||||||
7991 | return false; | ||||||
7992 | // Figure out what value we're actually looking for (after converting to | ||||||
7993 | // the corresponding unsigned type if necessary). | ||||||
7994 | uint64_t DesiredVal; | ||||||
7995 | bool StopAtNull = false; | ||||||
7996 | switch (BuiltinOp) { | ||||||
7997 | case Builtin::BIstrchr: | ||||||
7998 | case Builtin::BI__builtin_strchr: | ||||||
7999 | // strchr compares directly to the passed integer, and therefore | ||||||
8000 | // always fails if given an int that is not a char. | ||||||
8001 | if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, | ||||||
8002 | E->getArg(1)->getType(), | ||||||
8003 | Desired), | ||||||
8004 | Desired)) | ||||||
8005 | return ZeroInitialization(E); | ||||||
8006 | StopAtNull = true; | ||||||
8007 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
8008 | case Builtin::BImemchr: | ||||||
8009 | case Builtin::BI__builtin_memchr: | ||||||
8010 | case Builtin::BI__builtin_char_memchr: | ||||||
8011 | // memchr compares by converting both sides to unsigned char. That's also | ||||||
8012 | // correct for strchr if we get this far (to cope with plain char being | ||||||
8013 | // unsigned in the strchr case). | ||||||
8014 | DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); | ||||||
8015 | break; | ||||||
8016 | |||||||
8017 | case Builtin::BIwcschr: | ||||||
8018 | case Builtin::BI__builtin_wcschr: | ||||||
8019 | StopAtNull = true; | ||||||
8020 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
8021 | case Builtin::BIwmemchr: | ||||||
8022 | case Builtin::BI__builtin_wmemchr: | ||||||
8023 | // wcschr and wmemchr are given a wchar_t to look for. Just use it. | ||||||
8024 | DesiredVal = Desired.getZExtValue(); | ||||||
8025 | break; | ||||||
8026 | } | ||||||
8027 | |||||||
8028 | for (; MaxLength; --MaxLength) { | ||||||
8029 | APValue Char; | ||||||
8030 | if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || | ||||||
8031 | !Char.isInt()) | ||||||
8032 | return false; | ||||||
8033 | if (Char.getInt().getZExtValue() == DesiredVal) | ||||||
8034 | return true; | ||||||
8035 | if (StopAtNull && !Char.getInt()) | ||||||
8036 | break; | ||||||
8037 | if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) | ||||||
8038 | return false; | ||||||
8039 | } | ||||||
8040 | // Not found: return nullptr. | ||||||
8041 | return ZeroInitialization(E); | ||||||
8042 | } | ||||||
8043 | |||||||
8044 | case Builtin::BImemcpy: | ||||||
8045 | case Builtin::BImemmove: | ||||||
8046 | case Builtin::BIwmemcpy: | ||||||
8047 | case Builtin::BIwmemmove: | ||||||
8048 | if (Info.getLangOpts().CPlusPlus11) | ||||||
8049 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||||
8050 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||||
8051 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||||
8052 | else | ||||||
8053 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
8054 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
8055 | case Builtin::BI__builtin_memcpy: | ||||||
8056 | case Builtin::BI__builtin_memmove: | ||||||
8057 | case Builtin::BI__builtin_wmemcpy: | ||||||
8058 | case Builtin::BI__builtin_wmemmove: { | ||||||
8059 | bool WChar = BuiltinOp == Builtin::BIwmemcpy || | ||||||
8060 | BuiltinOp == Builtin::BIwmemmove || | ||||||
8061 | BuiltinOp == Builtin::BI__builtin_wmemcpy || | ||||||
8062 | BuiltinOp == Builtin::BI__builtin_wmemmove; | ||||||
8063 | bool Move = BuiltinOp == Builtin::BImemmove || | ||||||
8064 | BuiltinOp == Builtin::BIwmemmove || | ||||||
8065 | BuiltinOp == Builtin::BI__builtin_memmove || | ||||||
8066 | BuiltinOp == Builtin::BI__builtin_wmemmove; | ||||||
8067 | |||||||
8068 | // The result of mem* is the first argument. | ||||||
8069 | if (!Visit(E->getArg(0))) | ||||||
8070 | return false; | ||||||
8071 | LValue Dest = Result; | ||||||
8072 | |||||||
8073 | LValue Src; | ||||||
8074 | if (!EvaluatePointer(E->getArg(1), Src, Info)) | ||||||
8075 | return false; | ||||||
8076 | |||||||
8077 | APSInt N; | ||||||
8078 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||||
8079 | return false; | ||||||
8080 | assert(!N.isSigned() && "memcpy and friends take an unsigned size")((!N.isSigned() && "memcpy and friends take an unsigned size" ) ? static_cast<void> (0) : __assert_fail ("!N.isSigned() && \"memcpy and friends take an unsigned size\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8080, __PRETTY_FUNCTION__)); | ||||||
8081 | |||||||
8082 | // If the size is zero, we treat this as always being a valid no-op. | ||||||
8083 | // (Even if one of the src and dest pointers is null.) | ||||||
8084 | if (!N) | ||||||
8085 | return true; | ||||||
8086 | |||||||
8087 | // Otherwise, if either of the operands is null, we can't proceed. Don't | ||||||
8088 | // try to determine the type of the copied objects, because there aren't | ||||||
8089 | // any. | ||||||
8090 | if (!Src.Base || !Dest.Base) { | ||||||
8091 | APValue Val; | ||||||
8092 | (!Src.Base ? Src : Dest).moveInto(Val); | ||||||
8093 | Info.FFDiag(E, diag::note_constexpr_memcpy_null) | ||||||
8094 | << Move << WChar << !!Src.Base | ||||||
8095 | << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); | ||||||
8096 | return false; | ||||||
8097 | } | ||||||
8098 | if (Src.Designator.Invalid || Dest.Designator.Invalid) | ||||||
8099 | return false; | ||||||
8100 | |||||||
8101 | // We require that Src and Dest are both pointers to arrays of | ||||||
8102 | // trivially-copyable type. (For the wide version, the designator will be | ||||||
8103 | // invalid if the designated object is not a wchar_t.) | ||||||
8104 | QualType T = Dest.Designator.getType(Info.Ctx); | ||||||
8105 | QualType SrcT = Src.Designator.getType(Info.Ctx); | ||||||
8106 | if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { | ||||||
8107 | Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; | ||||||
8108 | return false; | ||||||
8109 | } | ||||||
8110 | if (T->isIncompleteType()) { | ||||||
8111 | Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; | ||||||
8112 | return false; | ||||||
8113 | } | ||||||
8114 | if (!T.isTriviallyCopyableType(Info.Ctx)) { | ||||||
8115 | Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; | ||||||
8116 | return false; | ||||||
8117 | } | ||||||
8118 | |||||||
8119 | // Figure out how many T's we're copying. | ||||||
8120 | uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); | ||||||
8121 | if (!WChar) { | ||||||
8122 | uint64_t Remainder; | ||||||
8123 | llvm::APInt OrigN = N; | ||||||
8124 | llvm::APInt::udivrem(OrigN, TSize, N, Remainder); | ||||||
8125 | if (Remainder) { | ||||||
8126 | Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) | ||||||
8127 | << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) | ||||||
8128 | << (unsigned)TSize; | ||||||
8129 | return false; | ||||||
8130 | } | ||||||
8131 | } | ||||||
8132 | |||||||
8133 | // Check that the copying will remain within the arrays, just so that we | ||||||
8134 | // can give a more meaningful diagnostic. This implicitly also checks that | ||||||
8135 | // N fits into 64 bits. | ||||||
8136 | uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; | ||||||
8137 | uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; | ||||||
8138 | if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { | ||||||
8139 | Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) | ||||||
8140 | << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T | ||||||
8141 | << N.toString(10, /*Signed*/false); | ||||||
8142 | return false; | ||||||
8143 | } | ||||||
8144 | uint64_t NElems = N.getZExtValue(); | ||||||
8145 | uint64_t NBytes = NElems * TSize; | ||||||
8146 | |||||||
8147 | // Check for overlap. | ||||||
8148 | int Direction = 1; | ||||||
8149 | if (HasSameBase(Src, Dest)) { | ||||||
8150 | uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); | ||||||
8151 | uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); | ||||||
8152 | if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { | ||||||
8153 | // Dest is inside the source region. | ||||||
8154 | if (!Move) { | ||||||
8155 | Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; | ||||||
8156 | return false; | ||||||
8157 | } | ||||||
8158 | // For memmove and friends, copy backwards. | ||||||
8159 | if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || | ||||||
8160 | !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) | ||||||
8161 | return false; | ||||||
8162 | Direction = -1; | ||||||
8163 | } else if (!Move && SrcOffset >= DestOffset && | ||||||
8164 | SrcOffset - DestOffset < NBytes) { | ||||||
8165 | // Src is inside the destination region for memcpy: invalid. | ||||||
8166 | Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; | ||||||
8167 | return false; | ||||||
8168 | } | ||||||
8169 | } | ||||||
8170 | |||||||
8171 | while (true) { | ||||||
8172 | APValue Val; | ||||||
8173 | // FIXME: Set WantObjectRepresentation to true if we're copying a | ||||||
8174 | // char-like type? | ||||||
8175 | if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || | ||||||
8176 | !handleAssignment(Info, E, Dest, T, Val)) | ||||||
8177 | return false; | ||||||
8178 | // Do not iterate past the last element; if we're copying backwards, that | ||||||
8179 | // might take us off the start of the array. | ||||||
8180 | if (--NElems == 0) | ||||||
8181 | return true; | ||||||
8182 | if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || | ||||||
8183 | !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) | ||||||
8184 | return false; | ||||||
8185 | } | ||||||
8186 | } | ||||||
8187 | |||||||
8188 | default: | ||||||
8189 | return visitNonBuiltinCallExpr(E); | ||||||
8190 | } | ||||||
8191 | } | ||||||
8192 | |||||||
8193 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, | ||||||
8194 | APValue &Result, const InitListExpr *ILE, | ||||||
8195 | QualType AllocType); | ||||||
8196 | |||||||
8197 | bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { | ||||||
8198 | if (!Info.getLangOpts().CPlusPlus2a) | ||||||
8199 | Info.CCEDiag(E, diag::note_constexpr_new); | ||||||
8200 | |||||||
8201 | // We cannot speculatively evaluate a delete expression. | ||||||
8202 | if (Info.SpeculativeEvaluationDepth) | ||||||
8203 | return false; | ||||||
8204 | |||||||
8205 | FunctionDecl *OperatorNew = E->getOperatorNew(); | ||||||
8206 | if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { | ||||||
8207 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | ||||||
8208 | << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; | ||||||
8209 | return false; | ||||||
8210 | } | ||||||
8211 | |||||||
8212 | bool IsNothrow = false; | ||||||
8213 | if (E->getNumPlacementArgs()) { | ||||||
8214 | // The only new-placement list we support is of the form (std::nothrow). | ||||||
8215 | // | ||||||
8216 | // FIXME: There is no restriction on this, but it's not clear that any | ||||||
8217 | // other form makes any sense. We get here for cases such as: | ||||||
8218 | // | ||||||
8219 | // new (std::align_val_t{N}) X(int) | ||||||
8220 | // | ||||||
8221 | // (which should presumably be valid only if N is a multiple of | ||||||
8222 | // alignof(int), and in any case can't be deallocated unless N is | ||||||
8223 | // alignof(X) and X has new-extended alignment). | ||||||
8224 | if (E->getNumPlacementArgs() != 1 || | ||||||
8225 | !E->getPlacementArg(0)->getType()->isNothrowT()) | ||||||
8226 | return Error(E, diag::note_constexpr_new_placement); | ||||||
8227 | |||||||
8228 | LValue Nothrow; | ||||||
8229 | if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) | ||||||
8230 | return false; | ||||||
8231 | IsNothrow = true; | ||||||
8232 | } | ||||||
8233 | |||||||
8234 | const Expr *Init = E->getInitializer(); | ||||||
8235 | const InitListExpr *ResizedArrayILE = nullptr; | ||||||
8236 | |||||||
8237 | QualType AllocType = E->getAllocatedType(); | ||||||
8238 | if (Optional<const Expr*> ArraySize = E->getArraySize()) { | ||||||
8239 | const Expr *Stripped = *ArraySize; | ||||||
8240 | for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); | ||||||
8241 | Stripped = ICE->getSubExpr()) | ||||||
8242 | if (ICE->getCastKind() != CK_NoOp && | ||||||
8243 | ICE->getCastKind() != CK_IntegralCast) | ||||||
8244 | break; | ||||||
8245 | |||||||
8246 | llvm::APSInt ArrayBound; | ||||||
8247 | if (!EvaluateInteger(Stripped, ArrayBound, Info)) | ||||||
8248 | return false; | ||||||
8249 | |||||||
8250 | // C++ [expr.new]p9: | ||||||
8251 | // The expression is erroneous if: | ||||||
8252 | // -- [...] its value before converting to size_t [or] applying the | ||||||
8253 | // second standard conversion sequence is less than zero | ||||||
8254 | if (ArrayBound.isSigned() && ArrayBound.isNegative()) { | ||||||
8255 | if (IsNothrow) | ||||||
8256 | return ZeroInitialization(E); | ||||||
8257 | |||||||
8258 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) | ||||||
8259 | << ArrayBound << (*ArraySize)->getSourceRange(); | ||||||
8260 | return false; | ||||||
8261 | } | ||||||
8262 | |||||||
8263 | // -- its value is such that the size of the allocated object would | ||||||
8264 | // exceed the implementation-defined limit | ||||||
8265 | if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, | ||||||
8266 | ArrayBound) > | ||||||
8267 | ConstantArrayType::getMaxSizeBits(Info.Ctx)) { | ||||||
8268 | if (IsNothrow) | ||||||
8269 | return ZeroInitialization(E); | ||||||
8270 | |||||||
8271 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) | ||||||
8272 | << ArrayBound << (*ArraySize)->getSourceRange(); | ||||||
8273 | return false; | ||||||
8274 | } | ||||||
8275 | |||||||
8276 | // -- the new-initializer is a braced-init-list and the number of | ||||||
8277 | // array elements for which initializers are provided [...] | ||||||
8278 | // exceeds the number of elements to initialize | ||||||
8279 | if (Init) { | ||||||
8280 | auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); | ||||||
8281 | assert(CAT && "unexpected type for array initializer")((CAT && "unexpected type for array initializer") ? static_cast <void> (0) : __assert_fail ("CAT && \"unexpected type for array initializer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8281, __PRETTY_FUNCTION__)); | ||||||
8282 | |||||||
8283 | unsigned Bits = | ||||||
8284 | std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); | ||||||
8285 | llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); | ||||||
8286 | llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); | ||||||
8287 | if (InitBound.ugt(AllocBound)) { | ||||||
8288 | if (IsNothrow) | ||||||
8289 | return ZeroInitialization(E); | ||||||
8290 | |||||||
8291 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) | ||||||
8292 | << AllocBound.toString(10, /*Signed=*/false) | ||||||
8293 | << InitBound.toString(10, /*Signed=*/false) | ||||||
8294 | << (*ArraySize)->getSourceRange(); | ||||||
8295 | return false; | ||||||
8296 | } | ||||||
8297 | |||||||
8298 | // If the sizes differ, we must have an initializer list, and we need | ||||||
8299 | // special handling for this case when we initialize. | ||||||
8300 | if (InitBound != AllocBound) | ||||||
8301 | ResizedArrayILE = cast<InitListExpr>(Init); | ||||||
8302 | } | ||||||
8303 | |||||||
8304 | AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, | ||||||
8305 | ArrayType::Normal, 0); | ||||||
8306 | } else { | ||||||
8307 | assert(!AllocType->isArrayType() &&((!AllocType->isArrayType() && "array allocation with non-array new" ) ? static_cast<void> (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8308, __PRETTY_FUNCTION__)) | ||||||
8308 | "array allocation with non-array new")((!AllocType->isArrayType() && "array allocation with non-array new" ) ? static_cast<void> (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8308, __PRETTY_FUNCTION__)); | ||||||
8309 | } | ||||||
8310 | |||||||
8311 | // Perform the allocation and obtain a pointer to the resulting object. | ||||||
8312 | APValue *Val = Info.createHeapAlloc(E, AllocType, Result); | ||||||
8313 | if (!Val) | ||||||
8314 | return false; | ||||||
8315 | |||||||
8316 | if (ResizedArrayILE) { | ||||||
8317 | if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, | ||||||
8318 | AllocType)) | ||||||
8319 | return false; | ||||||
8320 | } else if (Init) { | ||||||
8321 | if (!EvaluateInPlace(*Val, Info, Result, Init)) | ||||||
8322 | return false; | ||||||
8323 | } else { | ||||||
8324 | *Val = getDefaultInitValue(AllocType); | ||||||
8325 | } | ||||||
8326 | |||||||
8327 | // Array new returns a pointer to the first element, not a pointer to the | ||||||
8328 | // array. | ||||||
8329 | if (auto *AT = AllocType->getAsArrayTypeUnsafe()) | ||||||
8330 | Result.addArray(Info, E, cast<ConstantArrayType>(AT)); | ||||||
8331 | |||||||
8332 | return true; | ||||||
8333 | } | ||||||
8334 | //===----------------------------------------------------------------------===// | ||||||
8335 | // Member Pointer Evaluation | ||||||
8336 | //===----------------------------------------------------------------------===// | ||||||
8337 | |||||||
8338 | namespace { | ||||||
8339 | class MemberPointerExprEvaluator | ||||||
8340 | : public ExprEvaluatorBase<MemberPointerExprEvaluator> { | ||||||
8341 | MemberPtr &Result; | ||||||
8342 | |||||||
8343 | bool Success(const ValueDecl *D) { | ||||||
8344 | Result = MemberPtr(D); | ||||||
8345 | return true; | ||||||
8346 | } | ||||||
8347 | public: | ||||||
8348 | |||||||
8349 | MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) | ||||||
8350 | : ExprEvaluatorBaseTy(Info), Result(Result) {} | ||||||
8351 | |||||||
8352 | bool Success(const APValue &V, const Expr *E) { | ||||||
8353 | Result.setFrom(V); | ||||||
8354 | return true; | ||||||
8355 | } | ||||||
8356 | bool ZeroInitialization(const Expr *E) { | ||||||
8357 | return Success((const ValueDecl*)nullptr); | ||||||
8358 | } | ||||||
8359 | |||||||
8360 | bool VisitCastExpr(const CastExpr *E); | ||||||
8361 | bool VisitUnaryAddrOf(const UnaryOperator *E); | ||||||
8362 | }; | ||||||
8363 | } // end anonymous namespace | ||||||
8364 | |||||||
8365 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, | ||||||
8366 | EvalInfo &Info) { | ||||||
8367 | assert(E->isRValue() && E->getType()->isMemberPointerType())((E->isRValue() && E->getType()->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8367, __PRETTY_FUNCTION__)); | ||||||
8368 | return MemberPointerExprEvaluator(Info, Result).Visit(E); | ||||||
8369 | } | ||||||
8370 | |||||||
8371 | bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||||
8372 | switch (E->getCastKind()) { | ||||||
8373 | default: | ||||||
8374 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
8375 | |||||||
8376 | case CK_NullToMemberPointer: | ||||||
8377 | VisitIgnoredValue(E->getSubExpr()); | ||||||
8378 | return ZeroInitialization(E); | ||||||
8379 | |||||||
8380 | case CK_BaseToDerivedMemberPointer: { | ||||||
8381 | if (!Visit(E->getSubExpr())) | ||||||
8382 | return false; | ||||||
8383 | if (E->path_empty()) | ||||||
8384 | return true; | ||||||
8385 | // Base-to-derived member pointer casts store the path in derived-to-base | ||||||
8386 | // order, so iterate backwards. The CXXBaseSpecifier also provides us with | ||||||
8387 | // the wrong end of the derived->base arc, so stagger the path by one class. | ||||||
8388 | typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; | ||||||
8389 | for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); | ||||||
8390 | PathI != PathE; ++PathI) { | ||||||
8391 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase")((!(*PathI)->isVirtual() && "memptr cast through vbase" ) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8391, __PRETTY_FUNCTION__)); | ||||||
8392 | const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||||
8393 | if (!Result.castToDerived(Derived)) | ||||||
8394 | return Error(E); | ||||||
8395 | } | ||||||
8396 | const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); | ||||||
8397 | if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) | ||||||
8398 | return Error(E); | ||||||
8399 | return true; | ||||||
8400 | } | ||||||
8401 | |||||||
8402 | case CK_DerivedToBaseMemberPointer: | ||||||
8403 | if (!Visit(E->getSubExpr())) | ||||||
8404 | return false; | ||||||
8405 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||||
8406 | PathE = E->path_end(); PathI != PathE; ++PathI) { | ||||||
8407 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase")((!(*PathI)->isVirtual() && "memptr cast through vbase" ) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8407, __PRETTY_FUNCTION__)); | ||||||
8408 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||||
8409 | if (!Result.castToBase(Base)) | ||||||
8410 | return Error(E); | ||||||
8411 | } | ||||||
8412 | return true; | ||||||
8413 | } | ||||||
8414 | } | ||||||
8415 | |||||||
8416 | bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { | ||||||
8417 | // C++11 [expr.unary.op]p3 has very strict rules on how the address of a | ||||||
8418 | // member can be formed. | ||||||
8419 | return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); | ||||||
8420 | } | ||||||
8421 | |||||||
8422 | //===----------------------------------------------------------------------===// | ||||||
8423 | // Record Evaluation | ||||||
8424 | //===----------------------------------------------------------------------===// | ||||||
8425 | |||||||
8426 | namespace { | ||||||
8427 | class RecordExprEvaluator | ||||||
8428 | : public ExprEvaluatorBase<RecordExprEvaluator> { | ||||||
8429 | const LValue &This; | ||||||
8430 | APValue &Result; | ||||||
8431 | public: | ||||||
8432 | |||||||
8433 | RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) | ||||||
8434 | : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} | ||||||
8435 | |||||||
8436 | bool Success(const APValue &V, const Expr *E) { | ||||||
8437 | Result = V; | ||||||
8438 | return true; | ||||||
8439 | } | ||||||
8440 | bool ZeroInitialization(const Expr *E) { | ||||||
8441 | return ZeroInitialization(E, E->getType()); | ||||||
8442 | } | ||||||
8443 | bool ZeroInitialization(const Expr *E, QualType T); | ||||||
8444 | |||||||
8445 | bool VisitCallExpr(const CallExpr *E) { | ||||||
8446 | return handleCallExpr(E, Result, &This); | ||||||
8447 | } | ||||||
8448 | bool VisitCastExpr(const CastExpr *E); | ||||||
8449 | bool VisitInitListExpr(const InitListExpr *E); | ||||||
8450 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||||
8451 | return VisitCXXConstructExpr(E, E->getType()); | ||||||
8452 | } | ||||||
8453 | bool VisitLambdaExpr(const LambdaExpr *E); | ||||||
8454 | bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); | ||||||
8455 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); | ||||||
8456 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); | ||||||
8457 | bool VisitBinCmp(const BinaryOperator *E); | ||||||
8458 | }; | ||||||
8459 | } | ||||||
8460 | |||||||
8461 | /// Perform zero-initialization on an object of non-union class type. | ||||||
8462 | /// C++11 [dcl.init]p5: | ||||||
8463 | /// To zero-initialize an object or reference of type T means: | ||||||
8464 | /// [...] | ||||||
8465 | /// -- if T is a (possibly cv-qualified) non-union class type, | ||||||
8466 | /// each non-static data member and each base-class subobject is | ||||||
8467 | /// zero-initialized | ||||||
8468 | static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, | ||||||
8469 | const RecordDecl *RD, | ||||||
8470 | const LValue &This, APValue &Result) { | ||||||
8471 | assert(!RD->isUnion() && "Expected non-union class type")((!RD->isUnion() && "Expected non-union class type" ) ? static_cast<void> (0) : __assert_fail ("!RD->isUnion() && \"Expected non-union class type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8471, __PRETTY_FUNCTION__)); | ||||||
8472 | const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); | ||||||
8473 | Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, | ||||||
8474 | std::distance(RD->field_begin(), RD->field_end())); | ||||||
8475 | |||||||
8476 | if (RD->isInvalidDecl()) return false; | ||||||
8477 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||||
8478 | |||||||
8479 | if (CD) { | ||||||
8480 | unsigned Index = 0; | ||||||
8481 | for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), | ||||||
8482 | End = CD->bases_end(); I != End; ++I, ++Index) { | ||||||
8483 | const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); | ||||||
8484 | LValue Subobject = This; | ||||||
8485 | if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) | ||||||
8486 | return false; | ||||||
8487 | if (!HandleClassZeroInitialization(Info, E, Base, Subobject, | ||||||
8488 | Result.getStructBase(Index))) | ||||||
8489 | return false; | ||||||
8490 | } | ||||||
8491 | } | ||||||
8492 | |||||||
8493 | for (const auto *I : RD->fields()) { | ||||||
8494 | // -- if T is a reference type, no initialization is performed. | ||||||
8495 | if (I->getType()->isReferenceType()) | ||||||
8496 | continue; | ||||||
8497 | |||||||
8498 | LValue Subobject = This; | ||||||
8499 | if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) | ||||||
8500 | return false; | ||||||
8501 | |||||||
8502 | ImplicitValueInitExpr VIE(I->getType()); | ||||||
8503 | if (!EvaluateInPlace( | ||||||
8504 | Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) | ||||||
8505 | return false; | ||||||
8506 | } | ||||||
8507 | |||||||
8508 | return true; | ||||||
8509 | } | ||||||
8510 | |||||||
8511 | bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { | ||||||
8512 | const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); | ||||||
8513 | if (RD->isInvalidDecl()) return false; | ||||||
8514 | if (RD->isUnion()) { | ||||||
8515 | // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the | ||||||
8516 | // object's first non-static named data member is zero-initialized | ||||||
8517 | RecordDecl::field_iterator I = RD->field_begin(); | ||||||
8518 | if (I == RD->field_end()) { | ||||||
8519 | Result = APValue((const FieldDecl*)nullptr); | ||||||
8520 | return true; | ||||||
8521 | } | ||||||
8522 | |||||||
8523 | LValue Subobject = This; | ||||||
8524 | if (!HandleLValueMember(Info, E, Subobject, *I)) | ||||||
8525 | return false; | ||||||
8526 | Result = APValue(*I); | ||||||
8527 | ImplicitValueInitExpr VIE(I->getType()); | ||||||
8528 | return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); | ||||||
8529 | } | ||||||
8530 | |||||||
8531 | if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { | ||||||
8532 | Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; | ||||||
8533 | return false; | ||||||
8534 | } | ||||||
8535 | |||||||
8536 | return HandleClassZeroInitialization(Info, E, RD, This, Result); | ||||||
8537 | } | ||||||
8538 | |||||||
8539 | bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||||
8540 | switch (E->getCastKind()) { | ||||||
8541 | default: | ||||||
8542 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
8543 | |||||||
8544 | case CK_ConstructorConversion: | ||||||
8545 | return Visit(E->getSubExpr()); | ||||||
8546 | |||||||
8547 | case CK_DerivedToBase: | ||||||
8548 | case CK_UncheckedDerivedToBase: { | ||||||
8549 | APValue DerivedObject; | ||||||
8550 | if (!Evaluate(DerivedObject, Info, E->getSubExpr())) | ||||||
8551 | return false; | ||||||
8552 | if (!DerivedObject.isStruct()) | ||||||
8553 | return Error(E->getSubExpr()); | ||||||
8554 | |||||||
8555 | // Derived-to-base rvalue conversion: just slice off the derived part. | ||||||
8556 | APValue *Value = &DerivedObject; | ||||||
8557 | const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); | ||||||
8558 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||||
8559 | PathE = E->path_end(); PathI != PathE; ++PathI) { | ||||||
8560 | assert(!(*PathI)->isVirtual() && "record rvalue with virtual base")((!(*PathI)->isVirtual() && "record rvalue with virtual base" ) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"record rvalue with virtual base\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8560, __PRETTY_FUNCTION__)); | ||||||
8561 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||||
8562 | Value = &Value->getStructBase(getBaseIndex(RD, Base)); | ||||||
8563 | RD = Base; | ||||||
8564 | } | ||||||
8565 | Result = *Value; | ||||||
8566 | return true; | ||||||
8567 | } | ||||||
8568 | } | ||||||
8569 | } | ||||||
8570 | |||||||
8571 | bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||||
8572 | if (E->isTransparent()) | ||||||
8573 | return Visit(E->getInit(0)); | ||||||
8574 | |||||||
8575 | const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); | ||||||
8576 | if (RD->isInvalidDecl()) return false; | ||||||
8577 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||||
8578 | auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); | ||||||
8579 | |||||||
8580 | EvalInfo::EvaluatingConstructorRAII EvalObj( | ||||||
8581 | Info, | ||||||
8582 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, | ||||||
8583 | CXXRD && CXXRD->getNumBases()); | ||||||
8584 | |||||||
8585 | if (RD->isUnion()) { | ||||||
8586 | const FieldDecl *Field = E->getInitializedFieldInUnion(); | ||||||
8587 | Result = APValue(Field); | ||||||
8588 | if (!Field) | ||||||
8589 | return true; | ||||||
8590 | |||||||
8591 | // If the initializer list for a union does not contain any elements, the | ||||||
8592 | // first element of the union is value-initialized. | ||||||
8593 | // FIXME: The element should be initialized from an initializer list. | ||||||
8594 | // Is this difference ever observable for initializer lists which | ||||||
8595 | // we don't build? | ||||||
8596 | ImplicitValueInitExpr VIE(Field->getType()); | ||||||
8597 | const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; | ||||||
8598 | |||||||
8599 | LValue Subobject = This; | ||||||
8600 | if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) | ||||||
8601 | return false; | ||||||
8602 | |||||||
8603 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. | ||||||
8604 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, | ||||||
8605 | isa<CXXDefaultInitExpr>(InitExpr)); | ||||||
8606 | |||||||
8607 | return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); | ||||||
8608 | } | ||||||
8609 | |||||||
8610 | if (!Result.hasValue()) | ||||||
8611 | Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, | ||||||
8612 | std::distance(RD->field_begin(), RD->field_end())); | ||||||
8613 | unsigned ElementNo = 0; | ||||||
8614 | bool Success = true; | ||||||
8615 | |||||||
8616 | // Initialize base classes. | ||||||
8617 | if (CXXRD && CXXRD->getNumBases()) { | ||||||
8618 | for (const auto &Base : CXXRD->bases()) { | ||||||
8619 | assert(ElementNo < E->getNumInits() && "missing init for base class")((ElementNo < E->getNumInits() && "missing init for base class" ) ? static_cast<void> (0) : __assert_fail ("ElementNo < E->getNumInits() && \"missing init for base class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8619, __PRETTY_FUNCTION__)); | ||||||
8620 | const Expr *Init = E->getInit(ElementNo); | ||||||
8621 | |||||||
8622 | LValue Subobject = This; | ||||||
8623 | if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) | ||||||
8624 | return false; | ||||||
8625 | |||||||
8626 | APValue &FieldVal = Result.getStructBase(ElementNo); | ||||||
8627 | if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { | ||||||
8628 | if (!Info.noteFailure()) | ||||||
8629 | return false; | ||||||
8630 | Success = false; | ||||||
8631 | } | ||||||
8632 | ++ElementNo; | ||||||
8633 | } | ||||||
8634 | |||||||
8635 | EvalObj.finishedConstructingBases(); | ||||||
8636 | } | ||||||
8637 | |||||||
8638 | // Initialize members. | ||||||
8639 | for (const auto *Field : RD->fields()) { | ||||||
8640 | // Anonymous bit-fields are not considered members of the class for | ||||||
8641 | // purposes of aggregate initialization. | ||||||
8642 | if (Field->isUnnamedBitfield()) | ||||||
8643 | continue; | ||||||
8644 | |||||||
8645 | LValue Subobject = This; | ||||||
8646 | |||||||
8647 | bool HaveInit = ElementNo < E->getNumInits(); | ||||||
8648 | |||||||
8649 | // FIXME: Diagnostics here should point to the end of the initializer | ||||||
8650 | // list, not the start. | ||||||
8651 | if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, | ||||||
8652 | Subobject, Field, &Layout)) | ||||||
8653 | return false; | ||||||
8654 | |||||||
8655 | // Perform an implicit value-initialization for members beyond the end of | ||||||
8656 | // the initializer list. | ||||||
8657 | ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); | ||||||
8658 | const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; | ||||||
8659 | |||||||
8660 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. | ||||||
8661 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, | ||||||
8662 | isa<CXXDefaultInitExpr>(Init)); | ||||||
8663 | |||||||
8664 | APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); | ||||||
8665 | if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || | ||||||
8666 | (Field->isBitField() && !truncateBitfieldValue(Info, Init, | ||||||
8667 | FieldVal, Field))) { | ||||||
8668 | if (!Info.noteFailure()) | ||||||
8669 | return false; | ||||||
8670 | Success = false; | ||||||
8671 | } | ||||||
8672 | } | ||||||
8673 | |||||||
8674 | return Success; | ||||||
8675 | } | ||||||
8676 | |||||||
8677 | bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||||
8678 | QualType T) { | ||||||
8679 | // Note that E's type is not necessarily the type of our class here; we might | ||||||
8680 | // be initializing an array element instead. | ||||||
8681 | const CXXConstructorDecl *FD = E->getConstructor(); | ||||||
8682 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; | ||||||
8683 | |||||||
8684 | bool ZeroInit = E->requiresZeroInitialization(); | ||||||
8685 | if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { | ||||||
8686 | // If we've already performed zero-initialization, we're already done. | ||||||
8687 | if (Result.hasValue()) | ||||||
8688 | return true; | ||||||
8689 | |||||||
8690 | if (ZeroInit) | ||||||
8691 | return ZeroInitialization(E, T); | ||||||
8692 | |||||||
8693 | Result = getDefaultInitValue(T); | ||||||
8694 | return true; | ||||||
8695 | } | ||||||
8696 | |||||||
8697 | const FunctionDecl *Definition = nullptr; | ||||||
8698 | auto Body = FD->getBody(Definition); | ||||||
8699 | |||||||
8700 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) | ||||||
8701 | return false; | ||||||
8702 | |||||||
8703 | // Avoid materializing a temporary for an elidable copy/move constructor. | ||||||
8704 | if (E->isElidable() && !ZeroInit) | ||||||
8705 | if (const MaterializeTemporaryExpr *ME | ||||||
8706 | = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) | ||||||
8707 | return Visit(ME->GetTemporaryExpr()); | ||||||
8708 | |||||||
8709 | if (ZeroInit && !ZeroInitialization(E, T)) | ||||||
8710 | return false; | ||||||
8711 | |||||||
8712 | auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); | ||||||
8713 | return HandleConstructorCall(E, This, Args, | ||||||
8714 | cast<CXXConstructorDecl>(Definition), Info, | ||||||
8715 | Result); | ||||||
8716 | } | ||||||
8717 | |||||||
8718 | bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( | ||||||
8719 | const CXXInheritedCtorInitExpr *E) { | ||||||
8720 | if (!Info.CurrentCall) { | ||||||
8721 | assert(Info.checkingPotentialConstantExpression())((Info.checkingPotentialConstantExpression()) ? static_cast< void> (0) : __assert_fail ("Info.checkingPotentialConstantExpression()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8721, __PRETTY_FUNCTION__)); | ||||||
8722 | return false; | ||||||
8723 | } | ||||||
8724 | |||||||
8725 | const CXXConstructorDecl *FD = E->getConstructor(); | ||||||
8726 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) | ||||||
8727 | return false; | ||||||
8728 | |||||||
8729 | const FunctionDecl *Definition = nullptr; | ||||||
8730 | auto Body = FD->getBody(Definition); | ||||||
8731 | |||||||
8732 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) | ||||||
8733 | return false; | ||||||
8734 | |||||||
8735 | return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, | ||||||
8736 | cast<CXXConstructorDecl>(Definition), Info, | ||||||
8737 | Result); | ||||||
8738 | } | ||||||
8739 | |||||||
8740 | bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( | ||||||
8741 | const CXXStdInitializerListExpr *E) { | ||||||
8742 | const ConstantArrayType *ArrayType = | ||||||
8743 | Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); | ||||||
8744 | |||||||
8745 | LValue Array; | ||||||
8746 | if (!EvaluateLValue(E->getSubExpr(), Array, Info)) | ||||||
8747 | return false; | ||||||
8748 | |||||||
8749 | // Get a pointer to the first element of the array. | ||||||
8750 | Array.addArray(Info, E, ArrayType); | ||||||
8751 | |||||||
8752 | // FIXME: Perform the checks on the field types in SemaInit. | ||||||
8753 | RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); | ||||||
8754 | RecordDecl::field_iterator Field = Record->field_begin(); | ||||||
8755 | if (Field == Record->field_end()) | ||||||
8756 | return Error(E); | ||||||
8757 | |||||||
8758 | // Start pointer. | ||||||
8759 | if (!Field->getType()->isPointerType() || | ||||||
8760 | !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), | ||||||
8761 | ArrayType->getElementType())) | ||||||
8762 | return Error(E); | ||||||
8763 | |||||||
8764 | // FIXME: What if the initializer_list type has base classes, etc? | ||||||
8765 | Result = APValue(APValue::UninitStruct(), 0, 2); | ||||||
8766 | Array.moveInto(Result.getStructField(0)); | ||||||
8767 | |||||||
8768 | if (++Field == Record->field_end()) | ||||||
8769 | return Error(E); | ||||||
8770 | |||||||
8771 | if (Field->getType()->isPointerType() && | ||||||
8772 | Info.Ctx.hasSameType(Field->getType()->getPointeeType(), | ||||||
8773 | ArrayType->getElementType())) { | ||||||
8774 | // End pointer. | ||||||
8775 | if (!HandleLValueArrayAdjustment(Info, E, Array, | ||||||
8776 | ArrayType->getElementType(), | ||||||
8777 | ArrayType->getSize().getZExtValue())) | ||||||
8778 | return false; | ||||||
8779 | Array.moveInto(Result.getStructField(1)); | ||||||
8780 | } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) | ||||||
8781 | // Length. | ||||||
8782 | Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); | ||||||
8783 | else | ||||||
8784 | return Error(E); | ||||||
8785 | |||||||
8786 | if (++Field != Record->field_end()) | ||||||
8787 | return Error(E); | ||||||
8788 | |||||||
8789 | return true; | ||||||
8790 | } | ||||||
8791 | |||||||
8792 | bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { | ||||||
8793 | const CXXRecordDecl *ClosureClass = E->getLambdaClass(); | ||||||
8794 | if (ClosureClass->isInvalidDecl()) | ||||||
8795 | return false; | ||||||
8796 | |||||||
8797 | const size_t NumFields = | ||||||
8798 | std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); | ||||||
8799 | |||||||
8800 | assert(NumFields == (size_t)std::distance(E->capture_init_begin(),((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") ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8803, __PRETTY_FUNCTION__)) | ||||||
8801 | E->capture_init_end()) &&((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") ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8803, __PRETTY_FUNCTION__)) | ||||||
8802 | "The number of lambda capture initializers should equal the number of "((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") ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8803, __PRETTY_FUNCTION__)) | ||||||
8803 | "fields within the closure type")((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") ? static_cast<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-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8803, __PRETTY_FUNCTION__)); | ||||||
8804 | |||||||
8805 | Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); | ||||||
8806 | // Iterate through all the lambda's closure object's fields and initialize | ||||||
8807 | // them. | ||||||
8808 | auto *CaptureInitIt = E->capture_init_begin(); | ||||||
8809 | const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); | ||||||
8810 | bool Success = true; | ||||||
8811 | for (const auto *Field : ClosureClass->fields()) { | ||||||
8812 | assert(CaptureInitIt != E->capture_init_end())((CaptureInitIt != E->capture_init_end()) ? static_cast< void> (0) : __assert_fail ("CaptureInitIt != E->capture_init_end()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8812, __PRETTY_FUNCTION__)); | ||||||
8813 | // Get the initializer for this field | ||||||
8814 | Expr *const CurFieldInit = *CaptureInitIt++; | ||||||
8815 | |||||||
8816 | // If there is no initializer, either this is a VLA or an error has | ||||||
8817 | // occurred. | ||||||
8818 | if (!CurFieldInit) | ||||||
8819 | return Error(E); | ||||||
8820 | |||||||
8821 | APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); | ||||||
8822 | if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { | ||||||
8823 | if (!Info.keepEvaluatingAfterFailure()) | ||||||
8824 | return false; | ||||||
8825 | Success = false; | ||||||
8826 | } | ||||||
8827 | ++CaptureIt; | ||||||
8828 | } | ||||||
8829 | return Success; | ||||||
8830 | } | ||||||
8831 | |||||||
8832 | static bool EvaluateRecord(const Expr *E, const LValue &This, | ||||||
8833 | APValue &Result, EvalInfo &Info) { | ||||||
8834 | assert(E->isRValue() && E->getType()->isRecordType() &&((E->isRValue() && E->getType()->isRecordType () && "can't evaluate expression as a record rvalue") ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8835, __PRETTY_FUNCTION__)) | ||||||
8835 | "can't evaluate expression as a record rvalue")((E->isRValue() && E->getType()->isRecordType () && "can't evaluate expression as a record rvalue") ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8835, __PRETTY_FUNCTION__)); | ||||||
8836 | return RecordExprEvaluator(Info, This, Result).Visit(E); | ||||||
8837 | } | ||||||
8838 | |||||||
8839 | //===----------------------------------------------------------------------===// | ||||||
8840 | // Temporary Evaluation | ||||||
8841 | // | ||||||
8842 | // Temporaries are represented in the AST as rvalues, but generally behave like | ||||||
8843 | // lvalues. The full-object of which the temporary is a subobject is implicitly | ||||||
8844 | // materialized so that a reference can bind to it. | ||||||
8845 | //===----------------------------------------------------------------------===// | ||||||
8846 | namespace { | ||||||
8847 | class TemporaryExprEvaluator | ||||||
8848 | : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { | ||||||
8849 | public: | ||||||
8850 | TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : | ||||||
8851 | LValueExprEvaluatorBaseTy(Info, Result, false) {} | ||||||
8852 | |||||||
8853 | /// Visit an expression which constructs the value of this temporary. | ||||||
8854 | bool VisitConstructExpr(const Expr *E) { | ||||||
8855 | APValue &Value = | ||||||
8856 | Info.CurrentCall->createTemporary(E, E->getType(), false, Result); | ||||||
8857 | return EvaluateInPlace(Value, Info, Result, E); | ||||||
8858 | } | ||||||
8859 | |||||||
8860 | bool VisitCastExpr(const CastExpr *E) { | ||||||
8861 | switch (E->getCastKind()) { | ||||||
8862 | default: | ||||||
8863 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
8864 | |||||||
8865 | case CK_ConstructorConversion: | ||||||
8866 | return VisitConstructExpr(E->getSubExpr()); | ||||||
8867 | } | ||||||
8868 | } | ||||||
8869 | bool VisitInitListExpr(const InitListExpr *E) { | ||||||
8870 | return VisitConstructExpr(E); | ||||||
8871 | } | ||||||
8872 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||||
8873 | return VisitConstructExpr(E); | ||||||
8874 | } | ||||||
8875 | bool VisitCallExpr(const CallExpr *E) { | ||||||
8876 | return VisitConstructExpr(E); | ||||||
8877 | } | ||||||
8878 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { | ||||||
8879 | return VisitConstructExpr(E); | ||||||
8880 | } | ||||||
8881 | bool VisitLambdaExpr(const LambdaExpr *E) { | ||||||
8882 | return VisitConstructExpr(E); | ||||||
8883 | } | ||||||
8884 | }; | ||||||
8885 | } // end anonymous namespace | ||||||
8886 | |||||||
8887 | /// Evaluate an expression of record type as a temporary. | ||||||
8888 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { | ||||||
8889 | assert(E->isRValue() && E->getType()->isRecordType())((E->isRValue() && E->getType()->isRecordType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8889, __PRETTY_FUNCTION__)); | ||||||
8890 | return TemporaryExprEvaluator(Info, Result).Visit(E); | ||||||
8891 | } | ||||||
8892 | |||||||
8893 | //===----------------------------------------------------------------------===// | ||||||
8894 | // Vector Evaluation | ||||||
8895 | //===----------------------------------------------------------------------===// | ||||||
8896 | |||||||
8897 | namespace { | ||||||
8898 | class VectorExprEvaluator | ||||||
8899 | : public ExprEvaluatorBase<VectorExprEvaluator> { | ||||||
8900 | APValue &Result; | ||||||
8901 | public: | ||||||
8902 | |||||||
8903 | VectorExprEvaluator(EvalInfo &info, APValue &Result) | ||||||
8904 | : ExprEvaluatorBaseTy(info), Result(Result) {} | ||||||
8905 | |||||||
8906 | bool Success(ArrayRef<APValue> V, const Expr *E) { | ||||||
8907 | assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements())((V.size() == E->getType()->castAs<VectorType>()-> getNumElements()) ? static_cast<void> (0) : __assert_fail ("V.size() == E->getType()->castAs<VectorType>()->getNumElements()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8907, __PRETTY_FUNCTION__)); | ||||||
8908 | // FIXME: remove this APValue copy. | ||||||
8909 | Result = APValue(V.data(), V.size()); | ||||||
8910 | return true; | ||||||
8911 | } | ||||||
8912 | bool Success(const APValue &V, const Expr *E) { | ||||||
8913 | assert(V.isVector())((V.isVector()) ? static_cast<void> (0) : __assert_fail ("V.isVector()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8913, __PRETTY_FUNCTION__)); | ||||||
8914 | Result = V; | ||||||
8915 | return true; | ||||||
8916 | } | ||||||
8917 | bool ZeroInitialization(const Expr *E); | ||||||
8918 | |||||||
8919 | bool VisitUnaryReal(const UnaryOperator *E) | ||||||
8920 | { return Visit(E->getSubExpr()); } | ||||||
8921 | bool VisitCastExpr(const CastExpr* E); | ||||||
8922 | bool VisitInitListExpr(const InitListExpr *E); | ||||||
8923 | bool VisitUnaryImag(const UnaryOperator *E); | ||||||
8924 | // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, | ||||||
8925 | // binary comparisons, binary and/or/xor, | ||||||
8926 | // shufflevector, ExtVectorElementExpr | ||||||
8927 | }; | ||||||
8928 | } // end anonymous namespace | ||||||
8929 | |||||||
8930 | static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { | ||||||
8931 | assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue")((E->isRValue() && E->getType()->isVectorType () &&"not a vector rvalue") ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isVectorType() &&\"not a vector rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8931, __PRETTY_FUNCTION__)); | ||||||
8932 | return VectorExprEvaluator(Info, Result).Visit(E); | ||||||
8933 | } | ||||||
8934 | |||||||
8935 | bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||||
8936 | const VectorType *VTy = E->getType()->castAs<VectorType>(); | ||||||
8937 | unsigned NElts = VTy->getNumElements(); | ||||||
8938 | |||||||
8939 | const Expr *SE = E->getSubExpr(); | ||||||
8940 | QualType SETy = SE->getType(); | ||||||
8941 | |||||||
8942 | switch (E->getCastKind()) { | ||||||
8943 | case CK_VectorSplat: { | ||||||
8944 | APValue Val = APValue(); | ||||||
8945 | if (SETy->isIntegerType()) { | ||||||
8946 | APSInt IntResult; | ||||||
8947 | if (!EvaluateInteger(SE, IntResult, Info)) | ||||||
8948 | return false; | ||||||
8949 | Val = APValue(std::move(IntResult)); | ||||||
8950 | } else if (SETy->isRealFloatingType()) { | ||||||
8951 | APFloat FloatResult(0.0); | ||||||
8952 | if (!EvaluateFloat(SE, FloatResult, Info)) | ||||||
8953 | return false; | ||||||
8954 | Val = APValue(std::move(FloatResult)); | ||||||
8955 | } else { | ||||||
8956 | return Error(E); | ||||||
8957 | } | ||||||
8958 | |||||||
8959 | // Splat and create vector APValue. | ||||||
8960 | SmallVector<APValue, 4> Elts(NElts, Val); | ||||||
8961 | return Success(Elts, E); | ||||||
8962 | } | ||||||
8963 | case CK_BitCast: { | ||||||
8964 | // Evaluate the operand into an APInt we can extract from. | ||||||
8965 | llvm::APInt SValInt; | ||||||
8966 | if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) | ||||||
8967 | return false; | ||||||
8968 | // Extract the elements | ||||||
8969 | QualType EltTy = VTy->getElementType(); | ||||||
8970 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); | ||||||
8971 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); | ||||||
8972 | SmallVector<APValue, 4> Elts; | ||||||
8973 | if (EltTy->isRealFloatingType()) { | ||||||
8974 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); | ||||||
8975 | unsigned FloatEltSize = EltSize; | ||||||
8976 | if (&Sem == &APFloat::x87DoubleExtended()) | ||||||
8977 | FloatEltSize = 80; | ||||||
8978 | for (unsigned i = 0; i < NElts; i++) { | ||||||
8979 | llvm::APInt Elt; | ||||||
8980 | if (BigEndian) | ||||||
8981 | Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); | ||||||
8982 | else | ||||||
8983 | Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); | ||||||
8984 | Elts.push_back(APValue(APFloat(Sem, Elt))); | ||||||
8985 | } | ||||||
8986 | } else if (EltTy->isIntegerType()) { | ||||||
8987 | for (unsigned i = 0; i < NElts; i++) { | ||||||
8988 | llvm::APInt Elt; | ||||||
8989 | if (BigEndian) | ||||||
8990 | Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); | ||||||
8991 | else | ||||||
8992 | Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); | ||||||
8993 | Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); | ||||||
8994 | } | ||||||
8995 | } else { | ||||||
8996 | return Error(E); | ||||||
8997 | } | ||||||
8998 | return Success(Elts, E); | ||||||
8999 | } | ||||||
9000 | default: | ||||||
9001 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
9002 | } | ||||||
9003 | } | ||||||
9004 | |||||||
9005 | bool | ||||||
9006 | VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||||
9007 | const VectorType *VT = E->getType()->castAs<VectorType>(); | ||||||
9008 | unsigned NumInits = E->getNumInits(); | ||||||
9009 | unsigned NumElements = VT->getNumElements(); | ||||||
9010 | |||||||
9011 | QualType EltTy = VT->getElementType(); | ||||||
9012 | SmallVector<APValue, 4> Elements; | ||||||
9013 | |||||||
9014 | // The number of initializers can be less than the number of | ||||||
9015 | // vector elements. For OpenCL, this can be due to nested vector | ||||||
9016 | // initialization. For GCC compatibility, missing trailing elements | ||||||
9017 | // should be initialized with zeroes. | ||||||
9018 | unsigned CountInits = 0, CountElts = 0; | ||||||
9019 | while (CountElts < NumElements) { | ||||||
9020 | // Handle nested vector initialization. | ||||||
9021 | if (CountInits < NumInits | ||||||
9022 | && E->getInit(CountInits)->getType()->isVectorType()) { | ||||||
9023 | APValue v; | ||||||
9024 | if (!EvaluateVector(E->getInit(CountInits), v, Info)) | ||||||
9025 | return Error(E); | ||||||
9026 | unsigned vlen = v.getVectorLength(); | ||||||
9027 | for (unsigned j = 0; j < vlen; j++) | ||||||
9028 | Elements.push_back(v.getVectorElt(j)); | ||||||
9029 | CountElts += vlen; | ||||||
9030 | } else if (EltTy->isIntegerType()) { | ||||||
9031 | llvm::APSInt sInt(32); | ||||||
9032 | if (CountInits < NumInits) { | ||||||
9033 | if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) | ||||||
9034 | return false; | ||||||
9035 | } else // trailing integer zero. | ||||||
9036 | sInt = Info.Ctx.MakeIntValue(0, EltTy); | ||||||
9037 | Elements.push_back(APValue(sInt)); | ||||||
9038 | CountElts++; | ||||||
9039 | } else { | ||||||
9040 | llvm::APFloat f(0.0); | ||||||
9041 | if (CountInits < NumInits) { | ||||||
9042 | if (!EvaluateFloat(E->getInit(CountInits), f, Info)) | ||||||
9043 | return false; | ||||||
9044 | } else // trailing float zero. | ||||||
9045 | f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); | ||||||
9046 | Elements.push_back(APValue(f)); | ||||||
9047 | CountElts++; | ||||||
9048 | } | ||||||
9049 | CountInits++; | ||||||
9050 | } | ||||||
9051 | return Success(Elements, E); | ||||||
9052 | } | ||||||
9053 | |||||||
9054 | bool | ||||||
9055 | VectorExprEvaluator::ZeroInitialization(const Expr *E) { | ||||||
9056 | const VectorType *VT = E->getType()->getAs<VectorType>(); | ||||||
9057 | QualType EltTy = VT->getElementType(); | ||||||
9058 | APValue ZeroElement; | ||||||
9059 | if (EltTy->isIntegerType()) | ||||||
9060 | ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); | ||||||
9061 | else | ||||||
9062 | ZeroElement = | ||||||
9063 | APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); | ||||||
9064 | |||||||
9065 | SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); | ||||||
9066 | return Success(Elements, E); | ||||||
9067 | } | ||||||
9068 | |||||||
9069 | bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||||
9070 | VisitIgnoredValue(E->getSubExpr()); | ||||||
9071 | return ZeroInitialization(E); | ||||||
9072 | } | ||||||
9073 | |||||||
9074 | //===----------------------------------------------------------------------===// | ||||||
9075 | // Array Evaluation | ||||||
9076 | //===----------------------------------------------------------------------===// | ||||||
9077 | |||||||
9078 | namespace { | ||||||
9079 | class ArrayExprEvaluator | ||||||
9080 | : public ExprEvaluatorBase<ArrayExprEvaluator> { | ||||||
9081 | const LValue &This; | ||||||
9082 | APValue &Result; | ||||||
9083 | public: | ||||||
9084 | |||||||
9085 | ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) | ||||||
9086 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} | ||||||
9087 | |||||||
9088 | bool Success(const APValue &V, const Expr *E) { | ||||||
9089 | assert(V.isArray() && "expected array")((V.isArray() && "expected array") ? static_cast<void > (0) : __assert_fail ("V.isArray() && \"expected array\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9089, __PRETTY_FUNCTION__)); | ||||||
9090 | Result = V; | ||||||
9091 | return true; | ||||||
9092 | } | ||||||
9093 | |||||||
9094 | bool ZeroInitialization(const Expr *E) { | ||||||
9095 | const ConstantArrayType *CAT = | ||||||
9096 | Info.Ctx.getAsConstantArrayType(E->getType()); | ||||||
9097 | if (!CAT) | ||||||
9098 | return Error(E); | ||||||
9099 | |||||||
9100 | Result = APValue(APValue::UninitArray(), 0, | ||||||
9101 | CAT->getSize().getZExtValue()); | ||||||
9102 | if (!Result.hasArrayFiller()) return true; | ||||||
9103 | |||||||
9104 | // Zero-initialize all elements. | ||||||
9105 | LValue Subobject = This; | ||||||
9106 | Subobject.addArray(Info, E, CAT); | ||||||
9107 | ImplicitValueInitExpr VIE(CAT->getElementType()); | ||||||
9108 | return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); | ||||||
9109 | } | ||||||
9110 | |||||||
9111 | bool VisitCallExpr(const CallExpr *E) { | ||||||
9112 | return handleCallExpr(E, Result, &This); | ||||||
9113 | } | ||||||
9114 | bool VisitInitListExpr(const InitListExpr *E, | ||||||
9115 | QualType AllocType = QualType()); | ||||||
9116 | bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); | ||||||
9117 | bool VisitCXXConstructExpr(const CXXConstructExpr *E); | ||||||
9118 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||||
9119 | const LValue &Subobject, | ||||||
9120 | APValue *Value, QualType Type); | ||||||
9121 | bool VisitStringLiteral(const StringLiteral *E, | ||||||
9122 | QualType AllocType = QualType()) { | ||||||
9123 | expandStringLiteral(Info, E, Result, AllocType); | ||||||
9124 | return true; | ||||||
9125 | } | ||||||
9126 | }; | ||||||
9127 | } // end anonymous namespace | ||||||
9128 | |||||||
9129 | static bool EvaluateArray(const Expr *E, const LValue &This, | ||||||
9130 | APValue &Result, EvalInfo &Info) { | ||||||
9131 | assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue")((E->isRValue() && E->getType()->isArrayType () && "not an array rvalue") ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isArrayType() && \"not an array rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9131, __PRETTY_FUNCTION__)); | ||||||
9132 | return ArrayExprEvaluator(Info, This, Result).Visit(E); | ||||||
9133 | } | ||||||
9134 | |||||||
9135 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, | ||||||
9136 | APValue &Result, const InitListExpr *ILE, | ||||||
9137 | QualType AllocType) { | ||||||
9138 | assert(ILE->isRValue() && ILE->getType()->isArrayType() &&((ILE->isRValue() && ILE->getType()->isArrayType () && "not an array rvalue") ? static_cast<void> (0) : __assert_fail ("ILE->isRValue() && ILE->getType()->isArrayType() && \"not an array rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9139, __PRETTY_FUNCTION__)) | ||||||
9139 | "not an array rvalue")((ILE->isRValue() && ILE->getType()->isArrayType () && "not an array rvalue") ? static_cast<void> (0) : __assert_fail ("ILE->isRValue() && ILE->getType()->isArrayType() && \"not an array rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9139, __PRETTY_FUNCTION__)); | ||||||
9140 | return ArrayExprEvaluator(Info, This, Result) | ||||||
9141 | .VisitInitListExpr(ILE, AllocType); | ||||||
9142 | } | ||||||
9143 | |||||||
9144 | // Return true iff the given array filler may depend on the element index. | ||||||
9145 | static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { | ||||||
9146 | // For now, just whitelist non-class value-initialization and initialization | ||||||
9147 | // lists comprised of them. | ||||||
9148 | if (isa<ImplicitValueInitExpr>(FillerExpr)) | ||||||
9149 | return false; | ||||||
9150 | if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { | ||||||
9151 | for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { | ||||||
9152 | if (MaybeElementDependentArrayFiller(ILE->getInit(I))) | ||||||
9153 | return true; | ||||||
9154 | } | ||||||
9155 | return false; | ||||||
9156 | } | ||||||
9157 | return true; | ||||||
9158 | } | ||||||
9159 | |||||||
9160 | bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, | ||||||
9161 | QualType AllocType) { | ||||||
9162 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( | ||||||
9163 | AllocType.isNull() ? E->getType() : AllocType); | ||||||
9164 | if (!CAT) | ||||||
9165 | return Error(E); | ||||||
9166 | |||||||
9167 | // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] | ||||||
9168 | // an appropriately-typed string literal enclosed in braces. | ||||||
9169 | if (E->isStringLiteralInit()) { | ||||||
9170 | auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); | ||||||
9171 | // FIXME: Support ObjCEncodeExpr here once we support it in | ||||||
9172 | // ArrayExprEvaluator generally. | ||||||
9173 | if (!SL) | ||||||
9174 | return Error(E); | ||||||
9175 | return VisitStringLiteral(SL, AllocType); | ||||||
9176 | } | ||||||
9177 | |||||||
9178 | bool Success = true; | ||||||
9179 | |||||||
9180 | assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&(((!Result.isArray() || Result.getArrayInitializedElts() == 0 ) && "zero-initialized array shouldn't have any initialized elts" ) ? static_cast<void> (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9181, __PRETTY_FUNCTION__)) | ||||||
9181 | "zero-initialized array shouldn't have any initialized elts")(((!Result.isArray() || Result.getArrayInitializedElts() == 0 ) && "zero-initialized array shouldn't have any initialized elts" ) ? static_cast<void> (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9181, __PRETTY_FUNCTION__)); | ||||||
9182 | APValue Filler; | ||||||
9183 | if (Result.isArray() && Result.hasArrayFiller()) | ||||||
9184 | Filler = Result.getArrayFiller(); | ||||||
9185 | |||||||
9186 | unsigned NumEltsToInit = E->getNumInits(); | ||||||
9187 | unsigned NumElts = CAT->getSize().getZExtValue(); | ||||||
9188 | const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; | ||||||
9189 | |||||||
9190 | // If the initializer might depend on the array index, run it for each | ||||||
9191 | // array element. | ||||||
9192 | if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) | ||||||
9193 | NumEltsToInit = NumElts; | ||||||
9194 | |||||||
9195 | 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) | ||||||
9196 | << NumEltsToInit << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: " << NumEltsToInit << ".\n"; } } while (false); | ||||||
9197 | |||||||
9198 | Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); | ||||||
9199 | |||||||
9200 | // If the array was previously zero-initialized, preserve the | ||||||
9201 | // zero-initialized values. | ||||||
9202 | if (Filler.hasValue()) { | ||||||
9203 | for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) | ||||||
9204 | Result.getArrayInitializedElt(I) = Filler; | ||||||
9205 | if (Result.hasArrayFiller()) | ||||||
9206 | Result.getArrayFiller() = Filler; | ||||||
9207 | } | ||||||
9208 | |||||||
9209 | LValue Subobject = This; | ||||||
9210 | Subobject.addArray(Info, E, CAT); | ||||||
9211 | for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { | ||||||
9212 | const Expr *Init = | ||||||
9213 | Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; | ||||||
9214 | if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), | ||||||
9215 | Info, Subobject, Init) || | ||||||
9216 | !HandleLValueArrayAdjustment(Info, Init, Subobject, | ||||||
9217 | CAT->getElementType(), 1)) { | ||||||
9218 | if (!Info.noteFailure()) | ||||||
9219 | return false; | ||||||
9220 | Success = false; | ||||||
9221 | } | ||||||
9222 | } | ||||||
9223 | |||||||
9224 | if (!Result.hasArrayFiller()) | ||||||
9225 | return Success; | ||||||
9226 | |||||||
9227 | // If we get here, we have a trivial filler, which we can just evaluate | ||||||
9228 | // once and splat over the rest of the array elements. | ||||||
9229 | assert(FillerExpr && "no array filler for incomplete init list")((FillerExpr && "no array filler for incomplete init list" ) ? static_cast<void> (0) : __assert_fail ("FillerExpr && \"no array filler for incomplete init list\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9229, __PRETTY_FUNCTION__)); | ||||||
9230 | return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, | ||||||
9231 | FillerExpr) && Success; | ||||||
9232 | } | ||||||
9233 | |||||||
9234 | bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { | ||||||
9235 | LValue CommonLV; | ||||||
9236 | if (E->getCommonExpr() && | ||||||
9237 | !Evaluate(Info.CurrentCall->createTemporary( | ||||||
9238 | E->getCommonExpr(), | ||||||
9239 | getStorageType(Info.Ctx, E->getCommonExpr()), false, | ||||||
9240 | CommonLV), | ||||||
9241 | Info, E->getCommonExpr()->getSourceExpr())) | ||||||
9242 | return false; | ||||||
9243 | |||||||
9244 | auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); | ||||||
9245 | |||||||
9246 | uint64_t Elements = CAT->getSize().getZExtValue(); | ||||||
9247 | Result = APValue(APValue::UninitArray(), Elements, Elements); | ||||||
9248 | |||||||
9249 | LValue Subobject = This; | ||||||
9250 | Subobject.addArray(Info, E, CAT); | ||||||
9251 | |||||||
9252 | bool Success = true; | ||||||
9253 | for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { | ||||||
9254 | if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), | ||||||
9255 | Info, Subobject, E->getSubExpr()) || | ||||||
9256 | !HandleLValueArrayAdjustment(Info, E, Subobject, | ||||||
9257 | CAT->getElementType(), 1)) { | ||||||
9258 | if (!Info.noteFailure()) | ||||||
9259 | return false; | ||||||
9260 | Success = false; | ||||||
9261 | } | ||||||
9262 | } | ||||||
9263 | |||||||
9264 | return Success; | ||||||
9265 | } | ||||||
9266 | |||||||
9267 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||||
9268 | return VisitCXXConstructExpr(E, This, &Result, E->getType()); | ||||||
9269 | } | ||||||
9270 | |||||||
9271 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||||
9272 | const LValue &Subobject, | ||||||
9273 | APValue *Value, | ||||||
9274 | QualType Type) { | ||||||
9275 | bool HadZeroInit = Value->hasValue(); | ||||||
9276 | |||||||
9277 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { | ||||||
9278 | unsigned N = CAT->getSize().getZExtValue(); | ||||||
9279 | |||||||
9280 | // Preserve the array filler if we had prior zero-initialization. | ||||||
9281 | APValue Filler = | ||||||
9282 | HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() | ||||||
9283 | : APValue(); | ||||||
9284 | |||||||
9285 | *Value = APValue(APValue::UninitArray(), N, N); | ||||||
9286 | |||||||
9287 | if (HadZeroInit) | ||||||
9288 | for (unsigned I = 0; I != N; ++I) | ||||||
9289 | Value->getArrayInitializedElt(I) = Filler; | ||||||
9290 | |||||||
9291 | // Initialize the elements. | ||||||
9292 | LValue ArrayElt = Subobject; | ||||||
9293 | ArrayElt.addArray(Info, E, CAT); | ||||||
9294 | for (unsigned I = 0; I != N; ++I) | ||||||
9295 | if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), | ||||||
9296 | CAT->getElementType()) || | ||||||
9297 | !HandleLValueArrayAdjustment(Info, E, ArrayElt, | ||||||
9298 | CAT->getElementType(), 1)) | ||||||
9299 | return false; | ||||||
9300 | |||||||
9301 | return true; | ||||||
9302 | } | ||||||
9303 | |||||||
9304 | if (!Type->isRecordType()) | ||||||
9305 | return Error(E); | ||||||
9306 | |||||||
9307 | return RecordExprEvaluator(Info, Subobject, *Value) | ||||||
9308 | .VisitCXXConstructExpr(E, Type); | ||||||
9309 | } | ||||||
9310 | |||||||
9311 | //===----------------------------------------------------------------------===// | ||||||
9312 | // Integer Evaluation | ||||||
9313 | // | ||||||
9314 | // As a GNU extension, we support casting pointers to sufficiently-wide integer | ||||||
9315 | // types and back in constant folding. Integer values are thus represented | ||||||
9316 | // either as an integer-valued APValue, or as an lvalue-valued APValue. | ||||||
9317 | //===----------------------------------------------------------------------===// | ||||||
9318 | |||||||
9319 | namespace { | ||||||
9320 | class IntExprEvaluator | ||||||
9321 | : public ExprEvaluatorBase<IntExprEvaluator> { | ||||||
9322 | APValue &Result; | ||||||
9323 | public: | ||||||
9324 | IntExprEvaluator(EvalInfo &info, APValue &result) | ||||||
9325 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||||
9326 | |||||||
9327 | bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { | ||||||
9328 | assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9329, __PRETTY_FUNCTION__)) | ||||||
9329 | "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9329, __PRETTY_FUNCTION__)); | ||||||
9330 | assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&((SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType () && "Invalid evaluation result.") ? static_cast< void> (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9331, __PRETTY_FUNCTION__)) | ||||||
9331 | "Invalid evaluation result.")((SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType () && "Invalid evaluation result.") ? static_cast< void> (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9331, __PRETTY_FUNCTION__)); | ||||||
9332 | assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&((SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9333, __PRETTY_FUNCTION__)) | ||||||
9333 | "Invalid evaluation result.")((SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9333, __PRETTY_FUNCTION__)); | ||||||
9334 | Result = APValue(SI); | ||||||
9335 | return true; | ||||||
9336 | } | ||||||
9337 | bool Success(const llvm::APSInt &SI, const Expr *E) { | ||||||
9338 | return Success(SI, E, Result); | ||||||
9339 | } | ||||||
9340 | |||||||
9341 | bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { | ||||||
9342 | assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9343, __PRETTY_FUNCTION__)) | ||||||
9343 | "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9343, __PRETTY_FUNCTION__)); | ||||||
9344 | assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&((I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9345, __PRETTY_FUNCTION__)) | ||||||
9345 | "Invalid evaluation result.")((I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9345, __PRETTY_FUNCTION__)); | ||||||
9346 | Result = APValue(APSInt(I)); | ||||||
9347 | Result.getInt().setIsUnsigned( | ||||||
9348 | E->getType()->isUnsignedIntegerOrEnumerationType()); | ||||||
9349 | return true; | ||||||
9350 | } | ||||||
9351 | bool Success(const llvm::APInt &I, const Expr *E) { | ||||||
9352 | return Success(I, E, Result); | ||||||
9353 | } | ||||||
9354 | |||||||
9355 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { | ||||||
9356 | assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9357, __PRETTY_FUNCTION__)) | ||||||
9357 | "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9357, __PRETTY_FUNCTION__)); | ||||||
9358 | Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); | ||||||
9359 | return true; | ||||||
9360 | } | ||||||
9361 | bool Success(uint64_t Value, const Expr *E) { | ||||||
9362 | return Success(Value, E, Result); | ||||||
9363 | } | ||||||
9364 | |||||||
9365 | bool Success(CharUnits Size, const Expr *E) { | ||||||
9366 | return Success(Size.getQuantity(), E); | ||||||
9367 | } | ||||||
9368 | |||||||
9369 | bool Success(const APValue &V, const Expr *E) { | ||||||
9370 | if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { | ||||||
9371 | Result = V; | ||||||
9372 | return true; | ||||||
9373 | } | ||||||
9374 | return Success(V.getInt(), E); | ||||||
9375 | } | ||||||
9376 | |||||||
9377 | bool ZeroInitialization(const Expr *E) { return Success(0, E); } | ||||||
9378 | |||||||
9379 | //===--------------------------------------------------------------------===// | ||||||
9380 | // Visitor Methods | ||||||
9381 | //===--------------------------------------------------------------------===// | ||||||
9382 | |||||||
9383 | bool VisitConstantExpr(const ConstantExpr *E); | ||||||
9384 | |||||||
9385 | bool VisitIntegerLiteral(const IntegerLiteral *E) { | ||||||
9386 | return Success(E->getValue(), E); | ||||||
9387 | } | ||||||
9388 | bool VisitCharacterLiteral(const CharacterLiteral *E) { | ||||||
9389 | return Success(E->getValue(), E); | ||||||
9390 | } | ||||||
9391 | |||||||
9392 | bool CheckReferencedDecl(const Expr *E, const Decl *D); | ||||||
9393 | bool VisitDeclRefExpr(const DeclRefExpr *E) { | ||||||
9394 | if (CheckReferencedDecl(E, E->getDecl())) | ||||||
9395 | return true; | ||||||
9396 | |||||||
9397 | return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); | ||||||
9398 | } | ||||||
9399 | bool VisitMemberExpr(const MemberExpr *E) { | ||||||
9400 | if (CheckReferencedDecl(E, E->getMemberDecl())) { | ||||||
9401 | VisitIgnoredBaseExpression(E->getBase()); | ||||||
9402 | return true; | ||||||
9403 | } | ||||||
9404 | |||||||
9405 | return ExprEvaluatorBaseTy::VisitMemberExpr(E); | ||||||
9406 | } | ||||||
9407 | |||||||
9408 | bool VisitCallExpr(const CallExpr *E); | ||||||
9409 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); | ||||||
9410 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||||
9411 | bool VisitOffsetOfExpr(const OffsetOfExpr *E); | ||||||
9412 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||||
9413 | |||||||
9414 | bool VisitCastExpr(const CastExpr* E); | ||||||
9415 | bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); | ||||||
9416 | |||||||
9417 | bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { | ||||||
9418 | return Success(E->getValue(), E); | ||||||
9419 | } | ||||||
9420 | |||||||
9421 | bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { | ||||||
9422 | return Success(E->getValue(), E); | ||||||
9423 | } | ||||||
9424 | |||||||
9425 | bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { | ||||||
9426 | if (Info.ArrayInitIndex == uint64_t(-1)) { | ||||||
9427 | // We were asked to evaluate this subexpression independent of the | ||||||
9428 | // enclosing ArrayInitLoopExpr. We can't do that. | ||||||
9429 | Info.FFDiag(E); | ||||||
9430 | return false; | ||||||
9431 | } | ||||||
9432 | return Success(Info.ArrayInitIndex, E); | ||||||
9433 | } | ||||||
9434 | |||||||
9435 | // Note, GNU defines __null as an integer, not a pointer. | ||||||
9436 | bool VisitGNUNullExpr(const GNUNullExpr *E) { | ||||||
9437 | return ZeroInitialization(E); | ||||||
9438 | } | ||||||
9439 | |||||||
9440 | bool VisitTypeTraitExpr(const TypeTraitExpr *E) { | ||||||
9441 | return Success(E->getValue(), E); | ||||||
9442 | } | ||||||
9443 | |||||||
9444 | bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { | ||||||
9445 | return Success(E->getValue(), E); | ||||||
9446 | } | ||||||
9447 | |||||||
9448 | bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { | ||||||
9449 | return Success(E->getValue(), E); | ||||||
9450 | } | ||||||
9451 | |||||||
9452 | bool VisitUnaryReal(const UnaryOperator *E); | ||||||
9453 | bool VisitUnaryImag(const UnaryOperator *E); | ||||||
9454 | |||||||
9455 | bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); | ||||||
9456 | bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); | ||||||
9457 | bool VisitSourceLocExpr(const SourceLocExpr *E); | ||||||
9458 | // FIXME: Missing: array subscript of vector, member of vector | ||||||
9459 | }; | ||||||
9460 | |||||||
9461 | class FixedPointExprEvaluator | ||||||
9462 | : public ExprEvaluatorBase<FixedPointExprEvaluator> { | ||||||
9463 | APValue &Result; | ||||||
9464 | |||||||
9465 | public: | ||||||
9466 | FixedPointExprEvaluator(EvalInfo &info, APValue &result) | ||||||
9467 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||||
9468 | |||||||
9469 | bool Success(const llvm::APInt &I, const Expr *E) { | ||||||
9470 | return Success( | ||||||
9471 | APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); | ||||||
9472 | } | ||||||
9473 | |||||||
9474 | bool Success(uint64_t Value, const Expr *E) { | ||||||
9475 | return Success( | ||||||
9476 | APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); | ||||||
9477 | } | ||||||
9478 | |||||||
9479 | bool Success(const APValue &V, const Expr *E) { | ||||||
9480 | return Success(V.getFixedPoint(), E); | ||||||
9481 | } | ||||||
9482 | |||||||
9483 | bool Success(const APFixedPoint &V, const Expr *E) { | ||||||
9484 | assert(E->getType()->isFixedPointType() && "Invalid evaluation result.")((E->getType()->isFixedPointType() && "Invalid evaluation result." ) ? static_cast<void> (0) : __assert_fail ("E->getType()->isFixedPointType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9484, __PRETTY_FUNCTION__)); | ||||||
9485 | assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&((V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9486, __PRETTY_FUNCTION__)) | ||||||
9486 | "Invalid evaluation result.")((V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9486, __PRETTY_FUNCTION__)); | ||||||
9487 | Result = APValue(V); | ||||||
9488 | return true; | ||||||
9489 | } | ||||||
9490 | |||||||
9491 | //===--------------------------------------------------------------------===// | ||||||
9492 | // Visitor Methods | ||||||
9493 | //===--------------------------------------------------------------------===// | ||||||
9494 | |||||||
9495 | bool VisitFixedPointLiteral(const FixedPointLiteral *E) { | ||||||
9496 | return Success(E->getValue(), E); | ||||||
9497 | } | ||||||
9498 | |||||||
9499 | bool VisitCastExpr(const CastExpr *E); | ||||||
9500 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||||
9501 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||||
9502 | }; | ||||||
9503 | } // end anonymous namespace | ||||||
9504 | |||||||
9505 | /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and | ||||||
9506 | /// produce either the integer value or a pointer. | ||||||
9507 | /// | ||||||
9508 | /// GCC has a heinous extension which folds casts between pointer types and | ||||||
9509 | /// pointer-sized integral types. We support this by allowing the evaluation of | ||||||
9510 | /// an integer rvalue to produce a pointer (represented as an lvalue) instead. | ||||||
9511 | /// Some simple arithmetic on such values is supported (they are treated much | ||||||
9512 | /// like char*). | ||||||
9513 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, | ||||||
9514 | EvalInfo &Info) { | ||||||
9515 | assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType())((E->isRValue() && E->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9515, __PRETTY_FUNCTION__)); | ||||||
9516 | return IntExprEvaluator(Info, Result).Visit(E); | ||||||
9517 | } | ||||||
9518 | |||||||
9519 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { | ||||||
9520 | APValue Val; | ||||||
9521 | if (!EvaluateIntegerOrLValue(E, Val, Info)) | ||||||
9522 | return false; | ||||||
9523 | if (!Val.isInt()) { | ||||||
9524 | // FIXME: It would be better to produce the diagnostic for casting | ||||||
9525 | // a pointer to an integer. | ||||||
9526 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
9527 | return false; | ||||||
9528 | } | ||||||
9529 | Result = Val.getInt(); | ||||||
9530 | return true; | ||||||
9531 | } | ||||||
9532 | |||||||
9533 | bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { | ||||||
9534 | APValue Evaluated = E->EvaluateInContext( | ||||||
9535 | Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); | ||||||
9536 | return Success(Evaluated, E); | ||||||
9537 | } | ||||||
9538 | |||||||
9539 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, | ||||||
9540 | EvalInfo &Info) { | ||||||
9541 | if (E->getType()->isFixedPointType()) { | ||||||
9542 | APValue Val; | ||||||
9543 | if (!FixedPointExprEvaluator(Info, Val).Visit(E)) | ||||||
9544 | return false; | ||||||
9545 | if (!Val.isFixedPoint()) | ||||||
9546 | return false; | ||||||
9547 | |||||||
9548 | Result = Val.getFixedPoint(); | ||||||
9549 | return true; | ||||||
9550 | } | ||||||
9551 | return false; | ||||||
9552 | } | ||||||
9553 | |||||||
9554 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, | ||||||
9555 | EvalInfo &Info) { | ||||||
9556 | if (E->getType()->isIntegerType()) { | ||||||
9557 | auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); | ||||||
9558 | APSInt Val; | ||||||
9559 | if (!EvaluateInteger(E, Val, Info)) | ||||||
9560 | return false; | ||||||
9561 | Result = APFixedPoint(Val, FXSema); | ||||||
9562 | return true; | ||||||
9563 | } else if (E->getType()->isFixedPointType()) { | ||||||
9564 | return EvaluateFixedPoint(E, Result, Info); | ||||||
9565 | } | ||||||
9566 | return false; | ||||||
9567 | } | ||||||
9568 | |||||||
9569 | /// Check whether the given declaration can be directly converted to an integral | ||||||
9570 | /// rvalue. If not, no diagnostic is produced; there are other things we can | ||||||
9571 | /// try. | ||||||
9572 | bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { | ||||||
9573 | // Enums are integer constant exprs. | ||||||
9574 | if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { | ||||||
9575 | // Check for signedness/width mismatches between E type and ECD value. | ||||||
9576 | bool SameSign = (ECD->getInitVal().isSigned() | ||||||
9577 | == E->getType()->isSignedIntegerOrEnumerationType()); | ||||||
9578 | bool SameWidth = (ECD->getInitVal().getBitWidth() | ||||||
9579 | == Info.Ctx.getIntWidth(E->getType())); | ||||||
9580 | if (SameSign && SameWidth) | ||||||
9581 | return Success(ECD->getInitVal(), E); | ||||||
9582 | else { | ||||||
9583 | // Get rid of mismatch (otherwise Success assertions will fail) | ||||||
9584 | // by computing a new value matching the type of E. | ||||||
9585 | llvm::APSInt Val = ECD->getInitVal(); | ||||||
9586 | if (!SameSign) | ||||||
9587 | Val.setIsSigned(!ECD->getInitVal().isSigned()); | ||||||
9588 | if (!SameWidth) | ||||||
9589 | Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); | ||||||
9590 | return Success(Val, E); | ||||||
9591 | } | ||||||
9592 | } | ||||||
9593 | return false; | ||||||
9594 | } | ||||||
9595 | |||||||
9596 | /// Values returned by __builtin_classify_type, chosen to match the values | ||||||
9597 | /// produced by GCC's builtin. | ||||||
9598 | enum class GCCTypeClass { | ||||||
9599 | None = -1, | ||||||
9600 | Void = 0, | ||||||
9601 | Integer = 1, | ||||||
9602 | // GCC reserves 2 for character types, but instead classifies them as | ||||||
9603 | // integers. | ||||||
9604 | Enum = 3, | ||||||
9605 | Bool = 4, | ||||||
9606 | Pointer = 5, | ||||||
9607 | // GCC reserves 6 for references, but appears to never use it (because | ||||||
9608 | // expressions never have reference type, presumably). | ||||||
9609 | PointerToDataMember = 7, | ||||||
9610 | RealFloat = 8, | ||||||
9611 | Complex = 9, | ||||||
9612 | // GCC reserves 10 for functions, but does not use it since GCC version 6 due | ||||||
9613 | // to decay to pointer. (Prior to version 6 it was only used in C++ mode). | ||||||
9614 | // GCC claims to reserve 11 for pointers to member functions, but *actually* | ||||||
9615 | // uses 12 for that purpose, same as for a class or struct. Maybe it | ||||||
9616 | // internally implements a pointer to member as a struct? Who knows. | ||||||
9617 | PointerToMemberFunction = 12, // Not a bug, see above. | ||||||
9618 | ClassOrStruct = 12, | ||||||
9619 | Union = 13, | ||||||
9620 | // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to | ||||||
9621 | // decay to pointer. (Prior to version 6 it was only used in C++ mode). | ||||||
9622 | // GCC reserves 15 for strings, but actually uses 5 (pointer) for string | ||||||
9623 | // literals. | ||||||
9624 | }; | ||||||
9625 | |||||||
9626 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way | ||||||
9627 | /// as GCC. | ||||||
9628 | static GCCTypeClass | ||||||
9629 | EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { | ||||||
9630 | assert(!T->isDependentType() && "unexpected dependent type")((!T->isDependentType() && "unexpected dependent type" ) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"unexpected dependent type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9630, __PRETTY_FUNCTION__)); | ||||||
9631 | |||||||
9632 | QualType CanTy = T.getCanonicalType(); | ||||||
9633 | const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); | ||||||
9634 | |||||||
9635 | switch (CanTy->getTypeClass()) { | ||||||
9636 | #define TYPE(ID, BASE) | ||||||
9637 | #define DEPENDENT_TYPE(ID, BASE) case Type::ID: | ||||||
9638 | #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: | ||||||
9639 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: | ||||||
9640 | #include "clang/AST/TypeNodes.inc" | ||||||
9641 | case Type::Auto: | ||||||
9642 | case Type::DeducedTemplateSpecialization: | ||||||
9643 | llvm_unreachable("unexpected non-canonical or dependent type")::llvm::llvm_unreachable_internal("unexpected non-canonical or dependent type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9643); | ||||||
9644 | |||||||
9645 | case Type::Builtin: | ||||||
9646 | switch (BT->getKind()) { | ||||||
9647 | #define BUILTIN_TYPE(ID, SINGLETON_ID) | ||||||
9648 | #define SIGNED_TYPE(ID, SINGLETON_ID) \ | ||||||
9649 | case BuiltinType::ID: return GCCTypeClass::Integer; | ||||||
9650 | #define FLOATING_TYPE(ID, SINGLETON_ID) \ | ||||||
9651 | case BuiltinType::ID: return GCCTypeClass::RealFloat; | ||||||
9652 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ | ||||||
9653 | case BuiltinType::ID: break; | ||||||
9654 | #include "clang/AST/BuiltinTypes.def" | ||||||
9655 | case BuiltinType::Void: | ||||||
9656 | return GCCTypeClass::Void; | ||||||
9657 | |||||||
9658 | case BuiltinType::Bool: | ||||||
9659 | return GCCTypeClass::Bool; | ||||||
9660 | |||||||
9661 | case BuiltinType::Char_U: | ||||||
9662 | case BuiltinType::UChar: | ||||||
9663 | case BuiltinType::WChar_U: | ||||||
9664 | case BuiltinType::Char8: | ||||||
9665 | case BuiltinType::Char16: | ||||||
9666 | case BuiltinType::Char32: | ||||||
9667 | case BuiltinType::UShort: | ||||||
9668 | case BuiltinType::UInt: | ||||||
9669 | case BuiltinType::ULong: | ||||||
9670 | case BuiltinType::ULongLong: | ||||||
9671 | case BuiltinType::UInt128: | ||||||
9672 | return GCCTypeClass::Integer; | ||||||
9673 | |||||||
9674 | case BuiltinType::UShortAccum: | ||||||
9675 | case BuiltinType::UAccum: | ||||||
9676 | case BuiltinType::ULongAccum: | ||||||
9677 | case BuiltinType::UShortFract: | ||||||
9678 | case BuiltinType::UFract: | ||||||
9679 | case BuiltinType::ULongFract: | ||||||
9680 | case BuiltinType::SatUShortAccum: | ||||||
9681 | case BuiltinType::SatUAccum: | ||||||
9682 | case BuiltinType::SatULongAccum: | ||||||
9683 | case BuiltinType::SatUShortFract: | ||||||
9684 | case BuiltinType::SatUFract: | ||||||
9685 | case BuiltinType::SatULongFract: | ||||||
9686 | return GCCTypeClass::None; | ||||||
9687 | |||||||
9688 | case BuiltinType::NullPtr: | ||||||
9689 | |||||||
9690 | case BuiltinType::ObjCId: | ||||||
9691 | case BuiltinType::ObjCClass: | ||||||
9692 | case BuiltinType::ObjCSel: | ||||||
9693 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||||
9694 | case BuiltinType::Id: | ||||||
9695 | #include "clang/Basic/OpenCLImageTypes.def" | ||||||
9696 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||||
9697 | case BuiltinType::Id: | ||||||
9698 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||||
9699 | case BuiltinType::OCLSampler: | ||||||
9700 | case BuiltinType::OCLEvent: | ||||||
9701 | case BuiltinType::OCLClkEvent: | ||||||
9702 | case BuiltinType::OCLQueue: | ||||||
9703 | case BuiltinType::OCLReserveID: | ||||||
9704 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||||
9705 | case BuiltinType::Id: | ||||||
9706 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||||
9707 | return GCCTypeClass::None; | ||||||
9708 | |||||||
9709 | case BuiltinType::Dependent: | ||||||
9710 | llvm_unreachable("unexpected dependent type")::llvm::llvm_unreachable_internal("unexpected dependent type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9710); | ||||||
9711 | }; | ||||||
9712 | llvm_unreachable("unexpected placeholder type")::llvm::llvm_unreachable_internal("unexpected placeholder type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9712); | ||||||
9713 | |||||||
9714 | case Type::Enum: | ||||||
9715 | return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; | ||||||
9716 | |||||||
9717 | case Type::Pointer: | ||||||
9718 | case Type::ConstantArray: | ||||||
9719 | case Type::VariableArray: | ||||||
9720 | case Type::IncompleteArray: | ||||||
9721 | case Type::FunctionNoProto: | ||||||
9722 | case Type::FunctionProto: | ||||||
9723 | return GCCTypeClass::Pointer; | ||||||
9724 | |||||||
9725 | case Type::MemberPointer: | ||||||
9726 | return CanTy->isMemberDataPointerType() | ||||||
9727 | ? GCCTypeClass::PointerToDataMember | ||||||
9728 | : GCCTypeClass::PointerToMemberFunction; | ||||||
9729 | |||||||
9730 | case Type::Complex: | ||||||
9731 | return GCCTypeClass::Complex; | ||||||
9732 | |||||||
9733 | case Type::Record: | ||||||
9734 | return CanTy->isUnionType() ? GCCTypeClass::Union | ||||||
9735 | : GCCTypeClass::ClassOrStruct; | ||||||
9736 | |||||||
9737 | case Type::Atomic: | ||||||
9738 | // GCC classifies _Atomic T the same as T. | ||||||
9739 | return EvaluateBuiltinClassifyType( | ||||||
9740 | CanTy->castAs<AtomicType>()->getValueType(), LangOpts); | ||||||
9741 | |||||||
9742 | case Type::BlockPointer: | ||||||
9743 | case Type::Vector: | ||||||
9744 | case Type::ExtVector: | ||||||
9745 | case Type::ObjCObject: | ||||||
9746 | case Type::ObjCInterface: | ||||||
9747 | case Type::ObjCObjectPointer: | ||||||
9748 | case Type::Pipe: | ||||||
9749 | // GCC classifies vectors as None. We follow its lead and classify all | ||||||
9750 | // other types that don't fit into the regular classification the same way. | ||||||
9751 | return GCCTypeClass::None; | ||||||
9752 | |||||||
9753 | case Type::LValueReference: | ||||||
9754 | case Type::RValueReference: | ||||||
9755 | llvm_unreachable("invalid type for expression")::llvm::llvm_unreachable_internal("invalid type for expression" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9755); | ||||||
9756 | } | ||||||
9757 | |||||||
9758 | llvm_unreachable("unexpected type class")::llvm::llvm_unreachable_internal("unexpected type class", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9758); | ||||||
9759 | } | ||||||
9760 | |||||||
9761 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way | ||||||
9762 | /// as GCC. | ||||||
9763 | static GCCTypeClass | ||||||
9764 | EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { | ||||||
9765 | // If no argument was supplied, default to None. This isn't | ||||||
9766 | // ideal, however it is what gcc does. | ||||||
9767 | if (E->getNumArgs() == 0) | ||||||
9768 | return GCCTypeClass::None; | ||||||
9769 | |||||||
9770 | // FIXME: Bizarrely, GCC treats a call with more than one argument as not | ||||||
9771 | // being an ICE, but still folds it to a constant using the type of the first | ||||||
9772 | // argument. | ||||||
9773 | return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); | ||||||
9774 | } | ||||||
9775 | |||||||
9776 | /// EvaluateBuiltinConstantPForLValue - Determine the result of | ||||||
9777 | /// __builtin_constant_p when applied to the given pointer. | ||||||
9778 | /// | ||||||
9779 | /// A pointer is only "constant" if it is null (or a pointer cast to integer) | ||||||
9780 | /// or it points to the first character of a string literal. | ||||||
9781 | static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { | ||||||
9782 | APValue::LValueBase Base = LV.getLValueBase(); | ||||||
9783 | if (Base.isNull()) { | ||||||
9784 | // A null base is acceptable. | ||||||
9785 | return true; | ||||||
9786 | } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { | ||||||
9787 | if (!isa<StringLiteral>(E)) | ||||||
9788 | return false; | ||||||
9789 | return LV.getLValueOffset().isZero(); | ||||||
9790 | } else if (Base.is<TypeInfoLValue>()) { | ||||||
9791 | // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to | ||||||
9792 | // evaluate to true. | ||||||
9793 | return true; | ||||||
9794 | } else { | ||||||
9795 | // Any other base is not constant enough for GCC. | ||||||
9796 | return false; | ||||||
9797 | } | ||||||
9798 | } | ||||||
9799 | |||||||
9800 | /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to | ||||||
9801 | /// GCC as we can manage. | ||||||
9802 | static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { | ||||||
9803 | // This evaluation is not permitted to have side-effects, so evaluate it in | ||||||
9804 | // a speculative evaluation context. | ||||||
9805 | SpeculativeEvaluationRAII SpeculativeEval(Info); | ||||||
9806 | |||||||
9807 | // Constant-folding is always enabled for the operand of __builtin_constant_p | ||||||
9808 | // (even when the enclosing evaluation context otherwise requires a strict | ||||||
9809 | // language-specific constant expression). | ||||||
9810 | FoldConstant Fold(Info, true); | ||||||
9811 | |||||||
9812 | QualType ArgType = Arg->getType(); | ||||||
9813 | |||||||
9814 | // __builtin_constant_p always has one operand. The rules which gcc follows | ||||||
9815 | // are not precisely documented, but are as follows: | ||||||
9816 | // | ||||||
9817 | // - If the operand is of integral, floating, complex or enumeration type, | ||||||
9818 | // and can be folded to a known value of that type, it returns 1. | ||||||
9819 | // - If the operand can be folded to a pointer to the first character | ||||||
9820 | // of a string literal (or such a pointer cast to an integral type) | ||||||
9821 | // or to a null pointer or an integer cast to a pointer, it returns 1. | ||||||
9822 | // | ||||||
9823 | // Otherwise, it returns 0. | ||||||
9824 | // | ||||||
9825 | // FIXME: GCC also intends to return 1 for literals of aggregate types, but | ||||||
9826 | // its support for this did not work prior to GCC 9 and is not yet well | ||||||
9827 | // understood. | ||||||
9828 | if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || | ||||||
9829 | ArgType->isAnyComplexType() || ArgType->isPointerType() || | ||||||
9830 | ArgType->isNullPtrType()) { | ||||||
9831 | APValue V; | ||||||
9832 | if (!::EvaluateAsRValue(Info, Arg, V)) { | ||||||
9833 | Fold.keepDiagnostics(); | ||||||
9834 | return false; | ||||||
9835 | } | ||||||
9836 | |||||||
9837 | // For a pointer (possibly cast to integer), there are special rules. | ||||||
9838 | if (V.getKind() == APValue::LValue) | ||||||
9839 | return EvaluateBuiltinConstantPForLValue(V); | ||||||
9840 | |||||||
9841 | // Otherwise, any constant value is good enough. | ||||||
9842 | return V.hasValue(); | ||||||
9843 | } | ||||||
9844 | |||||||
9845 | // Anything else isn't considered to be sufficiently constant. | ||||||
9846 | return false; | ||||||
9847 | } | ||||||
9848 | |||||||
9849 | /// Retrieves the "underlying object type" of the given expression, | ||||||
9850 | /// as used by __builtin_object_size. | ||||||
9851 | static QualType getObjectType(APValue::LValueBase B) { | ||||||
9852 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | ||||||
9853 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||||
9854 | return VD->getType(); | ||||||
9855 | } else if (const Expr *E = B.get<const Expr*>()) { | ||||||
9856 | if (isa<CompoundLiteralExpr>(E)) | ||||||
9857 | return E->getType(); | ||||||
9858 | } else if (B.is<TypeInfoLValue>()) { | ||||||
9859 | return B.getTypeInfoType(); | ||||||
9860 | } else if (B.is<DynamicAllocLValue>()) { | ||||||
9861 | return B.getDynamicAllocType(); | ||||||
9862 | } | ||||||
9863 | |||||||
9864 | return QualType(); | ||||||
9865 | } | ||||||
9866 | |||||||
9867 | /// A more selective version of E->IgnoreParenCasts for | ||||||
9868 | /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only | ||||||
9869 | /// to change the type of E. | ||||||
9870 | /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` | ||||||
9871 | /// | ||||||
9872 | /// Always returns an RValue with a pointer representation. | ||||||
9873 | static const Expr *ignorePointerCastsAndParens(const Expr *E) { | ||||||
9874 | assert(E->isRValue() && E->getType()->hasPointerRepresentation())((E->isRValue() && E->getType()->hasPointerRepresentation ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->hasPointerRepresentation()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9874, __PRETTY_FUNCTION__)); | ||||||
9875 | |||||||
9876 | auto *NoParens = E->IgnoreParens(); | ||||||
9877 | auto *Cast = dyn_cast<CastExpr>(NoParens); | ||||||
9878 | if (Cast == nullptr) | ||||||
9879 | return NoParens; | ||||||
9880 | |||||||
9881 | // We only conservatively allow a few kinds of casts, because this code is | ||||||
9882 | // inherently a simple solution that seeks to support the common case. | ||||||
9883 | auto CastKind = Cast->getCastKind(); | ||||||
9884 | if (CastKind != CK_NoOp && CastKind != CK_BitCast && | ||||||
9885 | CastKind != CK_AddressSpaceConversion) | ||||||
9886 | return NoParens; | ||||||
9887 | |||||||
9888 | auto *SubExpr = Cast->getSubExpr(); | ||||||
9889 | if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) | ||||||
9890 | return NoParens; | ||||||
9891 | return ignorePointerCastsAndParens(SubExpr); | ||||||
9892 | } | ||||||
9893 | |||||||
9894 | /// Checks to see if the given LValue's Designator is at the end of the LValue's | ||||||
9895 | /// record layout. e.g. | ||||||
9896 | /// struct { struct { int a, b; } fst, snd; } obj; | ||||||
9897 | /// obj.fst // no | ||||||
9898 | /// obj.snd // yes | ||||||
9899 | /// obj.fst.a // no | ||||||
9900 | /// obj.fst.b // no | ||||||
9901 | /// obj.snd.a // no | ||||||
9902 | /// obj.snd.b // yes | ||||||
9903 | /// | ||||||
9904 | /// Please note: this function is specialized for how __builtin_object_size | ||||||
9905 | /// views "objects". | ||||||
9906 | /// | ||||||
9907 | /// If this encounters an invalid RecordDecl or otherwise cannot determine the | ||||||
9908 | /// correct result, it will always return true. | ||||||
9909 | static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { | ||||||
9910 | assert(!LVal.Designator.Invalid)((!LVal.Designator.Invalid) ? static_cast<void> (0) : __assert_fail ("!LVal.Designator.Invalid", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9910, __PRETTY_FUNCTION__)); | ||||||
9911 | |||||||
9912 | auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { | ||||||
9913 | const RecordDecl *Parent = FD->getParent(); | ||||||
9914 | Invalid = Parent->isInvalidDecl(); | ||||||
9915 | if (Invalid || Parent->isUnion()) | ||||||
9916 | return true; | ||||||
9917 | const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); | ||||||
9918 | return FD->getFieldIndex() + 1 == Layout.getFieldCount(); | ||||||
9919 | }; | ||||||
9920 | |||||||
9921 | auto &Base = LVal.getLValueBase(); | ||||||
9922 | if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { | ||||||
9923 | if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { | ||||||
9924 | bool Invalid; | ||||||
9925 | if (!IsLastOrInvalidFieldDecl(FD, Invalid)) | ||||||
9926 | return Invalid; | ||||||
9927 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { | ||||||
9928 | for (auto *FD : IFD->chain()) { | ||||||
9929 | bool Invalid; | ||||||
9930 | if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) | ||||||
9931 | return Invalid; | ||||||
9932 | } | ||||||
9933 | } | ||||||
9934 | } | ||||||
9935 | |||||||
9936 | unsigned I = 0; | ||||||
9937 | QualType BaseType = getType(Base); | ||||||
9938 | if (LVal.Designator.FirstEntryIsAnUnsizedArray) { | ||||||
9939 | // If we don't know the array bound, conservatively assume we're looking at | ||||||
9940 | // the final array element. | ||||||
9941 | ++I; | ||||||
9942 | if (BaseType->isIncompleteArrayType()) | ||||||
9943 | BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); | ||||||
9944 | else | ||||||
9945 | BaseType = BaseType->castAs<PointerType>()->getPointeeType(); | ||||||
9946 | } | ||||||
9947 | |||||||
9948 | for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { | ||||||
9949 | const auto &Entry = LVal.Designator.Entries[I]; | ||||||
9950 | if (BaseType->isArrayType()) { | ||||||
9951 | // Because __builtin_object_size treats arrays as objects, we can ignore | ||||||
9952 | // the index iff this is the last array in the Designator. | ||||||
9953 | if (I + 1 == E) | ||||||
9954 | return true; | ||||||
9955 | const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); | ||||||
9956 | uint64_t Index = Entry.getAsArrayIndex(); | ||||||
9957 | if (Index + 1 != CAT->getSize()) | ||||||
9958 | return false; | ||||||
9959 | BaseType = CAT->getElementType(); | ||||||
9960 | } else if (BaseType->isAnyComplexType()) { | ||||||
9961 | const auto *CT = BaseType->castAs<ComplexType>(); | ||||||
9962 | uint64_t Index = Entry.getAsArrayIndex(); | ||||||
9963 | if (Index != 1) | ||||||
9964 | return false; | ||||||
9965 | BaseType = CT->getElementType(); | ||||||
9966 | } else if (auto *FD = getAsField(Entry)) { | ||||||
9967 | bool Invalid; | ||||||
9968 | if (!IsLastOrInvalidFieldDecl(FD, Invalid)) | ||||||
9969 | return Invalid; | ||||||
9970 | BaseType = FD->getType(); | ||||||
9971 | } else { | ||||||
9972 | assert(getAsBaseClass(Entry) && "Expecting cast to a base class")((getAsBaseClass(Entry) && "Expecting cast to a base class" ) ? static_cast<void> (0) : __assert_fail ("getAsBaseClass(Entry) && \"Expecting cast to a base class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9972, __PRETTY_FUNCTION__)); | ||||||
9973 | return false; | ||||||
9974 | } | ||||||
9975 | } | ||||||
9976 | return true; | ||||||
9977 | } | ||||||
9978 | |||||||
9979 | /// Tests to see if the LValue has a user-specified designator (that isn't | ||||||
9980 | /// necessarily valid). Note that this always returns 'true' if the LValue has | ||||||
9981 | /// an unsized array as its first designator entry, because there's currently no | ||||||
9982 | /// way to tell if the user typed *foo or foo[0]. | ||||||
9983 | static bool refersToCompleteObject(const LValue &LVal) { | ||||||
9984 | if (LVal.Designator.Invalid) | ||||||
9985 | return false; | ||||||
9986 | |||||||
9987 | if (!LVal.Designator.Entries.empty()) | ||||||
9988 | return LVal.Designator.isMostDerivedAnUnsizedArray(); | ||||||
9989 | |||||||
9990 | if (!LVal.InvalidBase) | ||||||
9991 | return true; | ||||||
9992 | |||||||
9993 | // If `E` is a MemberExpr, then the first part of the designator is hiding in | ||||||
9994 | // the LValueBase. | ||||||
9995 | const auto *E = LVal.Base.dyn_cast<const Expr *>(); | ||||||
9996 | return !E || !isa<MemberExpr>(E); | ||||||
9997 | } | ||||||
9998 | |||||||
9999 | /// Attempts to detect a user writing into a piece of memory that's impossible | ||||||
10000 | /// to figure out the size of by just using types. | ||||||
10001 | static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { | ||||||
10002 | const SubobjectDesignator &Designator = LVal.Designator; | ||||||
10003 | // Notes: | ||||||
10004 | // - Users can only write off of the end when we have an invalid base. Invalid | ||||||
10005 | // bases imply we don't know where the memory came from. | ||||||
10006 | // - We used to be a bit more aggressive here; we'd only be conservative if | ||||||
10007 | // the array at the end was flexible, or if it had 0 or 1 elements. This | ||||||
10008 | // broke some common standard library extensions (PR30346), but was | ||||||
10009 | // otherwise seemingly fine. It may be useful to reintroduce this behavior | ||||||
10010 | // with some sort of whitelist. OTOH, it seems that GCC is always | ||||||
10011 | // conservative with the last element in structs (if it's an array), so our | ||||||
10012 | // current behavior is more compatible than a whitelisting approach would | ||||||
10013 | // be. | ||||||
10014 | return LVal.InvalidBase && | ||||||
10015 | Designator.Entries.size() == Designator.MostDerivedPathLength && | ||||||
10016 | Designator.MostDerivedIsArrayElement && | ||||||
10017 | isDesignatorAtObjectEnd(Ctx, LVal); | ||||||
10018 | } | ||||||
10019 | |||||||
10020 | /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. | ||||||
10021 | /// Fails if the conversion would cause loss of precision. | ||||||
10022 | static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, | ||||||
10023 | CharUnits &Result) { | ||||||
10024 | auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); | ||||||
10025 | if (Int.ugt(CharUnitsMax)) | ||||||
10026 | return false; | ||||||
10027 | Result = CharUnits::fromQuantity(Int.getZExtValue()); | ||||||
10028 | return true; | ||||||
10029 | } | ||||||
10030 | |||||||
10031 | /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will | ||||||
10032 | /// determine how many bytes exist from the beginning of the object to either | ||||||
10033 | /// the end of the current subobject, or the end of the object itself, depending | ||||||
10034 | /// on what the LValue looks like + the value of Type. | ||||||
10035 | /// | ||||||
10036 | /// If this returns false, the value of Result is undefined. | ||||||
10037 | static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, | ||||||
10038 | unsigned Type, const LValue &LVal, | ||||||
10039 | CharUnits &EndOffset) { | ||||||
10040 | bool DetermineForCompleteObject = refersToCompleteObject(LVal); | ||||||
10041 | |||||||
10042 | auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { | ||||||
10043 | if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) | ||||||
10044 | return false; | ||||||
10045 | return HandleSizeof(Info, ExprLoc, Ty, Result); | ||||||
10046 | }; | ||||||
10047 | |||||||
10048 | // We want to evaluate the size of the entire object. This is a valid fallback | ||||||
10049 | // for when Type=1 and the designator is invalid, because we're asked for an | ||||||
10050 | // upper-bound. | ||||||
10051 | if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { | ||||||
10052 | // Type=3 wants a lower bound, so we can't fall back to this. | ||||||
10053 | if (Type == 3 && !DetermineForCompleteObject) | ||||||
10054 | return false; | ||||||
10055 | |||||||
10056 | llvm::APInt APEndOffset; | ||||||
10057 | if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && | ||||||
10058 | getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) | ||||||
10059 | return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); | ||||||
10060 | |||||||
10061 | if (LVal.InvalidBase) | ||||||
10062 | return false; | ||||||
10063 | |||||||
10064 | QualType BaseTy = getObjectType(LVal.getLValueBase()); | ||||||
10065 | return CheckedHandleSizeof(BaseTy, EndOffset); | ||||||
10066 | } | ||||||
10067 | |||||||
10068 | // We want to evaluate the size of a subobject. | ||||||
10069 | const SubobjectDesignator &Designator = LVal.Designator; | ||||||
10070 | |||||||
10071 | // The following is a moderately common idiom in C: | ||||||
10072 | // | ||||||
10073 | // struct Foo { int a; char c[1]; }; | ||||||
10074 | // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); | ||||||
10075 | // strcpy(&F->c[0], Bar); | ||||||
10076 | // | ||||||
10077 | // In order to not break too much legacy code, we need to support it. | ||||||
10078 | if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { | ||||||
10079 | // If we can resolve this to an alloc_size call, we can hand that back, | ||||||
10080 | // because we know for certain how many bytes there are to write to. | ||||||
10081 | llvm::APInt APEndOffset; | ||||||
10082 | if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && | ||||||
10083 | getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) | ||||||
10084 | return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); | ||||||
10085 | |||||||
10086 | // If we cannot determine the size of the initial allocation, then we can't | ||||||
10087 | // given an accurate upper-bound. However, we are still able to give | ||||||
10088 | // conservative lower-bounds for Type=3. | ||||||
10089 | if (Type == 1) | ||||||
10090 | return false; | ||||||
10091 | } | ||||||
10092 | |||||||
10093 | CharUnits BytesPerElem; | ||||||
10094 | if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) | ||||||
10095 | return false; | ||||||
10096 | |||||||
10097 | // According to the GCC documentation, we want the size of the subobject | ||||||
10098 | // denoted by the pointer. But that's not quite right -- what we actually | ||||||
10099 | // want is the size of the immediately-enclosing array, if there is one. | ||||||
10100 | int64_t ElemsRemaining; | ||||||
10101 | if (Designator.MostDerivedIsArrayElement && | ||||||
10102 | Designator.Entries.size() == Designator.MostDerivedPathLength) { | ||||||
10103 | uint64_t ArraySize = Designator.getMostDerivedArraySize(); | ||||||
10104 | uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); | ||||||
10105 | ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; | ||||||
10106 | } else { | ||||||
10107 | ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; | ||||||
10108 | } | ||||||
10109 | |||||||
10110 | EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; | ||||||
10111 | return true; | ||||||
10112 | } | ||||||
10113 | |||||||
10114 | /// Tries to evaluate the __builtin_object_size for @p E. If successful, | ||||||
10115 | /// returns true and stores the result in @p Size. | ||||||
10116 | /// | ||||||
10117 | /// If @p WasError is non-null, this will report whether the failure to evaluate | ||||||
10118 | /// is to be treated as an Error in IntExprEvaluator. | ||||||
10119 | static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, | ||||||
10120 | EvalInfo &Info, uint64_t &Size) { | ||||||
10121 | // Determine the denoted object. | ||||||
10122 | LValue LVal; | ||||||
10123 | { | ||||||
10124 | // The operand of __builtin_object_size is never evaluated for side-effects. | ||||||
10125 | // If there are any, but we can determine the pointed-to object anyway, then | ||||||
10126 | // ignore the side-effects. | ||||||
10127 | SpeculativeEvaluationRAII SpeculativeEval(Info); | ||||||
10128 | IgnoreSideEffectsRAII Fold(Info); | ||||||
10129 | |||||||
10130 | if (E->isGLValue()) { | ||||||
10131 | // It's possible for us to be given GLValues if we're called via | ||||||
10132 | // Expr::tryEvaluateObjectSize. | ||||||
10133 | APValue RVal; | ||||||
10134 | if (!EvaluateAsRValue(Info, E, RVal)) | ||||||
10135 | return false; | ||||||
10136 | LVal.setFrom(Info.Ctx, RVal); | ||||||
10137 | } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, | ||||||
10138 | /*InvalidBaseOK=*/true)) | ||||||
10139 | return false; | ||||||
10140 | } | ||||||
10141 | |||||||
10142 | // If we point to before the start of the object, there are no accessible | ||||||
10143 | // bytes. | ||||||
10144 | if (LVal.getLValueOffset().isNegative()) { | ||||||
10145 | Size = 0; | ||||||
10146 | return true; | ||||||
10147 | } | ||||||
10148 | |||||||
10149 | CharUnits EndOffset; | ||||||
10150 | if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) | ||||||
10151 | return false; | ||||||
10152 | |||||||
10153 | // If we've fallen outside of the end offset, just pretend there's nothing to | ||||||
10154 | // write to/read from. | ||||||
10155 | if (EndOffset <= LVal.getLValueOffset()) | ||||||
10156 | Size = 0; | ||||||
10157 | else | ||||||
10158 | Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); | ||||||
10159 | return true; | ||||||
10160 | } | ||||||
10161 | |||||||
10162 | bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { | ||||||
10163 | llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); | ||||||
10164 | if (E->getResultAPValueKind() != APValue::None) | ||||||
10165 | return Success(E->getAPValueResult(), E); | ||||||
10166 | return ExprEvaluatorBaseTy::VisitConstantExpr(E); | ||||||
10167 | } | ||||||
10168 | |||||||
10169 | bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||||
10170 | if (unsigned BuiltinOp = E->getBuiltinCallee()) | ||||||
10171 | return VisitBuiltinCallExpr(E, BuiltinOp); | ||||||
10172 | |||||||
10173 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||||
10174 | } | ||||||
10175 | |||||||
10176 | bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, | ||||||
10177 | unsigned BuiltinOp) { | ||||||
10178 | switch (unsigned BuiltinOp = E->getBuiltinCallee()) { | ||||||
10179 | default: | ||||||
10180 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||||
10181 | |||||||
10182 | case Builtin::BI__builtin_dynamic_object_size: | ||||||
10183 | case Builtin::BI__builtin_object_size: { | ||||||
10184 | // The type was checked when we built the expression. | ||||||
10185 | unsigned Type = | ||||||
10186 | E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); | ||||||
10187 | assert(Type <= 3 && "unexpected type")((Type <= 3 && "unexpected type") ? static_cast< void> (0) : __assert_fail ("Type <= 3 && \"unexpected type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10187, __PRETTY_FUNCTION__)); | ||||||
10188 | |||||||
10189 | uint64_t Size; | ||||||
10190 | if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) | ||||||
10191 | return Success(Size, E); | ||||||
10192 | |||||||
10193 | if (E->getArg(0)->HasSideEffects(Info.Ctx)) | ||||||
10194 | return Success((Type & 2) ? 0 : -1, E); | ||||||
10195 | |||||||
10196 | // Expression had no side effects, but we couldn't statically determine the | ||||||
10197 | // size of the referenced object. | ||||||
10198 | switch (Info.EvalMode) { | ||||||
10199 | case EvalInfo::EM_ConstantExpression: | ||||||
10200 | case EvalInfo::EM_ConstantFold: | ||||||
10201 | case EvalInfo::EM_IgnoreSideEffects: | ||||||
10202 | // Leave it to IR generation. | ||||||
10203 | return Error(E); | ||||||
10204 | case EvalInfo::EM_ConstantExpressionUnevaluated: | ||||||
10205 | // Reduce it to a constant now. | ||||||
10206 | return Success((Type & 2) ? 0 : -1, E); | ||||||
10207 | } | ||||||
10208 | |||||||
10209 | llvm_unreachable("unexpected EvalMode")::llvm::llvm_unreachable_internal("unexpected EvalMode", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10209); | ||||||
10210 | } | ||||||
10211 | |||||||
10212 | case Builtin::BI__builtin_os_log_format_buffer_size: { | ||||||
10213 | analyze_os_log::OSLogBufferLayout Layout; | ||||||
10214 | analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); | ||||||
10215 | return Success(Layout.size().getQuantity(), E); | ||||||
10216 | } | ||||||
10217 | |||||||
10218 | case Builtin::BI__builtin_bswap16: | ||||||
10219 | case Builtin::BI__builtin_bswap32: | ||||||
10220 | case Builtin::BI__builtin_bswap64: { | ||||||
10221 | APSInt Val; | ||||||
10222 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||||
10223 | return false; | ||||||
10224 | |||||||
10225 | return Success(Val.byteSwap(), E); | ||||||
10226 | } | ||||||
10227 | |||||||
10228 | case Builtin::BI__builtin_classify_type: | ||||||
10229 | return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); | ||||||
10230 | |||||||
10231 | case Builtin::BI__builtin_clrsb: | ||||||
10232 | case Builtin::BI__builtin_clrsbl: | ||||||
10233 | case Builtin::BI__builtin_clrsbll: { | ||||||
10234 | APSInt Val; | ||||||
10235 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||||
10236 | return false; | ||||||
10237 | |||||||
10238 | return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); | ||||||
10239 | } | ||||||
10240 | |||||||
10241 | case Builtin::BI__builtin_clz: | ||||||
10242 | case Builtin::BI__builtin_clzl: | ||||||
10243 | case Builtin::BI__builtin_clzll: | ||||||
10244 | case Builtin::BI__builtin_clzs: { | ||||||
10245 | APSInt Val; | ||||||
10246 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||||
10247 | return false; | ||||||
10248 | if (!Val) | ||||||
10249 | return Error(E); | ||||||
10250 | |||||||
10251 | return Success(Val.countLeadingZeros(), E); | ||||||
10252 | } | ||||||
10253 | |||||||
10254 | case Builtin::BI__builtin_constant_p: { | ||||||
10255 | const Expr *Arg = E->getArg(0); | ||||||
10256 | if (EvaluateBuiltinConstantP(Info, Arg)) | ||||||
10257 | return Success(true, E); | ||||||
10258 | if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { | ||||||
10259 | // Outside a constant context, eagerly evaluate to false in the presence | ||||||
10260 | // of side-effects in order to avoid -Wunsequenced false-positives in | ||||||
10261 | // a branch on __builtin_constant_p(expr). | ||||||
10262 | return Success(false, E); | ||||||
10263 | } | ||||||
10264 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
10265 | return false; | ||||||
10266 | } | ||||||
10267 | |||||||
10268 | case Builtin::BI__builtin_is_constant_evaluated: | ||||||
10269 | return Success(Info.InConstantContext, E); | ||||||
10270 | |||||||
10271 | case Builtin::BI__builtin_ctz: | ||||||
10272 | case Builtin::BI__builtin_ctzl: | ||||||
10273 | case Builtin::BI__builtin_ctzll: | ||||||
10274 | case Builtin::BI__builtin_ctzs: { | ||||||
10275 | APSInt Val; | ||||||
10276 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||||
10277 | return false; | ||||||
10278 | if (!Val) | ||||||
10279 | return Error(E); | ||||||
10280 | |||||||
10281 | return Success(Val.countTrailingZeros(), E); | ||||||
10282 | } | ||||||
10283 | |||||||
10284 | case Builtin::BI__builtin_eh_return_data_regno: { | ||||||
10285 | int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); | ||||||
10286 | Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); | ||||||
10287 | return Success(Operand, E); | ||||||
10288 | } | ||||||
10289 | |||||||
10290 | case Builtin::BI__builtin_expect: | ||||||
10291 | return Visit(E->getArg(0)); | ||||||
10292 | |||||||
10293 | case Builtin::BI__builtin_ffs: | ||||||
10294 | case Builtin::BI__builtin_ffsl: | ||||||
10295 | case Builtin::BI__builtin_ffsll: { | ||||||
10296 | APSInt Val; | ||||||
10297 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||||
10298 | return false; | ||||||
10299 | |||||||
10300 | unsigned N = Val.countTrailingZeros(); | ||||||
10301 | return Success(N == Val.getBitWidth() ? 0 : N + 1, E); | ||||||
10302 | } | ||||||
10303 | |||||||
10304 | case Builtin::BI__builtin_fpclassify: { | ||||||
10305 | APFloat Val(0.0); | ||||||
10306 | if (!EvaluateFloat(E->getArg(5), Val, Info)) | ||||||
10307 | return false; | ||||||
10308 | unsigned Arg; | ||||||
10309 | switch (Val.getCategory()) { | ||||||
10310 | case APFloat::fcNaN: Arg = 0; break; | ||||||
10311 | case APFloat::fcInfinity: Arg = 1; break; | ||||||
10312 | case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; | ||||||
10313 | case APFloat::fcZero: Arg = 4; break; | ||||||
10314 | } | ||||||
10315 | return Visit(E->getArg(Arg)); | ||||||
10316 | } | ||||||
10317 | |||||||
10318 | case Builtin::BI__builtin_isinf_sign: { | ||||||
10319 | APFloat Val(0.0); | ||||||
10320 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||||
10321 | Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); | ||||||
10322 | } | ||||||
10323 | |||||||
10324 | case Builtin::BI__builtin_isinf: { | ||||||
10325 | APFloat Val(0.0); | ||||||
10326 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||||
10327 | Success(Val.isInfinity() ? 1 : 0, E); | ||||||
10328 | } | ||||||
10329 | |||||||
10330 | case Builtin::BI__builtin_isfinite: { | ||||||
10331 | APFloat Val(0.0); | ||||||
10332 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||||
10333 | Success(Val.isFinite() ? 1 : 0, E); | ||||||
10334 | } | ||||||
10335 | |||||||
10336 | case Builtin::BI__builtin_isnan: { | ||||||
10337 | APFloat Val(0.0); | ||||||
10338 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||||
10339 | Success(Val.isNaN() ? 1 : 0, E); | ||||||
10340 | } | ||||||
10341 | |||||||
10342 | case Builtin::BI__builtin_isnormal: { | ||||||
10343 | APFloat Val(0.0); | ||||||
10344 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||||
10345 | Success(Val.isNormal() ? 1 : 0, E); | ||||||
10346 | } | ||||||
10347 | |||||||
10348 | case Builtin::BI__builtin_parity: | ||||||
10349 | case Builtin::BI__builtin_parityl: | ||||||
10350 | case Builtin::BI__builtin_parityll: { | ||||||
10351 | APSInt Val; | ||||||
10352 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||||
10353 | return false; | ||||||
10354 | |||||||
10355 | return Success(Val.countPopulation() % 2, E); | ||||||
10356 | } | ||||||
10357 | |||||||
10358 | case Builtin::BI__builtin_popcount: | ||||||
10359 | case Builtin::BI__builtin_popcountl: | ||||||
10360 | case Builtin::BI__builtin_popcountll: { | ||||||
10361 | APSInt Val; | ||||||
10362 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||||
10363 | return false; | ||||||
10364 | |||||||
10365 | return Success(Val.countPopulation(), E); | ||||||
10366 | } | ||||||
10367 | |||||||
10368 | case Builtin::BIstrlen: | ||||||
10369 | case Builtin::BIwcslen: | ||||||
10370 | // A call to strlen is not a constant expression. | ||||||
10371 | if (Info.getLangOpts().CPlusPlus11) | ||||||
10372 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||||
10373 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||||
10374 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||||
10375 | else | ||||||
10376 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
10377 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
10378 | case Builtin::BI__builtin_strlen: | ||||||
10379 | case Builtin::BI__builtin_wcslen: { | ||||||
10380 | // As an extension, we support __builtin_strlen() as a constant expression, | ||||||
10381 | // and support folding strlen() to a constant. | ||||||
10382 | LValue String; | ||||||
10383 | if (!EvaluatePointer(E->getArg(0), String, Info)) | ||||||
10384 | return false; | ||||||
10385 | |||||||
10386 | QualType CharTy = E->getArg(0)->getType()->getPointeeType(); | ||||||
10387 | |||||||
10388 | // Fast path: if it's a string literal, search the string value. | ||||||
10389 | if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( | ||||||
10390 | String.getLValueBase().dyn_cast<const Expr *>())) { | ||||||
10391 | // The string literal may have embedded null characters. Find the first | ||||||
10392 | // one and truncate there. | ||||||
10393 | StringRef Str = S->getBytes(); | ||||||
10394 | int64_t Off = String.Offset.getQuantity(); | ||||||
10395 | if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && | ||||||
10396 | S->getCharByteWidth() == 1 && | ||||||
10397 | // FIXME: Add fast-path for wchar_t too. | ||||||
10398 | Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { | ||||||
10399 | Str = Str.substr(Off); | ||||||
10400 | |||||||
10401 | StringRef::size_type Pos = Str.find(0); | ||||||
10402 | if (Pos != StringRef::npos) | ||||||
10403 | Str = Str.substr(0, Pos); | ||||||
10404 | |||||||
10405 | return Success(Str.size(), E); | ||||||
10406 | } | ||||||
10407 | |||||||
10408 | // Fall through to slow path to issue appropriate diagnostic. | ||||||
10409 | } | ||||||
10410 | |||||||
10411 | // Slow path: scan the bytes of the string looking for the terminating 0. | ||||||
10412 | for (uint64_t Strlen = 0; /**/; ++Strlen) { | ||||||
10413 | APValue Char; | ||||||
10414 | if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || | ||||||
10415 | !Char.isInt()) | ||||||
10416 | return false; | ||||||
10417 | if (!Char.getInt()) | ||||||
10418 | return Success(Strlen, E); | ||||||
10419 | if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) | ||||||
10420 | return false; | ||||||
10421 | } | ||||||
10422 | } | ||||||
10423 | |||||||
10424 | case Builtin::BIstrcmp: | ||||||
10425 | case Builtin::BIwcscmp: | ||||||
10426 | case Builtin::BIstrncmp: | ||||||
10427 | case Builtin::BIwcsncmp: | ||||||
10428 | case Builtin::BImemcmp: | ||||||
10429 | case Builtin::BIbcmp: | ||||||
10430 | case Builtin::BIwmemcmp: | ||||||
10431 | // A call to strlen is not a constant expression. | ||||||
10432 | if (Info.getLangOpts().CPlusPlus11) | ||||||
10433 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||||
10434 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||||
10435 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||||
10436 | else | ||||||
10437 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
10438 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
10439 | case Builtin::BI__builtin_strcmp: | ||||||
10440 | case Builtin::BI__builtin_wcscmp: | ||||||
10441 | case Builtin::BI__builtin_strncmp: | ||||||
10442 | case Builtin::BI__builtin_wcsncmp: | ||||||
10443 | case Builtin::BI__builtin_memcmp: | ||||||
10444 | case Builtin::BI__builtin_bcmp: | ||||||
10445 | case Builtin::BI__builtin_wmemcmp: { | ||||||
10446 | LValue String1, String2; | ||||||
10447 | if (!EvaluatePointer(E->getArg(0), String1, Info) || | ||||||
10448 | !EvaluatePointer(E->getArg(1), String2, Info)) | ||||||
10449 | return false; | ||||||
10450 | |||||||
10451 | uint64_t MaxLength = uint64_t(-1); | ||||||
10452 | if (BuiltinOp != Builtin::BIstrcmp && | ||||||
10453 | BuiltinOp != Builtin::BIwcscmp && | ||||||
10454 | BuiltinOp != Builtin::BI__builtin_strcmp && | ||||||
10455 | BuiltinOp != Builtin::BI__builtin_wcscmp) { | ||||||
10456 | APSInt N; | ||||||
10457 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||||
10458 | return false; | ||||||
10459 | MaxLength = N.getExtValue(); | ||||||
10460 | } | ||||||
10461 | |||||||
10462 | // Empty substrings compare equal by definition. | ||||||
10463 | if (MaxLength == 0u) | ||||||
10464 | return Success(0, E); | ||||||
10465 | |||||||
10466 | if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||||
10467 | !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||||
10468 | String1.Designator.Invalid || String2.Designator.Invalid) | ||||||
10469 | return false; | ||||||
10470 | |||||||
10471 | QualType CharTy1 = String1.Designator.getType(Info.Ctx); | ||||||
10472 | QualType CharTy2 = String2.Designator.getType(Info.Ctx); | ||||||
10473 | |||||||
10474 | bool IsRawByte = BuiltinOp == Builtin::BImemcmp || | ||||||
10475 | BuiltinOp == Builtin::BIbcmp || | ||||||
10476 | BuiltinOp == Builtin::BI__builtin_memcmp || | ||||||
10477 | BuiltinOp == Builtin::BI__builtin_bcmp; | ||||||
10478 | |||||||
10479 | assert(IsRawByte ||((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E-> getArg(0)->getType()->getPointeeType()) && Info .Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast <void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10482, __PRETTY_FUNCTION__)) | ||||||
10480 | (Info.Ctx.hasSameUnqualifiedType(((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E-> getArg(0)->getType()->getPointeeType()) && Info .Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast <void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10482, __PRETTY_FUNCTION__)) | ||||||
10481 | CharTy1, E->getArg(0)->getType()->getPointeeType()) &&((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E-> getArg(0)->getType()->getPointeeType()) && Info .Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast <void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10482, __PRETTY_FUNCTION__)) | ||||||
10482 | Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)))((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E-> getArg(0)->getType()->getPointeeType()) && Info .Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast <void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10482, __PRETTY_FUNCTION__)); | ||||||
10483 | |||||||
10484 | const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { | ||||||
10485 | return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && | ||||||
10486 | handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && | ||||||
10487 | Char1.isInt() && Char2.isInt(); | ||||||
10488 | }; | ||||||
10489 | const auto &AdvanceElems = [&] { | ||||||
10490 | return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && | ||||||
10491 | HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); | ||||||
10492 | }; | ||||||
10493 | |||||||
10494 | if (IsRawByte) { | ||||||
10495 | uint64_t BytesRemaining = MaxLength; | ||||||
10496 | // Pointers to const void may point to objects of incomplete type. | ||||||
10497 | if (CharTy1->isIncompleteType()) { | ||||||
10498 | Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; | ||||||
10499 | return false; | ||||||
10500 | } | ||||||
10501 | if (CharTy2->isIncompleteType()) { | ||||||
10502 | Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; | ||||||
10503 | return false; | ||||||
10504 | } | ||||||
10505 | uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; | ||||||
10506 | CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); | ||||||
10507 | // Give up on comparing between elements with disparate widths. | ||||||
10508 | if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) | ||||||
10509 | return false; | ||||||
10510 | uint64_t BytesPerElement = CharTy1Size.getQuantity(); | ||||||
10511 | assert(BytesRemaining && "BytesRemaining should not be zero: the "((BytesRemaining && "BytesRemaining should not be zero: the " "following loop considers at least one element") ? static_cast <void> (0) : __assert_fail ("BytesRemaining && \"BytesRemaining should not be zero: the \" \"following loop considers at least one element\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10512, __PRETTY_FUNCTION__)) | ||||||
10512 | "following loop considers at least one element")((BytesRemaining && "BytesRemaining should not be zero: the " "following loop considers at least one element") ? static_cast <void> (0) : __assert_fail ("BytesRemaining && \"BytesRemaining should not be zero: the \" \"following loop considers at least one element\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10512, __PRETTY_FUNCTION__)); | ||||||
10513 | while (true) { | ||||||
10514 | APValue Char1, Char2; | ||||||
10515 | if (!ReadCurElems(Char1, Char2)) | ||||||
10516 | return false; | ||||||
10517 | // We have compatible in-memory widths, but a possible type and | ||||||
10518 | // (for `bool`) internal representation mismatch. | ||||||
10519 | // Assuming two's complement representation, including 0 for `false` and | ||||||
10520 | // 1 for `true`, we can check an appropriate number of elements for | ||||||
10521 | // equality even if they are not byte-sized. | ||||||
10522 | APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); | ||||||
10523 | APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); | ||||||
10524 | if (Char1InMem.ne(Char2InMem)) { | ||||||
10525 | // If the elements are byte-sized, then we can produce a three-way | ||||||
10526 | // comparison result in a straightforward manner. | ||||||
10527 | if (BytesPerElement == 1u) { | ||||||
10528 | // memcmp always compares unsigned chars. | ||||||
10529 | return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); | ||||||
10530 | } | ||||||
10531 | // The result is byte-order sensitive, and we have multibyte elements. | ||||||
10532 | // FIXME: We can compare the remaining bytes in the correct order. | ||||||
10533 | return false; | ||||||
10534 | } | ||||||
10535 | if (!AdvanceElems()) | ||||||
10536 | return false; | ||||||
10537 | if (BytesRemaining <= BytesPerElement) | ||||||
10538 | break; | ||||||
10539 | BytesRemaining -= BytesPerElement; | ||||||
10540 | } | ||||||
10541 | // Enough elements are equal to account for the memcmp limit. | ||||||
10542 | return Success(0, E); | ||||||
10543 | } | ||||||
10544 | |||||||
10545 | bool StopAtNull = | ||||||
10546 | (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && | ||||||
10547 | BuiltinOp != Builtin::BIwmemcmp && | ||||||
10548 | BuiltinOp != Builtin::BI__builtin_memcmp && | ||||||
10549 | BuiltinOp != Builtin::BI__builtin_bcmp && | ||||||
10550 | BuiltinOp != Builtin::BI__builtin_wmemcmp); | ||||||
10551 | bool IsWide = BuiltinOp == Builtin::BIwcscmp || | ||||||
10552 | BuiltinOp == Builtin::BIwcsncmp || | ||||||
10553 | BuiltinOp == Builtin::BIwmemcmp || | ||||||
10554 | BuiltinOp == Builtin::BI__builtin_wcscmp || | ||||||
10555 | BuiltinOp == Builtin::BI__builtin_wcsncmp || | ||||||
10556 | BuiltinOp == Builtin::BI__builtin_wmemcmp; | ||||||
10557 | |||||||
10558 | for (; MaxLength; --MaxLength) { | ||||||
10559 | APValue Char1, Char2; | ||||||
10560 | if (!ReadCurElems(Char1, Char2)) | ||||||
10561 | return false; | ||||||
10562 | if (Char1.getInt() != Char2.getInt()) { | ||||||
10563 | if (IsWide) // wmemcmp compares with wchar_t signedness. | ||||||
10564 | return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); | ||||||
10565 | // memcmp always compares unsigned chars. | ||||||
10566 | return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); | ||||||
10567 | } | ||||||
10568 | if (StopAtNull && !Char1.getInt()) | ||||||
10569 | return Success(0, E); | ||||||
10570 | assert(!(StopAtNull && !Char2.getInt()))((!(StopAtNull && !Char2.getInt())) ? static_cast< void> (0) : __assert_fail ("!(StopAtNull && !Char2.getInt())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10570, __PRETTY_FUNCTION__)); | ||||||
10571 | if (!AdvanceElems()) | ||||||
10572 | return false; | ||||||
10573 | } | ||||||
10574 | // We hit the strncmp / memcmp limit. | ||||||
10575 | return Success(0, E); | ||||||
10576 | } | ||||||
10577 | |||||||
10578 | case Builtin::BI__atomic_always_lock_free: | ||||||
10579 | case Builtin::BI__atomic_is_lock_free: | ||||||
10580 | case Builtin::BI__c11_atomic_is_lock_free: { | ||||||
10581 | APSInt SizeVal; | ||||||
10582 | if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) | ||||||
10583 | return false; | ||||||
10584 | |||||||
10585 | // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power | ||||||
10586 | // of two less than the maximum inline atomic width, we know it is | ||||||
10587 | // lock-free. If the size isn't a power of two, or greater than the | ||||||
10588 | // maximum alignment where we promote atomics, we know it is not lock-free | ||||||
10589 | // (at least not in the sense of atomic_is_lock_free). Otherwise, | ||||||
10590 | // the answer can only be determined at runtime; for example, 16-byte | ||||||
10591 | // atomics have lock-free implementations on some, but not all, | ||||||
10592 | // x86-64 processors. | ||||||
10593 | |||||||
10594 | // Check power-of-two. | ||||||
10595 | CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); | ||||||
10596 | if (Size.isPowerOfTwo()) { | ||||||
10597 | // Check against inlining width. | ||||||
10598 | unsigned InlineWidthBits = | ||||||
10599 | Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); | ||||||
10600 | if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { | ||||||
10601 | if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || | ||||||
10602 | Size == CharUnits::One() || | ||||||
10603 | E->getArg(1)->isNullPointerConstant(Info.Ctx, | ||||||
10604 | Expr::NPC_NeverValueDependent)) | ||||||
10605 | // OK, we will inline appropriately-aligned operations of this size, | ||||||
10606 | // and _Atomic(T) is appropriately-aligned. | ||||||
10607 | return Success(1, E); | ||||||
10608 | |||||||
10609 | QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> | ||||||
10610 | castAs<PointerType>()->getPointeeType(); | ||||||
10611 | if (!PointeeType->isIncompleteType() && | ||||||
10612 | Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { | ||||||
10613 | // OK, we will inline operations on this object. | ||||||
10614 | return Success(1, E); | ||||||
10615 | } | ||||||
10616 | } | ||||||
10617 | } | ||||||
10618 | |||||||
10619 | return BuiltinOp == Builtin::BI__atomic_always_lock_free ? | ||||||
10620 | Success(0, E) : Error(E); | ||||||
10621 | } | ||||||
10622 | case Builtin::BIomp_is_initial_device: | ||||||
10623 | // We can decide statically which value the runtime would return if called. | ||||||
10624 | return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); | ||||||
10625 | case Builtin::BI__builtin_add_overflow: | ||||||
10626 | case Builtin::BI__builtin_sub_overflow: | ||||||
10627 | case Builtin::BI__builtin_mul_overflow: | ||||||
10628 | case Builtin::BI__builtin_sadd_overflow: | ||||||
10629 | case Builtin::BI__builtin_uadd_overflow: | ||||||
10630 | case Builtin::BI__builtin_uaddl_overflow: | ||||||
10631 | case Builtin::BI__builtin_uaddll_overflow: | ||||||
10632 | case Builtin::BI__builtin_usub_overflow: | ||||||
10633 | case Builtin::BI__builtin_usubl_overflow: | ||||||
10634 | case Builtin::BI__builtin_usubll_overflow: | ||||||
10635 | case Builtin::BI__builtin_umul_overflow: | ||||||
10636 | case Builtin::BI__builtin_umull_overflow: | ||||||
10637 | case Builtin::BI__builtin_umulll_overflow: | ||||||
10638 | case Builtin::BI__builtin_saddl_overflow: | ||||||
10639 | case Builtin::BI__builtin_saddll_overflow: | ||||||
10640 | case Builtin::BI__builtin_ssub_overflow: | ||||||
10641 | case Builtin::BI__builtin_ssubl_overflow: | ||||||
10642 | case Builtin::BI__builtin_ssubll_overflow: | ||||||
10643 | case Builtin::BI__builtin_smul_overflow: | ||||||
10644 | case Builtin::BI__builtin_smull_overflow: | ||||||
10645 | case Builtin::BI__builtin_smulll_overflow: { | ||||||
10646 | LValue ResultLValue; | ||||||
10647 | APSInt LHS, RHS; | ||||||
10648 | |||||||
10649 | QualType ResultType = E->getArg(2)->getType()->getPointeeType(); | ||||||
10650 | if (!EvaluateInteger(E->getArg(0), LHS, Info) || | ||||||
10651 | !EvaluateInteger(E->getArg(1), RHS, Info) || | ||||||
10652 | !EvaluatePointer(E->getArg(2), ResultLValue, Info)) | ||||||
10653 | return false; | ||||||
10654 | |||||||
10655 | APSInt Result; | ||||||
10656 | bool DidOverflow = false; | ||||||
10657 | |||||||
10658 | // If the types don't have to match, enlarge all 3 to the largest of them. | ||||||
10659 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || | ||||||
10660 | BuiltinOp == Builtin::BI__builtin_sub_overflow || | ||||||
10661 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { | ||||||
10662 | bool IsSigned = LHS.isSigned() || RHS.isSigned() || | ||||||
10663 | ResultType->isSignedIntegerOrEnumerationType(); | ||||||
10664 | bool AllSigned = LHS.isSigned() && RHS.isSigned() && | ||||||
10665 | ResultType->isSignedIntegerOrEnumerationType(); | ||||||
10666 | uint64_t LHSSize = LHS.getBitWidth(); | ||||||
10667 | uint64_t RHSSize = RHS.getBitWidth(); | ||||||
10668 | uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); | ||||||
10669 | uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); | ||||||
10670 | |||||||
10671 | // Add an additional bit if the signedness isn't uniformly agreed to. We | ||||||
10672 | // could do this ONLY if there is a signed and an unsigned that both have | ||||||
10673 | // MaxBits, but the code to check that is pretty nasty. The issue will be | ||||||
10674 | // caught in the shrink-to-result later anyway. | ||||||
10675 | if (IsSigned && !AllSigned) | ||||||
10676 | ++MaxBits; | ||||||
10677 | |||||||
10678 | LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); | ||||||
10679 | RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); | ||||||
10680 | Result = APSInt(MaxBits, !IsSigned); | ||||||
10681 | } | ||||||
10682 | |||||||
10683 | // Find largest int. | ||||||
10684 | switch (BuiltinOp) { | ||||||
10685 | default: | ||||||
10686 | llvm_unreachable("Invalid value for BuiltinOp")::llvm::llvm_unreachable_internal("Invalid value for BuiltinOp" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10686); | ||||||
10687 | case Builtin::BI__builtin_add_overflow: | ||||||
10688 | case Builtin::BI__builtin_sadd_overflow: | ||||||
10689 | case Builtin::BI__builtin_saddl_overflow: | ||||||
10690 | case Builtin::BI__builtin_saddll_overflow: | ||||||
10691 | case Builtin::BI__builtin_uadd_overflow: | ||||||
10692 | case Builtin::BI__builtin_uaddl_overflow: | ||||||
10693 | case Builtin::BI__builtin_uaddll_overflow: | ||||||
10694 | Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) | ||||||
10695 | : LHS.uadd_ov(RHS, DidOverflow); | ||||||
10696 | break; | ||||||
10697 | case Builtin::BI__builtin_sub_overflow: | ||||||
10698 | case Builtin::BI__builtin_ssub_overflow: | ||||||
10699 | case Builtin::BI__builtin_ssubl_overflow: | ||||||
10700 | case Builtin::BI__builtin_ssubll_overflow: | ||||||
10701 | case Builtin::BI__builtin_usub_overflow: | ||||||
10702 | case Builtin::BI__builtin_usubl_overflow: | ||||||
10703 | case Builtin::BI__builtin_usubll_overflow: | ||||||
10704 | Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) | ||||||
10705 | : LHS.usub_ov(RHS, DidOverflow); | ||||||
10706 | break; | ||||||
10707 | case Builtin::BI__builtin_mul_overflow: | ||||||
10708 | case Builtin::BI__builtin_smul_overflow: | ||||||
10709 | case Builtin::BI__builtin_smull_overflow: | ||||||
10710 | case Builtin::BI__builtin_smulll_overflow: | ||||||
10711 | case Builtin::BI__builtin_umul_overflow: | ||||||
10712 | case Builtin::BI__builtin_umull_overflow: | ||||||
10713 | case Builtin::BI__builtin_umulll_overflow: | ||||||
10714 | Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) | ||||||
10715 | : LHS.umul_ov(RHS, DidOverflow); | ||||||
10716 | break; | ||||||
10717 | } | ||||||
10718 | |||||||
10719 | // In the case where multiple sizes are allowed, truncate and see if | ||||||
10720 | // the values are the same. | ||||||
10721 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || | ||||||
10722 | BuiltinOp == Builtin::BI__builtin_sub_overflow || | ||||||
10723 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { | ||||||
10724 | // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, | ||||||
10725 | // since it will give us the behavior of a TruncOrSelf in the case where | ||||||
10726 | // its parameter <= its size. We previously set Result to be at least the | ||||||
10727 | // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth | ||||||
10728 | // will work exactly like TruncOrSelf. | ||||||
10729 | APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); | ||||||
10730 | Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); | ||||||
10731 | |||||||
10732 | if (!APSInt::isSameValue(Temp, Result)) | ||||||
10733 | DidOverflow = true; | ||||||
10734 | Result = Temp; | ||||||
10735 | } | ||||||
10736 | |||||||
10737 | APValue APV{Result}; | ||||||
10738 | if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) | ||||||
10739 | return false; | ||||||
10740 | return Success(DidOverflow, E); | ||||||
10741 | } | ||||||
10742 | } | ||||||
10743 | } | ||||||
10744 | |||||||
10745 | /// Determine whether this is a pointer past the end of the complete | ||||||
10746 | /// object referred to by the lvalue. | ||||||
10747 | static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, | ||||||
10748 | const LValue &LV) { | ||||||
10749 | // A null pointer can be viewed as being "past the end" but we don't | ||||||
10750 | // choose to look at it that way here. | ||||||
10751 | if (!LV.getLValueBase()) | ||||||
10752 | return false; | ||||||
10753 | |||||||
10754 | // If the designator is valid and refers to a subobject, we're not pointing | ||||||
10755 | // past the end. | ||||||
10756 | if (!LV.getLValueDesignator().Invalid && | ||||||
10757 | !LV.getLValueDesignator().isOnePastTheEnd()) | ||||||
10758 | return false; | ||||||
10759 | |||||||
10760 | // A pointer to an incomplete type might be past-the-end if the type's size is | ||||||
10761 | // zero. We cannot tell because the type is incomplete. | ||||||
10762 | QualType Ty = getType(LV.getLValueBase()); | ||||||
10763 | if (Ty->isIncompleteType()) | ||||||
10764 | return true; | ||||||
10765 | |||||||
10766 | // We're a past-the-end pointer if we point to the byte after the object, | ||||||
10767 | // no matter what our type or path is. | ||||||
10768 | auto Size = Ctx.getTypeSizeInChars(Ty); | ||||||
10769 | return LV.getLValueOffset() == Size; | ||||||
10770 | } | ||||||
10771 | |||||||
10772 | namespace { | ||||||
10773 | |||||||
10774 | /// Data recursive integer evaluator of certain binary operators. | ||||||
10775 | /// | ||||||
10776 | /// We use a data recursive algorithm for binary operators so that we are able | ||||||
10777 | /// to handle extreme cases of chained binary operators without causing stack | ||||||
10778 | /// overflow. | ||||||
10779 | class DataRecursiveIntBinOpEvaluator { | ||||||
10780 | struct EvalResult { | ||||||
10781 | APValue Val; | ||||||
10782 | bool Failed; | ||||||
10783 | |||||||
10784 | EvalResult() : Failed(false) { } | ||||||
10785 | |||||||
10786 | void swap(EvalResult &RHS) { | ||||||
10787 | Val.swap(RHS.Val); | ||||||
10788 | Failed = RHS.Failed; | ||||||
10789 | RHS.Failed = false; | ||||||
10790 | } | ||||||
10791 | }; | ||||||
10792 | |||||||
10793 | struct Job { | ||||||
10794 | const Expr *E; | ||||||
10795 | EvalResult LHSResult; // meaningful only for binary operator expression. | ||||||
10796 | enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; | ||||||
10797 | |||||||
10798 | Job() = default; | ||||||
10799 | Job(Job &&) = default; | ||||||
10800 | |||||||
10801 | void startSpeculativeEval(EvalInfo &Info) { | ||||||
10802 | SpecEvalRAII = SpeculativeEvaluationRAII(Info); | ||||||
10803 | } | ||||||
10804 | |||||||
10805 | private: | ||||||
10806 | SpeculativeEvaluationRAII SpecEvalRAII; | ||||||
10807 | }; | ||||||
10808 | |||||||
10809 | SmallVector<Job, 16> Queue; | ||||||
10810 | |||||||
10811 | IntExprEvaluator &IntEval; | ||||||
10812 | EvalInfo &Info; | ||||||
10813 | APValue &FinalResult; | ||||||
10814 | |||||||
10815 | public: | ||||||
10816 | DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) | ||||||
10817 | : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } | ||||||
10818 | |||||||
10819 | /// True if \param E is a binary operator that we are going to handle | ||||||
10820 | /// data recursively. | ||||||
10821 | /// We handle binary operators that are comma, logical, or that have operands | ||||||
10822 | /// with integral or enumeration type. | ||||||
10823 | static bool shouldEnqueue(const BinaryOperator *E) { | ||||||
10824 | return E->getOpcode() == BO_Comma || E->isLogicalOp() || | ||||||
10825 | (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && | ||||||
10826 | E->getLHS()->getType()->isIntegralOrEnumerationType() && | ||||||
10827 | E->getRHS()->getType()->isIntegralOrEnumerationType()); | ||||||
10828 | } | ||||||
10829 | |||||||
10830 | bool Traverse(const BinaryOperator *E) { | ||||||
10831 | enqueue(E); | ||||||
10832 | EvalResult PrevResult; | ||||||
10833 | while (!Queue.empty()) | ||||||
10834 | process(PrevResult); | ||||||
10835 | |||||||
10836 | if (PrevResult.Failed) return false; | ||||||
10837 | |||||||
10838 | FinalResult.swap(PrevResult.Val); | ||||||
10839 | return true; | ||||||
10840 | } | ||||||
10841 | |||||||
10842 | private: | ||||||
10843 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { | ||||||
10844 | return IntEval.Success(Value, E, Result); | ||||||
10845 | } | ||||||
10846 | bool Success(const APSInt &Value, const Expr *E, APValue &Result) { | ||||||
10847 | return IntEval.Success(Value, E, Result); | ||||||
10848 | } | ||||||
10849 | bool Error(const Expr *E) { | ||||||
10850 | return IntEval.Error(E); | ||||||
10851 | } | ||||||
10852 | bool Error(const Expr *E, diag::kind D) { | ||||||
10853 | return IntEval.Error(E, D); | ||||||
10854 | } | ||||||
10855 | |||||||
10856 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { | ||||||
10857 | return Info.CCEDiag(E, D); | ||||||
10858 | } | ||||||
10859 | |||||||
10860 | // Returns true if visiting the RHS is necessary, false otherwise. | ||||||
10861 | bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, | ||||||
10862 | bool &SuppressRHSDiags); | ||||||
10863 | |||||||
10864 | bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, | ||||||
10865 | const BinaryOperator *E, APValue &Result); | ||||||
10866 | |||||||
10867 | void EvaluateExpr(const Expr *E, EvalResult &Result) { | ||||||
10868 | Result.Failed = !Evaluate(Result.Val, Info, E); | ||||||
10869 | if (Result.Failed) | ||||||
10870 | Result.Val = APValue(); | ||||||
10871 | } | ||||||
10872 | |||||||
10873 | void process(EvalResult &Result); | ||||||
10874 | |||||||
10875 | void enqueue(const Expr *E) { | ||||||
10876 | E = E->IgnoreParens(); | ||||||
10877 | Queue.resize(Queue.size()+1); | ||||||
10878 | Queue.back().E = E; | ||||||
10879 | Queue.back().Kind = Job::AnyExprKind; | ||||||
10880 | } | ||||||
10881 | }; | ||||||
10882 | |||||||
10883 | } | ||||||
10884 | |||||||
10885 | bool DataRecursiveIntBinOpEvaluator:: | ||||||
10886 | VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, | ||||||
10887 | bool &SuppressRHSDiags) { | ||||||
10888 | if (E->getOpcode() == BO_Comma) { | ||||||
10889 | // Ignore LHS but note if we could not evaluate it. | ||||||
10890 | if (LHSResult.Failed) | ||||||
10891 | return Info.noteSideEffect(); | ||||||
10892 | return true; | ||||||
10893 | } | ||||||
10894 | |||||||
10895 | if (E->isLogicalOp()) { | ||||||
10896 | bool LHSAsBool; | ||||||
10897 | if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { | ||||||
10898 | // We were able to evaluate the LHS, see if we can get away with not | ||||||
10899 | // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 | ||||||
10900 | if (LHSAsBool == (E->getOpcode() == BO_LOr)) { | ||||||
10901 | Success(LHSAsBool, E, LHSResult.Val); | ||||||
10902 | return false; // Ignore RHS | ||||||
10903 | } | ||||||
10904 | } else { | ||||||
10905 | LHSResult.Failed = true; | ||||||
10906 | |||||||
10907 | // Since we weren't able to evaluate the left hand side, it | ||||||
10908 | // might have had side effects. | ||||||
10909 | if (!Info.noteSideEffect()) | ||||||
10910 | return false; | ||||||
10911 | |||||||
10912 | // We can't evaluate the LHS; however, sometimes the result | ||||||
10913 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. | ||||||
10914 | // Don't ignore RHS and suppress diagnostics from this arm. | ||||||
10915 | SuppressRHSDiags = true; | ||||||
10916 | } | ||||||
10917 | |||||||
10918 | return true; | ||||||
10919 | } | ||||||
10920 | |||||||
10921 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&((E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10922, __PRETTY_FUNCTION__)) | ||||||
10922 | E->getRHS()->getType()->isIntegralOrEnumerationType())((E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10922, __PRETTY_FUNCTION__)); | ||||||
10923 | |||||||
10924 | if (LHSResult.Failed && !Info.noteFailure()) | ||||||
10925 | return false; // Ignore RHS; | ||||||
10926 | |||||||
10927 | return true; | ||||||
10928 | } | ||||||
10929 | |||||||
10930 | static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, | ||||||
10931 | bool IsSub) { | ||||||
10932 | // Compute the new offset in the appropriate width, wrapping at 64 bits. | ||||||
10933 | // FIXME: When compiling for a 32-bit target, we should use 32-bit | ||||||
10934 | // offsets. | ||||||
10935 | assert(!LVal.hasLValuePath() && "have designator for integer lvalue")((!LVal.hasLValuePath() && "have designator for integer lvalue" ) ? static_cast<void> (0) : __assert_fail ("!LVal.hasLValuePath() && \"have designator for integer lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10935, __PRETTY_FUNCTION__)); | ||||||
10936 | CharUnits &Offset = LVal.getLValueOffset(); | ||||||
10937 | uint64_t Offset64 = Offset.getQuantity(); | ||||||
10938 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); | ||||||
10939 | Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 | ||||||
10940 | : Offset64 + Index64); | ||||||
10941 | } | ||||||
10942 | |||||||
10943 | bool DataRecursiveIntBinOpEvaluator:: | ||||||
10944 | VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, | ||||||
10945 | const BinaryOperator *E, APValue &Result) { | ||||||
10946 | if (E->getOpcode() == BO_Comma) { | ||||||
10947 | if (RHSResult.Failed) | ||||||
10948 | return false; | ||||||
10949 | Result = RHSResult.Val; | ||||||
10950 | return true; | ||||||
10951 | } | ||||||
10952 | |||||||
10953 | if (E->isLogicalOp()) { | ||||||
10954 | bool lhsResult, rhsResult; | ||||||
10955 | bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); | ||||||
10956 | bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); | ||||||
10957 | |||||||
10958 | if (LHSIsOK) { | ||||||
10959 | if (RHSIsOK) { | ||||||
10960 | if (E->getOpcode() == BO_LOr) | ||||||
10961 | return Success(lhsResult || rhsResult, E, Result); | ||||||
10962 | else | ||||||
10963 | return Success(lhsResult && rhsResult, E, Result); | ||||||
10964 | } | ||||||
10965 | } else { | ||||||
10966 | if (RHSIsOK) { | ||||||
10967 | // We can't evaluate the LHS; however, sometimes the result | ||||||
10968 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. | ||||||
10969 | if (rhsResult == (E->getOpcode() == BO_LOr)) | ||||||
10970 | return Success(rhsResult, E, Result); | ||||||
10971 | } | ||||||
10972 | } | ||||||
10973 | |||||||
10974 | return false; | ||||||
10975 | } | ||||||
10976 | |||||||
10977 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&((E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10978, __PRETTY_FUNCTION__)) | ||||||
10978 | E->getRHS()->getType()->isIntegralOrEnumerationType())((E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10978, __PRETTY_FUNCTION__)); | ||||||
10979 | |||||||
10980 | if (LHSResult.Failed || RHSResult.Failed) | ||||||
10981 | return false; | ||||||
10982 | |||||||
10983 | const APValue &LHSVal = LHSResult.Val; | ||||||
10984 | const APValue &RHSVal = RHSResult.Val; | ||||||
10985 | |||||||
10986 | // Handle cases like (unsigned long)&a + 4. | ||||||
10987 | if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { | ||||||
10988 | Result = LHSVal; | ||||||
10989 | addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); | ||||||
10990 | return true; | ||||||
10991 | } | ||||||
10992 | |||||||
10993 | // Handle cases like 4 + (unsigned long)&a | ||||||
10994 | if (E->getOpcode() == BO_Add && | ||||||
10995 | RHSVal.isLValue() && LHSVal.isInt()) { | ||||||
10996 | Result = RHSVal; | ||||||
10997 | addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); | ||||||
10998 | return true; | ||||||
10999 | } | ||||||
11000 | |||||||
11001 | if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { | ||||||
11002 | // Handle (intptr_t)&&A - (intptr_t)&&B. | ||||||
11003 | if (!LHSVal.getLValueOffset().isZero() || | ||||||
11004 | !RHSVal.getLValueOffset().isZero()) | ||||||
11005 | return false; | ||||||
11006 | const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); | ||||||
11007 | const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); | ||||||
11008 | if (!LHSExpr || !RHSExpr) | ||||||
11009 | return false; | ||||||
11010 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); | ||||||
11011 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); | ||||||
11012 | if (!LHSAddrExpr || !RHSAddrExpr) | ||||||
11013 | return false; | ||||||
11014 | // Make sure both labels come from the same function. | ||||||
11015 | if (LHSAddrExpr->getLabel()->getDeclContext() != | ||||||
11016 | RHSAddrExpr->getLabel()->getDeclContext()) | ||||||
11017 | return false; | ||||||
11018 | Result = APValue(LHSAddrExpr, RHSAddrExpr); | ||||||
11019 | return true; | ||||||
11020 | } | ||||||
11021 | |||||||
11022 | // All the remaining cases expect both operands to be an integer | ||||||
11023 | if (!LHSVal.isInt() || !RHSVal.isInt()) | ||||||
11024 | return Error(E); | ||||||
11025 | |||||||
11026 | // Set up the width and signedness manually, in case it can't be deduced | ||||||
11027 | // from the operation we're performing. | ||||||
11028 | // FIXME: Don't do this in the cases where we can deduce it. | ||||||
11029 | APSInt Value(Info.Ctx.getIntWidth(E->getType()), | ||||||
11030 | E->getType()->isUnsignedIntegerOrEnumerationType()); | ||||||
11031 | if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), | ||||||
11032 | RHSVal.getInt(), Value)) | ||||||
11033 | return false; | ||||||
11034 | return Success(Value, E, Result); | ||||||
11035 | } | ||||||
11036 | |||||||
11037 | void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { | ||||||
11038 | Job &job = Queue.back(); | ||||||
11039 | |||||||
11040 | switch (job.Kind) { | ||||||
11041 | case Job::AnyExprKind: { | ||||||
11042 | if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { | ||||||
11043 | if (shouldEnqueue(Bop)) { | ||||||
11044 | job.Kind = Job::BinOpKind; | ||||||
11045 | enqueue(Bop->getLHS()); | ||||||
11046 | return; | ||||||
11047 | } | ||||||
11048 | } | ||||||
11049 | |||||||
11050 | EvaluateExpr(job.E, Result); | ||||||
11051 | Queue.pop_back(); | ||||||
11052 | return; | ||||||
11053 | } | ||||||
11054 | |||||||
11055 | case Job::BinOpKind: { | ||||||
11056 | const BinaryOperator *Bop = cast<BinaryOperator>(job.E); | ||||||
11057 | bool SuppressRHSDiags = false; | ||||||
11058 | if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { | ||||||
11059 | Queue.pop_back(); | ||||||
11060 | return; | ||||||
11061 | } | ||||||
11062 | if (SuppressRHSDiags) | ||||||
11063 | job.startSpeculativeEval(Info); | ||||||
11064 | job.LHSResult.swap(Result); | ||||||
11065 | job.Kind = Job::BinOpVisitedLHSKind; | ||||||
11066 | enqueue(Bop->getRHS()); | ||||||
11067 | return; | ||||||
11068 | } | ||||||
11069 | |||||||
11070 | case Job::BinOpVisitedLHSKind: { | ||||||
11071 | const BinaryOperator *Bop = cast<BinaryOperator>(job.E); | ||||||
11072 | EvalResult RHS; | ||||||
11073 | RHS.swap(Result); | ||||||
11074 | Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); | ||||||
11075 | Queue.pop_back(); | ||||||
11076 | return; | ||||||
11077 | } | ||||||
11078 | } | ||||||
11079 | |||||||
11080 | llvm_unreachable("Invalid Job::Kind!")::llvm::llvm_unreachable_internal("Invalid Job::Kind!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11080); | ||||||
11081 | } | ||||||
11082 | |||||||
11083 | namespace { | ||||||
11084 | /// Used when we determine that we should fail, but can keep evaluating prior to | ||||||
11085 | /// noting that we had a failure. | ||||||
11086 | class DelayedNoteFailureRAII { | ||||||
11087 | EvalInfo &Info; | ||||||
11088 | bool NoteFailure; | ||||||
11089 | |||||||
11090 | public: | ||||||
11091 | DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) | ||||||
11092 | : Info(Info), NoteFailure(NoteFailure) {} | ||||||
11093 | ~DelayedNoteFailureRAII() { | ||||||
11094 | if (NoteFailure) { | ||||||
11095 | bool ContinueAfterFailure = Info.noteFailure(); | ||||||
11096 | (void)ContinueAfterFailure; | ||||||
11097 | assert(ContinueAfterFailure &&((ContinueAfterFailure && "Shouldn't have kept evaluating on failure." ) ? static_cast<void> (0) : __assert_fail ("ContinueAfterFailure && \"Shouldn't have kept evaluating on failure.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11098, __PRETTY_FUNCTION__)) | ||||||
11098 | "Shouldn't have kept evaluating on failure.")((ContinueAfterFailure && "Shouldn't have kept evaluating on failure." ) ? static_cast<void> (0) : __assert_fail ("ContinueAfterFailure && \"Shouldn't have kept evaluating on failure.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11098, __PRETTY_FUNCTION__)); | ||||||
11099 | } | ||||||
11100 | } | ||||||
11101 | }; | ||||||
11102 | } | ||||||
11103 | |||||||
11104 | template <class SuccessCB, class AfterCB> | ||||||
11105 | static bool | ||||||
11106 | EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, | ||||||
11107 | SuccessCB &&Success, AfterCB &&DoAfter) { | ||||||
11108 | assert(E->isComparisonOp() && "expected comparison operator")((E->isComparisonOp() && "expected comparison operator" ) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"expected comparison operator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11108, __PRETTY_FUNCTION__)); | ||||||
11109 | assert((E->getOpcode() == BO_Cmp ||(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType ()) && "unsupported binary expression evaluation") ? static_cast <void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11111, __PRETTY_FUNCTION__)) | ||||||
11110 | E->getType()->isIntegralOrEnumerationType()) &&(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType ()) && "unsupported binary expression evaluation") ? static_cast <void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11111, __PRETTY_FUNCTION__)) | ||||||
11111 | "unsupported binary expression evaluation")(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType ()) && "unsupported binary expression evaluation") ? static_cast <void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11111, __PRETTY_FUNCTION__)); | ||||||
11112 | auto Error = [&](const Expr *E) { | ||||||
11113 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
11114 | return false; | ||||||
11115 | }; | ||||||
11116 | |||||||
11117 | using CCR = ComparisonCategoryResult; | ||||||
11118 | bool IsRelational = E->isRelationalOp(); | ||||||
11119 | bool IsEquality = E->isEqualityOp(); | ||||||
11120 | if (E->getOpcode() == BO_Cmp) { | ||||||
11121 | const ComparisonCategoryInfo &CmpInfo = | ||||||
11122 | Info.Ctx.CompCategories.getInfoForType(E->getType()); | ||||||
11123 | IsRelational = CmpInfo.isOrdered(); | ||||||
11124 | IsEquality = CmpInfo.isEquality(); | ||||||
11125 | } | ||||||
11126 | |||||||
11127 | QualType LHSTy = E->getLHS()->getType(); | ||||||
11128 | QualType RHSTy = E->getRHS()->getType(); | ||||||
11129 | |||||||
11130 | if (LHSTy->isIntegralOrEnumerationType() && | ||||||
11131 | RHSTy->isIntegralOrEnumerationType()) { | ||||||
11132 | APSInt LHS, RHS; | ||||||
11133 | bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); | ||||||
11134 | if (!LHSOK && !Info.noteFailure()) | ||||||
11135 | return false; | ||||||
11136 | if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) | ||||||
11137 | return false; | ||||||
11138 | if (LHS < RHS) | ||||||
11139 | return Success(CCR::Less, E); | ||||||
11140 | if (LHS > RHS) | ||||||
11141 | return Success(CCR::Greater, E); | ||||||
11142 | return Success(CCR::Equal, E); | ||||||
11143 | } | ||||||
11144 | |||||||
11145 | if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { | ||||||
11146 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); | ||||||
11147 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); | ||||||
11148 | |||||||
11149 | bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); | ||||||
11150 | if (!LHSOK && !Info.noteFailure()) | ||||||
11151 | return false; | ||||||
11152 | if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) | ||||||
11153 | return false; | ||||||
11154 | if (LHSFX < RHSFX) | ||||||
11155 | return Success(CCR::Less, E); | ||||||
11156 | if (LHSFX > RHSFX) | ||||||
11157 | return Success(CCR::Greater, E); | ||||||
11158 | return Success(CCR::Equal, E); | ||||||
11159 | } | ||||||
11160 | |||||||
11161 | if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { | ||||||
11162 | ComplexValue LHS, RHS; | ||||||
11163 | bool LHSOK; | ||||||
11164 | if (E->isAssignmentOp()) { | ||||||
11165 | LValue LV; | ||||||
11166 | EvaluateLValue(E->getLHS(), LV, Info); | ||||||
11167 | LHSOK = false; | ||||||
11168 | } else if (LHSTy->isRealFloatingType()) { | ||||||
11169 | LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); | ||||||
11170 | if (LHSOK) { | ||||||
11171 | LHS.makeComplexFloat(); | ||||||
11172 | LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); | ||||||
11173 | } | ||||||
11174 | } else { | ||||||
11175 | LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); | ||||||
11176 | } | ||||||
11177 | if (!LHSOK && !Info.noteFailure()) | ||||||
11178 | return false; | ||||||
11179 | |||||||
11180 | if (E->getRHS()->getType()->isRealFloatingType()) { | ||||||
11181 | if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) | ||||||
11182 | return false; | ||||||
11183 | RHS.makeComplexFloat(); | ||||||
11184 | RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); | ||||||
11185 | } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) | ||||||
11186 | return false; | ||||||
11187 | |||||||
11188 | if (LHS.isComplexFloat()) { | ||||||
11189 | APFloat::cmpResult CR_r = | ||||||
11190 | LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); | ||||||
11191 | APFloat::cmpResult CR_i = | ||||||
11192 | LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); | ||||||
11193 | bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; | ||||||
11194 | return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); | ||||||
11195 | } else { | ||||||
11196 | assert(IsEquality && "invalid complex comparison")((IsEquality && "invalid complex comparison") ? static_cast <void> (0) : __assert_fail ("IsEquality && \"invalid complex comparison\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11196, __PRETTY_FUNCTION__)); | ||||||
11197 | bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && | ||||||
11198 | LHS.getComplexIntImag() == RHS.getComplexIntImag(); | ||||||
11199 | return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); | ||||||
11200 | } | ||||||
11201 | } | ||||||
11202 | |||||||
11203 | if (LHSTy->isRealFloatingType() && | ||||||
11204 | RHSTy->isRealFloatingType()) { | ||||||
11205 | APFloat RHS(0.0), LHS(0.0); | ||||||
11206 | |||||||
11207 | bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); | ||||||
11208 | if (!LHSOK && !Info.noteFailure()) | ||||||
11209 | return false; | ||||||
11210 | |||||||
11211 | if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) | ||||||
11212 | return false; | ||||||
11213 | |||||||
11214 | assert(E->isComparisonOp() && "Invalid binary operator!")((E->isComparisonOp() && "Invalid binary operator!" ) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"Invalid binary operator!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11214, __PRETTY_FUNCTION__)); | ||||||
11215 | auto GetCmpRes = [&]() { | ||||||
11216 | switch (LHS.compare(RHS)) { | ||||||
11217 | case APFloat::cmpEqual: | ||||||
11218 | return CCR::Equal; | ||||||
11219 | case APFloat::cmpLessThan: | ||||||
11220 | return CCR::Less; | ||||||
11221 | case APFloat::cmpGreaterThan: | ||||||
11222 | return CCR::Greater; | ||||||
11223 | case APFloat::cmpUnordered: | ||||||
11224 | return CCR::Unordered; | ||||||
11225 | } | ||||||
11226 | llvm_unreachable("Unrecognised APFloat::cmpResult enum")::llvm::llvm_unreachable_internal("Unrecognised APFloat::cmpResult enum" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11226); | ||||||
11227 | }; | ||||||
11228 | return Success(GetCmpRes(), E); | ||||||
11229 | } | ||||||
11230 | |||||||
11231 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) { | ||||||
11232 | LValue LHSValue, RHSValue; | ||||||
11233 | |||||||
11234 | bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); | ||||||
11235 | if (!LHSOK && !Info.noteFailure()) | ||||||
11236 | return false; | ||||||
11237 | |||||||
11238 | if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) | ||||||
11239 | return false; | ||||||
11240 | |||||||
11241 | // Reject differing bases from the normal codepath; we special-case | ||||||
11242 | // comparisons to null. | ||||||
11243 | if (!HasSameBase(LHSValue, RHSValue)) { | ||||||
11244 | // Inequalities and subtractions between unrelated pointers have | ||||||
11245 | // unspecified or undefined behavior. | ||||||
11246 | if (!IsEquality) | ||||||
11247 | return Error(E); | ||||||
11248 | // A constant address may compare equal to the address of a symbol. | ||||||
11249 | // The one exception is that address of an object cannot compare equal | ||||||
11250 | // to a null pointer constant. | ||||||
11251 | if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || | ||||||
11252 | (!RHSValue.Base && !RHSValue.Offset.isZero())) | ||||||
11253 | return Error(E); | ||||||
11254 | // It's implementation-defined whether distinct literals will have | ||||||
11255 | // distinct addresses. In clang, the result of such a comparison is | ||||||
11256 | // unspecified, so it is not a constant expression. However, we do know | ||||||
11257 | // that the address of a literal will be non-null. | ||||||
11258 | if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && | ||||||
11259 | LHSValue.Base && RHSValue.Base) | ||||||
11260 | return Error(E); | ||||||
11261 | // We can't tell whether weak symbols will end up pointing to the same | ||||||
11262 | // object. | ||||||
11263 | if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) | ||||||
11264 | return Error(E); | ||||||
11265 | // We can't compare the address of the start of one object with the | ||||||
11266 | // past-the-end address of another object, per C++ DR1652. | ||||||
11267 | if ((LHSValue.Base && LHSValue.Offset.isZero() && | ||||||
11268 | isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || | ||||||
11269 | (RHSValue.Base && RHSValue.Offset.isZero() && | ||||||
11270 | isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) | ||||||
11271 | return Error(E); | ||||||
11272 | // We can't tell whether an object is at the same address as another | ||||||
11273 | // zero sized object. | ||||||
11274 | if ((RHSValue.Base && isZeroSized(LHSValue)) || | ||||||
11275 | (LHSValue.Base && isZeroSized(RHSValue))) | ||||||
11276 | return Error(E); | ||||||
11277 | return Success(CCR::Nonequal, E); | ||||||
11278 | } | ||||||
11279 | |||||||
11280 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); | ||||||
11281 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); | ||||||
11282 | |||||||
11283 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); | ||||||
11284 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); | ||||||
11285 | |||||||
11286 | // C++11 [expr.rel]p3: | ||||||
11287 | // Pointers to void (after pointer conversions) can be compared, with a | ||||||
11288 | // result defined as follows: If both pointers represent the same | ||||||
11289 | // address or are both the null pointer value, the result is true if the | ||||||
11290 | // operator is <= or >= and false otherwise; otherwise the result is | ||||||
11291 | // unspecified. | ||||||
11292 | // We interpret this as applying to pointers to *cv* void. | ||||||
11293 | if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) | ||||||
11294 | Info.CCEDiag(E, diag::note_constexpr_void_comparison); | ||||||
11295 | |||||||
11296 | // C++11 [expr.rel]p2: | ||||||
11297 | // - If two pointers point to non-static data members of the same object, | ||||||
11298 | // or to subobjects or array elements fo such members, recursively, the | ||||||
11299 | // pointer to the later declared member compares greater provided the | ||||||
11300 | // two members have the same access control and provided their class is | ||||||
11301 | // not a union. | ||||||
11302 | // [...] | ||||||
11303 | // - Otherwise pointer comparisons are unspecified. | ||||||
11304 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { | ||||||
11305 | bool WasArrayIndex; | ||||||
11306 | unsigned Mismatch = FindDesignatorMismatch( | ||||||
11307 | getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); | ||||||
11308 | // At the point where the designators diverge, the comparison has a | ||||||
11309 | // specified value if: | ||||||
11310 | // - we are comparing array indices | ||||||
11311 | // - we are comparing fields of a union, or fields with the same access | ||||||
11312 | // Otherwise, the result is unspecified and thus the comparison is not a | ||||||
11313 | // constant expression. | ||||||
11314 | if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && | ||||||
11315 | Mismatch < RHSDesignator.Entries.size()) { | ||||||
11316 | const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); | ||||||
11317 | const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); | ||||||
11318 | if (!LF && !RF) | ||||||
11319 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); | ||||||
11320 | else if (!LF) | ||||||
11321 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) | ||||||
11322 | << getAsBaseClass(LHSDesignator.Entries[Mismatch]) | ||||||
11323 | << RF->getParent() << RF; | ||||||
11324 | else if (!RF) | ||||||
11325 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) | ||||||
11326 | << getAsBaseClass(RHSDesignator.Entries[Mismatch]) | ||||||
11327 | << LF->getParent() << LF; | ||||||
11328 | else if (!LF->getParent()->isUnion() && | ||||||
11329 | LF->getAccess() != RF->getAccess()) | ||||||
11330 | Info.CCEDiag(E, | ||||||
11331 | diag::note_constexpr_pointer_comparison_differing_access) | ||||||
11332 | << LF << LF->getAccess() << RF << RF->getAccess() | ||||||
11333 | << LF->getParent(); | ||||||
11334 | } | ||||||
11335 | } | ||||||
11336 | |||||||
11337 | // The comparison here must be unsigned, and performed with the same | ||||||
11338 | // width as the pointer. | ||||||
11339 | unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); | ||||||
11340 | uint64_t CompareLHS = LHSOffset.getQuantity(); | ||||||
11341 | uint64_t CompareRHS = RHSOffset.getQuantity(); | ||||||
11342 | assert(PtrSize <= 64 && "Unexpected pointer width")((PtrSize <= 64 && "Unexpected pointer width") ? static_cast <void> (0) : __assert_fail ("PtrSize <= 64 && \"Unexpected pointer width\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11342, __PRETTY_FUNCTION__)); | ||||||
11343 | uint64_t Mask = ~0ULL >> (64 - PtrSize); | ||||||
11344 | CompareLHS &= Mask; | ||||||
11345 | CompareRHS &= Mask; | ||||||
11346 | |||||||
11347 | // If there is a base and this is a relational operator, we can only | ||||||
11348 | // compare pointers within the object in question; otherwise, the result | ||||||
11349 | // depends on where the object is located in memory. | ||||||
11350 | if (!LHSValue.Base.isNull() && IsRelational) { | ||||||
11351 | QualType BaseTy = getType(LHSValue.Base); | ||||||
11352 | if (BaseTy->isIncompleteType()) | ||||||
11353 | return Error(E); | ||||||
11354 | CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); | ||||||
11355 | uint64_t OffsetLimit = Size.getQuantity(); | ||||||
11356 | if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) | ||||||
11357 | return Error(E); | ||||||
11358 | } | ||||||
11359 | |||||||
11360 | if (CompareLHS < CompareRHS) | ||||||
11361 | return Success(CCR::Less, E); | ||||||
11362 | if (CompareLHS > CompareRHS) | ||||||
11363 | return Success(CCR::Greater, E); | ||||||
11364 | return Success(CCR::Equal, E); | ||||||
11365 | } | ||||||
11366 | |||||||
11367 | if (LHSTy->isMemberPointerType()) { | ||||||
11368 | assert(IsEquality && "unexpected member pointer operation")((IsEquality && "unexpected member pointer operation" ) ? static_cast<void> (0) : __assert_fail ("IsEquality && \"unexpected member pointer operation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11368, __PRETTY_FUNCTION__)); | ||||||
11369 | assert(RHSTy->isMemberPointerType() && "invalid comparison")((RHSTy->isMemberPointerType() && "invalid comparison" ) ? static_cast<void> (0) : __assert_fail ("RHSTy->isMemberPointerType() && \"invalid comparison\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11369, __PRETTY_FUNCTION__)); | ||||||
11370 | |||||||
11371 | MemberPtr LHSValue, RHSValue; | ||||||
11372 | |||||||
11373 | bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); | ||||||
11374 | if (!LHSOK && !Info.noteFailure()) | ||||||
11375 | return false; | ||||||
11376 | |||||||
11377 | if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) | ||||||
11378 | return false; | ||||||
11379 | |||||||
11380 | // C++11 [expr.eq]p2: | ||||||
11381 | // If both operands are null, they compare equal. Otherwise if only one is | ||||||
11382 | // null, they compare unequal. | ||||||
11383 | if (!LHSValue.getDecl() || !RHSValue.getDecl()) { | ||||||
11384 | bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); | ||||||
11385 | return Success(Equal ? CCR::Equal : CCR::Nonequal, E); | ||||||
11386 | } | ||||||
11387 | |||||||
11388 | // Otherwise if either is a pointer to a virtual member function, the | ||||||
11389 | // result is unspecified. | ||||||
11390 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) | ||||||
11391 | if (MD->isVirtual()) | ||||||
11392 | Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; | ||||||
11393 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) | ||||||
11394 | if (MD->isVirtual()) | ||||||
11395 | Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; | ||||||
11396 | |||||||
11397 | // Otherwise they compare equal if and only if they would refer to the | ||||||
11398 | // same member of the same most derived object or the same subobject if | ||||||
11399 | // they were dereferenced with a hypothetical object of the associated | ||||||
11400 | // class type. | ||||||
11401 | bool Equal = LHSValue == RHSValue; | ||||||
11402 | return Success(Equal ? CCR::Equal : CCR::Nonequal, E); | ||||||
11403 | } | ||||||
11404 | |||||||
11405 | if (LHSTy->isNullPtrType()) { | ||||||
11406 | assert(E->isComparisonOp() && "unexpected nullptr operation")((E->isComparisonOp() && "unexpected nullptr operation" ) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"unexpected nullptr operation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11406, __PRETTY_FUNCTION__)); | ||||||
11407 | assert(RHSTy->isNullPtrType() && "missing pointer conversion")((RHSTy->isNullPtrType() && "missing pointer conversion" ) ? static_cast<void> (0) : __assert_fail ("RHSTy->isNullPtrType() && \"missing pointer conversion\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11407, __PRETTY_FUNCTION__)); | ||||||
11408 | // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t | ||||||
11409 | // are compared, the result is true of the operator is <=, >= or ==, and | ||||||
11410 | // false otherwise. | ||||||
11411 | return Success(CCR::Equal, E); | ||||||
11412 | } | ||||||
11413 | |||||||
11414 | return DoAfter(); | ||||||
11415 | } | ||||||
11416 | |||||||
11417 | bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { | ||||||
11418 | if (!CheckLiteralType(Info, E)) | ||||||
11419 | return false; | ||||||
11420 | |||||||
11421 | auto OnSuccess = [&](ComparisonCategoryResult ResKind, | ||||||
11422 | const BinaryOperator *E) { | ||||||
11423 | // Evaluation succeeded. Lookup the information for the comparison category | ||||||
11424 | // type and fetch the VarDecl for the result. | ||||||
11425 | const ComparisonCategoryInfo &CmpInfo = | ||||||
11426 | Info.Ctx.CompCategories.getInfoForType(E->getType()); | ||||||
11427 | const VarDecl *VD = | ||||||
11428 | CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; | ||||||
11429 | // Check and evaluate the result as a constant expression. | ||||||
11430 | LValue LV; | ||||||
11431 | LV.set(VD); | ||||||
11432 | if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) | ||||||
11433 | return false; | ||||||
11434 | return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); | ||||||
11435 | }; | ||||||
11436 | return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { | ||||||
11437 | return ExprEvaluatorBaseTy::VisitBinCmp(E); | ||||||
11438 | }); | ||||||
11439 | } | ||||||
11440 | |||||||
11441 | bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||||
11442 | // We don't call noteFailure immediately because the assignment happens after | ||||||
11443 | // we evaluate LHS and RHS. | ||||||
11444 | if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) | ||||||
| |||||||
11445 | return Error(E); | ||||||
11446 | |||||||
11447 | DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); | ||||||
11448 | if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) | ||||||
11449 | return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); | ||||||
11450 | |||||||
11451 | assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||(((!E->getLHS()->getType()->isIntegralOrEnumerationType () || !E->getRHS()->getType()->isIntegralOrEnumerationType ()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11453, __PRETTY_FUNCTION__)) | ||||||
11452 | !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&(((!E->getLHS()->getType()->isIntegralOrEnumerationType () || !E->getRHS()->getType()->isIntegralOrEnumerationType ()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11453, __PRETTY_FUNCTION__)) | ||||||
11453 | "DataRecursiveIntBinOpEvaluator should have handled integral types")(((!E->getLHS()->getType()->isIntegralOrEnumerationType () || !E->getRHS()->getType()->isIntegralOrEnumerationType ()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11453, __PRETTY_FUNCTION__)); | ||||||
11454 | |||||||
11455 | if (E->isComparisonOp()) { | ||||||
11456 | // Evaluate builtin binary comparisons by evaluating them as C++2a three-way | ||||||
11457 | // comparisons and then translating the result. | ||||||
11458 | auto OnSuccess = [&](ComparisonCategoryResult ResKind, | ||||||
11459 | const BinaryOperator *E) { | ||||||
11460 | using CCR = ComparisonCategoryResult; | ||||||
11461 | bool IsEqual = ResKind == CCR::Equal, | ||||||
11462 | IsLess = ResKind == CCR::Less, | ||||||
11463 | IsGreater = ResKind == CCR::Greater; | ||||||
11464 | auto Op = E->getOpcode(); | ||||||
11465 | switch (Op) { | ||||||
11466 | default: | ||||||
11467 | llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11467); | ||||||
11468 | case BO_EQ: | ||||||
11469 | case BO_NE: | ||||||
11470 | return Success(IsEqual == (Op == BO_EQ), E); | ||||||
11471 | case BO_LT: return Success(IsLess, E); | ||||||
11472 | case BO_GT: return Success(IsGreater, E); | ||||||
11473 | case BO_LE: return Success(IsEqual || IsLess, E); | ||||||
11474 | case BO_GE: return Success(IsEqual || IsGreater, E); | ||||||
11475 | } | ||||||
11476 | }; | ||||||
11477 | return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { | ||||||
11478 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||||
11479 | }); | ||||||
11480 | } | ||||||
11481 | |||||||
11482 | QualType LHSTy = E->getLHS()->getType(); | ||||||
11483 | QualType RHSTy = E->getRHS()->getType(); | ||||||
11484 | |||||||
11485 | if (LHSTy->isPointerType() && RHSTy->isPointerType() && | ||||||
11486 | E->getOpcode() == BO_Sub) { | ||||||
11487 | LValue LHSValue, RHSValue; | ||||||
11488 | |||||||
11489 | bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); | ||||||
11490 | if (!LHSOK && !Info.noteFailure()) | ||||||
11491 | return false; | ||||||
11492 | |||||||
11493 | if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK
| ||||||
11494 | return false; | ||||||
11495 | |||||||
11496 | // Reject differing bases from the normal codepath; we special-case | ||||||
11497 | // comparisons to null. | ||||||
11498 | if (!HasSameBase(LHSValue, RHSValue)) { | ||||||
11499 | // Handle &&A - &&B. | ||||||
11500 | if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) | ||||||
11501 | return Error(E); | ||||||
11502 | const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); | ||||||
11503 | const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); | ||||||
11504 | if (!LHSExpr || !RHSExpr) | ||||||
11505 | return Error(E); | ||||||
11506 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); | ||||||
11507 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); | ||||||
11508 | if (!LHSAddrExpr || !RHSAddrExpr) | ||||||
11509 | return Error(E); | ||||||
11510 | // Make sure both labels come from the same function. | ||||||
11511 | if (LHSAddrExpr->getLabel()->getDeclContext() != | ||||||
11512 | RHSAddrExpr->getLabel()->getDeclContext()) | ||||||
11513 | return Error(E); | ||||||
11514 | return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); | ||||||
11515 | } | ||||||
11516 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); | ||||||
11517 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); | ||||||
11518 | |||||||
11519 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); | ||||||
11520 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); | ||||||
11521 | |||||||
11522 | // C++11 [expr.add]p6: | ||||||
11523 | // Unless both pointers point to elements of the same array object, or | ||||||
11524 | // one past the last element of the array object, the behavior is | ||||||
11525 | // undefined. | ||||||
11526 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && | ||||||
11527 | !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, | ||||||
11528 | RHSDesignator)) | ||||||
11529 | Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); | ||||||
11530 | |||||||
11531 | QualType Type = E->getLHS()->getType(); | ||||||
11532 | QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); | ||||||
| |||||||
11533 | |||||||
11534 | CharUnits ElementSize; | ||||||
11535 | if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) | ||||||
11536 | return false; | ||||||
11537 | |||||||
11538 | // As an extension, a type may have zero size (empty struct or union in | ||||||
11539 | // C, array of zero length). Pointer subtraction in such cases has | ||||||
11540 | // undefined behavior, so is not constant. | ||||||
11541 | if (ElementSize.isZero()) { | ||||||
11542 | Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) | ||||||
11543 | << ElementType; | ||||||
11544 | return false; | ||||||
11545 | } | ||||||
11546 | |||||||
11547 | // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, | ||||||
11548 | // and produce incorrect results when it overflows. Such behavior | ||||||
11549 | // appears to be non-conforming, but is common, so perhaps we should | ||||||
11550 | // assume the standard intended for such cases to be undefined behavior | ||||||
11551 | // and check for them. | ||||||
11552 | |||||||
11553 | // Compute (LHSOffset - RHSOffset) / Size carefully, checking for | ||||||
11554 | // overflow in the final conversion to ptrdiff_t. | ||||||
11555 | APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); | ||||||
11556 | APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); | ||||||
11557 | APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), | ||||||
11558 | false); | ||||||
11559 | APSInt TrueResult = (LHS - RHS) / ElemSize; | ||||||
11560 | APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); | ||||||
11561 | |||||||
11562 | if (Result.extend(65) != TrueResult && | ||||||
11563 | !HandleOverflow(Info, E, TrueResult, E->getType())) | ||||||
11564 | return false; | ||||||
11565 | return Success(Result, E); | ||||||
11566 | } | ||||||
11567 | |||||||
11568 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||||
11569 | } | ||||||
11570 | |||||||
11571 | /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with | ||||||
11572 | /// a result as the expression's type. | ||||||
11573 | bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( | ||||||
11574 | const UnaryExprOrTypeTraitExpr *E) { | ||||||
11575 | switch(E->getKind()) { | ||||||
11576 | case UETT_PreferredAlignOf: | ||||||
11577 | case UETT_AlignOf: { | ||||||
11578 | if (E->isArgumentType()) | ||||||
11579 | return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), | ||||||
11580 | E); | ||||||
11581 | else | ||||||
11582 | return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), | ||||||
11583 | E); | ||||||
11584 | } | ||||||
11585 | |||||||
11586 | case UETT_VecStep: { | ||||||
11587 | QualType Ty = E->getTypeOfArgument(); | ||||||
11588 | |||||||
11589 | if (Ty->isVectorType()) { | ||||||
11590 | unsigned n = Ty->castAs<VectorType>()->getNumElements(); | ||||||
11591 | |||||||
11592 | // The vec_step built-in functions that take a 3-component | ||||||
11593 | // vector return 4. (OpenCL 1.1 spec 6.11.12) | ||||||
11594 | if (n == 3) | ||||||
11595 | n = 4; | ||||||
11596 | |||||||
11597 | return Success(n, E); | ||||||
11598 | } else | ||||||
11599 | return Success(1, E); | ||||||
11600 | } | ||||||
11601 | |||||||
11602 | case UETT_SizeOf: { | ||||||
11603 | QualType SrcTy = E->getTypeOfArgument(); | ||||||
11604 | // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, | ||||||
11605 | // the result is the size of the referenced type." | ||||||
11606 | if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) | ||||||
11607 | SrcTy = Ref->getPointeeType(); | ||||||
11608 | |||||||
11609 | CharUnits Sizeof; | ||||||
11610 | if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) | ||||||
11611 | return false; | ||||||
11612 | return Success(Sizeof, E); | ||||||
11613 | } | ||||||
11614 | case UETT_OpenMPRequiredSimdAlign: | ||||||
11615 | assert(E->isArgumentType())((E->isArgumentType()) ? static_cast<void> (0) : __assert_fail ("E->isArgumentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11615, __PRETTY_FUNCTION__)); | ||||||
11616 | return Success( | ||||||
11617 | Info.Ctx.toCharUnitsFromBits( | ||||||
11618 | Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) | ||||||
11619 | .getQuantity(), | ||||||
11620 | E); | ||||||
11621 | } | ||||||
11622 | |||||||
11623 | llvm_unreachable("unknown expr/type trait")::llvm::llvm_unreachable_internal("unknown expr/type trait", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11623); | ||||||
11624 | } | ||||||
11625 | |||||||
11626 | bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { | ||||||
11627 | CharUnits Result; | ||||||
11628 | unsigned n = OOE->getNumComponents(); | ||||||
11629 | if (n == 0) | ||||||
11630 | return Error(OOE); | ||||||
11631 | QualType CurrentType = OOE->getTypeSourceInfo()->getType(); | ||||||
11632 | for (unsigned i = 0; i != n; ++i) { | ||||||
11633 | OffsetOfNode ON = OOE->getComponent(i); | ||||||
11634 | switch (ON.getKind()) { | ||||||
11635 | case OffsetOfNode::Array: { | ||||||
11636 | const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); | ||||||
11637 | APSInt IdxResult; | ||||||
11638 | if (!EvaluateInteger(Idx, IdxResult, Info)) | ||||||
11639 | return false; | ||||||
11640 | const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); | ||||||
11641 | if (!AT) | ||||||
11642 | return Error(OOE); | ||||||
11643 | CurrentType = AT->getElementType(); | ||||||
11644 | CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); | ||||||
11645 | Result += IdxResult.getSExtValue() * ElementSize; | ||||||
11646 | break; | ||||||
11647 | } | ||||||
11648 | |||||||
11649 | case OffsetOfNode::Field: { | ||||||
11650 | FieldDecl *MemberDecl = ON.getField(); | ||||||
11651 | const RecordType *RT = CurrentType->getAs<RecordType>(); | ||||||
11652 | if (!RT) | ||||||
11653 | return Error(OOE); | ||||||
11654 | RecordDecl *RD = RT->getDecl(); | ||||||
11655 | if (RD->isInvalidDecl()) return false; | ||||||
11656 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); | ||||||
11657 | unsigned i = MemberDecl->getFieldIndex(); | ||||||
11658 | assert(i < RL.getFieldCount() && "offsetof field in wrong type")((i < RL.getFieldCount() && "offsetof field in wrong type" ) ? static_cast<void> (0) : __assert_fail ("i < RL.getFieldCount() && \"offsetof field in wrong type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11658, __PRETTY_FUNCTION__)); | ||||||
11659 | Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); | ||||||
11660 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||||
11661 | break; | ||||||
11662 | } | ||||||
11663 | |||||||
11664 | case OffsetOfNode::Identifier: | ||||||
11665 | llvm_unreachable("dependent __builtin_offsetof")::llvm::llvm_unreachable_internal("dependent __builtin_offsetof" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11665); | ||||||
11666 | |||||||
11667 | case OffsetOfNode::Base: { | ||||||
11668 | CXXBaseSpecifier *BaseSpec = ON.getBase(); | ||||||
11669 | if (BaseSpec->isVirtual()) | ||||||
11670 | return Error(OOE); | ||||||
11671 | |||||||
11672 | // Find the layout of the class whose base we are looking into. | ||||||
11673 | const RecordType *RT = CurrentType->getAs<RecordType>(); | ||||||
11674 | if (!RT) | ||||||
11675 | return Error(OOE); | ||||||
11676 | RecordDecl *RD = RT->getDecl(); | ||||||
11677 | if (RD->isInvalidDecl()) return false; | ||||||
11678 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); | ||||||
11679 | |||||||
11680 | // Find the base class itself. | ||||||
11681 | CurrentType = BaseSpec->getType(); | ||||||
11682 | const RecordType *BaseRT = CurrentType->getAs<RecordType>(); | ||||||
11683 | if (!BaseRT) | ||||||
11684 | return Error(OOE); | ||||||
11685 | |||||||
11686 | // Add the offset to the base. | ||||||
11687 | Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); | ||||||
11688 | break; | ||||||
11689 | } | ||||||
11690 | } | ||||||
11691 | } | ||||||
11692 | return Success(Result, OOE); | ||||||
11693 | } | ||||||
11694 | |||||||
11695 | bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||||
11696 | switch (E->getOpcode()) { | ||||||
11697 | default: | ||||||
11698 | // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. | ||||||
11699 | // See C99 6.6p3. | ||||||
11700 | return Error(E); | ||||||
11701 | case UO_Extension: | ||||||
11702 | // FIXME: Should extension allow i-c-e extension expressions in its scope? | ||||||
11703 | // If so, we could clear the diagnostic ID. | ||||||
11704 | return Visit(E->getSubExpr()); | ||||||
11705 | case UO_Plus: | ||||||
11706 | // The result is just the value. | ||||||
11707 | return Visit(E->getSubExpr()); | ||||||
11708 | case UO_Minus: { | ||||||
11709 | if (!Visit(E->getSubExpr())) | ||||||
11710 | return false; | ||||||
11711 | if (!Result.isInt()) return Error(E); | ||||||
11712 | const APSInt &Value = Result.getInt(); | ||||||
11713 | if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && | ||||||
11714 | !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), | ||||||
11715 | E->getType())) | ||||||
11716 | return false; | ||||||
11717 | return Success(-Value, E); | ||||||
11718 | } | ||||||
11719 | case UO_Not: { | ||||||
11720 | if (!Visit(E->getSubExpr())) | ||||||
11721 | return false; | ||||||
11722 | if (!Result.isInt()) return Error(E); | ||||||
11723 | return Success(~Result.getInt(), E); | ||||||
11724 | } | ||||||
11725 | case UO_LNot: { | ||||||
11726 | bool bres; | ||||||
11727 | if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) | ||||||
11728 | return false; | ||||||
11729 | return Success(!bres, E); | ||||||
11730 | } | ||||||
11731 | } | ||||||
11732 | } | ||||||
11733 | |||||||
11734 | /// HandleCast - This is used to evaluate implicit or explicit casts where the | ||||||
11735 | /// result type is integer. | ||||||
11736 | bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||||
11737 | const Expr *SubExpr = E->getSubExpr(); | ||||||
11738 | QualType DestType = E->getType(); | ||||||
11739 | QualType SrcType = SubExpr->getType(); | ||||||
11740 | |||||||
11741 | switch (E->getCastKind()) { | ||||||
11742 | case CK_BaseToDerived: | ||||||
11743 | case CK_DerivedToBase: | ||||||
11744 | case CK_UncheckedDerivedToBase: | ||||||
11745 | case CK_Dynamic: | ||||||
11746 | case CK_ToUnion: | ||||||
11747 | case CK_ArrayToPointerDecay: | ||||||
11748 | case CK_FunctionToPointerDecay: | ||||||
11749 | case CK_NullToPointer: | ||||||
11750 | case CK_NullToMemberPointer: | ||||||
11751 | case CK_BaseToDerivedMemberPointer: | ||||||
11752 | case CK_DerivedToBaseMemberPointer: | ||||||
11753 | case CK_ReinterpretMemberPointer: | ||||||
11754 | case CK_ConstructorConversion: | ||||||
11755 | case CK_IntegralToPointer: | ||||||
11756 | case CK_ToVoid: | ||||||
11757 | case CK_VectorSplat: | ||||||
11758 | case CK_IntegralToFloating: | ||||||
11759 | case CK_FloatingCast: | ||||||
11760 | case CK_CPointerToObjCPointerCast: | ||||||
11761 | case CK_BlockPointerToObjCPointerCast: | ||||||
11762 | case CK_AnyPointerToBlockPointerCast: | ||||||
11763 | case CK_ObjCObjectLValueCast: | ||||||
11764 | case CK_FloatingRealToComplex: | ||||||
11765 | case CK_FloatingComplexToReal: | ||||||
11766 | case CK_FloatingComplexCast: | ||||||
11767 | case CK_FloatingComplexToIntegralComplex: | ||||||
11768 | case CK_IntegralRealToComplex: | ||||||
11769 | case CK_IntegralComplexCast: | ||||||
11770 | case CK_IntegralComplexToFloatingComplex: | ||||||
11771 | case CK_BuiltinFnToFnPtr: | ||||||
11772 | case CK_ZeroToOCLOpaqueType: | ||||||
11773 | case CK_NonAtomicToAtomic: | ||||||
11774 | case CK_AddressSpaceConversion: | ||||||
11775 | case CK_IntToOCLSampler: | ||||||
11776 | case CK_FixedPointCast: | ||||||
11777 | case CK_IntegralToFixedPoint: | ||||||
11778 | llvm_unreachable("invalid cast kind for integral value")::llvm::llvm_unreachable_internal("invalid cast kind for integral value" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11778); | ||||||
11779 | |||||||
11780 | case CK_BitCast: | ||||||
11781 | case CK_Dependent: | ||||||
11782 | case CK_LValueBitCast: | ||||||
11783 | case CK_ARCProduceObject: | ||||||
11784 | case CK_ARCConsumeObject: | ||||||
11785 | case CK_ARCReclaimReturnedObject: | ||||||
11786 | case CK_ARCExtendBlockObject: | ||||||
11787 | case CK_CopyAndAutoreleaseBlockObject: | ||||||
11788 | return Error(E); | ||||||
11789 | |||||||
11790 | case CK_UserDefinedConversion: | ||||||
11791 | case CK_LValueToRValue: | ||||||
11792 | case CK_AtomicToNonAtomic: | ||||||
11793 | case CK_NoOp: | ||||||
11794 | case CK_LValueToRValueBitCast: | ||||||
11795 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
11796 | |||||||
11797 | case CK_MemberPointerToBoolean: | ||||||
11798 | case CK_PointerToBoolean: | ||||||
11799 | case CK_IntegralToBoolean: | ||||||
11800 | case CK_FloatingToBoolean: | ||||||
11801 | case CK_BooleanToSignedIntegral: | ||||||
11802 | case CK_FloatingComplexToBoolean: | ||||||
11803 | case CK_IntegralComplexToBoolean: { | ||||||
11804 | bool BoolResult; | ||||||
11805 | if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) | ||||||
11806 | return false; | ||||||
11807 | uint64_t IntResult = BoolResult; | ||||||
11808 | if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) | ||||||
11809 | IntResult = (uint64_t)-1; | ||||||
11810 | return Success(IntResult, E); | ||||||
11811 | } | ||||||
11812 | |||||||
11813 | case CK_FixedPointToIntegral: { | ||||||
11814 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); | ||||||
11815 | if (!EvaluateFixedPoint(SubExpr, Src, Info)) | ||||||
11816 | return false; | ||||||
11817 | bool Overflowed; | ||||||
11818 | llvm::APSInt Result = Src.convertToInt( | ||||||
11819 | Info.Ctx.getIntWidth(DestType), | ||||||
11820 | DestType->isSignedIntegerOrEnumerationType(), &Overflowed); | ||||||
11821 | if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) | ||||||
11822 | return false; | ||||||
11823 | return Success(Result, E); | ||||||
11824 | } | ||||||
11825 | |||||||
11826 | case CK_FixedPointToBoolean: { | ||||||
11827 | // Unsigned padding does not affect this. | ||||||
11828 | APValue Val; | ||||||
11829 | if (!Evaluate(Val, Info, SubExpr)) | ||||||
11830 | return false; | ||||||
11831 | return Success(Val.getFixedPoint().getBoolValue(), E); | ||||||
11832 | } | ||||||
11833 | |||||||
11834 | case CK_IntegralCast: { | ||||||
11835 | if (!Visit(SubExpr)) | ||||||
11836 | return false; | ||||||
11837 | |||||||
11838 | if (!Result.isInt()) { | ||||||
11839 | // Allow casts of address-of-label differences if they are no-ops | ||||||
11840 | // or narrowing. (The narrowing case isn't actually guaranteed to | ||||||
11841 | // be constant-evaluatable except in some narrow cases which are hard | ||||||
11842 | // to detect here. We let it through on the assumption the user knows | ||||||
11843 | // what they are doing.) | ||||||
11844 | if (Result.isAddrLabelDiff()) | ||||||
11845 | return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); | ||||||
11846 | // Only allow casts of lvalues if they are lossless. | ||||||
11847 | return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); | ||||||
11848 | } | ||||||
11849 | |||||||
11850 | return Success(HandleIntToIntCast(Info, E, DestType, SrcType, | ||||||
11851 | Result.getInt()), E); | ||||||
11852 | } | ||||||
11853 | |||||||
11854 | case CK_PointerToIntegral: { | ||||||
11855 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||||
11856 | |||||||
11857 | LValue LV; | ||||||
11858 | if (!EvaluatePointer(SubExpr, LV, Info)) | ||||||
11859 | return false; | ||||||
11860 | |||||||
11861 | if (LV.getLValueBase()) { | ||||||
11862 | // Only allow based lvalue casts if they are lossless. | ||||||
11863 | // FIXME: Allow a larger integer size than the pointer size, and allow | ||||||
11864 | // narrowing back down to pointer width in subsequent integral casts. | ||||||
11865 | // FIXME: Check integer type's active bits, not its type size. | ||||||
11866 | if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) | ||||||
11867 | return Error(E); | ||||||
11868 | |||||||
11869 | LV.Designator.setInvalid(); | ||||||
11870 | LV.moveInto(Result); | ||||||
11871 | return true; | ||||||
11872 | } | ||||||
11873 | |||||||
11874 | APSInt AsInt; | ||||||
11875 | APValue V; | ||||||
11876 | LV.moveInto(V); | ||||||
11877 | if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) | ||||||
11878 | llvm_unreachable("Can't cast this!")::llvm::llvm_unreachable_internal("Can't cast this!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11878); | ||||||
11879 | |||||||
11880 | return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); | ||||||
11881 | } | ||||||
11882 | |||||||
11883 | case CK_IntegralComplexToReal: { | ||||||
11884 | ComplexValue C; | ||||||
11885 | if (!EvaluateComplex(SubExpr, C, Info)) | ||||||
11886 | return false; | ||||||
11887 | return Success(C.getComplexIntReal(), E); | ||||||
11888 | } | ||||||
11889 | |||||||
11890 | case CK_FloatingToIntegral: { | ||||||
11891 | APFloat F(0.0); | ||||||
11892 | if (!EvaluateFloat(SubExpr, F, Info)) | ||||||
11893 | return false; | ||||||
11894 | |||||||
11895 | APSInt Value; | ||||||
11896 | if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) | ||||||
11897 | return false; | ||||||
11898 | return Success(Value, E); | ||||||
11899 | } | ||||||
11900 | } | ||||||
11901 | |||||||
11902 | llvm_unreachable("unknown cast resulting in integral value")::llvm::llvm_unreachable_internal("unknown cast resulting in integral value" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11902); | ||||||
11903 | } | ||||||
11904 | |||||||
11905 | bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||||
11906 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||||
11907 | ComplexValue LV; | ||||||
11908 | if (!EvaluateComplex(E->getSubExpr(), LV, Info)) | ||||||
11909 | return false; | ||||||
11910 | if (!LV.isComplexInt()) | ||||||
11911 | return Error(E); | ||||||
11912 | return Success(LV.getComplexIntReal(), E); | ||||||
11913 | } | ||||||
11914 | |||||||
11915 | return Visit(E->getSubExpr()); | ||||||
11916 | } | ||||||
11917 | |||||||
11918 | bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||||
11919 | if (E->getSubExpr()->getType()->isComplexIntegerType()) { | ||||||
11920 | ComplexValue LV; | ||||||
11921 | if (!EvaluateComplex(E->getSubExpr(), LV, Info)) | ||||||
11922 | return false; | ||||||
11923 | if (!LV.isComplexInt()) | ||||||
11924 | return Error(E); | ||||||
11925 | return Success(LV.getComplexIntImag(), E); | ||||||
11926 | } | ||||||
11927 | |||||||
11928 | VisitIgnoredValue(E->getSubExpr()); | ||||||
11929 | return Success(0, E); | ||||||
11930 | } | ||||||
11931 | |||||||
11932 | bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { | ||||||
11933 | return Success(E->getPackLength(), E); | ||||||
11934 | } | ||||||
11935 | |||||||
11936 | bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { | ||||||
11937 | return Success(E->getValue(), E); | ||||||
11938 | } | ||||||
11939 | |||||||
11940 | bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||||
11941 | switch (E->getOpcode()) { | ||||||
11942 | default: | ||||||
11943 | // Invalid unary operators | ||||||
11944 | return Error(E); | ||||||
11945 | case UO_Plus: | ||||||
11946 | // The result is just the value. | ||||||
11947 | return Visit(E->getSubExpr()); | ||||||
11948 | case UO_Minus: { | ||||||
11949 | if (!Visit(E->getSubExpr())) return false; | ||||||
11950 | if (!Result.isFixedPoint()) | ||||||
11951 | return Error(E); | ||||||
11952 | bool Overflowed; | ||||||
11953 | APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); | ||||||
11954 | if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) | ||||||
11955 | return false; | ||||||
11956 | return Success(Negated, E); | ||||||
11957 | } | ||||||
11958 | case UO_LNot: { | ||||||
11959 | bool bres; | ||||||
11960 | if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) | ||||||
11961 | return false; | ||||||
11962 | return Success(!bres, E); | ||||||
11963 | } | ||||||
11964 | } | ||||||
11965 | } | ||||||
11966 | |||||||
11967 | bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||||
11968 | const Expr *SubExpr = E->getSubExpr(); | ||||||
11969 | QualType DestType = E->getType(); | ||||||
11970 | assert(DestType->isFixedPointType() &&((DestType->isFixedPointType() && "Expected destination type to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11971, __PRETTY_FUNCTION__)) | ||||||
11971 | "Expected destination type to be a fixed point type")((DestType->isFixedPointType() && "Expected destination type to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11971, __PRETTY_FUNCTION__)); | ||||||
11972 | auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); | ||||||
11973 | |||||||
11974 | switch (E->getCastKind()) { | ||||||
11975 | case CK_FixedPointCast: { | ||||||
11976 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); | ||||||
11977 | if (!EvaluateFixedPoint(SubExpr, Src, Info)) | ||||||
11978 | return false; | ||||||
11979 | bool Overflowed; | ||||||
11980 | APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); | ||||||
11981 | if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) | ||||||
11982 | return false; | ||||||
11983 | return Success(Result, E); | ||||||
11984 | } | ||||||
11985 | case CK_IntegralToFixedPoint: { | ||||||
11986 | APSInt Src; | ||||||
11987 | if (!EvaluateInteger(SubExpr, Src, Info)) | ||||||
11988 | return false; | ||||||
11989 | |||||||
11990 | bool Overflowed; | ||||||
11991 | APFixedPoint IntResult = APFixedPoint::getFromIntValue( | ||||||
11992 | Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); | ||||||
11993 | |||||||
11994 | if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) | ||||||
11995 | return false; | ||||||
11996 | |||||||
11997 | return Success(IntResult, E); | ||||||
11998 | } | ||||||
11999 | case CK_NoOp: | ||||||
12000 | case CK_LValueToRValue: | ||||||
12001 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
12002 | default: | ||||||
12003 | return Error(E); | ||||||
12004 | } | ||||||
12005 | } | ||||||
12006 | |||||||
12007 | bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||||
12008 | const Expr *LHS = E->getLHS(); | ||||||
12009 | const Expr *RHS = E->getRHS(); | ||||||
12010 | FixedPointSemantics ResultFXSema = | ||||||
12011 | Info.Ctx.getFixedPointSemantics(E->getType()); | ||||||
12012 | |||||||
12013 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); | ||||||
12014 | if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) | ||||||
12015 | return false; | ||||||
12016 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); | ||||||
12017 | if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) | ||||||
12018 | return false; | ||||||
12019 | |||||||
12020 | switch (E->getOpcode()) { | ||||||
12021 | case BO_Add: { | ||||||
12022 | bool AddOverflow, ConversionOverflow; | ||||||
12023 | APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) | ||||||
12024 | .convert(ResultFXSema, &ConversionOverflow); | ||||||
12025 | if ((AddOverflow || ConversionOverflow) && | ||||||
12026 | !HandleOverflow(Info, E, Result, E->getType())) | ||||||
12027 | return false; | ||||||
12028 | return Success(Result, E); | ||||||
12029 | } | ||||||
12030 | default: | ||||||
12031 | return false; | ||||||
12032 | } | ||||||
12033 | llvm_unreachable("Should've exited before this")::llvm::llvm_unreachable_internal("Should've exited before this" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12033); | ||||||
12034 | } | ||||||
12035 | |||||||
12036 | //===----------------------------------------------------------------------===// | ||||||
12037 | // Float Evaluation | ||||||
12038 | //===----------------------------------------------------------------------===// | ||||||
12039 | |||||||
12040 | namespace { | ||||||
12041 | class FloatExprEvaluator | ||||||
12042 | : public ExprEvaluatorBase<FloatExprEvaluator> { | ||||||
12043 | APFloat &Result; | ||||||
12044 | public: | ||||||
12045 | FloatExprEvaluator(EvalInfo &info, APFloat &result) | ||||||
12046 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||||
12047 | |||||||
12048 | bool Success(const APValue &V, const Expr *e) { | ||||||
12049 | Result = V.getFloat(); | ||||||
12050 | return true; | ||||||
12051 | } | ||||||
12052 | |||||||
12053 | bool ZeroInitialization(const Expr *E) { | ||||||
12054 | Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); | ||||||
12055 | return true; | ||||||
12056 | } | ||||||
12057 | |||||||
12058 | bool VisitCallExpr(const CallExpr *E); | ||||||
12059 | |||||||
12060 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||||
12061 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||||
12062 | bool VisitFloatingLiteral(const FloatingLiteral *E); | ||||||
12063 | bool VisitCastExpr(const CastExpr *E); | ||||||
12064 | |||||||
12065 | bool VisitUnaryReal(const UnaryOperator *E); | ||||||
12066 | bool VisitUnaryImag(const UnaryOperator *E); | ||||||
12067 | |||||||
12068 | // FIXME: Missing: array subscript of vector, member of vector | ||||||
12069 | }; | ||||||
12070 | } // end anonymous namespace | ||||||
12071 | |||||||
12072 | static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { | ||||||
12073 | assert(E->isRValue() && E->getType()->isRealFloatingType())((E->isRValue() && E->getType()->isRealFloatingType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRealFloatingType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12073, __PRETTY_FUNCTION__)); | ||||||
12074 | return FloatExprEvaluator(Info, Result).Visit(E); | ||||||
12075 | } | ||||||
12076 | |||||||
12077 | static bool TryEvaluateBuiltinNaN(const ASTContext &Context, | ||||||
12078 | QualType ResultTy, | ||||||
12079 | const Expr *Arg, | ||||||
12080 | bool SNaN, | ||||||
12081 | llvm::APFloat &Result) { | ||||||
12082 | const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); | ||||||
12083 | if (!S) return false; | ||||||
12084 | |||||||
12085 | const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); | ||||||
12086 | |||||||
12087 | llvm::APInt fill; | ||||||
12088 | |||||||
12089 | // Treat empty strings as if they were zero. | ||||||
12090 | if (S->getString().empty()) | ||||||
12091 | fill = llvm::APInt(32, 0); | ||||||
12092 | else if (S->getString().getAsInteger(0, fill)) | ||||||
12093 | return false; | ||||||
12094 | |||||||
12095 | if (Context.getTargetInfo().isNan2008()) { | ||||||
12096 | if (SNaN) | ||||||
12097 | Result = llvm::APFloat::getSNaN(Sem, false, &fill); | ||||||
12098 | else | ||||||
12099 | Result = llvm::APFloat::getQNaN(Sem, false, &fill); | ||||||
12100 | } else { | ||||||
12101 | // Prior to IEEE 754-2008, architectures were allowed to choose whether | ||||||
12102 | // the first bit of their significand was set for qNaN or sNaN. MIPS chose | ||||||
12103 | // a different encoding to what became a standard in 2008, and for pre- | ||||||
12104 | // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as | ||||||
12105 | // sNaN. This is now known as "legacy NaN" encoding. | ||||||
12106 | if (SNaN) | ||||||
12107 | Result = llvm::APFloat::getQNaN(Sem, false, &fill); | ||||||
12108 | else | ||||||
12109 | Result = llvm::APFloat::getSNaN(Sem, false, &fill); | ||||||
12110 | } | ||||||
12111 | |||||||
12112 | return true; | ||||||
12113 | } | ||||||
12114 | |||||||
12115 | bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||||
12116 | switch (E->getBuiltinCallee()) { | ||||||
12117 | default: | ||||||
12118 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||||
12119 | |||||||
12120 | case Builtin::BI__builtin_huge_val: | ||||||
12121 | case Builtin::BI__builtin_huge_valf: | ||||||
12122 | case Builtin::BI__builtin_huge_vall: | ||||||
12123 | case Builtin::BI__builtin_huge_valf128: | ||||||
12124 | case Builtin::BI__builtin_inf: | ||||||
12125 | case Builtin::BI__builtin_inff: | ||||||
12126 | case Builtin::BI__builtin_infl: | ||||||
12127 | case Builtin::BI__builtin_inff128: { | ||||||
12128 | const llvm::fltSemantics &Sem = | ||||||
12129 | Info.Ctx.getFloatTypeSemantics(E->getType()); | ||||||
12130 | Result = llvm::APFloat::getInf(Sem); | ||||||
12131 | return true; | ||||||
12132 | } | ||||||
12133 | |||||||
12134 | case Builtin::BI__builtin_nans: | ||||||
12135 | case Builtin::BI__builtin_nansf: | ||||||
12136 | case Builtin::BI__builtin_nansl: | ||||||
12137 | case Builtin::BI__builtin_nansf128: | ||||||
12138 | if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), | ||||||
12139 | true, Result)) | ||||||
12140 | return Error(E); | ||||||
12141 | return true; | ||||||
12142 | |||||||
12143 | case Builtin::BI__builtin_nan: | ||||||
12144 | case Builtin::BI__builtin_nanf: | ||||||
12145 | case Builtin::BI__builtin_nanl: | ||||||
12146 | case Builtin::BI__builtin_nanf128: | ||||||
12147 | // If this is __builtin_nan() turn this into a nan, otherwise we | ||||||
12148 | // can't constant fold it. | ||||||
12149 | if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), | ||||||
12150 | false, Result)) | ||||||
12151 | return Error(E); | ||||||
12152 | return true; | ||||||
12153 | |||||||
12154 | case Builtin::BI__builtin_fabs: | ||||||
12155 | case Builtin::BI__builtin_fabsf: | ||||||
12156 | case Builtin::BI__builtin_fabsl: | ||||||
12157 | case Builtin::BI__builtin_fabsf128: | ||||||
12158 | if (!EvaluateFloat(E->getArg(0), Result, Info)) | ||||||
12159 | return false; | ||||||
12160 | |||||||
12161 | if (Result.isNegative()) | ||||||
12162 | Result.changeSign(); | ||||||
12163 | return true; | ||||||
12164 | |||||||
12165 | // FIXME: Builtin::BI__builtin_powi | ||||||
12166 | // FIXME: Builtin::BI__builtin_powif | ||||||
12167 | // FIXME: Builtin::BI__builtin_powil | ||||||
12168 | |||||||
12169 | case Builtin::BI__builtin_copysign: | ||||||
12170 | case Builtin::BI__builtin_copysignf: | ||||||
12171 | case Builtin::BI__builtin_copysignl: | ||||||
12172 | case Builtin::BI__builtin_copysignf128: { | ||||||
12173 | APFloat RHS(0.); | ||||||
12174 | if (!EvaluateFloat(E->getArg(0), Result, Info) || | ||||||
12175 | !EvaluateFloat(E->getArg(1), RHS, Info)) | ||||||
12176 | return false; | ||||||
12177 | Result.copySign(RHS); | ||||||
12178 | return true; | ||||||
12179 | } | ||||||
12180 | } | ||||||
12181 | } | ||||||
12182 | |||||||
12183 | bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||||
12184 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||||
12185 | ComplexValue CV; | ||||||
12186 | if (!EvaluateComplex(E->getSubExpr(), CV, Info)) | ||||||
12187 | return false; | ||||||
12188 | Result = CV.FloatReal; | ||||||
12189 | return true; | ||||||
12190 | } | ||||||
12191 | |||||||
12192 | return Visit(E->getSubExpr()); | ||||||
12193 | } | ||||||
12194 | |||||||
12195 | bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||||
12196 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||||
12197 | ComplexValue CV; | ||||||
12198 | if (!EvaluateComplex(E->getSubExpr(), CV, Info)) | ||||||
12199 | return false; | ||||||
12200 | Result = CV.FloatImag; | ||||||
12201 | return true; | ||||||
12202 | } | ||||||
12203 | |||||||
12204 | VisitIgnoredValue(E->getSubExpr()); | ||||||
12205 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); | ||||||
12206 | Result = llvm::APFloat::getZero(Sem); | ||||||
12207 | return true; | ||||||
12208 | } | ||||||
12209 | |||||||
12210 | bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||||
12211 | switch (E->getOpcode()) { | ||||||
12212 | default: return Error(E); | ||||||
12213 | case UO_Plus: | ||||||
12214 | return EvaluateFloat(E->getSubExpr(), Result, Info); | ||||||
12215 | case UO_Minus: | ||||||
12216 | if (!EvaluateFloat(E->getSubExpr(), Result, Info)) | ||||||
12217 | return false; | ||||||
12218 | Result.changeSign(); | ||||||
12219 | return true; | ||||||
12220 | } | ||||||
12221 | } | ||||||
12222 | |||||||
12223 | bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||||
12224 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | ||||||
12225 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||||
12226 | |||||||
12227 | APFloat RHS(0.0); | ||||||
12228 | bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); | ||||||
12229 | if (!LHSOK && !Info.noteFailure()) | ||||||
12230 | return false; | ||||||
12231 | return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && | ||||||
12232 | handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); | ||||||
12233 | } | ||||||
12234 | |||||||
12235 | bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { | ||||||
12236 | Result = E->getValue(); | ||||||
12237 | return true; | ||||||
12238 | } | ||||||
12239 | |||||||
12240 | bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||||
12241 | const Expr* SubExpr = E->getSubExpr(); | ||||||
12242 | |||||||
12243 | switch (E->getCastKind()) { | ||||||
12244 | default: | ||||||
12245 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
12246 | |||||||
12247 | case CK_IntegralToFloating: { | ||||||
12248 | APSInt IntResult; | ||||||
12249 | return EvaluateInteger(SubExpr, IntResult, Info) && | ||||||
12250 | HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, | ||||||
12251 | E->getType(), Result); | ||||||
12252 | } | ||||||
12253 | |||||||
12254 | case CK_FloatingCast: { | ||||||
12255 | if (!Visit(SubExpr)) | ||||||
12256 | return false; | ||||||
12257 | return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), | ||||||
12258 | Result); | ||||||
12259 | } | ||||||
12260 | |||||||
12261 | case CK_FloatingComplexToReal: { | ||||||
12262 | ComplexValue V; | ||||||
12263 | if (!EvaluateComplex(SubExpr, V, Info)) | ||||||
12264 | return false; | ||||||
12265 | Result = V.getComplexFloatReal(); | ||||||
12266 | return true; | ||||||
12267 | } | ||||||
12268 | } | ||||||
12269 | } | ||||||
12270 | |||||||
12271 | //===----------------------------------------------------------------------===// | ||||||
12272 | // Complex Evaluation (for float and integer) | ||||||
12273 | //===----------------------------------------------------------------------===// | ||||||
12274 | |||||||
12275 | namespace { | ||||||
12276 | class ComplexExprEvaluator | ||||||
12277 | : public ExprEvaluatorBase<ComplexExprEvaluator> { | ||||||
12278 | ComplexValue &Result; | ||||||
12279 | |||||||
12280 | public: | ||||||
12281 | ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) | ||||||
12282 | : ExprEvaluatorBaseTy(info), Result(Result) {} | ||||||
12283 | |||||||
12284 | bool Success(const APValue &V, const Expr *e) { | ||||||
12285 | Result.setFrom(V); | ||||||
12286 | return true; | ||||||
12287 | } | ||||||
12288 | |||||||
12289 | bool ZeroInitialization(const Expr *E); | ||||||
12290 | |||||||
12291 | //===--------------------------------------------------------------------===// | ||||||
12292 | // Visitor Methods | ||||||
12293 | //===--------------------------------------------------------------------===// | ||||||
12294 | |||||||
12295 | bool VisitImaginaryLiteral(const ImaginaryLiteral *E); | ||||||
12296 | bool VisitCastExpr(const CastExpr *E); | ||||||
12297 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||||
12298 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||||
12299 | bool VisitInitListExpr(const InitListExpr *E); | ||||||
12300 | }; | ||||||
12301 | } // end anonymous namespace | ||||||
12302 | |||||||
12303 | static bool EvaluateComplex(const Expr *E, ComplexValue &Result, | ||||||
12304 | EvalInfo &Info) { | ||||||
12305 | assert(E->isRValue() && E->getType()->isAnyComplexType())((E->isRValue() && E->getType()->isAnyComplexType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isAnyComplexType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12305, __PRETTY_FUNCTION__)); | ||||||
12306 | return ComplexExprEvaluator(Info, Result).Visit(E); | ||||||
12307 | } | ||||||
12308 | |||||||
12309 | bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { | ||||||
12310 | QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); | ||||||
12311 | if (ElemTy->isRealFloatingType()) { | ||||||
12312 | Result.makeComplexFloat(); | ||||||
12313 | APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); | ||||||
12314 | Result.FloatReal = Zero; | ||||||
12315 | Result.FloatImag = Zero; | ||||||
12316 | } else { | ||||||
12317 | Result.makeComplexInt(); | ||||||
12318 | APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); | ||||||
12319 | Result.IntReal = Zero; | ||||||
12320 | Result.IntImag = Zero; | ||||||
12321 | } | ||||||
12322 | return true; | ||||||
12323 | } | ||||||
12324 | |||||||
12325 | bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { | ||||||
12326 | const Expr* SubExpr = E->getSubExpr(); | ||||||
12327 | |||||||
12328 | if (SubExpr->getType()->isRealFloatingType()) { | ||||||
12329 | Result.makeComplexFloat(); | ||||||
12330 | APFloat &Imag = Result.FloatImag; | ||||||
12331 | if (!EvaluateFloat(SubExpr, Imag, Info)) | ||||||
12332 | return false; | ||||||
12333 | |||||||
12334 | Result.FloatReal = APFloat(Imag.getSemantics()); | ||||||
12335 | return true; | ||||||
12336 | } else { | ||||||
12337 | assert(SubExpr->getType()->isIntegerType() &&((SubExpr->getType()->isIntegerType() && "Unexpected imaginary literal." ) ? static_cast<void> (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12338, __PRETTY_FUNCTION__)) | ||||||
12338 | "Unexpected imaginary literal.")((SubExpr->getType()->isIntegerType() && "Unexpected imaginary literal." ) ? static_cast<void> (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12338, __PRETTY_FUNCTION__)); | ||||||
12339 | |||||||
12340 | Result.makeComplexInt(); | ||||||
12341 | APSInt &Imag = Result.IntImag; | ||||||
12342 | if (!EvaluateInteger(SubExpr, Imag, Info)) | ||||||
12343 | return false; | ||||||
12344 | |||||||
12345 | Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); | ||||||
12346 | return true; | ||||||
12347 | } | ||||||
12348 | } | ||||||
12349 | |||||||
12350 | bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||||
12351 | |||||||
12352 | switch (E->getCastKind()) { | ||||||
12353 | case CK_BitCast: | ||||||
12354 | case CK_BaseToDerived: | ||||||
12355 | case CK_DerivedToBase: | ||||||
12356 | case CK_UncheckedDerivedToBase: | ||||||
12357 | case CK_Dynamic: | ||||||
12358 | case CK_ToUnion: | ||||||
12359 | case CK_ArrayToPointerDecay: | ||||||
12360 | case CK_FunctionToPointerDecay: | ||||||
12361 | case CK_NullToPointer: | ||||||
12362 | case CK_NullToMemberPointer: | ||||||
12363 | case CK_BaseToDerivedMemberPointer: | ||||||
12364 | case CK_DerivedToBaseMemberPointer: | ||||||
12365 | case CK_MemberPointerToBoolean: | ||||||
12366 | case CK_ReinterpretMemberPointer: | ||||||
12367 | case CK_ConstructorConversion: | ||||||
12368 | case CK_IntegralToPointer: | ||||||
12369 | case CK_PointerToIntegral: | ||||||
12370 | case CK_PointerToBoolean: | ||||||
12371 | case CK_ToVoid: | ||||||
12372 | case CK_VectorSplat: | ||||||
12373 | case CK_IntegralCast: | ||||||
12374 | case CK_BooleanToSignedIntegral: | ||||||
12375 | case CK_IntegralToBoolean: | ||||||
12376 | case CK_IntegralToFloating: | ||||||
12377 | case CK_FloatingToIntegral: | ||||||
12378 | case CK_FloatingToBoolean: | ||||||
12379 | case CK_FloatingCast: | ||||||
12380 | case CK_CPointerToObjCPointerCast: | ||||||
12381 | case CK_BlockPointerToObjCPointerCast: | ||||||
12382 | case CK_AnyPointerToBlockPointerCast: | ||||||
12383 | case CK_ObjCObjectLValueCast: | ||||||
12384 | case CK_FloatingComplexToReal: | ||||||
12385 | case CK_FloatingComplexToBoolean: | ||||||
12386 | case CK_IntegralComplexToReal: | ||||||
12387 | case CK_IntegralComplexToBoolean: | ||||||
12388 | case CK_ARCProduceObject: | ||||||
12389 | case CK_ARCConsumeObject: | ||||||
12390 | case CK_ARCReclaimReturnedObject: | ||||||
12391 | case CK_ARCExtendBlockObject: | ||||||
12392 | case CK_CopyAndAutoreleaseBlockObject: | ||||||
12393 | case CK_BuiltinFnToFnPtr: | ||||||
12394 | case CK_ZeroToOCLOpaqueType: | ||||||
12395 | case CK_NonAtomicToAtomic: | ||||||
12396 | case CK_AddressSpaceConversion: | ||||||
12397 | case CK_IntToOCLSampler: | ||||||
12398 | case CK_FixedPointCast: | ||||||
12399 | case CK_FixedPointToBoolean: | ||||||
12400 | case CK_FixedPointToIntegral: | ||||||
12401 | case CK_IntegralToFixedPoint: | ||||||
12402 | llvm_unreachable("invalid cast kind for complex value")::llvm::llvm_unreachable_internal("invalid cast kind for complex value" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12402); | ||||||
12403 | |||||||
12404 | case CK_LValueToRValue: | ||||||
12405 | case CK_AtomicToNonAtomic: | ||||||
12406 | case CK_NoOp: | ||||||
12407 | case CK_LValueToRValueBitCast: | ||||||
12408 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
12409 | |||||||
12410 | case CK_Dependent: | ||||||
12411 | case CK_LValueBitCast: | ||||||
12412 | case CK_UserDefinedConversion: | ||||||
12413 | return Error(E); | ||||||
12414 | |||||||
12415 | case CK_FloatingRealToComplex: { | ||||||
12416 | APFloat &Real = Result.FloatReal; | ||||||
12417 | if (!EvaluateFloat(E->getSubExpr(), Real, Info)) | ||||||
12418 | return false; | ||||||
12419 | |||||||
12420 | Result.makeComplexFloat(); | ||||||
12421 | Result.FloatImag = APFloat(Real.getSemantics()); | ||||||
12422 | return true; | ||||||
12423 | } | ||||||
12424 | |||||||
12425 | case CK_FloatingComplexCast: { | ||||||
12426 | if (!Visit(E->getSubExpr())) | ||||||
12427 | return false; | ||||||
12428 | |||||||
12429 | QualType To = E->getType()->getAs<ComplexType>()->getElementType(); | ||||||
12430 | QualType From | ||||||
12431 | = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); | ||||||
12432 | |||||||
12433 | return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && | ||||||
12434 | HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); | ||||||
12435 | } | ||||||
12436 | |||||||
12437 | case CK_FloatingComplexToIntegralComplex: { | ||||||
12438 | if (!Visit(E->getSubExpr())) | ||||||
12439 | return false; | ||||||
12440 | |||||||
12441 | QualType To = E->getType()->getAs<ComplexType>()->getElementType(); | ||||||
12442 | QualType From | ||||||
12443 | = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); | ||||||
12444 | Result.makeComplexInt(); | ||||||
12445 | return HandleFloatToIntCast(Info, E, From, Result.FloatReal, | ||||||
12446 | To, Result.IntReal) && | ||||||
12447 | HandleFloatToIntCast(Info, E, From, Result.FloatImag, | ||||||
12448 | To, Result.IntImag); | ||||||
12449 | } | ||||||
12450 | |||||||
12451 | case CK_IntegralRealToComplex: { | ||||||
12452 | APSInt &Real = Result.IntReal; | ||||||
12453 | if (!EvaluateInteger(E->getSubExpr(), Real, Info)) | ||||||
12454 | return false; | ||||||
12455 | |||||||
12456 | Result.makeComplexInt(); | ||||||
12457 | Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); | ||||||
12458 | return true; | ||||||
12459 | } | ||||||
12460 | |||||||
12461 | case CK_IntegralComplexCast: { | ||||||
12462 | if (!Visit(E->getSubExpr())) | ||||||
12463 | return false; | ||||||
12464 | |||||||
12465 | QualType To = E->getType()->getAs<ComplexType>()->getElementType(); | ||||||
12466 | QualType From | ||||||
12467 | = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); | ||||||
12468 | |||||||
12469 | Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); | ||||||
12470 | Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); | ||||||
12471 | return true; | ||||||
12472 | } | ||||||
12473 | |||||||
12474 | case CK_IntegralComplexToFloatingComplex: { | ||||||
12475 | if (!Visit(E->getSubExpr())) | ||||||
12476 | return false; | ||||||
12477 | |||||||
12478 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | ||||||
12479 | QualType From | ||||||
12480 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | ||||||
12481 | Result.makeComplexFloat(); | ||||||
12482 | return HandleIntToFloatCast(Info, E, From, Result.IntReal, | ||||||
12483 | To, Result.FloatReal) && | ||||||
12484 | HandleIntToFloatCast(Info, E, From, Result.IntImag, | ||||||
12485 | To, Result.FloatImag); | ||||||
12486 | } | ||||||
12487 | } | ||||||
12488 | |||||||
12489 | llvm_unreachable("unknown cast resulting in complex value")::llvm::llvm_unreachable_internal("unknown cast resulting in complex value" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12489); | ||||||
12490 | } | ||||||
12491 | |||||||
12492 | bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||||
12493 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | ||||||
12494 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||||
12495 | |||||||
12496 | // Track whether the LHS or RHS is real at the type system level. When this is | ||||||
12497 | // the case we can simplify our evaluation strategy. | ||||||
12498 | bool LHSReal = false, RHSReal = false; | ||||||
12499 | |||||||
12500 | bool LHSOK; | ||||||
12501 | if (E->getLHS()->getType()->isRealFloatingType()) { | ||||||
12502 | LHSReal = true; | ||||||
12503 | APFloat &Real = Result.FloatReal; | ||||||
12504 | LHSOK = EvaluateFloat(E->getLHS(), Real, Info); | ||||||
12505 | if (LHSOK) { | ||||||
12506 | Result.makeComplexFloat(); | ||||||
12507 | Result.FloatImag = APFloat(Real.getSemantics()); | ||||||
12508 | } | ||||||
12509 | } else { | ||||||
12510 | LHSOK = Visit(E->getLHS()); | ||||||
12511 | } | ||||||
12512 | if (!LHSOK && !Info.noteFailure()) | ||||||
12513 | return false; | ||||||
12514 | |||||||
12515 | ComplexValue RHS; | ||||||
12516 | if (E->getRHS()->getType()->isRealFloatingType()) { | ||||||
12517 | RHSReal = true; | ||||||
12518 | APFloat &Real = RHS.FloatReal; | ||||||
12519 | if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) | ||||||
12520 | return false; | ||||||
12521 | RHS.makeComplexFloat(); | ||||||
12522 | RHS.FloatImag = APFloat(Real.getSemantics()); | ||||||
12523 | } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) | ||||||
12524 | return false; | ||||||
12525 | |||||||
12526 | assert(!(LHSReal && RHSReal) &&((!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real." ) ? static_cast<void> (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12527, __PRETTY_FUNCTION__)) | ||||||
12527 | "Cannot have both operands of a complex operation be real.")((!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real." ) ? static_cast<void> (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12527, __PRETTY_FUNCTION__)); | ||||||
12528 | switch (E->getOpcode()) { | ||||||
12529 | default: return Error(E); | ||||||
12530 | case BO_Add: | ||||||
12531 | if (Result.isComplexFloat()) { | ||||||
12532 | Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), | ||||||
12533 | APFloat::rmNearestTiesToEven); | ||||||
12534 | if (LHSReal) | ||||||
12535 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); | ||||||
12536 | else if (!RHSReal) | ||||||
12537 | Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), | ||||||
12538 | APFloat::rmNearestTiesToEven); | ||||||
12539 | } else { | ||||||
12540 | Result.getComplexIntReal() += RHS.getComplexIntReal(); | ||||||
12541 | Result.getComplexIntImag() += RHS.getComplexIntImag(); | ||||||
12542 | } | ||||||
12543 | break; | ||||||
12544 | case BO_Sub: | ||||||
12545 | if (Result.isComplexFloat()) { | ||||||
12546 | Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), | ||||||
12547 | APFloat::rmNearestTiesToEven); | ||||||
12548 | if (LHSReal) { | ||||||
12549 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); | ||||||
12550 | Result.getComplexFloatImag().changeSign(); | ||||||
12551 | } else if (!RHSReal) { | ||||||
12552 | Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), | ||||||
12553 | APFloat::rmNearestTiesToEven); | ||||||
12554 | } | ||||||
12555 | } else { | ||||||
12556 | Result.getComplexIntReal() -= RHS.getComplexIntReal(); | ||||||
12557 | Result.getComplexIntImag() -= RHS.getComplexIntImag(); | ||||||
12558 | } | ||||||
12559 | break; | ||||||
12560 | case BO_Mul: | ||||||
12561 | if (Result.isComplexFloat()) { | ||||||
12562 | // This is an implementation of complex multiplication according to the | ||||||
12563 | // constraints laid out in C11 Annex G. The implementation uses the | ||||||
12564 | // following naming scheme: | ||||||
12565 | // (a + ib) * (c + id) | ||||||
12566 | ComplexValue LHS = Result; | ||||||
12567 | APFloat &A = LHS.getComplexFloatReal(); | ||||||
12568 | APFloat &B = LHS.getComplexFloatImag(); | ||||||
12569 | APFloat &C = RHS.getComplexFloatReal(); | ||||||
12570 | APFloat &D = RHS.getComplexFloatImag(); | ||||||
12571 | APFloat &ResR = Result.getComplexFloatReal(); | ||||||
12572 | APFloat &ResI = Result.getComplexFloatImag(); | ||||||
12573 | if (LHSReal) { | ||||||
12574 | assert(!RHSReal && "Cannot have two real operands for a complex op!")((!RHSReal && "Cannot have two real operands for a complex op!" ) ? static_cast<void> (0) : __assert_fail ("!RHSReal && \"Cannot have two real operands for a complex op!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12574, __PRETTY_FUNCTION__)); | ||||||
12575 | ResR = A * C; | ||||||
12576 | ResI = A * D; | ||||||
12577 | } else if (RHSReal) { | ||||||
12578 | ResR = C * A; | ||||||
12579 | ResI = C * B; | ||||||
12580 | } else { | ||||||
12581 | // In the fully general case, we need to handle NaNs and infinities | ||||||
12582 | // robustly. | ||||||
12583 | APFloat AC = A * C; | ||||||
12584 | APFloat BD = B * D; | ||||||
12585 | APFloat AD = A * D; | ||||||
12586 | APFloat BC = B * C; | ||||||
12587 | ResR = AC - BD; | ||||||
12588 | ResI = AD + BC; | ||||||
12589 | if (ResR.isNaN() && ResI.isNaN()) { | ||||||
12590 | bool Recalc = false; | ||||||
12591 | if (A.isInfinity() || B.isInfinity()) { | ||||||
12592 | A = APFloat::copySign( | ||||||
12593 | APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); | ||||||
12594 | B = APFloat::copySign( | ||||||
12595 | APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); | ||||||
12596 | if (C.isNaN()) | ||||||
12597 | C = APFloat::copySign(APFloat(C.getSemantics()), C); | ||||||
12598 | if (D.isNaN()) | ||||||
12599 | D = APFloat::copySign(APFloat(D.getSemantics()), D); | ||||||
12600 | Recalc = true; | ||||||
12601 | } | ||||||
12602 | if (C.isInfinity() || D.isInfinity()) { | ||||||
12603 | C = APFloat::copySign( | ||||||
12604 | APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); | ||||||
12605 | D = APFloat::copySign( | ||||||
12606 | APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); | ||||||
12607 | if (A.isNaN()) | ||||||
12608 | A = APFloat::copySign(APFloat(A.getSemantics()), A); | ||||||
12609 | if (B.isNaN()) | ||||||
12610 | B = APFloat::copySign(APFloat(B.getSemantics()), B); | ||||||
12611 | Recalc = true; | ||||||
12612 | } | ||||||
12613 | if (!Recalc && (AC.isInfinity() || BD.isInfinity() || | ||||||
12614 | AD.isInfinity() || BC.isInfinity())) { | ||||||
12615 | if (A.isNaN()) | ||||||
12616 | A = APFloat::copySign(APFloat(A.getSemantics()), A); | ||||||
12617 | if (B.isNaN()) | ||||||
12618 | B = APFloat::copySign(APFloat(B.getSemantics()), B); | ||||||
12619 | if (C.isNaN()) | ||||||
12620 | C = APFloat::copySign(APFloat(C.getSemantics()), C); | ||||||
12621 | if (D.isNaN()) | ||||||
12622 | D = APFloat::copySign(APFloat(D.getSemantics()), D); | ||||||
12623 | Recalc = true; | ||||||
12624 | } | ||||||
12625 | if (Recalc) { | ||||||
12626 | ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); | ||||||
12627 | ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); | ||||||
12628 | } | ||||||
12629 | } | ||||||
12630 | } | ||||||
12631 | } else { | ||||||
12632 | ComplexValue LHS = Result; | ||||||
12633 | Result.getComplexIntReal() = | ||||||
12634 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() - | ||||||
12635 | LHS.getComplexIntImag() * RHS.getComplexIntImag()); | ||||||
12636 | Result.getComplexIntImag() = | ||||||
12637 | (LHS.getComplexIntReal() * RHS.getComplexIntImag() + | ||||||
12638 | LHS.getComplexIntImag() * RHS.getComplexIntReal()); | ||||||
12639 | } | ||||||
12640 | break; | ||||||
12641 | case BO_Div: | ||||||
12642 | if (Result.isComplexFloat()) { | ||||||
12643 | // This is an implementation of complex division according to the | ||||||
12644 | // constraints laid out in C11 Annex G. The implementation uses the | ||||||
12645 | // following naming scheme: | ||||||
12646 | // (a + ib) / (c + id) | ||||||
12647 | ComplexValue LHS = Result; | ||||||
12648 | APFloat &A = LHS.getComplexFloatReal(); | ||||||
12649 | APFloat &B = LHS.getComplexFloatImag(); | ||||||
12650 | APFloat &C = RHS.getComplexFloatReal(); | ||||||
12651 | APFloat &D = RHS.getComplexFloatImag(); | ||||||
12652 | APFloat &ResR = Result.getComplexFloatReal(); | ||||||
12653 | APFloat &ResI = Result.getComplexFloatImag(); | ||||||
12654 | if (RHSReal) { | ||||||
12655 | ResR = A / C; | ||||||
12656 | ResI = B / C; | ||||||
12657 | } else { | ||||||
12658 | if (LHSReal) { | ||||||
12659 | // No real optimizations we can do here, stub out with zero. | ||||||
12660 | B = APFloat::getZero(A.getSemantics()); | ||||||
12661 | } | ||||||
12662 | int DenomLogB = 0; | ||||||
12663 | APFloat MaxCD = maxnum(abs(C), abs(D)); | ||||||
12664 | if (MaxCD.isFinite()) { | ||||||
12665 | DenomLogB = ilogb(MaxCD); | ||||||
12666 | C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); | ||||||
12667 | D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); | ||||||
12668 | } | ||||||
12669 | APFloat Denom = C * C + D * D; | ||||||
12670 | ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, | ||||||
12671 | APFloat::rmNearestTiesToEven); | ||||||
12672 | ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, | ||||||
12673 | APFloat::rmNearestTiesToEven); | ||||||
12674 | if (ResR.isNaN() && ResI.isNaN()) { | ||||||
12675 | if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { | ||||||
12676 | ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; | ||||||
12677 | ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; | ||||||
12678 | } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && | ||||||
12679 | D.isFinite()) { | ||||||
12680 | A = APFloat::copySign( | ||||||
12681 | APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); | ||||||
12682 | B = APFloat::copySign( | ||||||
12683 | APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); | ||||||
12684 | ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); | ||||||
12685 | ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); | ||||||
12686 | } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { | ||||||
12687 | C = APFloat::copySign( | ||||||
12688 | APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); | ||||||
12689 | D = APFloat::copySign( | ||||||
12690 | APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); | ||||||
12691 | ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); | ||||||
12692 | ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); | ||||||
12693 | } | ||||||
12694 | } | ||||||
12695 | } | ||||||
12696 | } else { | ||||||
12697 | if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) | ||||||
12698 | return Error(E, diag::note_expr_divide_by_zero); | ||||||
12699 | |||||||
12700 | ComplexValue LHS = Result; | ||||||
12701 | APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + | ||||||
12702 | RHS.getComplexIntImag() * RHS.getComplexIntImag(); | ||||||
12703 | Result.getComplexIntReal() = | ||||||
12704 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() + | ||||||
12705 | LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; | ||||||
12706 | Result.getComplexIntImag() = | ||||||
12707 | (LHS.getComplexIntImag() * RHS.getComplexIntReal() - | ||||||
12708 | LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; | ||||||
12709 | } | ||||||
12710 | break; | ||||||
12711 | } | ||||||
12712 | |||||||
12713 | return true; | ||||||
12714 | } | ||||||
12715 | |||||||
12716 | bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||||
12717 | // Get the operand value into 'Result'. | ||||||
12718 | if (!Visit(E->getSubExpr())) | ||||||
12719 | return false; | ||||||
12720 | |||||||
12721 | switch (E->getOpcode()) { | ||||||
12722 | default: | ||||||
12723 | return Error(E); | ||||||
12724 | case UO_Extension: | ||||||
12725 | return true; | ||||||
12726 | case UO_Plus: | ||||||
12727 | // The result is always just the subexpr. | ||||||
12728 | return true; | ||||||
12729 | case UO_Minus: | ||||||
12730 | if (Result.isComplexFloat()) { | ||||||
12731 | Result.getComplexFloatReal().changeSign(); | ||||||
12732 | Result.getComplexFloatImag().changeSign(); | ||||||
12733 | } | ||||||
12734 | else { | ||||||
12735 | Result.getComplexIntReal() = -Result.getComplexIntReal(); | ||||||
12736 | Result.getComplexIntImag() = -Result.getComplexIntImag(); | ||||||
12737 | } | ||||||
12738 | return true; | ||||||
12739 | case UO_Not: | ||||||
12740 | if (Result.isComplexFloat()) | ||||||
12741 | Result.getComplexFloatImag().changeSign(); | ||||||
12742 | else | ||||||
12743 | Result.getComplexIntImag() = -Result.getComplexIntImag(); | ||||||
12744 | return true; | ||||||
12745 | } | ||||||
12746 | } | ||||||
12747 | |||||||
12748 | bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||||
12749 | if (E->getNumInits() == 2) { | ||||||
12750 | if (E->getType()->isComplexType()) { | ||||||
12751 | Result.makeComplexFloat(); | ||||||
12752 | if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) | ||||||
12753 | return false; | ||||||
12754 | if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) | ||||||
12755 | return false; | ||||||
12756 | } else { | ||||||
12757 | Result.makeComplexInt(); | ||||||
12758 | if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) | ||||||
12759 | return false; | ||||||
12760 | if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) | ||||||
12761 | return false; | ||||||
12762 | } | ||||||
12763 | return true; | ||||||
12764 | } | ||||||
12765 | return ExprEvaluatorBaseTy::VisitInitListExpr(E); | ||||||
12766 | } | ||||||
12767 | |||||||
12768 | //===----------------------------------------------------------------------===// | ||||||
12769 | // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic | ||||||
12770 | // implicit conversion. | ||||||
12771 | //===----------------------------------------------------------------------===// | ||||||
12772 | |||||||
12773 | namespace { | ||||||
12774 | class AtomicExprEvaluator : | ||||||
12775 | public ExprEvaluatorBase<AtomicExprEvaluator> { | ||||||
12776 | const LValue *This; | ||||||
12777 | APValue &Result; | ||||||
12778 | public: | ||||||
12779 | AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) | ||||||
12780 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} | ||||||
12781 | |||||||
12782 | bool Success(const APValue &V, const Expr *E) { | ||||||
12783 | Result = V; | ||||||
12784 | return true; | ||||||
12785 | } | ||||||
12786 | |||||||
12787 | bool ZeroInitialization(const Expr *E) { | ||||||
12788 | ImplicitValueInitExpr VIE( | ||||||
12789 | E->getType()->castAs<AtomicType>()->getValueType()); | ||||||
12790 | // For atomic-qualified class (and array) types in C++, initialize the | ||||||
12791 | // _Atomic-wrapped subobject directly, in-place. | ||||||
12792 | return This ? EvaluateInPlace(Result, Info, *This, &VIE) | ||||||
12793 | : Evaluate(Result, Info, &VIE); | ||||||
12794 | } | ||||||
12795 | |||||||
12796 | bool VisitCastExpr(const CastExpr *E) { | ||||||
12797 | switch (E->getCastKind()) { | ||||||
12798 | default: | ||||||
12799 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
12800 | case CK_NonAtomicToAtomic: | ||||||
12801 | return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) | ||||||
12802 | : Evaluate(Result, Info, E->getSubExpr()); | ||||||
12803 | } | ||||||
12804 | } | ||||||
12805 | }; | ||||||
12806 | } // end anonymous namespace | ||||||
12807 | |||||||
12808 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, | ||||||
12809 | EvalInfo &Info) { | ||||||
12810 | assert(E->isRValue() && E->getType()->isAtomicType())((E->isRValue() && E->getType()->isAtomicType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isAtomicType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12810, __PRETTY_FUNCTION__)); | ||||||
12811 | return AtomicExprEvaluator(Info, This, Result).Visit(E); | ||||||
12812 | } | ||||||
12813 | |||||||
12814 | //===----------------------------------------------------------------------===// | ||||||
12815 | // Void expression evaluation, primarily for a cast to void on the LHS of a | ||||||
12816 | // comma operator | ||||||
12817 | //===----------------------------------------------------------------------===// | ||||||
12818 | |||||||
12819 | namespace { | ||||||
12820 | class VoidExprEvaluator | ||||||
12821 | : public ExprEvaluatorBase<VoidExprEvaluator> { | ||||||
12822 | public: | ||||||
12823 | VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} | ||||||
12824 | |||||||
12825 | bool Success(const APValue &V, const Expr *e) { return true; } | ||||||
12826 | |||||||
12827 | bool ZeroInitialization(const Expr *E) { return true; } | ||||||
12828 | |||||||
12829 | bool VisitCastExpr(const CastExpr *E) { | ||||||
12830 | switch (E->getCastKind()) { | ||||||
12831 | default: | ||||||
12832 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||||
12833 | case CK_ToVoid: | ||||||
12834 | VisitIgnoredValue(E->getSubExpr()); | ||||||
12835 | return true; | ||||||
12836 | } | ||||||
12837 | } | ||||||
12838 | |||||||
12839 | bool VisitCallExpr(const CallExpr *E) { | ||||||
12840 | switch (E->getBuiltinCallee()) { | ||||||
12841 | default: | ||||||
12842 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||||
12843 | case Builtin::BI__assume: | ||||||
12844 | case Builtin::BI__builtin_assume: | ||||||
12845 | // The argument is not evaluated! | ||||||
12846 | return true; | ||||||
12847 | } | ||||||
12848 | } | ||||||
12849 | |||||||
12850 | bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); | ||||||
12851 | }; | ||||||
12852 | } // end anonymous namespace | ||||||
12853 | |||||||
12854 | static bool hasVirtualDestructor(QualType T) { | ||||||
12855 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | ||||||
12856 | if (CXXDestructorDecl *DD = RD->getDestructor()) | ||||||
12857 | return DD->isVirtual(); | ||||||
12858 | return false; | ||||||
12859 | } | ||||||
12860 | |||||||
12861 | bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { | ||||||
12862 | // We cannot speculatively evaluate a delete expression. | ||||||
12863 | if (Info.SpeculativeEvaluationDepth) | ||||||
12864 | return false; | ||||||
12865 | |||||||
12866 | FunctionDecl *OperatorDelete = E->getOperatorDelete(); | ||||||
12867 | if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { | ||||||
12868 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | ||||||
12869 | << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; | ||||||
12870 | return false; | ||||||
12871 | } | ||||||
12872 | |||||||
12873 | const Expr *Arg = E->getArgument(); | ||||||
12874 | |||||||
12875 | LValue Pointer; | ||||||
12876 | if (!EvaluatePointer(Arg, Pointer, Info)) | ||||||
12877 | return false; | ||||||
12878 | if (Pointer.Designator.Invalid) | ||||||
12879 | return false; | ||||||
12880 | |||||||
12881 | // Deleting a null pointer has no effect. | ||||||
12882 | if (Pointer.isNullPointer()) { | ||||||
12883 | // This is the only case where we need to produce an extension warning: | ||||||
12884 | // the only other way we can succeed is if we find a dynamic allocation, | ||||||
12885 | // and we will have warned when we allocated it in that case. | ||||||
12886 | if (!Info.getLangOpts().CPlusPlus2a) | ||||||
12887 | Info.CCEDiag(E, diag::note_constexpr_new); | ||||||
12888 | return true; | ||||||
12889 | } | ||||||
12890 | |||||||
12891 | auto PointerAsString = [&] { | ||||||
12892 | APValue Printable; | ||||||
12893 | Pointer.moveInto(Printable); | ||||||
12894 | return Printable.getAsString(Info.Ctx, Arg->getType()); | ||||||
12895 | }; | ||||||
12896 | |||||||
12897 | DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); | ||||||
12898 | if (!DA) { | ||||||
12899 | Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) | ||||||
12900 | << PointerAsString(); | ||||||
12901 | if (Pointer.Base) | ||||||
12902 | NoteLValueLocation(Info, Pointer.Base); | ||||||
12903 | return false; | ||||||
12904 | } | ||||||
12905 | QualType AllocType = Pointer.Base.getDynamicAllocType(); | ||||||
12906 | |||||||
12907 | Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); | ||||||
12908 | if (!Alloc) { | ||||||
12909 | Info.FFDiag(E, diag::note_constexpr_double_delete); | ||||||
12910 | return false; | ||||||
12911 | } | ||||||
12912 | |||||||
12913 | if (E->isArrayForm() != AllocType->isConstantArrayType()) { | ||||||
12914 | Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) | ||||||
12915 | << E->isArrayForm() << AllocType; | ||||||
12916 | NoteLValueLocation(Info, Pointer.Base); | ||||||
12917 | return false; | ||||||
12918 | } | ||||||
12919 | |||||||
12920 | bool Subobject = false; | ||||||
12921 | if (E->isArrayForm()) { | ||||||
12922 | Subobject = Pointer.Designator.Entries.size() != 1 || | ||||||
12923 | Pointer.Designator.Entries[0].getAsArrayIndex() != 0; | ||||||
12924 | } else { | ||||||
12925 | Subobject = Pointer.Designator.MostDerivedPathLength != 0 || | ||||||
12926 | Pointer.Designator.isOnePastTheEnd(); | ||||||
12927 | } | ||||||
12928 | if (Subobject) { | ||||||
12929 | Info.FFDiag(E, diag::note_constexpr_delete_subobject) | ||||||
12930 | << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); | ||||||
12931 | return false; | ||||||
12932 | } | ||||||
12933 | |||||||
12934 | // For the non-array case, the designator must be empty if the static type | ||||||
12935 | // does not have a virtual destructor. | ||||||
12936 | if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && | ||||||
12937 | !hasVirtualDestructor(Arg->getType()->getPointeeType())) { | ||||||
12938 | Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) | ||||||
12939 | << Arg->getType()->getPointeeType() << AllocType; | ||||||
12940 | return false; | ||||||
12941 | } | ||||||
12942 | |||||||
12943 | if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), | ||||||
12944 | (*Alloc)->Value, AllocType)) | ||||||
12945 | return false; | ||||||
12946 | |||||||
12947 | if (!Info.HeapAllocs.erase(DA)) { | ||||||
12948 | // The element was already erased. This means the destructor call also | ||||||
12949 | // deleted the object. | ||||||
12950 | // FIXME: This probably results in undefined behavior before we get this | ||||||
12951 | // far, and should be diagnosed elsewhere first. | ||||||
12952 | Info.FFDiag(E, diag::note_constexpr_double_delete); | ||||||
12953 | return false; | ||||||
12954 | } | ||||||
12955 | |||||||
12956 | return true; | ||||||
12957 | } | ||||||
12958 | |||||||
12959 | static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { | ||||||
12960 | assert(E->isRValue() && E->getType()->isVoidType())((E->isRValue() && E->getType()->isVoidType( )) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isVoidType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12960, __PRETTY_FUNCTION__)); | ||||||
12961 | return VoidExprEvaluator(Info).Visit(E); | ||||||
12962 | } | ||||||
12963 | |||||||
12964 | //===----------------------------------------------------------------------===// | ||||||
12965 | // Top level Expr::EvaluateAsRValue method. | ||||||
12966 | //===----------------------------------------------------------------------===// | ||||||
12967 | |||||||
12968 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { | ||||||
12969 | // In C, function designators are not lvalues, but we evaluate them as if they | ||||||
12970 | // are. | ||||||
12971 | QualType T = E->getType(); | ||||||
12972 | if (E->isGLValue() || T->isFunctionType()) { | ||||||
12973 | LValue LV; | ||||||
12974 | if (!EvaluateLValue(E, LV, Info)) | ||||||
12975 | return false; | ||||||
12976 | LV.moveInto(Result); | ||||||
12977 | } else if (T->isVectorType()) { | ||||||
12978 | if (!EvaluateVector(E, Result, Info)) | ||||||
12979 | return false; | ||||||
12980 | } else if (T->isIntegralOrEnumerationType()) { | ||||||
12981 | if (!IntExprEvaluator(Info, Result).Visit(E)) | ||||||
12982 | return false; | ||||||
12983 | } else if (T->hasPointerRepresentation()) { | ||||||
12984 | LValue LV; | ||||||
12985 | if (!EvaluatePointer(E, LV, Info)) | ||||||
12986 | return false; | ||||||
12987 | LV.moveInto(Result); | ||||||
12988 | } else if (T->isRealFloatingType()) { | ||||||
12989 | llvm::APFloat F(0.0); | ||||||
12990 | if (!EvaluateFloat(E, F, Info)) | ||||||
12991 | return false; | ||||||
12992 | Result = APValue(F); | ||||||
12993 | } else if (T->isAnyComplexType()) { | ||||||
12994 | ComplexValue C; | ||||||
12995 | if (!EvaluateComplex(E, C, Info)) | ||||||
12996 | return false; | ||||||
12997 | C.moveInto(Result); | ||||||
12998 | } else if (T->isFixedPointType()) { | ||||||
12999 | if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; | ||||||
13000 | } else if (T->isMemberPointerType()) { | ||||||
13001 | MemberPtr P; | ||||||
13002 | if (!EvaluateMemberPointer(E, P, Info)) | ||||||
13003 | return false; | ||||||
13004 | P.moveInto(Result); | ||||||
13005 | return true; | ||||||
13006 | } else if (T->isArrayType()) { | ||||||
13007 | LValue LV; | ||||||
13008 | APValue &Value = | ||||||
13009 | Info.CurrentCall->createTemporary(E, T, false, LV); | ||||||
13010 | if (!EvaluateArray(E, LV, Value, Info)) | ||||||
13011 | return false; | ||||||
13012 | Result = Value; | ||||||
13013 | } else if (T->isRecordType()) { | ||||||
13014 | LValue LV; | ||||||
13015 | APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); | ||||||
13016 | if (!EvaluateRecord(E, LV, Value, Info)) | ||||||
13017 | return false; | ||||||
13018 | Result = Value; | ||||||
13019 | } else if (T->isVoidType()) { | ||||||
13020 | if (!Info.getLangOpts().CPlusPlus11) | ||||||
13021 | Info.CCEDiag(E, diag::note_constexpr_nonliteral) | ||||||
13022 | << E->getType(); | ||||||
13023 | if (!EvaluateVoid(E, Info)) | ||||||
13024 | return false; | ||||||
13025 | } else if (T->isAtomicType()) { | ||||||
13026 | QualType Unqual = T.getAtomicUnqualifiedType(); | ||||||
13027 | if (Unqual->isArrayType() || Unqual->isRecordType()) { | ||||||
13028 | LValue LV; | ||||||
13029 | APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); | ||||||
13030 | if (!EvaluateAtomic(E, &LV, Value, Info)) | ||||||
13031 | return false; | ||||||
13032 | } else { | ||||||
13033 | if (!EvaluateAtomic(E, nullptr, Result, Info)) | ||||||
13034 | return false; | ||||||
13035 | } | ||||||
13036 | } else if (Info.getLangOpts().CPlusPlus11) { | ||||||
13037 | Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); | ||||||
13038 | return false; | ||||||
13039 | } else { | ||||||
13040 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||||
13041 | return false; | ||||||
13042 | } | ||||||
13043 | |||||||
13044 | return true; | ||||||
13045 | } | ||||||
13046 | |||||||
13047 | /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some | ||||||
13048 | /// cases, the in-place evaluation is essential, since later initializers for | ||||||
13049 | /// an object can indirectly refer to subobjects which were initialized earlier. | ||||||
13050 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, | ||||||
13051 | const Expr *E, bool AllowNonLiteralTypes) { | ||||||
13052 | assert(!E->isValueDependent())((!E->isValueDependent()) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13052, __PRETTY_FUNCTION__)); | ||||||
13053 | |||||||
13054 | if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) | ||||||
13055 | return false; | ||||||
13056 | |||||||
13057 | if (E->isRValue()) { | ||||||
13058 | // Evaluate arrays and record types in-place, so that later initializers can | ||||||
13059 | // refer to earlier-initialized members of the object. | ||||||
13060 | QualType T = E->getType(); | ||||||
13061 | if (T->isArrayType()) | ||||||
13062 | return EvaluateArray(E, This, Result, Info); | ||||||
13063 | else if (T->isRecordType()) | ||||||
13064 | return EvaluateRecord(E, This, Result, Info); | ||||||
13065 | else if (T->isAtomicType()) { | ||||||
13066 | QualType Unqual = T.getAtomicUnqualifiedType(); | ||||||
13067 | if (Unqual->isArrayType() || Unqual->isRecordType()) | ||||||
13068 | return EvaluateAtomic(E, &This, Result, Info); | ||||||
13069 | } | ||||||
13070 | } | ||||||
13071 | |||||||
13072 | // For any other type, in-place evaluation is unimportant. | ||||||
13073 | return Evaluate(Result, Info, E); | ||||||
13074 | } | ||||||
13075 | |||||||
13076 | /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit | ||||||
13077 | /// lvalue-to-rvalue cast if it is an lvalue. | ||||||
13078 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { | ||||||
13079 | if (Info.EnableNewConstInterp) { | ||||||
13080 | auto &InterpCtx = Info.Ctx.getInterpContext(); | ||||||
13081 | switch (InterpCtx.evaluateAsRValue(Info, E, Result)) { | ||||||
13082 | case interp::InterpResult::Success: | ||||||
13083 | return true; | ||||||
13084 | case interp::InterpResult::Fail: | ||||||
13085 | return false; | ||||||
13086 | case interp::InterpResult::Bail: | ||||||
13087 | break; | ||||||
13088 | } | ||||||
13089 | } | ||||||
13090 | |||||||
13091 | if (E->getType().isNull()) | ||||||
13092 | return false; | ||||||
13093 | |||||||
13094 | if (!CheckLiteralType(Info, E)) | ||||||
13095 | return false; | ||||||
13096 | |||||||
13097 | if (!::Evaluate(Result, Info, E)) | ||||||
13098 | return false; | ||||||
13099 | |||||||
13100 | if (E->isGLValue()) { | ||||||
13101 | LValue LV; | ||||||
13102 | LV.setFrom(Info.Ctx, Result); | ||||||
13103 | if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) | ||||||
13104 | return false; | ||||||
13105 | } | ||||||
13106 | |||||||
13107 | // Check this core constant expression is a constant expression. | ||||||
13108 | return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && | ||||||
13109 | CheckMemoryLeaks(Info); | ||||||
13110 | } | ||||||
13111 | |||||||
13112 | static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, | ||||||
13113 | const ASTContext &Ctx, bool &IsConst) { | ||||||
13114 | // Fast-path evaluations of integer literals, since we sometimes see files | ||||||
13115 | // containing vast quantities of these. | ||||||
13116 | if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { | ||||||
13117 | Result.Val = APValue(APSInt(L->getValue(), | ||||||
13118 | L->getType()->isUnsignedIntegerType())); | ||||||
13119 | IsConst = true; | ||||||
13120 | return true; | ||||||
13121 | } | ||||||
13122 | |||||||
13123 | // This case should be rare, but we need to check it before we check on | ||||||
13124 | // the type below. | ||||||
13125 | if (Exp->getType().isNull()) { | ||||||
13126 | IsConst = false; | ||||||
13127 | return true; | ||||||
13128 | } | ||||||
13129 | |||||||
13130 | // FIXME: Evaluating values of large array and record types can cause | ||||||
13131 | // performance problems. Only do so in C++11 for now. | ||||||
13132 | if (Exp->isRValue() && (Exp->getType()->isArrayType() || | ||||||
13133 | Exp->getType()->isRecordType()) && | ||||||
13134 | !Ctx.getLangOpts().CPlusPlus11) { | ||||||
13135 | IsConst = false; | ||||||
13136 | return true; | ||||||
13137 | } | ||||||
13138 | return false; | ||||||
13139 | } | ||||||
13140 | |||||||
13141 | static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, | ||||||
13142 | Expr::SideEffectsKind SEK) { | ||||||
13143 | return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || | ||||||
13144 | (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); | ||||||
13145 | } | ||||||
13146 | |||||||
13147 | static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, | ||||||
13148 | const ASTContext &Ctx, EvalInfo &Info) { | ||||||
13149 | bool IsConst; | ||||||
13150 | if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) | ||||||
13151 | return IsConst; | ||||||
13152 | |||||||
13153 | return EvaluateAsRValue(Info, E, Result.Val); | ||||||
13154 | } | ||||||
13155 | |||||||
13156 | static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, | ||||||
13157 | const ASTContext &Ctx, | ||||||
13158 | Expr::SideEffectsKind AllowSideEffects, | ||||||
13159 | EvalInfo &Info) { | ||||||
13160 | if (!E->getType()->isIntegralOrEnumerationType()) | ||||||
13161 | return false; | ||||||
13162 | |||||||
13163 | if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || | ||||||
13164 | !ExprResult.Val.isInt() || | ||||||
13165 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||||
13166 | return false; | ||||||
13167 | |||||||
13168 | return true; | ||||||
13169 | } | ||||||
13170 | |||||||
13171 | static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, | ||||||
13172 | const ASTContext &Ctx, | ||||||
13173 | Expr::SideEffectsKind AllowSideEffects, | ||||||
13174 | EvalInfo &Info) { | ||||||
13175 | if (!E->getType()->isFixedPointType()) | ||||||
13176 | return false; | ||||||
13177 | |||||||
13178 | if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) | ||||||
13179 | return false; | ||||||
13180 | |||||||
13181 | if (!ExprResult.Val.isFixedPoint() || | ||||||
13182 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||||
13183 | return false; | ||||||
13184 | |||||||
13185 | return true; | ||||||
13186 | } | ||||||
13187 | |||||||
13188 | /// EvaluateAsRValue - Return true if this is a constant which we can fold using | ||||||
13189 | /// any crazy technique (that has nothing to do with language standards) that | ||||||
13190 | /// we want to. If this function returns true, it returns the folded constant | ||||||
13191 | /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion | ||||||
13192 | /// will be applied to the result. | ||||||
13193 | bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, | ||||||
13194 | bool InConstantContext) const { | ||||||
13195 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13196, __PRETTY_FUNCTION__)) | ||||||
13196 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13196, __PRETTY_FUNCTION__)); | ||||||
13197 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||||
13198 | Info.InConstantContext = InConstantContext; | ||||||
13199 | return ::EvaluateAsRValue(this, Result, Ctx, Info); | ||||||
13200 | } | ||||||
13201 | |||||||
13202 | bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, | ||||||
13203 | bool InConstantContext) const { | ||||||
13204 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13205, __PRETTY_FUNCTION__)) | ||||||
13205 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13205, __PRETTY_FUNCTION__)); | ||||||
13206 | EvalResult Scratch; | ||||||
13207 | return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && | ||||||
13208 | HandleConversionToBool(Scratch.Val, Result); | ||||||
13209 | } | ||||||
13210 | |||||||
13211 | bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, | ||||||
13212 | SideEffectsKind AllowSideEffects, | ||||||
13213 | bool InConstantContext) const { | ||||||
13214 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13215, __PRETTY_FUNCTION__)) | ||||||
13215 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13215, __PRETTY_FUNCTION__)); | ||||||
13216 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||||
13217 | Info.InConstantContext = InConstantContext; | ||||||
13218 | return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); | ||||||
13219 | } | ||||||
13220 | |||||||
13221 | bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, | ||||||
13222 | SideEffectsKind AllowSideEffects, | ||||||
13223 | bool InConstantContext) const { | ||||||
13224 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13225, __PRETTY_FUNCTION__)) | ||||||
13225 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13225, __PRETTY_FUNCTION__)); | ||||||
13226 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||||
13227 | Info.InConstantContext = InConstantContext; | ||||||
13228 | return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); | ||||||
13229 | } | ||||||
13230 | |||||||
13231 | bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, | ||||||
13232 | SideEffectsKind AllowSideEffects, | ||||||
13233 | bool InConstantContext) const { | ||||||
13234 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13235, __PRETTY_FUNCTION__)) | ||||||
13235 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13235, __PRETTY_FUNCTION__)); | ||||||
13236 | |||||||
13237 | if (!getType()->isRealFloatingType()) | ||||||
13238 | return false; | ||||||
13239 | |||||||
13240 | EvalResult ExprResult; | ||||||
13241 | if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || | ||||||
13242 | !ExprResult.Val.isFloat() || | ||||||
13243 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||||
13244 | return false; | ||||||
13245 | |||||||
13246 | Result = ExprResult.Val.getFloat(); | ||||||
13247 | return true; | ||||||
13248 | } | ||||||
13249 | |||||||
13250 | bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, | ||||||
13251 | bool InConstantContext) const { | ||||||
13252 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13253, __PRETTY_FUNCTION__)) | ||||||
13253 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13253, __PRETTY_FUNCTION__)); | ||||||
13254 | |||||||
13255 | EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); | ||||||
13256 | Info.InConstantContext = InConstantContext; | ||||||
13257 | LValue LV; | ||||||
13258 | CheckedTemporaries CheckedTemps; | ||||||
13259 | if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || | ||||||
13260 | Result.HasSideEffects || | ||||||
13261 | !CheckLValueConstantExpression(Info, getExprLoc(), | ||||||
13262 | Ctx.getLValueReferenceType(getType()), LV, | ||||||
13263 | Expr::EvaluateForCodeGen, CheckedTemps)) | ||||||
13264 | return false; | ||||||
13265 | |||||||
13266 | LV.moveInto(Result.Val); | ||||||
13267 | return true; | ||||||
13268 | } | ||||||
13269 | |||||||
13270 | bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, | ||||||
13271 | const ASTContext &Ctx) const { | ||||||
13272 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13273, __PRETTY_FUNCTION__)) | ||||||
13273 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13273, __PRETTY_FUNCTION__)); | ||||||
13274 | |||||||
13275 | EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; | ||||||
13276 | EvalInfo Info(Ctx, Result, EM); | ||||||
13277 | Info.InConstantContext = true; | ||||||
13278 | |||||||
13279 | if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) | ||||||
13280 | return false; | ||||||
13281 | |||||||
13282 | if (!Info.discardCleanups()) | ||||||
13283 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13283); | ||||||
13284 | |||||||
13285 | return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, | ||||||
13286 | Usage) && | ||||||
13287 | CheckMemoryLeaks(Info); | ||||||
13288 | } | ||||||
13289 | |||||||
13290 | bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, | ||||||
13291 | const VarDecl *VD, | ||||||
13292 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const { | ||||||
13293 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13294, __PRETTY_FUNCTION__)) | ||||||
13294 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13294, __PRETTY_FUNCTION__)); | ||||||
13295 | |||||||
13296 | // FIXME: Evaluating initializers for large array and record types can cause | ||||||
13297 | // performance problems. Only do so in C++11 for now. | ||||||
13298 | if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && | ||||||
13299 | !Ctx.getLangOpts().CPlusPlus11) | ||||||
13300 | return false; | ||||||
13301 | |||||||
13302 | Expr::EvalStatus EStatus; | ||||||
13303 | EStatus.Diag = &Notes; | ||||||
13304 | |||||||
13305 | EvalInfo Info(Ctx, EStatus, VD->isConstexpr() | ||||||
13306 | ? EvalInfo::EM_ConstantExpression | ||||||
13307 | : EvalInfo::EM_ConstantFold); | ||||||
13308 | Info.setEvaluatingDecl(VD, Value); | ||||||
13309 | Info.InConstantContext = true; | ||||||
13310 | |||||||
13311 | SourceLocation DeclLoc = VD->getLocation(); | ||||||
13312 | QualType DeclTy = VD->getType(); | ||||||
13313 | |||||||
13314 | if (Info.EnableNewConstInterp) { | ||||||
13315 | auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); | ||||||
13316 | switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) { | ||||||
13317 | case interp::InterpResult::Fail: | ||||||
13318 | // Bail out if an error was encountered. | ||||||
13319 | return false; | ||||||
13320 | case interp::InterpResult::Success: | ||||||
13321 | // Evaluation succeeded and value was set. | ||||||
13322 | return CheckConstantExpression(Info, DeclLoc, DeclTy, Value); | ||||||
13323 | case interp::InterpResult::Bail: | ||||||
13324 | // Evaluate the value again for the tree evaluator to use. | ||||||
13325 | break; | ||||||
13326 | } | ||||||
13327 | } | ||||||
13328 | |||||||
13329 | LValue LVal; | ||||||
13330 | LVal.set(VD); | ||||||
13331 | |||||||
13332 | // C++11 [basic.start.init]p2: | ||||||
13333 | // Variables with static storage duration or thread storage duration shall be | ||||||
13334 | // zero-initialized before any other initialization takes place. | ||||||
13335 | // This behavior is not present in C. | ||||||
13336 | if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && | ||||||
13337 | !DeclTy->isReferenceType()) { | ||||||
13338 | ImplicitValueInitExpr VIE(DeclTy); | ||||||
13339 | if (!EvaluateInPlace(Value, Info, LVal, &VIE, | ||||||
13340 | /*AllowNonLiteralTypes=*/true)) | ||||||
13341 | return false; | ||||||
13342 | } | ||||||
13343 | |||||||
13344 | if (!EvaluateInPlace(Value, Info, LVal, this, | ||||||
13345 | /*AllowNonLiteralTypes=*/true) || | ||||||
13346 | EStatus.HasSideEffects) | ||||||
13347 | return false; | ||||||
13348 | |||||||
13349 | // At this point, any lifetime-extended temporaries are completely | ||||||
13350 | // initialized. | ||||||
13351 | Info.performLifetimeExtension(); | ||||||
13352 | |||||||
13353 | if (!Info.discardCleanups()) | ||||||
13354 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13354); | ||||||
13355 | |||||||
13356 | return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && | ||||||
13357 | CheckMemoryLeaks(Info); | ||||||
13358 | } | ||||||
13359 | |||||||
13360 | bool VarDecl::evaluateDestruction( | ||||||
13361 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const { | ||||||
13362 | assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&((getEvaluatedValue() && !getEvaluatedValue()->isAbsent () && "cannot evaluate destruction of non-constant-initialized variable" ) ? static_cast<void> (0) : __assert_fail ("getEvaluatedValue() && !getEvaluatedValue()->isAbsent() && \"cannot evaluate destruction of non-constant-initialized variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13363, __PRETTY_FUNCTION__)) | ||||||
13363 | "cannot evaluate destruction of non-constant-initialized variable")((getEvaluatedValue() && !getEvaluatedValue()->isAbsent () && "cannot evaluate destruction of non-constant-initialized variable" ) ? static_cast<void> (0) : __assert_fail ("getEvaluatedValue() && !getEvaluatedValue()->isAbsent() && \"cannot evaluate destruction of non-constant-initialized variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13363, __PRETTY_FUNCTION__)); | ||||||
13364 | |||||||
13365 | Expr::EvalStatus EStatus; | ||||||
13366 | EStatus.Diag = &Notes; | ||||||
13367 | |||||||
13368 | // Make a copy of the value for the destructor to mutate. | ||||||
13369 | APValue DestroyedValue = *getEvaluatedValue(); | ||||||
13370 | |||||||
13371 | EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); | ||||||
13372 | Info.setEvaluatingDecl(this, DestroyedValue, | ||||||
13373 | EvalInfo::EvaluatingDeclKind::Dtor); | ||||||
13374 | Info.InConstantContext = true; | ||||||
13375 | |||||||
13376 | SourceLocation DeclLoc = getLocation(); | ||||||
13377 | QualType DeclTy = getType(); | ||||||
13378 | |||||||
13379 | LValue LVal; | ||||||
13380 | LVal.set(this); | ||||||
13381 | |||||||
13382 | // FIXME: Consider storing whether this variable has constant destruction in | ||||||
13383 | // the EvaluatedStmt so that CodeGen can query it. | ||||||
13384 | if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || | ||||||
13385 | EStatus.HasSideEffects) | ||||||
13386 | return false; | ||||||
13387 | |||||||
13388 | if (!Info.discardCleanups()) | ||||||
13389 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13389); | ||||||
13390 | |||||||
13391 | ensureEvaluatedStmt()->HasConstantDestruction = true; | ||||||
13392 | return true; | ||||||
13393 | } | ||||||
13394 | |||||||
13395 | /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be | ||||||
13396 | /// constant folded, but discard the result. | ||||||
13397 | bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { | ||||||
13398 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13399, __PRETTY_FUNCTION__)) | ||||||
13399 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13399, __PRETTY_FUNCTION__)); | ||||||
13400 | |||||||
13401 | EvalResult Result; | ||||||
13402 | return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && | ||||||
13403 | !hasUnacceptableSideEffect(Result, SEK); | ||||||
13404 | } | ||||||
13405 | |||||||
13406 | APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, | ||||||
13407 | SmallVectorImpl<PartialDiagnosticAt> *Diag) const { | ||||||
13408 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13409, __PRETTY_FUNCTION__)) | ||||||
13409 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13409, __PRETTY_FUNCTION__)); | ||||||
13410 | |||||||
13411 | EvalResult EVResult; | ||||||
13412 | EVResult.Diag = Diag; | ||||||
13413 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||||
13414 | Info.InConstantContext = true; | ||||||
13415 | |||||||
13416 | bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); | ||||||
13417 | (void)Result; | ||||||
13418 | assert(Result && "Could not evaluate expression")((Result && "Could not evaluate expression") ? static_cast <void> (0) : __assert_fail ("Result && \"Could not evaluate expression\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13418, __PRETTY_FUNCTION__)); | ||||||
13419 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")((EVResult.Val.isInt() && "Expression did not evaluate to integer" ) ? static_cast<void> (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13419, __PRETTY_FUNCTION__)); | ||||||
13420 | |||||||
13421 | return EVResult.Val.getInt(); | ||||||
13422 | } | ||||||
13423 | |||||||
13424 | APSInt Expr::EvaluateKnownConstIntCheckOverflow( | ||||||
13425 | const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { | ||||||
13426 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13427, __PRETTY_FUNCTION__)) | ||||||
13427 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13427, __PRETTY_FUNCTION__)); | ||||||
13428 | |||||||
13429 | EvalResult EVResult; | ||||||
13430 | EVResult.Diag = Diag; | ||||||
13431 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||||
13432 | Info.InConstantContext = true; | ||||||
13433 | Info.CheckingForUndefinedBehavior = true; | ||||||
13434 | |||||||
13435 | bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); | ||||||
13436 | (void)Result; | ||||||
13437 | assert(Result && "Could not evaluate expression")((Result && "Could not evaluate expression") ? static_cast <void> (0) : __assert_fail ("Result && \"Could not evaluate expression\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13437, __PRETTY_FUNCTION__)); | ||||||
13438 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")((EVResult.Val.isInt() && "Expression did not evaluate to integer" ) ? static_cast<void> (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13438, __PRETTY_FUNCTION__)); | ||||||
13439 | |||||||
13440 | return EVResult.Val.getInt(); | ||||||
13441 | } | ||||||
13442 | |||||||
13443 | void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { | ||||||
13444 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13445, __PRETTY_FUNCTION__)) | ||||||
13445 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13445, __PRETTY_FUNCTION__)); | ||||||
13446 | |||||||
13447 | bool IsConst; | ||||||
13448 | EvalResult EVResult; | ||||||
13449 | if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { | ||||||
13450 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||||
13451 | Info.CheckingForUndefinedBehavior = true; | ||||||
13452 | (void)::EvaluateAsRValue(Info, this, EVResult.Val); | ||||||
13453 | } | ||||||
13454 | } | ||||||
13455 | |||||||
13456 | bool Expr::EvalResult::isGlobalLValue() const { | ||||||
13457 | assert(Val.isLValue())((Val.isLValue()) ? static_cast<void> (0) : __assert_fail ("Val.isLValue()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13457, __PRETTY_FUNCTION__)); | ||||||
13458 | return IsGlobalLValue(Val.getLValueBase()); | ||||||
13459 | } | ||||||
13460 | |||||||
13461 | |||||||
13462 | /// isIntegerConstantExpr - this recursive routine will test if an expression is | ||||||
13463 | /// an integer constant expression. | ||||||
13464 | |||||||
13465 | /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, | ||||||
13466 | /// comma, etc | ||||||
13467 | |||||||
13468 | // CheckICE - This function does the fundamental ICE checking: the returned | ||||||
13469 | // ICEDiag contains an ICEKind indicating whether the expression is an ICE, | ||||||
13470 | // and a (possibly null) SourceLocation indicating the location of the problem. | ||||||
13471 | // | ||||||
13472 | // Note that to reduce code duplication, this helper does no evaluation | ||||||
13473 | // itself; the caller checks whether the expression is evaluatable, and | ||||||
13474 | // in the rare cases where CheckICE actually cares about the evaluated | ||||||
13475 | // value, it calls into Evaluate. | ||||||
13476 | |||||||
13477 | namespace { | ||||||
13478 | |||||||
13479 | enum ICEKind { | ||||||
13480 | /// This expression is an ICE. | ||||||
13481 | IK_ICE, | ||||||
13482 | /// This expression is not an ICE, but if it isn't evaluated, it's | ||||||
13483 | /// a legal subexpression for an ICE. This return value is used to handle | ||||||
13484 | /// the comma operator in C99 mode, and non-constant subexpressions. | ||||||
13485 | IK_ICEIfUnevaluated, | ||||||
13486 | /// This expression is not an ICE, and is not a legal subexpression for one. | ||||||
13487 | IK_NotICE | ||||||
13488 | }; | ||||||
13489 | |||||||
13490 | struct ICEDiag { | ||||||
13491 | ICEKind Kind; | ||||||
13492 | SourceLocation Loc; | ||||||
13493 | |||||||
13494 | ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} | ||||||
13495 | }; | ||||||
13496 | |||||||
13497 | } | ||||||
13498 | |||||||
13499 | static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } | ||||||
13500 | |||||||
13501 | static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } | ||||||
13502 | |||||||
13503 | static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { | ||||||
13504 | Expr::EvalResult EVResult; | ||||||
13505 | Expr::EvalStatus Status; | ||||||
13506 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); | ||||||
13507 | |||||||
13508 | Info.InConstantContext = true; | ||||||
13509 | if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || | ||||||
13510 | !EVResult.Val.isInt()) | ||||||
13511 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13512 | |||||||
13513 | return NoDiag(); | ||||||
13514 | } | ||||||
13515 | |||||||
13516 | static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { | ||||||
13517 | assert(!E->isValueDependent() && "Should not see value dependent exprs!")((!E->isValueDependent() && "Should not see value dependent exprs!" ) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Should not see value dependent exprs!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13517, __PRETTY_FUNCTION__)); | ||||||
13518 | if (!E->getType()->isIntegralOrEnumerationType()) | ||||||
13519 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13520 | |||||||
13521 | switch (E->getStmtClass()) { | ||||||
13522 | #define ABSTRACT_STMT(Node) | ||||||
13523 | #define STMT(Node, Base) case Expr::Node##Class: | ||||||
13524 | #define EXPR(Node, Base) | ||||||
13525 | #include "clang/AST/StmtNodes.inc" | ||||||
13526 | case Expr::PredefinedExprClass: | ||||||
13527 | case Expr::FloatingLiteralClass: | ||||||
13528 | case Expr::ImaginaryLiteralClass: | ||||||
13529 | case Expr::StringLiteralClass: | ||||||
13530 | case Expr::ArraySubscriptExprClass: | ||||||
13531 | case Expr::OMPArraySectionExprClass: | ||||||
13532 | case Expr::MemberExprClass: | ||||||
13533 | case Expr::CompoundAssignOperatorClass: | ||||||
13534 | case Expr::CompoundLiteralExprClass: | ||||||
13535 | case Expr::ExtVectorElementExprClass: | ||||||
13536 | case Expr::DesignatedInitExprClass: | ||||||
13537 | case Expr::ArrayInitLoopExprClass: | ||||||
13538 | case Expr::ArrayInitIndexExprClass: | ||||||
13539 | case Expr::NoInitExprClass: | ||||||
13540 | case Expr::DesignatedInitUpdateExprClass: | ||||||
13541 | case Expr::ImplicitValueInitExprClass: | ||||||
13542 | case Expr::ParenListExprClass: | ||||||
13543 | case Expr::VAArgExprClass: | ||||||
13544 | case Expr::AddrLabelExprClass: | ||||||
13545 | case Expr::StmtExprClass: | ||||||
13546 | case Expr::CXXMemberCallExprClass: | ||||||
13547 | case Expr::CUDAKernelCallExprClass: | ||||||
13548 | case Expr::CXXDynamicCastExprClass: | ||||||
13549 | case Expr::CXXTypeidExprClass: | ||||||
13550 | case Expr::CXXUuidofExprClass: | ||||||
13551 | case Expr::MSPropertyRefExprClass: | ||||||
13552 | case Expr::MSPropertySubscriptExprClass: | ||||||
13553 | case Expr::CXXNullPtrLiteralExprClass: | ||||||
13554 | case Expr::UserDefinedLiteralClass: | ||||||
13555 | case Expr::CXXThisExprClass: | ||||||
13556 | case Expr::CXXThrowExprClass: | ||||||
13557 | case Expr::CXXNewExprClass: | ||||||
13558 | case Expr::CXXDeleteExprClass: | ||||||
13559 | case Expr::CXXPseudoDestructorExprClass: | ||||||
13560 | case Expr::UnresolvedLookupExprClass: | ||||||
13561 | case Expr::TypoExprClass: | ||||||
13562 | case Expr::DependentScopeDeclRefExprClass: | ||||||
13563 | case Expr::CXXConstructExprClass: | ||||||
13564 | case Expr::CXXInheritedCtorInitExprClass: | ||||||
13565 | case Expr::CXXStdInitializerListExprClass: | ||||||
13566 | case Expr::CXXBindTemporaryExprClass: | ||||||
13567 | case Expr::ExprWithCleanupsClass: | ||||||
13568 | case Expr::CXXTemporaryObjectExprClass: | ||||||
13569 | case Expr::CXXUnresolvedConstructExprClass: | ||||||
13570 | case Expr::CXXDependentScopeMemberExprClass: | ||||||
13571 | case Expr::UnresolvedMemberExprClass: | ||||||
13572 | case Expr::ObjCStringLiteralClass: | ||||||
13573 | case Expr::ObjCBoxedExprClass: | ||||||
13574 | case Expr::ObjCArrayLiteralClass: | ||||||
13575 | case Expr::ObjCDictionaryLiteralClass: | ||||||
13576 | case Expr::ObjCEncodeExprClass: | ||||||
13577 | case Expr::ObjCMessageExprClass: | ||||||
13578 | case Expr::ObjCSelectorExprClass: | ||||||
13579 | case Expr::ObjCProtocolExprClass: | ||||||
13580 | case Expr::ObjCIvarRefExprClass: | ||||||
13581 | case Expr::ObjCPropertyRefExprClass: | ||||||
13582 | case Expr::ObjCSubscriptRefExprClass: | ||||||
13583 | case Expr::ObjCIsaExprClass: | ||||||
13584 | case Expr::ObjCAvailabilityCheckExprClass: | ||||||
13585 | case Expr::ShuffleVectorExprClass: | ||||||
13586 | case Expr::ConvertVectorExprClass: | ||||||
13587 | case Expr::BlockExprClass: | ||||||
13588 | case Expr::NoStmtClass: | ||||||
13589 | case Expr::OpaqueValueExprClass: | ||||||
13590 | case Expr::PackExpansionExprClass: | ||||||
13591 | case Expr::SubstNonTypeTemplateParmPackExprClass: | ||||||
13592 | case Expr::FunctionParmPackExprClass: | ||||||
13593 | case Expr::AsTypeExprClass: | ||||||
13594 | case Expr::ObjCIndirectCopyRestoreExprClass: | ||||||
13595 | case Expr::MaterializeTemporaryExprClass: | ||||||
13596 | case Expr::PseudoObjectExprClass: | ||||||
13597 | case Expr::AtomicExprClass: | ||||||
13598 | case Expr::LambdaExprClass: | ||||||
13599 | case Expr::CXXFoldExprClass: | ||||||
13600 | case Expr::CoawaitExprClass: | ||||||
13601 | case Expr::DependentCoawaitExprClass: | ||||||
13602 | case Expr::CoyieldExprClass: | ||||||
13603 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13604 | |||||||
13605 | case Expr::InitListExprClass: { | ||||||
13606 | // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the | ||||||
13607 | // form "T x = { a };" is equivalent to "T x = a;". | ||||||
13608 | // Unless we're initializing a reference, T is a scalar as it is known to be | ||||||
13609 | // of integral or enumeration type. | ||||||
13610 | if (E->isRValue()) | ||||||
13611 | if (cast<InitListExpr>(E)->getNumInits() == 1) | ||||||
13612 | return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); | ||||||
13613 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13614 | } | ||||||
13615 | |||||||
13616 | case Expr::SizeOfPackExprClass: | ||||||
13617 | case Expr::GNUNullExprClass: | ||||||
13618 | case Expr::SourceLocExprClass: | ||||||
13619 | return NoDiag(); | ||||||
13620 | |||||||
13621 | case Expr::SubstNonTypeTemplateParmExprClass: | ||||||
13622 | return | ||||||
13623 | CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); | ||||||
13624 | |||||||
13625 | case Expr::ConstantExprClass: | ||||||
13626 | return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); | ||||||
13627 | |||||||
13628 | case Expr::ParenExprClass: | ||||||
13629 | return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); | ||||||
13630 | case Expr::GenericSelectionExprClass: | ||||||
13631 | return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); | ||||||
13632 | case Expr::IntegerLiteralClass: | ||||||
13633 | case Expr::FixedPointLiteralClass: | ||||||
13634 | case Expr::CharacterLiteralClass: | ||||||
13635 | case Expr::ObjCBoolLiteralExprClass: | ||||||
13636 | case Expr::CXXBoolLiteralExprClass: | ||||||
13637 | case Expr::CXXScalarValueInitExprClass: | ||||||
13638 | case Expr::TypeTraitExprClass: | ||||||
13639 | case Expr::ArrayTypeTraitExprClass: | ||||||
13640 | case Expr::ExpressionTraitExprClass: | ||||||
13641 | case Expr::CXXNoexceptExprClass: | ||||||
13642 | return NoDiag(); | ||||||
13643 | case Expr::CallExprClass: | ||||||
13644 | case Expr::CXXOperatorCallExprClass: { | ||||||
13645 | // C99 6.6/3 allows function calls within unevaluated subexpressions of | ||||||
13646 | // constant expressions, but they can never be ICEs because an ICE cannot | ||||||
13647 | // contain an operand of (pointer to) function type. | ||||||
13648 | const CallExpr *CE = cast<CallExpr>(E); | ||||||
13649 | if (CE->getBuiltinCallee()) | ||||||
13650 | return CheckEvalInICE(E, Ctx); | ||||||
13651 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13652 | } | ||||||
13653 | case Expr::DeclRefExprClass: { | ||||||
13654 | if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) | ||||||
13655 | return NoDiag(); | ||||||
13656 | const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); | ||||||
13657 | if (Ctx.getLangOpts().CPlusPlus && | ||||||
13658 | D && IsConstNonVolatile(D->getType())) { | ||||||
13659 | // Parameter variables are never constants. Without this check, | ||||||
13660 | // getAnyInitializer() can find a default argument, which leads | ||||||
13661 | // to chaos. | ||||||
13662 | if (isa<ParmVarDecl>(D)) | ||||||
13663 | return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); | ||||||
13664 | |||||||
13665 | // C++ 7.1.5.1p2 | ||||||
13666 | // A variable of non-volatile const-qualified integral or enumeration | ||||||
13667 | // type initialized by an ICE can be used in ICEs. | ||||||
13668 | if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { | ||||||
13669 | if (!Dcl->getType()->isIntegralOrEnumerationType()) | ||||||
13670 | return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); | ||||||
13671 | |||||||
13672 | const VarDecl *VD; | ||||||
13673 | // Look for a declaration of this variable that has an initializer, and | ||||||
13674 | // check whether it is an ICE. | ||||||
13675 | if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) | ||||||
13676 | return NoDiag(); | ||||||
13677 | else | ||||||
13678 | return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); | ||||||
13679 | } | ||||||
13680 | } | ||||||
13681 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13682 | } | ||||||
13683 | case Expr::UnaryOperatorClass: { | ||||||
13684 | const UnaryOperator *Exp = cast<UnaryOperator>(E); | ||||||
13685 | switch (Exp->getOpcode()) { | ||||||
13686 | case UO_PostInc: | ||||||
13687 | case UO_PostDec: | ||||||
13688 | case UO_PreInc: | ||||||
13689 | case UO_PreDec: | ||||||
13690 | case UO_AddrOf: | ||||||
13691 | case UO_Deref: | ||||||
13692 | case UO_Coawait: | ||||||
13693 | // C99 6.6/3 allows increment and decrement within unevaluated | ||||||
13694 | // subexpressions of constant expressions, but they can never be ICEs | ||||||
13695 | // because an ICE cannot contain an lvalue operand. | ||||||
13696 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13697 | case UO_Extension: | ||||||
13698 | case UO_LNot: | ||||||
13699 | case UO_Plus: | ||||||
13700 | case UO_Minus: | ||||||
13701 | case UO_Not: | ||||||
13702 | case UO_Real: | ||||||
13703 | case UO_Imag: | ||||||
13704 | return CheckICE(Exp->getSubExpr(), Ctx); | ||||||
13705 | } | ||||||
13706 | llvm_unreachable("invalid unary operator class")::llvm::llvm_unreachable_internal("invalid unary operator class" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13706); | ||||||
13707 | } | ||||||
13708 | case Expr::OffsetOfExprClass: { | ||||||
13709 | // Note that per C99, offsetof must be an ICE. And AFAIK, using | ||||||
13710 | // EvaluateAsRValue matches the proposed gcc behavior for cases like | ||||||
13711 | // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect | ||||||
13712 | // compliance: we should warn earlier for offsetof expressions with | ||||||
13713 | // array subscripts that aren't ICEs, and if the array subscripts | ||||||
13714 | // are ICEs, the value of the offsetof must be an integer constant. | ||||||
13715 | return CheckEvalInICE(E, Ctx); | ||||||
13716 | } | ||||||
13717 | case Expr::UnaryExprOrTypeTraitExprClass: { | ||||||
13718 | const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); | ||||||
13719 | if ((Exp->getKind() == UETT_SizeOf) && | ||||||
13720 | Exp->getTypeOfArgument()->isVariableArrayType()) | ||||||
13721 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13722 | return NoDiag(); | ||||||
13723 | } | ||||||
13724 | case Expr::BinaryOperatorClass: { | ||||||
13725 | const BinaryOperator *Exp = cast<BinaryOperator>(E); | ||||||
13726 | switch (Exp->getOpcode()) { | ||||||
13727 | case BO_PtrMemD: | ||||||
13728 | case BO_PtrMemI: | ||||||
13729 | case BO_Assign: | ||||||
13730 | case BO_MulAssign: | ||||||
13731 | case BO_DivAssign: | ||||||
13732 | case BO_RemAssign: | ||||||
13733 | case BO_AddAssign: | ||||||
13734 | case BO_SubAssign: | ||||||
13735 | case BO_ShlAssign: | ||||||
13736 | case BO_ShrAssign: | ||||||
13737 | case BO_AndAssign: | ||||||
13738 | case BO_XorAssign: | ||||||
13739 | case BO_OrAssign: | ||||||
13740 | // C99 6.6/3 allows assignments within unevaluated subexpressions of | ||||||
13741 | // constant expressions, but they can never be ICEs because an ICE cannot | ||||||
13742 | // contain an lvalue operand. | ||||||
13743 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13744 | |||||||
13745 | case BO_Mul: | ||||||
13746 | case BO_Div: | ||||||
13747 | case BO_Rem: | ||||||
13748 | case BO_Add: | ||||||
13749 | case BO_Sub: | ||||||
13750 | case BO_Shl: | ||||||
13751 | case BO_Shr: | ||||||
13752 | case BO_LT: | ||||||
13753 | case BO_GT: | ||||||
13754 | case BO_LE: | ||||||
13755 | case BO_GE: | ||||||
13756 | case BO_EQ: | ||||||
13757 | case BO_NE: | ||||||
13758 | case BO_And: | ||||||
13759 | case BO_Xor: | ||||||
13760 | case BO_Or: | ||||||
13761 | case BO_Comma: | ||||||
13762 | case BO_Cmp: { | ||||||
13763 | ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); | ||||||
13764 | ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); | ||||||
13765 | if (Exp->getOpcode() == BO_Div || | ||||||
13766 | Exp->getOpcode() == BO_Rem) { | ||||||
13767 | // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure | ||||||
13768 | // we don't evaluate one. | ||||||
13769 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { | ||||||
13770 | llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); | ||||||
13771 | if (REval == 0) | ||||||
13772 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||||
13773 | if (REval.isSigned() && REval.isAllOnesValue()) { | ||||||
13774 | llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); | ||||||
13775 | if (LEval.isMinSignedValue()) | ||||||
13776 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||||
13777 | } | ||||||
13778 | } | ||||||
13779 | } | ||||||
13780 | if (Exp->getOpcode() == BO_Comma) { | ||||||
13781 | if (Ctx.getLangOpts().C99) { | ||||||
13782 | // C99 6.6p3 introduces a strange edge case: comma can be in an ICE | ||||||
13783 | // if it isn't evaluated. | ||||||
13784 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) | ||||||
13785 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||||
13786 | } else { | ||||||
13787 | // In both C89 and C++, commas in ICEs are illegal. | ||||||
13788 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13789 | } | ||||||
13790 | } | ||||||
13791 | return Worst(LHSResult, RHSResult); | ||||||
13792 | } | ||||||
13793 | case BO_LAnd: | ||||||
13794 | case BO_LOr: { | ||||||
13795 | ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); | ||||||
13796 | ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); | ||||||
13797 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { | ||||||
13798 | // Rare case where the RHS has a comma "side-effect"; we need | ||||||
13799 | // to actually check the condition to see whether the side | ||||||
13800 | // with the comma is evaluated. | ||||||
13801 | if ((Exp->getOpcode() == BO_LAnd) != | ||||||
13802 | (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) | ||||||
13803 | return RHSResult; | ||||||
13804 | return NoDiag(); | ||||||
13805 | } | ||||||
13806 | |||||||
13807 | return Worst(LHSResult, RHSResult); | ||||||
13808 | } | ||||||
13809 | } | ||||||
13810 | llvm_unreachable("invalid binary operator kind")::llvm::llvm_unreachable_internal("invalid binary operator kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13810); | ||||||
13811 | } | ||||||
13812 | case Expr::ImplicitCastExprClass: | ||||||
13813 | case Expr::CStyleCastExprClass: | ||||||
13814 | case Expr::CXXFunctionalCastExprClass: | ||||||
13815 | case Expr::CXXStaticCastExprClass: | ||||||
13816 | case Expr::CXXReinterpretCastExprClass: | ||||||
13817 | case Expr::CXXConstCastExprClass: | ||||||
13818 | case Expr::ObjCBridgedCastExprClass: { | ||||||
13819 | const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); | ||||||
13820 | if (isa<ExplicitCastExpr>(E)) { | ||||||
13821 | if (const FloatingLiteral *FL | ||||||
13822 | = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { | ||||||
13823 | unsigned DestWidth = Ctx.getIntWidth(E->getType()); | ||||||
13824 | bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); | ||||||
13825 | APSInt IgnoredVal(DestWidth, !DestSigned); | ||||||
13826 | bool Ignored; | ||||||
13827 | // If the value does not fit in the destination type, the behavior is | ||||||
13828 | // undefined, so we are not required to treat it as a constant | ||||||
13829 | // expression. | ||||||
13830 | if (FL->getValue().convertToInteger(IgnoredVal, | ||||||
13831 | llvm::APFloat::rmTowardZero, | ||||||
13832 | &Ignored) & APFloat::opInvalidOp) | ||||||
13833 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13834 | return NoDiag(); | ||||||
13835 | } | ||||||
13836 | } | ||||||
13837 | switch (cast<CastExpr>(E)->getCastKind()) { | ||||||
13838 | case CK_LValueToRValue: | ||||||
13839 | case CK_AtomicToNonAtomic: | ||||||
13840 | case CK_NonAtomicToAtomic: | ||||||
13841 | case CK_NoOp: | ||||||
13842 | case CK_IntegralToBoolean: | ||||||
13843 | case CK_IntegralCast: | ||||||
13844 | return CheckICE(SubExpr, Ctx); | ||||||
13845 | default: | ||||||
13846 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13847 | } | ||||||
13848 | } | ||||||
13849 | case Expr::BinaryConditionalOperatorClass: { | ||||||
13850 | const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); | ||||||
13851 | ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); | ||||||
13852 | if (CommonResult.Kind == IK_NotICE) return CommonResult; | ||||||
13853 | ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); | ||||||
13854 | if (FalseResult.Kind == IK_NotICE) return FalseResult; | ||||||
13855 | if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; | ||||||
13856 | if (FalseResult.Kind == IK_ICEIfUnevaluated && | ||||||
13857 | Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); | ||||||
13858 | return FalseResult; | ||||||
13859 | } | ||||||
13860 | case Expr::ConditionalOperatorClass: { | ||||||
13861 | const ConditionalOperator *Exp = cast<ConditionalOperator>(E); | ||||||
13862 | // If the condition (ignoring parens) is a __builtin_constant_p call, | ||||||
13863 | // then only the true side is actually considered in an integer constant | ||||||
13864 | // expression, and it is fully evaluated. This is an important GNU | ||||||
13865 | // extension. See GCC PR38377 for discussion. | ||||||
13866 | if (const CallExpr *CallCE | ||||||
13867 | = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) | ||||||
13868 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) | ||||||
13869 | return CheckEvalInICE(E, Ctx); | ||||||
13870 | ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); | ||||||
13871 | if (CondResult.Kind == IK_NotICE) | ||||||
13872 | return CondResult; | ||||||
13873 | |||||||
13874 | ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); | ||||||
13875 | ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); | ||||||
13876 | |||||||
13877 | if (TrueResult.Kind == IK_NotICE) | ||||||
13878 | return TrueResult; | ||||||
13879 | if (FalseResult.Kind == IK_NotICE) | ||||||
13880 | return FalseResult; | ||||||
13881 | if (CondResult.Kind == IK_ICEIfUnevaluated) | ||||||
13882 | return CondResult; | ||||||
13883 | if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) | ||||||
13884 | return NoDiag(); | ||||||
13885 | // Rare case where the diagnostics depend on which side is evaluated | ||||||
13886 | // Note that if we get here, CondResult is 0, and at least one of | ||||||
13887 | // TrueResult and FalseResult is non-zero. | ||||||
13888 | if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) | ||||||
13889 | return FalseResult; | ||||||
13890 | return TrueResult; | ||||||
13891 | } | ||||||
13892 | case Expr::CXXDefaultArgExprClass: | ||||||
13893 | return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); | ||||||
13894 | case Expr::CXXDefaultInitExprClass: | ||||||
13895 | return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); | ||||||
13896 | case Expr::ChooseExprClass: { | ||||||
13897 | return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); | ||||||
13898 | } | ||||||
13899 | case Expr::BuiltinBitCastExprClass: { | ||||||
13900 | if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) | ||||||
13901 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||||
13902 | return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); | ||||||
13903 | } | ||||||
13904 | } | ||||||
13905 | |||||||
13906 | llvm_unreachable("Invalid StmtClass!")::llvm::llvm_unreachable_internal("Invalid StmtClass!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13906); | ||||||
13907 | } | ||||||
13908 | |||||||
13909 | /// Evaluate an expression as a C++11 integral constant expression. | ||||||
13910 | static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, | ||||||
13911 | const Expr *E, | ||||||
13912 | llvm::APSInt *Value, | ||||||
13913 | SourceLocation *Loc) { | ||||||
13914 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||||
13915 | if (Loc) *Loc = E->getExprLoc(); | ||||||
13916 | return false; | ||||||
13917 | } | ||||||
13918 | |||||||
13919 | APValue Result; | ||||||
13920 | if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) | ||||||
13921 | return false; | ||||||
13922 | |||||||
13923 | if (!Result.isInt()) { | ||||||
13924 | if (Loc) *Loc = E->getExprLoc(); | ||||||
13925 | return false; | ||||||
13926 | } | ||||||
13927 | |||||||
13928 | if (Value) *Value = Result.getInt(); | ||||||
13929 | return true; | ||||||
13930 | } | ||||||
13931 | |||||||
13932 | bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, | ||||||
13933 | SourceLocation *Loc) const { | ||||||
13934 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13935, __PRETTY_FUNCTION__)) | ||||||
13935 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13935, __PRETTY_FUNCTION__)); | ||||||
13936 | |||||||
13937 | if (Ctx.getLangOpts().CPlusPlus11) | ||||||
13938 | return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); | ||||||
13939 | |||||||
13940 | ICEDiag D = CheckICE(this, Ctx); | ||||||
13941 | if (D.Kind != IK_ICE) { | ||||||
13942 | if (Loc) *Loc = D.Loc; | ||||||
13943 | return false; | ||||||
13944 | } | ||||||
13945 | return true; | ||||||
13946 | } | ||||||
13947 | |||||||
13948 | bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, | ||||||
13949 | SourceLocation *Loc, bool isEvaluated) const { | ||||||
13950 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13951, __PRETTY_FUNCTION__)) | ||||||
13951 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13951, __PRETTY_FUNCTION__)); | ||||||
13952 | |||||||
13953 | if (Ctx.getLangOpts().CPlusPlus11) | ||||||
13954 | return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); | ||||||
13955 | |||||||
13956 | if (!isIntegerConstantExpr(Ctx, Loc)) | ||||||
13957 | return false; | ||||||
13958 | |||||||
13959 | // The only possible side-effects here are due to UB discovered in the | ||||||
13960 | // evaluation (for instance, INT_MAX + 1). In such a case, we are still | ||||||
13961 | // required to treat the expression as an ICE, so we produce the folded | ||||||
13962 | // value. | ||||||
13963 | EvalResult ExprResult; | ||||||
13964 | Expr::EvalStatus Status; | ||||||
13965 | EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); | ||||||
13966 | Info.InConstantContext = true; | ||||||
13967 | |||||||
13968 | if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) | ||||||
13969 | llvm_unreachable("ICE cannot be evaluated!")::llvm::llvm_unreachable_internal("ICE cannot be evaluated!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13969); | ||||||
13970 | |||||||
13971 | Value = ExprResult.Val.getInt(); | ||||||
13972 | return true; | ||||||
13973 | } | ||||||
13974 | |||||||
13975 | bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { | ||||||
13976 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13977, __PRETTY_FUNCTION__)) | ||||||
13977 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13977, __PRETTY_FUNCTION__)); | ||||||
13978 | |||||||
13979 | return CheckICE(this, Ctx).Kind == IK_ICE; | ||||||
13980 | } | ||||||
13981 | |||||||
13982 | bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, | ||||||
13983 | SourceLocation *Loc) const { | ||||||
13984 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13985, __PRETTY_FUNCTION__)) | ||||||
13985 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13985, __PRETTY_FUNCTION__)); | ||||||
13986 | |||||||
13987 | // We support this checking in C++98 mode in order to diagnose compatibility | ||||||
13988 | // issues. | ||||||
13989 | assert(Ctx.getLangOpts().CPlusPlus)((Ctx.getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13989, __PRETTY_FUNCTION__)); | ||||||
13990 | |||||||
13991 | // Build evaluation settings. | ||||||
13992 | Expr::EvalStatus Status; | ||||||
13993 | SmallVector<PartialDiagnosticAt, 8> Diags; | ||||||
13994 | Status.Diag = &Diags; | ||||||
13995 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); | ||||||
13996 | |||||||
13997 | APValue Scratch; | ||||||
13998 | bool IsConstExpr = | ||||||
13999 | ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && | ||||||
14000 | // FIXME: We don't produce a diagnostic for this, but the callers that | ||||||
14001 | // call us on arbitrary full-expressions should generally not care. | ||||||
14002 | Info.discardCleanups() && !Status.HasSideEffects; | ||||||
14003 | |||||||
14004 | if (!Diags.empty()) { | ||||||
14005 | IsConstExpr = false; | ||||||
14006 | if (Loc) *Loc = Diags[0].first; | ||||||
14007 | } else if (!IsConstExpr) { | ||||||
14008 | // FIXME: This shouldn't happen. | ||||||
14009 | if (Loc) *Loc = getExprLoc(); | ||||||
14010 | } | ||||||
14011 | |||||||
14012 | return IsConstExpr; | ||||||
14013 | } | ||||||
14014 | |||||||
14015 | bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, | ||||||
14016 | const FunctionDecl *Callee, | ||||||
14017 | ArrayRef<const Expr*> Args, | ||||||
14018 | const Expr *This) const { | ||||||
14019 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14020, __PRETTY_FUNCTION__)) | ||||||
14020 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14020, __PRETTY_FUNCTION__)); | ||||||
14021 | |||||||
14022 | Expr::EvalStatus Status; | ||||||
14023 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); | ||||||
14024 | Info.InConstantContext = true; | ||||||
14025 | |||||||
14026 | LValue ThisVal; | ||||||
14027 | const LValue *ThisPtr = nullptr; | ||||||
14028 | if (This) { | ||||||
14029 | #ifndef NDEBUG | ||||||
14030 | auto *MD = dyn_cast<CXXMethodDecl>(Callee); | ||||||
14031 | assert(MD && "Don't provide `this` for non-methods.")((MD && "Don't provide `this` for non-methods.") ? static_cast <void> (0) : __assert_fail ("MD && \"Don't provide `this` for non-methods.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14031, __PRETTY_FUNCTION__)); | ||||||
14032 | assert(!MD->isStatic() && "Don't provide `this` for static methods.")((!MD->isStatic() && "Don't provide `this` for static methods." ) ? static_cast<void> (0) : __assert_fail ("!MD->isStatic() && \"Don't provide `this` for static methods.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14032, __PRETTY_FUNCTION__)); | ||||||
14033 | #endif | ||||||
14034 | if (EvaluateObjectArgument(Info, This, ThisVal)) | ||||||
14035 | ThisPtr = &ThisVal; | ||||||
14036 | if (Info.EvalStatus.HasSideEffects) | ||||||
14037 | return false; | ||||||
14038 | } | ||||||
14039 | |||||||
14040 | ArgVector ArgValues(Args.size()); | ||||||
14041 | for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); | ||||||
14042 | I != E; ++I) { | ||||||
14043 | if ((*I)->isValueDependent() || | ||||||
14044 | !Evaluate(ArgValues[I - Args.begin()], Info, *I)) | ||||||
14045 | // If evaluation fails, throw away the argument entirely. | ||||||
14046 | ArgValues[I - Args.begin()] = APValue(); | ||||||
14047 | if (Info.EvalStatus.HasSideEffects) | ||||||
14048 | return false; | ||||||
14049 | } | ||||||
14050 | |||||||
14051 | // Build fake call to Callee. | ||||||
14052 | CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, | ||||||
14053 | ArgValues.data()); | ||||||
14054 | return Evaluate(Value, Info, this) && Info.discardCleanups() && | ||||||
14055 | !Info.EvalStatus.HasSideEffects; | ||||||
14056 | } | ||||||
14057 | |||||||
14058 | bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, | ||||||
14059 | SmallVectorImpl< | ||||||
14060 | PartialDiagnosticAt> &Diags) { | ||||||
14061 | // FIXME: It would be useful to check constexpr function templates, but at the | ||||||
14062 | // moment the constant expression evaluator cannot cope with the non-rigorous | ||||||
14063 | // ASTs which we build for dependent expressions. | ||||||
14064 | if (FD->isDependentContext()) | ||||||
14065 | return true; | ||||||
14066 | |||||||
14067 | Expr::EvalStatus Status; | ||||||
14068 | Status.Diag = &Diags; | ||||||
14069 | |||||||
14070 | EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); | ||||||
14071 | Info.InConstantContext = true; | ||||||
14072 | Info.CheckingPotentialConstantExpression = true; | ||||||
14073 | |||||||
14074 | // The constexpr VM attempts to compile all methods to bytecode here. | ||||||
14075 | if (Info.EnableNewConstInterp) { | ||||||
14076 | auto &InterpCtx = Info.Ctx.getInterpContext(); | ||||||
14077 | switch (InterpCtx.isPotentialConstantExpr(Info, FD)) { | ||||||
14078 | case interp::InterpResult::Success: | ||||||
14079 | case interp::InterpResult::Fail: | ||||||
14080 | return Diags.empty(); | ||||||
14081 | case interp::InterpResult::Bail: | ||||||
14082 | break; | ||||||
14083 | } | ||||||
14084 | } | ||||||
14085 | |||||||
14086 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||||
14087 | const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; | ||||||
14088 | |||||||
14089 | // Fabricate an arbitrary expression on the stack and pretend that it | ||||||
14090 | // is a temporary being used as the 'this' pointer. | ||||||
14091 | LValue This; | ||||||
14092 | ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); | ||||||
14093 | This.set({&VIE, Info.CurrentCall->Index}); | ||||||
14094 | |||||||
14095 | ArrayRef<const Expr*> Args; | ||||||
14096 | |||||||
14097 | APValue Scratch; | ||||||
14098 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { | ||||||
14099 | // Evaluate the call as a constant initializer, to allow the construction | ||||||
14100 | // of objects of non-literal types. | ||||||
14101 | Info.setEvaluatingDecl(This.getLValueBase(), Scratch); | ||||||
14102 | HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); | ||||||
14103 | } else { | ||||||
14104 | SourceLocation Loc = FD->getLocation(); | ||||||
14105 | HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, | ||||||
14106 | Args, FD->getBody(), Info, Scratch, nullptr); | ||||||
14107 | } | ||||||
14108 | |||||||
14109 | return Diags.empty(); | ||||||
14110 | } | ||||||
14111 | |||||||
14112 | bool Expr::isPotentialConstantExprUnevaluated(Expr *E, | ||||||
14113 | const FunctionDecl *FD, | ||||||
14114 | SmallVectorImpl< | ||||||
14115 | PartialDiagnosticAt> &Diags) { | ||||||
14116 | assert(!E->isValueDependent() &&((!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14117, __PRETTY_FUNCTION__)) | ||||||
14117 | "Expression evaluator can't be called on a dependent expression.")((!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14117, __PRETTY_FUNCTION__)); | ||||||
14118 | |||||||
14119 | Expr::EvalStatus Status; | ||||||
14120 | Status.Diag = &Diags; | ||||||
14121 | |||||||
14122 | EvalInfo Info(FD->getASTContext(), Status, | ||||||
14123 | EvalInfo::EM_ConstantExpressionUnevaluated); | ||||||
14124 | Info.InConstantContext = true; | ||||||
14125 | Info.CheckingPotentialConstantExpression = true; | ||||||
14126 | |||||||
14127 | // Fabricate a call stack frame to give the arguments a plausible cover story. | ||||||
14128 | ArrayRef<const Expr*> Args; | ||||||
14129 | ArgVector ArgValues(0); | ||||||
14130 | bool Success = EvaluateArgs(Args, ArgValues, Info, FD); | ||||||
14131 | (void)Success; | ||||||
14132 | assert(Success &&((Success && "Failed to set up arguments for potential constant evaluation" ) ? static_cast<void> (0) : __assert_fail ("Success && \"Failed to set up arguments for potential constant evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14133, __PRETTY_FUNCTION__)) | ||||||
14133 | "Failed to set up arguments for potential constant evaluation")((Success && "Failed to set up arguments for potential constant evaluation" ) ? static_cast<void> (0) : __assert_fail ("Success && \"Failed to set up arguments for potential constant evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14133, __PRETTY_FUNCTION__)); | ||||||
14134 | CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); | ||||||
14135 | |||||||
14136 | APValue ResultScratch; | ||||||
14137 | Evaluate(ResultScratch, Info, E); | ||||||
14138 | return Diags.empty(); | ||||||
14139 | } | ||||||
14140 | |||||||
14141 | bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, | ||||||
14142 | unsigned Type) const { | ||||||
14143 | if (!getType()->isPointerType()) | ||||||
14144 | return false; | ||||||
14145 | |||||||
14146 | Expr::EvalStatus Status; | ||||||
14147 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); | ||||||
14148 | return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); | ||||||
14149 | } |
1 | //===--- Expr.h - Classes for representing expressions ----------*- 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 Expr interface and subclasses. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_AST_EXPR_H |
14 | #define LLVM_CLANG_AST_EXPR_H |
15 | |
16 | #include "clang/AST/APValue.h" |
17 | #include "clang/AST/ASTVector.h" |
18 | #include "clang/AST/Decl.h" |
19 | #include "clang/AST/DeclAccessPair.h" |
20 | #include "clang/AST/OperationKinds.h" |
21 | #include "clang/AST/Stmt.h" |
22 | #include "clang/AST/TemplateBase.h" |
23 | #include "clang/AST/Type.h" |
24 | #include "clang/Basic/CharInfo.h" |
25 | #include "clang/Basic/FixedPoint.h" |
26 | #include "clang/Basic/LangOptions.h" |
27 | #include "clang/Basic/SyncScope.h" |
28 | #include "clang/Basic/TypeTraits.h" |
29 | #include "llvm/ADT/APFloat.h" |
30 | #include "llvm/ADT/APSInt.h" |
31 | #include "llvm/ADT/iterator.h" |
32 | #include "llvm/ADT/iterator_range.h" |
33 | #include "llvm/ADT/SmallVector.h" |
34 | #include "llvm/ADT/StringRef.h" |
35 | #include "llvm/Support/AtomicOrdering.h" |
36 | #include "llvm/Support/Compiler.h" |
37 | #include "llvm/Support/TrailingObjects.h" |
38 | |
39 | namespace clang { |
40 | class APValue; |
41 | class ASTContext; |
42 | class BlockDecl; |
43 | class CXXBaseSpecifier; |
44 | class CXXMemberCallExpr; |
45 | class CXXOperatorCallExpr; |
46 | class CastExpr; |
47 | class Decl; |
48 | class IdentifierInfo; |
49 | class MaterializeTemporaryExpr; |
50 | class NamedDecl; |
51 | class ObjCPropertyRefExpr; |
52 | class OpaqueValueExpr; |
53 | class ParmVarDecl; |
54 | class StringLiteral; |
55 | class TargetInfo; |
56 | class ValueDecl; |
57 | |
58 | /// A simple array of base specifiers. |
59 | typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; |
60 | |
61 | /// An adjustment to be made to the temporary created when emitting a |
62 | /// reference binding, which accesses a particular subobject of that temporary. |
63 | struct SubobjectAdjustment { |
64 | enum { |
65 | DerivedToBaseAdjustment, |
66 | FieldAdjustment, |
67 | MemberPointerAdjustment |
68 | } Kind; |
69 | |
70 | struct DTB { |
71 | const CastExpr *BasePath; |
72 | const CXXRecordDecl *DerivedClass; |
73 | }; |
74 | |
75 | struct P { |
76 | const MemberPointerType *MPT; |
77 | Expr *RHS; |
78 | }; |
79 | |
80 | union { |
81 | struct DTB DerivedToBase; |
82 | FieldDecl *Field; |
83 | struct P Ptr; |
84 | }; |
85 | |
86 | SubobjectAdjustment(const CastExpr *BasePath, |
87 | const CXXRecordDecl *DerivedClass) |
88 | : Kind(DerivedToBaseAdjustment) { |
89 | DerivedToBase.BasePath = BasePath; |
90 | DerivedToBase.DerivedClass = DerivedClass; |
91 | } |
92 | |
93 | SubobjectAdjustment(FieldDecl *Field) |
94 | : Kind(FieldAdjustment) { |
95 | this->Field = Field; |
96 | } |
97 | |
98 | SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS) |
99 | : Kind(MemberPointerAdjustment) { |
100 | this->Ptr.MPT = MPT; |
101 | this->Ptr.RHS = RHS; |
102 | } |
103 | }; |
104 | |
105 | /// This represents one expression. Note that Expr's are subclasses of Stmt. |
106 | /// This allows an expression to be transparently used any place a Stmt is |
107 | /// required. |
108 | class Expr : public ValueStmt { |
109 | QualType TR; |
110 | |
111 | public: |
112 | Expr() = delete; |
113 | Expr(const Expr&) = delete; |
114 | Expr(Expr &&) = delete; |
115 | Expr &operator=(const Expr&) = delete; |
116 | Expr &operator=(Expr&&) = delete; |
117 | |
118 | protected: |
119 | Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, |
120 | bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack) |
121 | : ValueStmt(SC) |
122 | { |
123 | ExprBits.TypeDependent = TD; |
124 | ExprBits.ValueDependent = VD; |
125 | ExprBits.InstantiationDependent = ID; |
126 | ExprBits.ValueKind = VK; |
127 | ExprBits.ObjectKind = OK; |
128 | assert(ExprBits.ObjectKind == OK && "truncated kind")((ExprBits.ObjectKind == OK && "truncated kind") ? static_cast <void> (0) : __assert_fail ("ExprBits.ObjectKind == OK && \"truncated kind\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 128, __PRETTY_FUNCTION__)); |
129 | ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
130 | setType(T); |
131 | } |
132 | |
133 | /// Construct an empty expression. |
134 | explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { } |
135 | |
136 | public: |
137 | QualType getType() const { return TR; } |
138 | void setType(QualType t) { |
139 | // In C++, the type of an expression is always adjusted so that it |
140 | // will not have reference type (C++ [expr]p6). Use |
141 | // QualType::getNonReferenceType() to retrieve the non-reference |
142 | // type. Additionally, inspect Expr::isLvalue to determine whether |
143 | // an expression that is adjusted in this manner should be |
144 | // considered an lvalue. |
145 | assert((t.isNull() || !t->isReferenceType()) &&(((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type" ) ? static_cast<void> (0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 146, __PRETTY_FUNCTION__)) |
146 | "Expressions can't have reference type")(((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type" ) ? static_cast<void> (0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 146, __PRETTY_FUNCTION__)); |
147 | |
148 | TR = t; |
149 | } |
150 | |
151 | /// isValueDependent - Determines whether this expression is |
152 | /// value-dependent (C++ [temp.dep.constexpr]). For example, the |
153 | /// array bound of "Chars" in the following example is |
154 | /// value-dependent. |
155 | /// @code |
156 | /// template<int Size, char (&Chars)[Size]> struct meta_string; |
157 | /// @endcode |
158 | bool isValueDependent() const { return ExprBits.ValueDependent; } |
159 | |
160 | /// Set whether this expression is value-dependent or not. |
161 | void setValueDependent(bool VD) { |
162 | ExprBits.ValueDependent = VD; |
163 | } |
164 | |
165 | /// isTypeDependent - Determines whether this expression is |
166 | /// type-dependent (C++ [temp.dep.expr]), which means that its type |
167 | /// could change from one template instantiation to the next. For |
168 | /// example, the expressions "x" and "x + y" are type-dependent in |
169 | /// the following code, but "y" is not type-dependent: |
170 | /// @code |
171 | /// template<typename T> |
172 | /// void add(T x, int y) { |
173 | /// x + y; |
174 | /// } |
175 | /// @endcode |
176 | bool isTypeDependent() const { return ExprBits.TypeDependent; } |
177 | |
178 | /// Set whether this expression is type-dependent or not. |
179 | void setTypeDependent(bool TD) { |
180 | ExprBits.TypeDependent = TD; |
181 | } |
182 | |
183 | /// Whether this expression is instantiation-dependent, meaning that |
184 | /// it depends in some way on a template parameter, even if neither its type |
185 | /// nor (constant) value can change due to the template instantiation. |
186 | /// |
187 | /// In the following example, the expression \c sizeof(sizeof(T() + T())) is |
188 | /// instantiation-dependent (since it involves a template parameter \c T), but |
189 | /// is neither type- nor value-dependent, since the type of the inner |
190 | /// \c sizeof is known (\c std::size_t) and therefore the size of the outer |
191 | /// \c sizeof is known. |
192 | /// |
193 | /// \code |
194 | /// template<typename T> |
195 | /// void f(T x, T y) { |
196 | /// sizeof(sizeof(T() + T()); |
197 | /// } |
198 | /// \endcode |
199 | /// |
200 | bool isInstantiationDependent() const { |
201 | return ExprBits.InstantiationDependent; |
202 | } |
203 | |
204 | /// Set whether this expression is instantiation-dependent or not. |
205 | void setInstantiationDependent(bool ID) { |
206 | ExprBits.InstantiationDependent = ID; |
207 | } |
208 | |
209 | /// Whether this expression contains an unexpanded parameter |
210 | /// pack (for C++11 variadic templates). |
211 | /// |
212 | /// Given the following function template: |
213 | /// |
214 | /// \code |
215 | /// template<typename F, typename ...Types> |
216 | /// void forward(const F &f, Types &&...args) { |
217 | /// f(static_cast<Types&&>(args)...); |
218 | /// } |
219 | /// \endcode |
220 | /// |
221 | /// The expressions \c args and \c static_cast<Types&&>(args) both |
222 | /// contain parameter packs. |
223 | bool containsUnexpandedParameterPack() const { |
224 | return ExprBits.ContainsUnexpandedParameterPack; |
225 | } |
226 | |
227 | /// Set the bit that describes whether this expression |
228 | /// contains an unexpanded parameter pack. |
229 | void setContainsUnexpandedParameterPack(bool PP = true) { |
230 | ExprBits.ContainsUnexpandedParameterPack = PP; |
231 | } |
232 | |
233 | /// getExprLoc - Return the preferred location for the arrow when diagnosing |
234 | /// a problem with a generic expression. |
235 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)); |
236 | |
237 | /// isUnusedResultAWarning - Return true if this immediate expression should |
238 | /// be warned about if the result is unused. If so, fill in expr, location, |
239 | /// and ranges with expr to warn on and source locations/ranges appropriate |
240 | /// for a warning. |
241 | bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, |
242 | SourceRange &R1, SourceRange &R2, |
243 | ASTContext &Ctx) const; |
244 | |
245 | /// isLValue - True if this expression is an "l-value" according to |
246 | /// the rules of the current language. C and C++ give somewhat |
247 | /// different rules for this concept, but in general, the result of |
248 | /// an l-value expression identifies a specific object whereas the |
249 | /// result of an r-value expression is a value detached from any |
250 | /// specific storage. |
251 | /// |
252 | /// C++11 divides the concept of "r-value" into pure r-values |
253 | /// ("pr-values") and so-called expiring values ("x-values"), which |
254 | /// identify specific objects that can be safely cannibalized for |
255 | /// their resources. This is an unfortunate abuse of terminology on |
256 | /// the part of the C++ committee. In Clang, when we say "r-value", |
257 | /// we generally mean a pr-value. |
258 | bool isLValue() const { return getValueKind() == VK_LValue; } |
259 | bool isRValue() const { return getValueKind() == VK_RValue; } |
260 | bool isXValue() const { return getValueKind() == VK_XValue; } |
261 | bool isGLValue() const { return getValueKind() != VK_RValue; } |
262 | |
263 | enum LValueClassification { |
264 | LV_Valid, |
265 | LV_NotObjectType, |
266 | LV_IncompleteVoidType, |
267 | LV_DuplicateVectorComponents, |
268 | LV_InvalidExpression, |
269 | LV_InvalidMessageExpression, |
270 | LV_MemberFunction, |
271 | LV_SubObjCPropertySetting, |
272 | LV_ClassTemporary, |
273 | LV_ArrayTemporary |
274 | }; |
275 | /// Reasons why an expression might not be an l-value. |
276 | LValueClassification ClassifyLValue(ASTContext &Ctx) const; |
277 | |
278 | enum isModifiableLvalueResult { |
279 | MLV_Valid, |
280 | MLV_NotObjectType, |
281 | MLV_IncompleteVoidType, |
282 | MLV_DuplicateVectorComponents, |
283 | MLV_InvalidExpression, |
284 | MLV_LValueCast, // Specialized form of MLV_InvalidExpression. |
285 | MLV_IncompleteType, |
286 | MLV_ConstQualified, |
287 | MLV_ConstQualifiedField, |
288 | MLV_ConstAddrSpace, |
289 | MLV_ArrayType, |
290 | MLV_NoSetterProperty, |
291 | MLV_MemberFunction, |
292 | MLV_SubObjCPropertySetting, |
293 | MLV_InvalidMessageExpression, |
294 | MLV_ClassTemporary, |
295 | MLV_ArrayTemporary |
296 | }; |
297 | /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, |
298 | /// does not have an incomplete type, does not have a const-qualified type, |
299 | /// and if it is a structure or union, does not have any member (including, |
300 | /// recursively, any member or element of all contained aggregates or unions) |
301 | /// with a const-qualified type. |
302 | /// |
303 | /// \param Loc [in,out] - A source location which *may* be filled |
304 | /// in with the location of the expression making this a |
305 | /// non-modifiable lvalue, if specified. |
306 | isModifiableLvalueResult |
307 | isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const; |
308 | |
309 | /// The return type of classify(). Represents the C++11 expression |
310 | /// taxonomy. |
311 | class Classification { |
312 | public: |
313 | /// The various classification results. Most of these mean prvalue. |
314 | enum Kinds { |
315 | CL_LValue, |
316 | CL_XValue, |
317 | CL_Function, // Functions cannot be lvalues in C. |
318 | CL_Void, // Void cannot be an lvalue in C. |
319 | CL_AddressableVoid, // Void expression whose address can be taken in C. |
320 | CL_DuplicateVectorComponents, // A vector shuffle with dupes. |
321 | CL_MemberFunction, // An expression referring to a member function |
322 | CL_SubObjCPropertySetting, |
323 | CL_ClassTemporary, // A temporary of class type, or subobject thereof. |
324 | CL_ArrayTemporary, // A temporary of array type. |
325 | CL_ObjCMessageRValue, // ObjC message is an rvalue |
326 | CL_PRValue // A prvalue for any other reason, of any other type |
327 | }; |
328 | /// The results of modification testing. |
329 | enum ModifiableType { |
330 | CM_Untested, // testModifiable was false. |
331 | CM_Modifiable, |
332 | CM_RValue, // Not modifiable because it's an rvalue |
333 | CM_Function, // Not modifiable because it's a function; C++ only |
334 | CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext |
335 | CM_NoSetterProperty,// Implicit assignment to ObjC property without setter |
336 | CM_ConstQualified, |
337 | CM_ConstQualifiedField, |
338 | CM_ConstAddrSpace, |
339 | CM_ArrayType, |
340 | CM_IncompleteType |
341 | }; |
342 | |
343 | private: |
344 | friend class Expr; |
345 | |
346 | unsigned short Kind; |
347 | unsigned short Modifiable; |
348 | |
349 | explicit Classification(Kinds k, ModifiableType m) |
350 | : Kind(k), Modifiable(m) |
351 | {} |
352 | |
353 | public: |
354 | Classification() {} |
355 | |
356 | Kinds getKind() const { return static_cast<Kinds>(Kind); } |
357 | ModifiableType getModifiable() const { |
358 | assert(Modifiable != CM_Untested && "Did not test for modifiability.")((Modifiable != CM_Untested && "Did not test for modifiability." ) ? static_cast<void> (0) : __assert_fail ("Modifiable != CM_Untested && \"Did not test for modifiability.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 358, __PRETTY_FUNCTION__)); |
359 | return static_cast<ModifiableType>(Modifiable); |
360 | } |
361 | bool isLValue() const { return Kind == CL_LValue; } |
362 | bool isXValue() const { return Kind == CL_XValue; } |
363 | bool isGLValue() const { return Kind <= CL_XValue; } |
364 | bool isPRValue() const { return Kind >= CL_Function; } |
365 | bool isRValue() const { return Kind >= CL_XValue; } |
366 | bool isModifiable() const { return getModifiable() == CM_Modifiable; } |
367 | |
368 | /// Create a simple, modifiably lvalue |
369 | static Classification makeSimpleLValue() { |
370 | return Classification(CL_LValue, CM_Modifiable); |
371 | } |
372 | |
373 | }; |
374 | /// Classify - Classify this expression according to the C++11 |
375 | /// expression taxonomy. |
376 | /// |
377 | /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the |
378 | /// old lvalue vs rvalue. This function determines the type of expression this |
379 | /// is. There are three expression types: |
380 | /// - lvalues are classical lvalues as in C++03. |
381 | /// - prvalues are equivalent to rvalues in C++03. |
382 | /// - xvalues are expressions yielding unnamed rvalue references, e.g. a |
383 | /// function returning an rvalue reference. |
384 | /// lvalues and xvalues are collectively referred to as glvalues, while |
385 | /// prvalues and xvalues together form rvalues. |
386 | Classification Classify(ASTContext &Ctx) const { |
387 | return ClassifyImpl(Ctx, nullptr); |
388 | } |
389 | |
390 | /// ClassifyModifiable - Classify this expression according to the |
391 | /// C++11 expression taxonomy, and see if it is valid on the left side |
392 | /// of an assignment. |
393 | /// |
394 | /// This function extends classify in that it also tests whether the |
395 | /// expression is modifiable (C99 6.3.2.1p1). |
396 | /// \param Loc A source location that might be filled with a relevant location |
397 | /// if the expression is not modifiable. |
398 | Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{ |
399 | return ClassifyImpl(Ctx, &Loc); |
400 | } |
401 | |
402 | /// getValueKindForType - Given a formal return or parameter type, |
403 | /// give its value kind. |
404 | static ExprValueKind getValueKindForType(QualType T) { |
405 | if (const ReferenceType *RT = T->getAs<ReferenceType>()) |
406 | return (isa<LValueReferenceType>(RT) |
407 | ? VK_LValue |
408 | : (RT->getPointeeType()->isFunctionType() |
409 | ? VK_LValue : VK_XValue)); |
410 | return VK_RValue; |
411 | } |
412 | |
413 | /// getValueKind - The value kind that this expression produces. |
414 | ExprValueKind getValueKind() const { |
415 | return static_cast<ExprValueKind>(ExprBits.ValueKind); |
416 | } |
417 | |
418 | /// getObjectKind - The object kind that this expression produces. |
419 | /// Object kinds are meaningful only for expressions that yield an |
420 | /// l-value or x-value. |
421 | ExprObjectKind getObjectKind() const { |
422 | return static_cast<ExprObjectKind>(ExprBits.ObjectKind); |
423 | } |
424 | |
425 | bool isOrdinaryOrBitFieldObject() const { |
426 | ExprObjectKind OK = getObjectKind(); |
427 | return (OK == OK_Ordinary || OK == OK_BitField); |
428 | } |
429 | |
430 | /// setValueKind - Set the value kind produced by this expression. |
431 | void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; } |
432 | |
433 | /// setObjectKind - Set the object kind produced by this expression. |
434 | void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; } |
435 | |
436 | private: |
437 | Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; |
438 | |
439 | public: |
440 | |
441 | /// Returns true if this expression is a gl-value that |
442 | /// potentially refers to a bit-field. |
443 | /// |
444 | /// In C++, whether a gl-value refers to a bitfield is essentially |
445 | /// an aspect of the value-kind type system. |
446 | bool refersToBitField() const { return getObjectKind() == OK_BitField; } |
447 | |
448 | /// If this expression refers to a bit-field, retrieve the |
449 | /// declaration of that bit-field. |
450 | /// |
451 | /// Note that this returns a non-null pointer in subtly different |
452 | /// places than refersToBitField returns true. In particular, this can |
453 | /// return a non-null pointer even for r-values loaded from |
454 | /// bit-fields, but it will return null for a conditional bit-field. |
455 | FieldDecl *getSourceBitField(); |
456 | |
457 | const FieldDecl *getSourceBitField() const { |
458 | return const_cast<Expr*>(this)->getSourceBitField(); |
459 | } |
460 | |
461 | Decl *getReferencedDeclOfCallee(); |
462 | const Decl *getReferencedDeclOfCallee() const { |
463 | return const_cast<Expr*>(this)->getReferencedDeclOfCallee(); |
464 | } |
465 | |
466 | /// If this expression is an l-value for an Objective C |
467 | /// property, find the underlying property reference expression. |
468 | const ObjCPropertyRefExpr *getObjCProperty() const; |
469 | |
470 | /// Check if this expression is the ObjC 'self' implicit parameter. |
471 | bool isObjCSelfExpr() const; |
472 | |
473 | /// Returns whether this expression refers to a vector element. |
474 | bool refersToVectorElement() const; |
475 | |
476 | /// Returns whether this expression refers to a global register |
477 | /// variable. |
478 | bool refersToGlobalRegisterVar() const; |
479 | |
480 | /// Returns whether this expression has a placeholder type. |
481 | bool hasPlaceholderType() const { |
482 | return getType()->isPlaceholderType(); |
483 | } |
484 | |
485 | /// Returns whether this expression has a specific placeholder type. |
486 | bool hasPlaceholderType(BuiltinType::Kind K) const { |
487 | assert(BuiltinType::isPlaceholderTypeKind(K))((BuiltinType::isPlaceholderTypeKind(K)) ? static_cast<void > (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind(K)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 487, __PRETTY_FUNCTION__)); |
488 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType())) |
489 | return BT->getKind() == K; |
490 | return false; |
491 | } |
492 | |
493 | /// isKnownToHaveBooleanValue - Return true if this is an integer expression |
494 | /// that is known to return 0 or 1. This happens for _Bool/bool expressions |
495 | /// but also int expressions which are produced by things like comparisons in |
496 | /// C. |
497 | bool isKnownToHaveBooleanValue() const; |
498 | |
499 | /// isIntegerConstantExpr - Return true if this expression is a valid integer |
500 | /// constant expression, and, if so, return its value in Result. If not a |
501 | /// valid i-c-e, return false and fill in Loc (if specified) with the location |
502 | /// of the invalid expression. |
503 | /// |
504 | /// Note: This does not perform the implicit conversions required by C++11 |
505 | /// [expr.const]p5. |
506 | bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, |
507 | SourceLocation *Loc = nullptr, |
508 | bool isEvaluated = true) const; |
509 | bool isIntegerConstantExpr(const ASTContext &Ctx, |
510 | SourceLocation *Loc = nullptr) const; |
511 | |
512 | /// isCXX98IntegralConstantExpr - Return true if this expression is an |
513 | /// integral constant expression in C++98. Can only be used in C++. |
514 | bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const; |
515 | |
516 | /// isCXX11ConstantExpr - Return true if this expression is a constant |
517 | /// expression in C++11. Can only be used in C++. |
518 | /// |
519 | /// Note: This does not perform the implicit conversions required by C++11 |
520 | /// [expr.const]p5. |
521 | bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr, |
522 | SourceLocation *Loc = nullptr) const; |
523 | |
524 | /// isPotentialConstantExpr - Return true if this function's definition |
525 | /// might be usable in a constant expression in C++11, if it were marked |
526 | /// constexpr. Return false if the function can never produce a constant |
527 | /// expression, along with diagnostics describing why not. |
528 | static bool isPotentialConstantExpr(const FunctionDecl *FD, |
529 | SmallVectorImpl< |
530 | PartialDiagnosticAt> &Diags); |
531 | |
532 | /// isPotentialConstantExprUnevaluted - Return true if this expression might |
533 | /// be usable in a constant expression in C++11 in an unevaluated context, if |
534 | /// it were in function FD marked constexpr. Return false if the function can |
535 | /// never produce a constant expression, along with diagnostics describing |
536 | /// why not. |
537 | static bool isPotentialConstantExprUnevaluated(Expr *E, |
538 | const FunctionDecl *FD, |
539 | SmallVectorImpl< |
540 | PartialDiagnosticAt> &Diags); |
541 | |
542 | /// isConstantInitializer - Returns true if this expression can be emitted to |
543 | /// IR as a constant, and thus can be used as a constant initializer in C. |
544 | /// If this expression is not constant and Culprit is non-null, |
545 | /// it is used to store the address of first non constant expr. |
546 | bool isConstantInitializer(ASTContext &Ctx, bool ForRef, |
547 | const Expr **Culprit = nullptr) const; |
548 | |
549 | /// EvalStatus is a struct with detailed info about an evaluation in progress. |
550 | struct EvalStatus { |
551 | /// Whether the evaluated expression has side effects. |
552 | /// For example, (f() && 0) can be folded, but it still has side effects. |
553 | bool HasSideEffects; |
554 | |
555 | /// Whether the evaluation hit undefined behavior. |
556 | /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior. |
557 | /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB. |
558 | bool HasUndefinedBehavior; |
559 | |
560 | /// Diag - If this is non-null, it will be filled in with a stack of notes |
561 | /// indicating why evaluation failed (or why it failed to produce a constant |
562 | /// expression). |
563 | /// If the expression is unfoldable, the notes will indicate why it's not |
564 | /// foldable. If the expression is foldable, but not a constant expression, |
565 | /// the notes will describes why it isn't a constant expression. If the |
566 | /// expression *is* a constant expression, no notes will be produced. |
567 | SmallVectorImpl<PartialDiagnosticAt> *Diag; |
568 | |
569 | EvalStatus() |
570 | : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {} |
571 | |
572 | // hasSideEffects - Return true if the evaluated expression has |
573 | // side effects. |
574 | bool hasSideEffects() const { |
575 | return HasSideEffects; |
576 | } |
577 | }; |
578 | |
579 | /// EvalResult is a struct with detailed info about an evaluated expression. |
580 | struct EvalResult : EvalStatus { |
581 | /// Val - This is the value the expression can be folded to. |
582 | APValue Val; |
583 | |
584 | // isGlobalLValue - Return true if the evaluated lvalue expression |
585 | // is global. |
586 | bool isGlobalLValue() const; |
587 | }; |
588 | |
589 | /// EvaluateAsRValue - Return true if this is a constant which we can fold to |
590 | /// an rvalue using any crazy technique (that has nothing to do with language |
591 | /// standards) that we want to, even if the expression has side-effects. If |
592 | /// this function returns true, it returns the folded constant in Result. If |
593 | /// the expression is a glvalue, an lvalue-to-rvalue conversion will be |
594 | /// applied. |
595 | bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, |
596 | bool InConstantContext = false) const; |
597 | |
598 | /// EvaluateAsBooleanCondition - Return true if this is a constant |
599 | /// which we can fold and convert to a boolean condition using |
600 | /// any crazy technique that we want to, even if the expression has |
601 | /// side-effects. |
602 | bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, |
603 | bool InConstantContext = false) const; |
604 | |
605 | enum SideEffectsKind { |
606 | SE_NoSideEffects, ///< Strictly evaluate the expression. |
607 | SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not |
608 | ///< arbitrary unmodeled side effects. |
609 | SE_AllowSideEffects ///< Allow any unmodeled side effect. |
610 | }; |
611 | |
612 | /// EvaluateAsInt - Return true if this is a constant which we can fold and |
613 | /// convert to an integer, using any crazy technique that we want to. |
614 | bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, |
615 | SideEffectsKind AllowSideEffects = SE_NoSideEffects, |
616 | bool InConstantContext = false) const; |
617 | |
618 | /// EvaluateAsFloat - Return true if this is a constant which we can fold and |
619 | /// convert to a floating point value, using any crazy technique that we |
620 | /// want to. |
621 | bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, |
622 | SideEffectsKind AllowSideEffects = SE_NoSideEffects, |
623 | bool InConstantContext = false) const; |
624 | |
625 | /// EvaluateAsFloat - Return true if this is a constant which we can fold and |
626 | /// convert to a fixed point value. |
627 | bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, |
628 | SideEffectsKind AllowSideEffects = SE_NoSideEffects, |
629 | bool InConstantContext = false) const; |
630 | |
631 | /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be |
632 | /// constant folded without side-effects, but discard the result. |
633 | bool isEvaluatable(const ASTContext &Ctx, |
634 | SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; |
635 | |
636 | /// HasSideEffects - This routine returns true for all those expressions |
637 | /// which have any effect other than producing a value. Example is a function |
638 | /// call, volatile variable read, or throwing an exception. If |
639 | /// IncludePossibleEffects is false, this call treats certain expressions with |
640 | /// potential side effects (such as function call-like expressions, |
641 | /// instantiation-dependent expressions, or invocations from a macro) as not |
642 | /// having side effects. |
643 | bool HasSideEffects(const ASTContext &Ctx, |
644 | bool IncludePossibleEffects = true) const; |
645 | |
646 | /// Determine whether this expression involves a call to any function |
647 | /// that is not trivial. |
648 | bool hasNonTrivialCall(const ASTContext &Ctx) const; |
649 | |
650 | /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded |
651 | /// integer. This must be called on an expression that constant folds to an |
652 | /// integer. |
653 | llvm::APSInt EvaluateKnownConstInt( |
654 | const ASTContext &Ctx, |
655 | SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; |
656 | |
657 | llvm::APSInt EvaluateKnownConstIntCheckOverflow( |
658 | const ASTContext &Ctx, |
659 | SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; |
660 | |
661 | void EvaluateForOverflow(const ASTContext &Ctx) const; |
662 | |
663 | /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an |
664 | /// lvalue with link time known address, with no side-effects. |
665 | bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, |
666 | bool InConstantContext = false) const; |
667 | |
668 | /// EvaluateAsInitializer - Evaluate an expression as if it were the |
669 | /// initializer of the given declaration. Returns true if the initializer |
670 | /// can be folded to a constant, and produces any relevant notes. In C++11, |
671 | /// notes will be produced if the expression is not a constant expression. |
672 | bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, |
673 | const VarDecl *VD, |
674 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
675 | |
676 | /// EvaluateWithSubstitution - Evaluate an expression as if from the context |
677 | /// of a call to the given function with the given arguments, inside an |
678 | /// unevaluated context. Returns true if the expression could be folded to a |
679 | /// constant. |
680 | bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, |
681 | const FunctionDecl *Callee, |
682 | ArrayRef<const Expr*> Args, |
683 | const Expr *This = nullptr) const; |
684 | |
685 | /// Indicates how the constant expression will be used. |
686 | enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling }; |
687 | |
688 | /// Evaluate an expression that is required to be a constant expression. |
689 | bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, |
690 | const ASTContext &Ctx) const; |
691 | |
692 | /// If the current Expr is a pointer, this will try to statically |
693 | /// determine the number of bytes available where the pointer is pointing. |
694 | /// Returns true if all of the above holds and we were able to figure out the |
695 | /// size, false otherwise. |
696 | /// |
697 | /// \param Type - How to evaluate the size of the Expr, as defined by the |
698 | /// "type" parameter of __builtin_object_size |
699 | bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, |
700 | unsigned Type) const; |
701 | |
702 | /// Enumeration used to describe the kind of Null pointer constant |
703 | /// returned from \c isNullPointerConstant(). |
704 | enum NullPointerConstantKind { |
705 | /// Expression is not a Null pointer constant. |
706 | NPCK_NotNull = 0, |
707 | |
708 | /// Expression is a Null pointer constant built from a zero integer |
709 | /// expression that is not a simple, possibly parenthesized, zero literal. |
710 | /// C++ Core Issue 903 will classify these expressions as "not pointers" |
711 | /// once it is adopted. |
712 | /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 |
713 | NPCK_ZeroExpression, |
714 | |
715 | /// Expression is a Null pointer constant built from a literal zero. |
716 | NPCK_ZeroLiteral, |
717 | |
718 | /// Expression is a C++11 nullptr. |
719 | NPCK_CXX11_nullptr, |
720 | |
721 | /// Expression is a GNU-style __null constant. |
722 | NPCK_GNUNull |
723 | }; |
724 | |
725 | /// Enumeration used to describe how \c isNullPointerConstant() |
726 | /// should cope with value-dependent expressions. |
727 | enum NullPointerConstantValueDependence { |
728 | /// Specifies that the expression should never be value-dependent. |
729 | NPC_NeverValueDependent = 0, |
730 | |
731 | /// Specifies that a value-dependent expression of integral or |
732 | /// dependent type should be considered a null pointer constant. |
733 | NPC_ValueDependentIsNull, |
734 | |
735 | /// Specifies that a value-dependent expression should be considered |
736 | /// to never be a null pointer constant. |
737 | NPC_ValueDependentIsNotNull |
738 | }; |
739 | |
740 | /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to |
741 | /// a Null pointer constant. The return value can further distinguish the |
742 | /// kind of NULL pointer constant that was detected. |
743 | NullPointerConstantKind isNullPointerConstant( |
744 | ASTContext &Ctx, |
745 | NullPointerConstantValueDependence NPC) const; |
746 | |
747 | /// isOBJCGCCandidate - Return true if this expression may be used in a read/ |
748 | /// write barrier. |
749 | bool isOBJCGCCandidate(ASTContext &Ctx) const; |
750 | |
751 | /// Returns true if this expression is a bound member function. |
752 | bool isBoundMemberFunction(ASTContext &Ctx) const; |
753 | |
754 | /// Given an expression of bound-member type, find the type |
755 | /// of the member. Returns null if this is an *overloaded* bound |
756 | /// member expression. |
757 | static QualType findBoundMemberType(const Expr *expr); |
758 | |
759 | /// Skip past any implicit casts which might surround this expression until |
760 | /// reaching a fixed point. Skips: |
761 | /// * ImplicitCastExpr |
762 | /// * FullExpr |
763 | Expr *IgnoreImpCasts() LLVM_READONLY__attribute__((__pure__)); |
764 | const Expr *IgnoreImpCasts() const { |
765 | return const_cast<Expr *>(this)->IgnoreImpCasts(); |
766 | } |
767 | |
768 | /// Skip past any casts which might surround this expression until reaching |
769 | /// a fixed point. Skips: |
770 | /// * CastExpr |
771 | /// * FullExpr |
772 | /// * MaterializeTemporaryExpr |
773 | /// * SubstNonTypeTemplateParmExpr |
774 | Expr *IgnoreCasts() LLVM_READONLY__attribute__((__pure__)); |
775 | const Expr *IgnoreCasts() const { |
776 | return const_cast<Expr *>(this)->IgnoreCasts(); |
777 | } |
778 | |
779 | /// Skip past any implicit AST nodes which might surround this expression |
780 | /// until reaching a fixed point. Skips: |
781 | /// * What IgnoreImpCasts() skips |
782 | /// * MaterializeTemporaryExpr |
783 | /// * CXXBindTemporaryExpr |
784 | Expr *IgnoreImplicit() LLVM_READONLY__attribute__((__pure__)); |
785 | const Expr *IgnoreImplicit() const { |
786 | return const_cast<Expr *>(this)->IgnoreImplicit(); |
787 | } |
788 | |
789 | /// Skip past any parentheses which might surround this expression until |
790 | /// reaching a fixed point. Skips: |
791 | /// * ParenExpr |
792 | /// * UnaryOperator if `UO_Extension` |
793 | /// * GenericSelectionExpr if `!isResultDependent()` |
794 | /// * ChooseExpr if `!isConditionDependent()` |
795 | /// * ConstantExpr |
796 | Expr *IgnoreParens() LLVM_READONLY__attribute__((__pure__)); |
797 | const Expr *IgnoreParens() const { |
798 | return const_cast<Expr *>(this)->IgnoreParens(); |
799 | } |
800 | |
801 | /// Skip past any parentheses and implicit casts which might surround this |
802 | /// expression until reaching a fixed point. |
803 | /// FIXME: IgnoreParenImpCasts really ought to be equivalent to |
804 | /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However |
805 | /// this is currently not the case. Instead IgnoreParenImpCasts() skips: |
806 | /// * What IgnoreParens() skips |
807 | /// * What IgnoreImpCasts() skips |
808 | /// * MaterializeTemporaryExpr |
809 | /// * SubstNonTypeTemplateParmExpr |
810 | Expr *IgnoreParenImpCasts() LLVM_READONLY__attribute__((__pure__)); |
811 | const Expr *IgnoreParenImpCasts() const { |
812 | return const_cast<Expr *>(this)->IgnoreParenImpCasts(); |
813 | } |
814 | |
815 | /// Skip past any parentheses and casts which might surround this expression |
816 | /// until reaching a fixed point. Skips: |
817 | /// * What IgnoreParens() skips |
818 | /// * What IgnoreCasts() skips |
819 | Expr *IgnoreParenCasts() LLVM_READONLY__attribute__((__pure__)); |
820 | const Expr *IgnoreParenCasts() const { |
821 | return const_cast<Expr *>(this)->IgnoreParenCasts(); |
822 | } |
823 | |
824 | /// Skip conversion operators. If this Expr is a call to a conversion |
825 | /// operator, return the argument. |
826 | Expr *IgnoreConversionOperator() LLVM_READONLY__attribute__((__pure__)); |
827 | const Expr *IgnoreConversionOperator() const { |
828 | return const_cast<Expr *>(this)->IgnoreConversionOperator(); |
829 | } |
830 | |
831 | /// Skip past any parentheses and lvalue casts which might surround this |
832 | /// expression until reaching a fixed point. Skips: |
833 | /// * What IgnoreParens() skips |
834 | /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue |
835 | /// casts are skipped |
836 | /// FIXME: This is intended purely as a temporary workaround for code |
837 | /// that hasn't yet been rewritten to do the right thing about those |
838 | /// casts, and may disappear along with the last internal use. |
839 | Expr *IgnoreParenLValueCasts() LLVM_READONLY__attribute__((__pure__)); |
840 | const Expr *IgnoreParenLValueCasts() const { |
841 | return const_cast<Expr *>(this)->IgnoreParenLValueCasts(); |
842 | } |
843 | |
844 | /// Skip past any parenthese and casts which do not change the value |
845 | /// (including ptr->int casts of the same size) until reaching a fixed point. |
846 | /// Skips: |
847 | /// * What IgnoreParens() skips |
848 | /// * CastExpr which do not change the value |
849 | /// * SubstNonTypeTemplateParmExpr |
850 | Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY__attribute__((__pure__)); |
851 | const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const { |
852 | return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx); |
853 | } |
854 | |
855 | /// Skip past any parentheses and derived-to-base casts until reaching a |
856 | /// fixed point. Skips: |
857 | /// * What IgnoreParens() skips |
858 | /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase, |
859 | /// CK_UncheckedDerivedToBase and CK_NoOp) |
860 | Expr *ignoreParenBaseCasts() LLVM_READONLY__attribute__((__pure__)); |
861 | const Expr *ignoreParenBaseCasts() const { |
862 | return const_cast<Expr *>(this)->ignoreParenBaseCasts(); |
863 | } |
864 | |
865 | /// Determine whether this expression is a default function argument. |
866 | /// |
867 | /// Default arguments are implicitly generated in the abstract syntax tree |
868 | /// by semantic analysis for function calls, object constructions, etc. in |
869 | /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; |
870 | /// this routine also looks through any implicit casts to determine whether |
871 | /// the expression is a default argument. |
872 | bool isDefaultArgument() const; |
873 | |
874 | /// Determine whether the result of this expression is a |
875 | /// temporary object of the given class type. |
876 | bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; |
877 | |
878 | /// Whether this expression is an implicit reference to 'this' in C++. |
879 | bool isImplicitCXXThis() const; |
880 | |
881 | static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs); |
882 | |
883 | /// For an expression of class type or pointer to class type, |
884 | /// return the most derived class decl the expression is known to refer to. |
885 | /// |
886 | /// If this expression is a cast, this method looks through it to find the |
887 | /// most derived decl that can be inferred from the expression. |
888 | /// This is valid because derived-to-base conversions have undefined |
889 | /// behavior if the object isn't dynamically of the derived type. |
890 | const CXXRecordDecl *getBestDynamicClassType() const; |
891 | |
892 | /// Get the inner expression that determines the best dynamic class. |
893 | /// If this is a prvalue, we guarantee that it is of the most-derived type |
894 | /// for the object itself. |
895 | const Expr *getBestDynamicClassTypeExpr() const; |
896 | |
897 | /// Walk outwards from an expression we want to bind a reference to and |
898 | /// find the expression whose lifetime needs to be extended. Record |
899 | /// the LHSs of comma expressions and adjustments needed along the path. |
900 | const Expr *skipRValueSubobjectAdjustments( |
901 | SmallVectorImpl<const Expr *> &CommaLHS, |
902 | SmallVectorImpl<SubobjectAdjustment> &Adjustments) const; |
903 | const Expr *skipRValueSubobjectAdjustments() const { |
904 | SmallVector<const Expr *, 8> CommaLHSs; |
905 | SmallVector<SubobjectAdjustment, 8> Adjustments; |
906 | return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); |
907 | } |
908 | |
909 | /// Checks that the two Expr's will refer to the same value as a comparison |
910 | /// operand. The caller must ensure that the values referenced by the Expr's |
911 | /// are not modified between E1 and E2 or the result my be invalid. |
912 | static bool isSameComparisonOperand(const Expr* E1, const Expr* E2); |
913 | |
914 | static bool classof(const Stmt *T) { |
915 | return T->getStmtClass() >= firstExprConstant && |
916 | T->getStmtClass() <= lastExprConstant; |
917 | } |
918 | }; |
919 | |
920 | //===----------------------------------------------------------------------===// |
921 | // Wrapper Expressions. |
922 | //===----------------------------------------------------------------------===// |
923 | |
924 | /// FullExpr - Represents a "full-expression" node. |
925 | class FullExpr : public Expr { |
926 | protected: |
927 | Stmt *SubExpr; |
928 | |
929 | FullExpr(StmtClass SC, Expr *subexpr) |
930 | : Expr(SC, subexpr->getType(), |
931 | subexpr->getValueKind(), subexpr->getObjectKind(), |
932 | subexpr->isTypeDependent(), subexpr->isValueDependent(), |
933 | subexpr->isInstantiationDependent(), |
934 | subexpr->containsUnexpandedParameterPack()), SubExpr(subexpr) {} |
935 | FullExpr(StmtClass SC, EmptyShell Empty) |
936 | : Expr(SC, Empty) {} |
937 | public: |
938 | const Expr *getSubExpr() const { return cast<Expr>(SubExpr); } |
939 | Expr *getSubExpr() { return cast<Expr>(SubExpr); } |
940 | |
941 | /// As with any mutator of the AST, be very careful when modifying an |
942 | /// existing AST to preserve its invariants. |
943 | void setSubExpr(Expr *E) { SubExpr = E; } |
944 | |
945 | static bool classof(const Stmt *T) { |
946 | return T->getStmtClass() >= firstFullExprConstant && |
947 | T->getStmtClass() <= lastFullExprConstant; |
948 | } |
949 | }; |
950 | |
951 | /// ConstantExpr - An expression that occurs in a constant context and |
952 | /// optionally the result of evaluating the expression. |
953 | class ConstantExpr final |
954 | : public FullExpr, |
955 | private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> { |
956 | static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value, |
957 | "this class assumes llvm::APInt::WordType is uint64_t for " |
958 | "trail-allocated storage"); |
959 | |
960 | public: |
961 | /// Describes the kind of result that can be trail-allocated. |
962 | enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue }; |
963 | |
964 | private: |
965 | size_t numTrailingObjects(OverloadToken<APValue>) const { |
966 | return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue; |
967 | } |
968 | size_t numTrailingObjects(OverloadToken<uint64_t>) const { |
969 | return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64; |
970 | } |
971 | |
972 | void DefaultInit(ResultStorageKind StorageKind); |
973 | uint64_t &Int64Result() { |
974 | assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&((ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && "invalid accessor") ? static_cast<void> (0) : __assert_fail ("ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && \"invalid accessor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 975, __PRETTY_FUNCTION__)) |
975 | "invalid accessor")((ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && "invalid accessor") ? static_cast<void> (0) : __assert_fail ("ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && \"invalid accessor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 975, __PRETTY_FUNCTION__)); |
976 | return *getTrailingObjects<uint64_t>(); |
977 | } |
978 | const uint64_t &Int64Result() const { |
979 | return const_cast<ConstantExpr *>(this)->Int64Result(); |
980 | } |
981 | APValue &APValueResult() { |
982 | assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&((ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && "invalid accessor") ? static_cast<void> (0) : __assert_fail ("ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && \"invalid accessor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 983, __PRETTY_FUNCTION__)) |
983 | "invalid accessor")((ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && "invalid accessor") ? static_cast<void> (0) : __assert_fail ("ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && \"invalid accessor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 983, __PRETTY_FUNCTION__)); |
984 | return *getTrailingObjects<APValue>(); |
985 | } |
986 | const APValue &APValueResult() const { |
987 | return const_cast<ConstantExpr *>(this)->APValueResult(); |
988 | } |
989 | |
990 | ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind); |
991 | ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty); |
992 | |
993 | public: |
994 | friend TrailingObjects; |
995 | friend class ASTStmtReader; |
996 | friend class ASTStmtWriter; |
997 | static ConstantExpr *Create(const ASTContext &Context, Expr *E, |
998 | const APValue &Result); |
999 | static ConstantExpr *Create(const ASTContext &Context, Expr *E, |
1000 | ResultStorageKind Storage = RSK_None); |
1001 | static ConstantExpr *CreateEmpty(const ASTContext &Context, |
1002 | ResultStorageKind StorageKind, |
1003 | EmptyShell Empty); |
1004 | |
1005 | static ResultStorageKind getStorageKind(const APValue &Value); |
1006 | static ResultStorageKind getStorageKind(const Type *T, |
1007 | const ASTContext &Context); |
1008 | |
1009 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1010 | return SubExpr->getBeginLoc(); |
1011 | } |
1012 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1013 | return SubExpr->getEndLoc(); |
1014 | } |
1015 | |
1016 | static bool classof(const Stmt *T) { |
1017 | return T->getStmtClass() == ConstantExprClass; |
1018 | } |
1019 | |
1020 | void SetResult(APValue Value, const ASTContext &Context) { |
1021 | MoveIntoResult(Value, Context); |
1022 | } |
1023 | void MoveIntoResult(APValue &Value, const ASTContext &Context); |
1024 | |
1025 | APValue::ValueKind getResultAPValueKind() const { |
1026 | return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind); |
1027 | } |
1028 | ResultStorageKind getResultStorageKind() const { |
1029 | return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind); |
1030 | } |
1031 | APValue getAPValueResult() const; |
1032 | const APValue &getResultAsAPValue() const { return APValueResult(); } |
1033 | llvm::APSInt getResultAsAPSInt() const; |
1034 | // Iterators |
1035 | child_range children() { return child_range(&SubExpr, &SubExpr+1); } |
1036 | const_child_range children() const { |
1037 | return const_child_range(&SubExpr, &SubExpr + 1); |
1038 | } |
1039 | }; |
1040 | |
1041 | //===----------------------------------------------------------------------===// |
1042 | // Primary Expressions. |
1043 | //===----------------------------------------------------------------------===// |
1044 | |
1045 | /// OpaqueValueExpr - An expression referring to an opaque object of a |
1046 | /// fixed type and value class. These don't correspond to concrete |
1047 | /// syntax; instead they're used to express operations (usually copy |
1048 | /// operations) on values whose source is generally obvious from |
1049 | /// context. |
1050 | class OpaqueValueExpr : public Expr { |
1051 | friend class ASTStmtReader; |
1052 | Expr *SourceExpr; |
1053 | |
1054 | public: |
1055 | OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, |
1056 | ExprObjectKind OK = OK_Ordinary, |
1057 | Expr *SourceExpr = nullptr) |
1058 | : Expr(OpaqueValueExprClass, T, VK, OK, |
1059 | T->isDependentType() || |
1060 | (SourceExpr && SourceExpr->isTypeDependent()), |
1061 | T->isDependentType() || |
1062 | (SourceExpr && SourceExpr->isValueDependent()), |
1063 | T->isInstantiationDependentType() || |
1064 | (SourceExpr && SourceExpr->isInstantiationDependent()), |
1065 | false), |
1066 | SourceExpr(SourceExpr) { |
1067 | setIsUnique(false); |
1068 | OpaqueValueExprBits.Loc = Loc; |
1069 | } |
1070 | |
1071 | /// Given an expression which invokes a copy constructor --- i.e. a |
1072 | /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- |
1073 | /// find the OpaqueValueExpr that's the source of the construction. |
1074 | static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); |
1075 | |
1076 | explicit OpaqueValueExpr(EmptyShell Empty) |
1077 | : Expr(OpaqueValueExprClass, Empty) {} |
1078 | |
1079 | /// Retrieve the location of this expression. |
1080 | SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; } |
1081 | |
1082 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1083 | return SourceExpr ? SourceExpr->getBeginLoc() : getLocation(); |
1084 | } |
1085 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1086 | return SourceExpr ? SourceExpr->getEndLoc() : getLocation(); |
1087 | } |
1088 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1089 | return SourceExpr ? SourceExpr->getExprLoc() : getLocation(); |
1090 | } |
1091 | |
1092 | child_range children() { |
1093 | return child_range(child_iterator(), child_iterator()); |
1094 | } |
1095 | |
1096 | const_child_range children() const { |
1097 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1098 | } |
1099 | |
1100 | /// The source expression of an opaque value expression is the |
1101 | /// expression which originally generated the value. This is |
1102 | /// provided as a convenience for analyses that don't wish to |
1103 | /// precisely model the execution behavior of the program. |
1104 | /// |
1105 | /// The source expression is typically set when building the |
1106 | /// expression which binds the opaque value expression in the first |
1107 | /// place. |
1108 | Expr *getSourceExpr() const { return SourceExpr; } |
1109 | |
1110 | void setIsUnique(bool V) { |
1111 | assert((!V || SourceExpr) &&(((!V || SourceExpr) && "unique OVEs are expected to have source expressions" ) ? static_cast<void> (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1112, __PRETTY_FUNCTION__)) |
1112 | "unique OVEs are expected to have source expressions")(((!V || SourceExpr) && "unique OVEs are expected to have source expressions" ) ? static_cast<void> (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1112, __PRETTY_FUNCTION__)); |
1113 | OpaqueValueExprBits.IsUnique = V; |
1114 | } |
1115 | |
1116 | bool isUnique() const { return OpaqueValueExprBits.IsUnique; } |
1117 | |
1118 | static bool classof(const Stmt *T) { |
1119 | return T->getStmtClass() == OpaqueValueExprClass; |
1120 | } |
1121 | }; |
1122 | |
1123 | /// A reference to a declared variable, function, enum, etc. |
1124 | /// [C99 6.5.1p2] |
1125 | /// |
1126 | /// This encodes all the information about how a declaration is referenced |
1127 | /// within an expression. |
1128 | /// |
1129 | /// There are several optional constructs attached to DeclRefExprs only when |
1130 | /// they apply in order to conserve memory. These are laid out past the end of |
1131 | /// the object, and flags in the DeclRefExprBitfield track whether they exist: |
1132 | /// |
1133 | /// DeclRefExprBits.HasQualifier: |
1134 | /// Specifies when this declaration reference expression has a C++ |
1135 | /// nested-name-specifier. |
1136 | /// DeclRefExprBits.HasFoundDecl: |
1137 | /// Specifies when this declaration reference expression has a record of |
1138 | /// a NamedDecl (different from the referenced ValueDecl) which was found |
1139 | /// during name lookup and/or overload resolution. |
1140 | /// DeclRefExprBits.HasTemplateKWAndArgsInfo: |
1141 | /// Specifies when this declaration reference expression has an explicit |
1142 | /// C++ template keyword and/or template argument list. |
1143 | /// DeclRefExprBits.RefersToEnclosingVariableOrCapture |
1144 | /// Specifies when this declaration reference expression (validly) |
1145 | /// refers to an enclosed local or a captured variable. |
1146 | class DeclRefExpr final |
1147 | : public Expr, |
1148 | private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc, |
1149 | NamedDecl *, ASTTemplateKWAndArgsInfo, |
1150 | TemplateArgumentLoc> { |
1151 | friend class ASTStmtReader; |
1152 | friend class ASTStmtWriter; |
1153 | friend TrailingObjects; |
1154 | |
1155 | /// The declaration that we are referencing. |
1156 | ValueDecl *D; |
1157 | |
1158 | /// Provides source/type location info for the declaration name |
1159 | /// embedded in D. |
1160 | DeclarationNameLoc DNLoc; |
1161 | |
1162 | size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const { |
1163 | return hasQualifier(); |
1164 | } |
1165 | |
1166 | size_t numTrailingObjects(OverloadToken<NamedDecl *>) const { |
1167 | return hasFoundDecl(); |
1168 | } |
1169 | |
1170 | size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { |
1171 | return hasTemplateKWAndArgsInfo(); |
1172 | } |
1173 | |
1174 | /// Test whether there is a distinct FoundDecl attached to the end of |
1175 | /// this DRE. |
1176 | bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } |
1177 | |
1178 | DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc, |
1179 | SourceLocation TemplateKWLoc, ValueDecl *D, |
1180 | bool RefersToEnlosingVariableOrCapture, |
1181 | const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, |
1182 | const TemplateArgumentListInfo *TemplateArgs, QualType T, |
1183 | ExprValueKind VK, NonOdrUseReason NOUR); |
1184 | |
1185 | /// Construct an empty declaration reference expression. |
1186 | explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {} |
1187 | |
1188 | /// Computes the type- and value-dependence flags for this |
1189 | /// declaration reference expression. |
1190 | void computeDependence(const ASTContext &Ctx); |
1191 | |
1192 | public: |
1193 | DeclRefExpr(const ASTContext &Ctx, ValueDecl *D, |
1194 | bool RefersToEnclosingVariableOrCapture, QualType T, |
1195 | ExprValueKind VK, SourceLocation L, |
1196 | const DeclarationNameLoc &LocInfo = DeclarationNameLoc(), |
1197 | NonOdrUseReason NOUR = NOUR_None); |
1198 | |
1199 | static DeclRefExpr * |
1200 | Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, |
1201 | SourceLocation TemplateKWLoc, ValueDecl *D, |
1202 | bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, |
1203 | QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr, |
1204 | const TemplateArgumentListInfo *TemplateArgs = nullptr, |
1205 | NonOdrUseReason NOUR = NOUR_None); |
1206 | |
1207 | static DeclRefExpr * |
1208 | Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, |
1209 | SourceLocation TemplateKWLoc, ValueDecl *D, |
1210 | bool RefersToEnclosingVariableOrCapture, |
1211 | const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK, |
1212 | NamedDecl *FoundD = nullptr, |
1213 | const TemplateArgumentListInfo *TemplateArgs = nullptr, |
1214 | NonOdrUseReason NOUR = NOUR_None); |
1215 | |
1216 | /// Construct an empty declaration reference expression. |
1217 | static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, |
1218 | bool HasFoundDecl, |
1219 | bool HasTemplateKWAndArgsInfo, |
1220 | unsigned NumTemplateArgs); |
1221 | |
1222 | ValueDecl *getDecl() { return D; } |
1223 | const ValueDecl *getDecl() const { return D; } |
1224 | void setDecl(ValueDecl *NewD) { D = NewD; } |
1225 | |
1226 | DeclarationNameInfo getNameInfo() const { |
1227 | return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc); |
1228 | } |
1229 | |
1230 | SourceLocation getLocation() const { return DeclRefExprBits.Loc; } |
1231 | void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; } |
1232 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
1233 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
1234 | |
1235 | /// Determine whether this declaration reference was preceded by a |
1236 | /// C++ nested-name-specifier, e.g., \c N::foo. |
1237 | bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } |
1238 | |
1239 | /// If the name was qualified, retrieves the nested-name-specifier |
1240 | /// that precedes the name, with source-location information. |
1241 | NestedNameSpecifierLoc getQualifierLoc() const { |
1242 | if (!hasQualifier()) |
1243 | return NestedNameSpecifierLoc(); |
1244 | return *getTrailingObjects<NestedNameSpecifierLoc>(); |
1245 | } |
1246 | |
1247 | /// If the name was qualified, retrieves the nested-name-specifier |
1248 | /// that precedes the name. Otherwise, returns NULL. |
1249 | NestedNameSpecifier *getQualifier() const { |
1250 | return getQualifierLoc().getNestedNameSpecifier(); |
1251 | } |
1252 | |
1253 | /// Get the NamedDecl through which this reference occurred. |
1254 | /// |
1255 | /// This Decl may be different from the ValueDecl actually referred to in the |
1256 | /// presence of using declarations, etc. It always returns non-NULL, and may |
1257 | /// simple return the ValueDecl when appropriate. |
1258 | |
1259 | NamedDecl *getFoundDecl() { |
1260 | return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; |
1261 | } |
1262 | |
1263 | /// Get the NamedDecl through which this reference occurred. |
1264 | /// See non-const variant. |
1265 | const NamedDecl *getFoundDecl() const { |
1266 | return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; |
1267 | } |
1268 | |
1269 | bool hasTemplateKWAndArgsInfo() const { |
1270 | return DeclRefExprBits.HasTemplateKWAndArgsInfo; |
1271 | } |
1272 | |
1273 | /// Retrieve the location of the template keyword preceding |
1274 | /// this name, if any. |
1275 | SourceLocation getTemplateKeywordLoc() const { |
1276 | if (!hasTemplateKWAndArgsInfo()) |
1277 | return SourceLocation(); |
1278 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; |
1279 | } |
1280 | |
1281 | /// Retrieve the location of the left angle bracket starting the |
1282 | /// explicit template argument list following the name, if any. |
1283 | SourceLocation getLAngleLoc() const { |
1284 | if (!hasTemplateKWAndArgsInfo()) |
1285 | return SourceLocation(); |
1286 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; |
1287 | } |
1288 | |
1289 | /// Retrieve the location of the right angle bracket ending the |
1290 | /// explicit template argument list following the name, if any. |
1291 | SourceLocation getRAngleLoc() const { |
1292 | if (!hasTemplateKWAndArgsInfo()) |
1293 | return SourceLocation(); |
1294 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; |
1295 | } |
1296 | |
1297 | /// Determines whether the name in this declaration reference |
1298 | /// was preceded by the template keyword. |
1299 | bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } |
1300 | |
1301 | /// Determines whether this declaration reference was followed by an |
1302 | /// explicit template argument list. |
1303 | bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } |
1304 | |
1305 | /// Copies the template arguments (if present) into the given |
1306 | /// structure. |
1307 | void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { |
1308 | if (hasExplicitTemplateArgs()) |
1309 | getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( |
1310 | getTrailingObjects<TemplateArgumentLoc>(), List); |
1311 | } |
1312 | |
1313 | /// Retrieve the template arguments provided as part of this |
1314 | /// template-id. |
1315 | const TemplateArgumentLoc *getTemplateArgs() const { |
1316 | if (!hasExplicitTemplateArgs()) |
1317 | return nullptr; |
1318 | return getTrailingObjects<TemplateArgumentLoc>(); |
1319 | } |
1320 | |
1321 | /// Retrieve the number of template arguments provided as part of this |
1322 | /// template-id. |
1323 | unsigned getNumTemplateArgs() const { |
1324 | if (!hasExplicitTemplateArgs()) |
1325 | return 0; |
1326 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; |
1327 | } |
1328 | |
1329 | ArrayRef<TemplateArgumentLoc> template_arguments() const { |
1330 | return {getTemplateArgs(), getNumTemplateArgs()}; |
1331 | } |
1332 | |
1333 | /// Returns true if this expression refers to a function that |
1334 | /// was resolved from an overloaded set having size greater than 1. |
1335 | bool hadMultipleCandidates() const { |
1336 | return DeclRefExprBits.HadMultipleCandidates; |
1337 | } |
1338 | /// Sets the flag telling whether this expression refers to |
1339 | /// a function that was resolved from an overloaded set having size |
1340 | /// greater than 1. |
1341 | void setHadMultipleCandidates(bool V = true) { |
1342 | DeclRefExprBits.HadMultipleCandidates = V; |
1343 | } |
1344 | |
1345 | /// Is this expression a non-odr-use reference, and if so, why? |
1346 | NonOdrUseReason isNonOdrUse() const { |
1347 | return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason); |
1348 | } |
1349 | |
1350 | /// Does this DeclRefExpr refer to an enclosing local or a captured |
1351 | /// variable? |
1352 | bool refersToEnclosingVariableOrCapture() const { |
1353 | return DeclRefExprBits.RefersToEnclosingVariableOrCapture; |
1354 | } |
1355 | |
1356 | static bool classof(const Stmt *T) { |
1357 | return T->getStmtClass() == DeclRefExprClass; |
1358 | } |
1359 | |
1360 | // Iterators |
1361 | child_range children() { |
1362 | return child_range(child_iterator(), child_iterator()); |
1363 | } |
1364 | |
1365 | const_child_range children() const { |
1366 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1367 | } |
1368 | }; |
1369 | |
1370 | /// Used by IntegerLiteral/FloatingLiteral to store the numeric without |
1371 | /// leaking memory. |
1372 | /// |
1373 | /// For large floats/integers, APFloat/APInt will allocate memory from the heap |
1374 | /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator |
1375 | /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with |
1376 | /// the APFloat/APInt values will never get freed. APNumericStorage uses |
1377 | /// ASTContext's allocator for memory allocation. |
1378 | class APNumericStorage { |
1379 | union { |
1380 | uint64_t VAL; ///< Used to store the <= 64 bits integer value. |
1381 | uint64_t *pVal; ///< Used to store the >64 bits integer value. |
1382 | }; |
1383 | unsigned BitWidth; |
1384 | |
1385 | bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } |
1386 | |
1387 | APNumericStorage(const APNumericStorage &) = delete; |
1388 | void operator=(const APNumericStorage &) = delete; |
1389 | |
1390 | protected: |
1391 | APNumericStorage() : VAL(0), BitWidth(0) { } |
1392 | |
1393 | llvm::APInt getIntValue() const { |
1394 | unsigned NumWords = llvm::APInt::getNumWords(BitWidth); |
1395 | if (NumWords > 1) |
1396 | return llvm::APInt(BitWidth, NumWords, pVal); |
1397 | else |
1398 | return llvm::APInt(BitWidth, VAL); |
1399 | } |
1400 | void setIntValue(const ASTContext &C, const llvm::APInt &Val); |
1401 | }; |
1402 | |
1403 | class APIntStorage : private APNumericStorage { |
1404 | public: |
1405 | llvm::APInt getValue() const { return getIntValue(); } |
1406 | void setValue(const ASTContext &C, const llvm::APInt &Val) { |
1407 | setIntValue(C, Val); |
1408 | } |
1409 | }; |
1410 | |
1411 | class APFloatStorage : private APNumericStorage { |
1412 | public: |
1413 | llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { |
1414 | return llvm::APFloat(Semantics, getIntValue()); |
1415 | } |
1416 | void setValue(const ASTContext &C, const llvm::APFloat &Val) { |
1417 | setIntValue(C, Val.bitcastToAPInt()); |
1418 | } |
1419 | }; |
1420 | |
1421 | class IntegerLiteral : public Expr, public APIntStorage { |
1422 | SourceLocation Loc; |
1423 | |
1424 | /// Construct an empty integer literal. |
1425 | explicit IntegerLiteral(EmptyShell Empty) |
1426 | : Expr(IntegerLiteralClass, Empty) { } |
1427 | |
1428 | public: |
1429 | // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, |
1430 | // or UnsignedLongLongTy |
1431 | IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, |
1432 | SourceLocation l); |
1433 | |
1434 | /// Returns a new integer literal with value 'V' and type 'type'. |
1435 | /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, |
1436 | /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V |
1437 | /// \param V - the value that the returned integer literal contains. |
1438 | static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V, |
1439 | QualType type, SourceLocation l); |
1440 | /// Returns a new empty integer literal. |
1441 | static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty); |
1442 | |
1443 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1444 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1445 | |
1446 | /// Retrieve the location of the literal. |
1447 | SourceLocation getLocation() const { return Loc; } |
1448 | |
1449 | void setLocation(SourceLocation Location) { Loc = Location; } |
1450 | |
1451 | static bool classof(const Stmt *T) { |
1452 | return T->getStmtClass() == IntegerLiteralClass; |
1453 | } |
1454 | |
1455 | // Iterators |
1456 | child_range children() { |
1457 | return child_range(child_iterator(), child_iterator()); |
1458 | } |
1459 | const_child_range children() const { |
1460 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1461 | } |
1462 | }; |
1463 | |
1464 | class FixedPointLiteral : public Expr, public APIntStorage { |
1465 | SourceLocation Loc; |
1466 | unsigned Scale; |
1467 | |
1468 | /// \brief Construct an empty integer literal. |
1469 | explicit FixedPointLiteral(EmptyShell Empty) |
1470 | : Expr(FixedPointLiteralClass, Empty) {} |
1471 | |
1472 | public: |
1473 | FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, |
1474 | SourceLocation l, unsigned Scale); |
1475 | |
1476 | // Store the int as is without any bit shifting. |
1477 | static FixedPointLiteral *CreateFromRawInt(const ASTContext &C, |
1478 | const llvm::APInt &V, |
1479 | QualType type, SourceLocation l, |
1480 | unsigned Scale); |
1481 | |
1482 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1483 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1484 | |
1485 | /// \brief Retrieve the location of the literal. |
1486 | SourceLocation getLocation() const { return Loc; } |
1487 | |
1488 | void setLocation(SourceLocation Location) { Loc = Location; } |
1489 | |
1490 | static bool classof(const Stmt *T) { |
1491 | return T->getStmtClass() == FixedPointLiteralClass; |
1492 | } |
1493 | |
1494 | std::string getValueAsString(unsigned Radix) const; |
1495 | |
1496 | // Iterators |
1497 | child_range children() { |
1498 | return child_range(child_iterator(), child_iterator()); |
1499 | } |
1500 | const_child_range children() const { |
1501 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1502 | } |
1503 | }; |
1504 | |
1505 | class CharacterLiteral : public Expr { |
1506 | public: |
1507 | enum CharacterKind { |
1508 | Ascii, |
1509 | Wide, |
1510 | UTF8, |
1511 | UTF16, |
1512 | UTF32 |
1513 | }; |
1514 | |
1515 | private: |
1516 | unsigned Value; |
1517 | SourceLocation Loc; |
1518 | public: |
1519 | // type should be IntTy |
1520 | CharacterLiteral(unsigned value, CharacterKind kind, QualType type, |
1521 | SourceLocation l) |
1522 | : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false, |
1523 | false, false), |
1524 | Value(value), Loc(l) { |
1525 | CharacterLiteralBits.Kind = kind; |
1526 | } |
1527 | |
1528 | /// Construct an empty character literal. |
1529 | CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } |
1530 | |
1531 | SourceLocation getLocation() const { return Loc; } |
1532 | CharacterKind getKind() const { |
1533 | return static_cast<CharacterKind>(CharacterLiteralBits.Kind); |
1534 | } |
1535 | |
1536 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1537 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1538 | |
1539 | unsigned getValue() const { return Value; } |
1540 | |
1541 | void setLocation(SourceLocation Location) { Loc = Location; } |
1542 | void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } |
1543 | void setValue(unsigned Val) { Value = Val; } |
1544 | |
1545 | static bool classof(const Stmt *T) { |
1546 | return T->getStmtClass() == CharacterLiteralClass; |
1547 | } |
1548 | |
1549 | // Iterators |
1550 | child_range children() { |
1551 | return child_range(child_iterator(), child_iterator()); |
1552 | } |
1553 | const_child_range children() const { |
1554 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1555 | } |
1556 | }; |
1557 | |
1558 | class FloatingLiteral : public Expr, private APFloatStorage { |
1559 | SourceLocation Loc; |
1560 | |
1561 | FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, |
1562 | QualType Type, SourceLocation L); |
1563 | |
1564 | /// Construct an empty floating-point literal. |
1565 | explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty); |
1566 | |
1567 | public: |
1568 | static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V, |
1569 | bool isexact, QualType Type, SourceLocation L); |
1570 | static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty); |
1571 | |
1572 | llvm::APFloat getValue() const { |
1573 | return APFloatStorage::getValue(getSemantics()); |
1574 | } |
1575 | void setValue(const ASTContext &C, const llvm::APFloat &Val) { |
1576 | assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics")((&getSemantics() == &Val.getSemantics() && "Inconsistent semantics" ) ? static_cast<void> (0) : __assert_fail ("&getSemantics() == &Val.getSemantics() && \"Inconsistent semantics\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1576, __PRETTY_FUNCTION__)); |
1577 | APFloatStorage::setValue(C, Val); |
1578 | } |
1579 | |
1580 | /// Get a raw enumeration value representing the floating-point semantics of |
1581 | /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. |
1582 | llvm::APFloatBase::Semantics getRawSemantics() const { |
1583 | return static_cast<llvm::APFloatBase::Semantics>( |
1584 | FloatingLiteralBits.Semantics); |
1585 | } |
1586 | |
1587 | /// Set the raw enumeration value representing the floating-point semantics of |
1588 | /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. |
1589 | void setRawSemantics(llvm::APFloatBase::Semantics Sem) { |
1590 | FloatingLiteralBits.Semantics = Sem; |
1591 | } |
1592 | |
1593 | /// Return the APFloat semantics this literal uses. |
1594 | const llvm::fltSemantics &getSemantics() const { |
1595 | return llvm::APFloatBase::EnumToSemantics( |
1596 | static_cast<llvm::APFloatBase::Semantics>( |
1597 | FloatingLiteralBits.Semantics)); |
1598 | } |
1599 | |
1600 | /// Set the APFloat semantics this literal uses. |
1601 | void setSemantics(const llvm::fltSemantics &Sem) { |
1602 | FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem); |
1603 | } |
1604 | |
1605 | bool isExact() const { return FloatingLiteralBits.IsExact; } |
1606 | void setExact(bool E) { FloatingLiteralBits.IsExact = E; } |
1607 | |
1608 | /// getValueAsApproximateDouble - This returns the value as an inaccurate |
1609 | /// double. Note that this may cause loss of precision, but is useful for |
1610 | /// debugging dumps, etc. |
1611 | double getValueAsApproximateDouble() const; |
1612 | |
1613 | SourceLocation getLocation() const { return Loc; } |
1614 | void setLocation(SourceLocation L) { Loc = L; } |
1615 | |
1616 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1617 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1618 | |
1619 | static bool classof(const Stmt *T) { |
1620 | return T->getStmtClass() == FloatingLiteralClass; |
1621 | } |
1622 | |
1623 | // Iterators |
1624 | child_range children() { |
1625 | return child_range(child_iterator(), child_iterator()); |
1626 | } |
1627 | const_child_range children() const { |
1628 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1629 | } |
1630 | }; |
1631 | |
1632 | /// ImaginaryLiteral - We support imaginary integer and floating point literals, |
1633 | /// like "1.0i". We represent these as a wrapper around FloatingLiteral and |
1634 | /// IntegerLiteral classes. Instances of this class always have a Complex type |
1635 | /// whose element type matches the subexpression. |
1636 | /// |
1637 | class ImaginaryLiteral : public Expr { |
1638 | Stmt *Val; |
1639 | public: |
1640 | ImaginaryLiteral(Expr *val, QualType Ty) |
1641 | : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false, |
1642 | false, false), |
1643 | Val(val) {} |
1644 | |
1645 | /// Build an empty imaginary literal. |
1646 | explicit ImaginaryLiteral(EmptyShell Empty) |
1647 | : Expr(ImaginaryLiteralClass, Empty) { } |
1648 | |
1649 | const Expr *getSubExpr() const { return cast<Expr>(Val); } |
1650 | Expr *getSubExpr() { return cast<Expr>(Val); } |
1651 | void setSubExpr(Expr *E) { Val = E; } |
1652 | |
1653 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1654 | return Val->getBeginLoc(); |
1655 | } |
1656 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Val->getEndLoc(); } |
1657 | |
1658 | static bool classof(const Stmt *T) { |
1659 | return T->getStmtClass() == ImaginaryLiteralClass; |
1660 | } |
1661 | |
1662 | // Iterators |
1663 | child_range children() { return child_range(&Val, &Val+1); } |
1664 | const_child_range children() const { |
1665 | return const_child_range(&Val, &Val + 1); |
1666 | } |
1667 | }; |
1668 | |
1669 | /// StringLiteral - This represents a string literal expression, e.g. "foo" |
1670 | /// or L"bar" (wide strings). The actual string data can be obtained with |
1671 | /// getBytes() and is NOT null-terminated. The length of the string data is |
1672 | /// determined by calling getByteLength(). |
1673 | /// |
1674 | /// The C type for a string is always a ConstantArrayType. In C++, the char |
1675 | /// type is const qualified, in C it is not. |
1676 | /// |
1677 | /// Note that strings in C can be formed by concatenation of multiple string |
1678 | /// literal pptokens in translation phase #6. This keeps track of the locations |
1679 | /// of each of these pieces. |
1680 | /// |
1681 | /// Strings in C can also be truncated and extended by assigning into arrays, |
1682 | /// e.g. with constructs like: |
1683 | /// char X[2] = "foobar"; |
1684 | /// In this case, getByteLength() will return 6, but the string literal will |
1685 | /// have type "char[2]". |
1686 | class StringLiteral final |
1687 | : public Expr, |
1688 | private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation, |
1689 | char> { |
1690 | friend class ASTStmtReader; |
1691 | friend TrailingObjects; |
1692 | |
1693 | /// StringLiteral is followed by several trailing objects. They are in order: |
1694 | /// |
1695 | /// * A single unsigned storing the length in characters of this string. The |
1696 | /// length in bytes is this length times the width of a single character. |
1697 | /// Always present and stored as a trailing objects because storing it in |
1698 | /// StringLiteral would increase the size of StringLiteral by sizeof(void *) |
1699 | /// due to alignment requirements. If you add some data to StringLiteral, |
1700 | /// consider moving it inside StringLiteral. |
1701 | /// |
1702 | /// * An array of getNumConcatenated() SourceLocation, one for each of the |
1703 | /// token this string is made of. |
1704 | /// |
1705 | /// * An array of getByteLength() char used to store the string data. |
1706 | |
1707 | public: |
1708 | enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 }; |
1709 | |
1710 | private: |
1711 | unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; } |
1712 | unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { |
1713 | return getNumConcatenated(); |
1714 | } |
1715 | |
1716 | unsigned numTrailingObjects(OverloadToken<char>) const { |
1717 | return getByteLength(); |
1718 | } |
1719 | |
1720 | char *getStrDataAsChar() { return getTrailingObjects<char>(); } |
1721 | const char *getStrDataAsChar() const { return getTrailingObjects<char>(); } |
1722 | |
1723 | const uint16_t *getStrDataAsUInt16() const { |
1724 | return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>()); |
1725 | } |
1726 | |
1727 | const uint32_t *getStrDataAsUInt32() const { |
1728 | return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>()); |
1729 | } |
1730 | |
1731 | /// Build a string literal. |
1732 | StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind, |
1733 | bool Pascal, QualType Ty, const SourceLocation *Loc, |
1734 | unsigned NumConcatenated); |
1735 | |
1736 | /// Build an empty string literal. |
1737 | StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length, |
1738 | unsigned CharByteWidth); |
1739 | |
1740 | /// Map a target and string kind to the appropriate character width. |
1741 | static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK); |
1742 | |
1743 | /// Set one of the string literal token. |
1744 | void setStrTokenLoc(unsigned TokNum, SourceLocation L) { |
1745 | assert(TokNum < getNumConcatenated() && "Invalid tok number")((TokNum < getNumConcatenated() && "Invalid tok number" ) ? static_cast<void> (0) : __assert_fail ("TokNum < getNumConcatenated() && \"Invalid tok number\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1745, __PRETTY_FUNCTION__)); |
1746 | getTrailingObjects<SourceLocation>()[TokNum] = L; |
1747 | } |
1748 | |
1749 | public: |
1750 | /// This is the "fully general" constructor that allows representation of |
1751 | /// strings formed from multiple concatenated tokens. |
1752 | static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, |
1753 | StringKind Kind, bool Pascal, QualType Ty, |
1754 | const SourceLocation *Loc, |
1755 | unsigned NumConcatenated); |
1756 | |
1757 | /// Simple constructor for string literals made from one token. |
1758 | static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, |
1759 | StringKind Kind, bool Pascal, QualType Ty, |
1760 | SourceLocation Loc) { |
1761 | return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1); |
1762 | } |
1763 | |
1764 | /// Construct an empty string literal. |
1765 | static StringLiteral *CreateEmpty(const ASTContext &Ctx, |
1766 | unsigned NumConcatenated, unsigned Length, |
1767 | unsigned CharByteWidth); |
1768 | |
1769 | StringRef getString() const { |
1770 | assert(getCharByteWidth() == 1 &&((getCharByteWidth() == 1 && "This function is used in places that assume strings use char" ) ? static_cast<void> (0) : __assert_fail ("getCharByteWidth() == 1 && \"This function is used in places that assume strings use char\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1771, __PRETTY_FUNCTION__)) |
1771 | "This function is used in places that assume strings use char")((getCharByteWidth() == 1 && "This function is used in places that assume strings use char" ) ? static_cast<void> (0) : __assert_fail ("getCharByteWidth() == 1 && \"This function is used in places that assume strings use char\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1771, __PRETTY_FUNCTION__)); |
1772 | return StringRef(getStrDataAsChar(), getByteLength()); |
1773 | } |
1774 | |
1775 | /// Allow access to clients that need the byte representation, such as |
1776 | /// ASTWriterStmt::VisitStringLiteral(). |
1777 | StringRef getBytes() const { |
1778 | // FIXME: StringRef may not be the right type to use as a result for this. |
1779 | return StringRef(getStrDataAsChar(), getByteLength()); |
1780 | } |
1781 | |
1782 | void outputString(raw_ostream &OS) const; |
1783 | |
1784 | uint32_t getCodeUnit(size_t i) const { |
1785 | assert(i < getLength() && "out of bounds access")((i < getLength() && "out of bounds access") ? static_cast <void> (0) : __assert_fail ("i < getLength() && \"out of bounds access\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1785, __PRETTY_FUNCTION__)); |
1786 | switch (getCharByteWidth()) { |
1787 | case 1: |
1788 | return static_cast<unsigned char>(getStrDataAsChar()[i]); |
1789 | case 2: |
1790 | return getStrDataAsUInt16()[i]; |
1791 | case 4: |
1792 | return getStrDataAsUInt32()[i]; |
1793 | } |
1794 | llvm_unreachable("Unsupported character width!")::llvm::llvm_unreachable_internal("Unsupported character width!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1794); |
1795 | } |
1796 | |
1797 | unsigned getByteLength() const { return getCharByteWidth() * getLength(); } |
1798 | unsigned getLength() const { return *getTrailingObjects<unsigned>(); } |
1799 | unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; } |
1800 | |
1801 | StringKind getKind() const { |
1802 | return static_cast<StringKind>(StringLiteralBits.Kind); |
1803 | } |
1804 | |
1805 | bool isAscii() const { return getKind() == Ascii; } |
1806 | bool isWide() const { return getKind() == Wide; } |
1807 | bool isUTF8() const { return getKind() == UTF8; } |
1808 | bool isUTF16() const { return getKind() == UTF16; } |
1809 | bool isUTF32() const { return getKind() == UTF32; } |
1810 | bool isPascal() const { return StringLiteralBits.IsPascal; } |
1811 | |
1812 | bool containsNonAscii() const { |
1813 | for (auto c : getString()) |
1814 | if (!isASCII(c)) |
1815 | return true; |
1816 | return false; |
1817 | } |
1818 | |
1819 | bool containsNonAsciiOrNull() const { |
1820 | for (auto c : getString()) |
1821 | if (!isASCII(c) || !c) |
1822 | return true; |
1823 | return false; |
1824 | } |
1825 | |
1826 | /// getNumConcatenated - Get the number of string literal tokens that were |
1827 | /// concatenated in translation phase #6 to form this string literal. |
1828 | unsigned getNumConcatenated() const { |
1829 | return StringLiteralBits.NumConcatenated; |
1830 | } |
1831 | |
1832 | /// Get one of the string literal token. |
1833 | SourceLocation getStrTokenLoc(unsigned TokNum) const { |
1834 | assert(TokNum < getNumConcatenated() && "Invalid tok number")((TokNum < getNumConcatenated() && "Invalid tok number" ) ? static_cast<void> (0) : __assert_fail ("TokNum < getNumConcatenated() && \"Invalid tok number\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1834, __PRETTY_FUNCTION__)); |
1835 | return getTrailingObjects<SourceLocation>()[TokNum]; |
1836 | } |
1837 | |
1838 | /// getLocationOfByte - Return a source location that points to the specified |
1839 | /// byte of this string literal. |
1840 | /// |
1841 | /// Strings are amazingly complex. They can be formed from multiple tokens |
1842 | /// and can have escape sequences in them in addition to the usual trigraph |
1843 | /// and escaped newline business. This routine handles this complexity. |
1844 | /// |
1845 | SourceLocation |
1846 | getLocationOfByte(unsigned ByteNo, const SourceManager &SM, |
1847 | const LangOptions &Features, const TargetInfo &Target, |
1848 | unsigned *StartToken = nullptr, |
1849 | unsigned *StartTokenByteOffset = nullptr) const; |
1850 | |
1851 | typedef const SourceLocation *tokloc_iterator; |
1852 | |
1853 | tokloc_iterator tokloc_begin() const { |
1854 | return getTrailingObjects<SourceLocation>(); |
1855 | } |
1856 | |
1857 | tokloc_iterator tokloc_end() const { |
1858 | return getTrailingObjects<SourceLocation>() + getNumConcatenated(); |
1859 | } |
1860 | |
1861 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return *tokloc_begin(); } |
1862 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return *(tokloc_end() - 1); } |
1863 | |
1864 | static bool classof(const Stmt *T) { |
1865 | return T->getStmtClass() == StringLiteralClass; |
1866 | } |
1867 | |
1868 | // Iterators |
1869 | child_range children() { |
1870 | return child_range(child_iterator(), child_iterator()); |
1871 | } |
1872 | const_child_range children() const { |
1873 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1874 | } |
1875 | }; |
1876 | |
1877 | /// [C99 6.4.2.2] - A predefined identifier such as __func__. |
1878 | class PredefinedExpr final |
1879 | : public Expr, |
1880 | private llvm::TrailingObjects<PredefinedExpr, Stmt *> { |
1881 | friend class ASTStmtReader; |
1882 | friend TrailingObjects; |
1883 | |
1884 | // PredefinedExpr is optionally followed by a single trailing |
1885 | // "Stmt *" for the predefined identifier. It is present if and only if |
1886 | // hasFunctionName() is true and is always a "StringLiteral *". |
1887 | |
1888 | public: |
1889 | enum IdentKind { |
1890 | Func, |
1891 | Function, |
1892 | LFunction, // Same as Function, but as wide string. |
1893 | FuncDName, |
1894 | FuncSig, |
1895 | LFuncSig, // Same as FuncSig, but as as wide string |
1896 | PrettyFunction, |
1897 | /// The same as PrettyFunction, except that the |
1898 | /// 'virtual' keyword is omitted for virtual member functions. |
1899 | PrettyFunctionNoVirtual |
1900 | }; |
1901 | |
1902 | private: |
1903 | PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK, |
1904 | StringLiteral *SL); |
1905 | |
1906 | explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName); |
1907 | |
1908 | /// True if this PredefinedExpr has storage for a function name. |
1909 | bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; } |
1910 | |
1911 | void setFunctionName(StringLiteral *SL) { |
1912 | assert(hasFunctionName() &&((hasFunctionName() && "This PredefinedExpr has no storage for a function name!" ) ? static_cast<void> (0) : __assert_fail ("hasFunctionName() && \"This PredefinedExpr has no storage for a function name!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1913, __PRETTY_FUNCTION__)) |
1913 | "This PredefinedExpr has no storage for a function name!")((hasFunctionName() && "This PredefinedExpr has no storage for a function name!" ) ? static_cast<void> (0) : __assert_fail ("hasFunctionName() && \"This PredefinedExpr has no storage for a function name!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1913, __PRETTY_FUNCTION__)); |
1914 | *getTrailingObjects<Stmt *>() = SL; |
1915 | } |
1916 | |
1917 | public: |
1918 | /// Create a PredefinedExpr. |
1919 | static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L, |
1920 | QualType FNTy, IdentKind IK, StringLiteral *SL); |
1921 | |
1922 | /// Create an empty PredefinedExpr. |
1923 | static PredefinedExpr *CreateEmpty(const ASTContext &Ctx, |
1924 | bool HasFunctionName); |
1925 | |
1926 | IdentKind getIdentKind() const { |
1927 | return static_cast<IdentKind>(PredefinedExprBits.Kind); |
1928 | } |
1929 | |
1930 | SourceLocation getLocation() const { return PredefinedExprBits.Loc; } |
1931 | void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; } |
1932 | |
1933 | StringLiteral *getFunctionName() { |
1934 | return hasFunctionName() |
1935 | ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) |
1936 | : nullptr; |
1937 | } |
1938 | |
1939 | const StringLiteral *getFunctionName() const { |
1940 | return hasFunctionName() |
1941 | ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) |
1942 | : nullptr; |
1943 | } |
1944 | |
1945 | static StringRef getIdentKindName(IdentKind IK); |
1946 | static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl); |
1947 | |
1948 | SourceLocation getBeginLoc() const { return getLocation(); } |
1949 | SourceLocation getEndLoc() const { return getLocation(); } |
1950 | |
1951 | static bool classof(const Stmt *T) { |
1952 | return T->getStmtClass() == PredefinedExprClass; |
1953 | } |
1954 | |
1955 | // Iterators |
1956 | child_range children() { |
1957 | return child_range(getTrailingObjects<Stmt *>(), |
1958 | getTrailingObjects<Stmt *>() + hasFunctionName()); |
1959 | } |
1960 | |
1961 | const_child_range children() const { |
1962 | return const_child_range(getTrailingObjects<Stmt *>(), |
1963 | getTrailingObjects<Stmt *>() + hasFunctionName()); |
1964 | } |
1965 | }; |
1966 | |
1967 | /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This |
1968 | /// AST node is only formed if full location information is requested. |
1969 | class ParenExpr : public Expr { |
1970 | SourceLocation L, R; |
1971 | Stmt *Val; |
1972 | public: |
1973 | ParenExpr(SourceLocation l, SourceLocation r, Expr *val) |
1974 | : Expr(ParenExprClass, val->getType(), |
1975 | val->getValueKind(), val->getObjectKind(), |
1976 | val->isTypeDependent(), val->isValueDependent(), |
1977 | val->isInstantiationDependent(), |
1978 | val->containsUnexpandedParameterPack()), |
1979 | L(l), R(r), Val(val) {} |
1980 | |
1981 | /// Construct an empty parenthesized expression. |
1982 | explicit ParenExpr(EmptyShell Empty) |
1983 | : Expr(ParenExprClass, Empty) { } |
1984 | |
1985 | const Expr *getSubExpr() const { return cast<Expr>(Val); } |
1986 | Expr *getSubExpr() { return cast<Expr>(Val); } |
1987 | void setSubExpr(Expr *E) { Val = E; } |
1988 | |
1989 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return L; } |
1990 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return R; } |
1991 | |
1992 | /// Get the location of the left parentheses '('. |
1993 | SourceLocation getLParen() const { return L; } |
1994 | void setLParen(SourceLocation Loc) { L = Loc; } |
1995 | |
1996 | /// Get the location of the right parentheses ')'. |
1997 | SourceLocation getRParen() const { return R; } |
1998 | void setRParen(SourceLocation Loc) { R = Loc; } |
1999 | |
2000 | static bool classof(const Stmt *T) { |
2001 | return T->getStmtClass() == ParenExprClass; |
2002 | } |
2003 | |
2004 | // Iterators |
2005 | child_range children() { return child_range(&Val, &Val+1); } |
2006 | const_child_range children() const { |
2007 | return const_child_range(&Val, &Val + 1); |
2008 | } |
2009 | }; |
2010 | |
2011 | /// UnaryOperator - This represents the unary-expression's (except sizeof and |
2012 | /// alignof), the postinc/postdec operators from postfix-expression, and various |
2013 | /// extensions. |
2014 | /// |
2015 | /// Notes on various nodes: |
2016 | /// |
2017 | /// Real/Imag - These return the real/imag part of a complex operand. If |
2018 | /// applied to a non-complex value, the former returns its operand and the |
2019 | /// later returns zero in the type of the operand. |
2020 | /// |
2021 | class UnaryOperator : public Expr { |
2022 | Stmt *Val; |
2023 | |
2024 | public: |
2025 | typedef UnaryOperatorKind Opcode; |
2026 | |
2027 | UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK, |
2028 | ExprObjectKind OK, SourceLocation l, bool CanOverflow) |
2029 | : Expr(UnaryOperatorClass, type, VK, OK, |
2030 | input->isTypeDependent() || type->isDependentType(), |
2031 | input->isValueDependent(), |
2032 | (input->isInstantiationDependent() || |
2033 | type->isInstantiationDependentType()), |
2034 | input->containsUnexpandedParameterPack()), |
2035 | Val(input) { |
2036 | UnaryOperatorBits.Opc = opc; |
2037 | UnaryOperatorBits.CanOverflow = CanOverflow; |
2038 | UnaryOperatorBits.Loc = l; |
2039 | } |
2040 | |
2041 | /// Build an empty unary operator. |
2042 | explicit UnaryOperator(EmptyShell Empty) : Expr(UnaryOperatorClass, Empty) { |
2043 | UnaryOperatorBits.Opc = UO_AddrOf; |
2044 | } |
2045 | |
2046 | Opcode getOpcode() const { |
2047 | return static_cast<Opcode>(UnaryOperatorBits.Opc); |
2048 | } |
2049 | void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; } |
2050 | |
2051 | Expr *getSubExpr() const { return cast<Expr>(Val); } |
2052 | void setSubExpr(Expr *E) { Val = E; } |
2053 | |
2054 | /// getOperatorLoc - Return the location of the operator. |
2055 | SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; } |
2056 | void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; } |
2057 | |
2058 | /// Returns true if the unary operator can cause an overflow. For instance, |
2059 | /// signed int i = INT_MAX; i++; |
2060 | /// signed char c = CHAR_MAX; c++; |
2061 | /// Due to integer promotions, c++ is promoted to an int before the postfix |
2062 | /// increment, and the result is an int that cannot overflow. However, i++ |
2063 | /// can overflow. |
2064 | bool canOverflow() const { return UnaryOperatorBits.CanOverflow; } |
2065 | void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; } |
2066 | |
2067 | /// isPostfix - Return true if this is a postfix operation, like x++. |
2068 | static bool isPostfix(Opcode Op) { |
2069 | return Op == UO_PostInc || Op == UO_PostDec; |
2070 | } |
2071 | |
2072 | /// isPrefix - Return true if this is a prefix operation, like --x. |
2073 | static bool isPrefix(Opcode Op) { |
2074 | return Op == UO_PreInc || Op == UO_PreDec; |
2075 | } |
2076 | |
2077 | bool isPrefix() const { return isPrefix(getOpcode()); } |
2078 | bool isPostfix() const { return isPostfix(getOpcode()); } |
2079 | |
2080 | static bool isIncrementOp(Opcode Op) { |
2081 | return Op == UO_PreInc || Op == UO_PostInc; |
2082 | } |
2083 | bool isIncrementOp() const { |
2084 | return isIncrementOp(getOpcode()); |
2085 | } |
2086 | |
2087 | static bool isDecrementOp(Opcode Op) { |
2088 | return Op == UO_PreDec || Op == UO_PostDec; |
2089 | } |
2090 | bool isDecrementOp() const { |
2091 | return isDecrementOp(getOpcode()); |
2092 | } |
2093 | |
2094 | static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } |
2095 | bool isIncrementDecrementOp() const { |
2096 | return isIncrementDecrementOp(getOpcode()); |
2097 | } |
2098 | |
2099 | static bool isArithmeticOp(Opcode Op) { |
2100 | return Op >= UO_Plus && Op <= UO_LNot; |
2101 | } |
2102 | bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } |
2103 | |
2104 | /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it |
2105 | /// corresponds to, e.g. "sizeof" or "[pre]++" |
2106 | static StringRef getOpcodeStr(Opcode Op); |
2107 | |
2108 | /// Retrieve the unary opcode that corresponds to the given |
2109 | /// overloaded operator. |
2110 | static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); |
2111 | |
2112 | /// Retrieve the overloaded operator kind that corresponds to |
2113 | /// the given unary opcode. |
2114 | static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); |
2115 | |
2116 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2117 | return isPostfix() ? Val->getBeginLoc() : getOperatorLoc(); |
2118 | } |
2119 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2120 | return isPostfix() ? getOperatorLoc() : Val->getEndLoc(); |
2121 | } |
2122 | SourceLocation getExprLoc() const { return getOperatorLoc(); } |
2123 | |
2124 | static bool classof(const Stmt *T) { |
2125 | return T->getStmtClass() == UnaryOperatorClass; |
2126 | } |
2127 | |
2128 | // Iterators |
2129 | child_range children() { return child_range(&Val, &Val+1); } |
2130 | const_child_range children() const { |
2131 | return const_child_range(&Val, &Val + 1); |
2132 | } |
2133 | }; |
2134 | |
2135 | /// Helper class for OffsetOfExpr. |
2136 | |
2137 | // __builtin_offsetof(type, identifier(.identifier|[expr])*) |
2138 | class OffsetOfNode { |
2139 | public: |
2140 | /// The kind of offsetof node we have. |
2141 | enum Kind { |
2142 | /// An index into an array. |
2143 | Array = 0x00, |
2144 | /// A field. |
2145 | Field = 0x01, |
2146 | /// A field in a dependent type, known only by its name. |
2147 | Identifier = 0x02, |
2148 | /// An implicit indirection through a C++ base class, when the |
2149 | /// field found is in a base class. |
2150 | Base = 0x03 |
2151 | }; |
2152 | |
2153 | private: |
2154 | enum { MaskBits = 2, Mask = 0x03 }; |
2155 | |
2156 | /// The source range that covers this part of the designator. |
2157 | SourceRange Range; |
2158 | |
2159 | /// The data describing the designator, which comes in three |
2160 | /// different forms, depending on the lower two bits. |
2161 | /// - An unsigned index into the array of Expr*'s stored after this node |
2162 | /// in memory, for [constant-expression] designators. |
2163 | /// - A FieldDecl*, for references to a known field. |
2164 | /// - An IdentifierInfo*, for references to a field with a given name |
2165 | /// when the class type is dependent. |
2166 | /// - A CXXBaseSpecifier*, for references that look at a field in a |
2167 | /// base class. |
2168 | uintptr_t Data; |
2169 | |
2170 | public: |
2171 | /// Create an offsetof node that refers to an array element. |
2172 | OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, |
2173 | SourceLocation RBracketLoc) |
2174 | : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {} |
2175 | |
2176 | /// Create an offsetof node that refers to a field. |
2177 | OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc) |
2178 | : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), |
2179 | Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {} |
2180 | |
2181 | /// Create an offsetof node that refers to an identifier. |
2182 | OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, |
2183 | SourceLocation NameLoc) |
2184 | : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), |
2185 | Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {} |
2186 | |
2187 | /// Create an offsetof node that refers into a C++ base class. |
2188 | explicit OffsetOfNode(const CXXBaseSpecifier *Base) |
2189 | : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} |
2190 | |
2191 | /// Determine what kind of offsetof node this is. |
2192 | Kind getKind() const { return static_cast<Kind>(Data & Mask); } |
2193 | |
2194 | /// For an array element node, returns the index into the array |
2195 | /// of expressions. |
2196 | unsigned getArrayExprIndex() const { |
2197 | assert(getKind() == Array)((getKind() == Array) ? static_cast<void> (0) : __assert_fail ("getKind() == Array", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2197, __PRETTY_FUNCTION__)); |
2198 | return Data >> 2; |
2199 | } |
2200 | |
2201 | /// For a field offsetof node, returns the field. |
2202 | FieldDecl *getField() const { |
2203 | assert(getKind() == Field)((getKind() == Field) ? static_cast<void> (0) : __assert_fail ("getKind() == Field", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2203, __PRETTY_FUNCTION__)); |
2204 | return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); |
2205 | } |
2206 | |
2207 | /// For a field or identifier offsetof node, returns the name of |
2208 | /// the field. |
2209 | IdentifierInfo *getFieldName() const; |
2210 | |
2211 | /// For a base class node, returns the base specifier. |
2212 | CXXBaseSpecifier *getBase() const { |
2213 | assert(getKind() == Base)((getKind() == Base) ? static_cast<void> (0) : __assert_fail ("getKind() == Base", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2213, __PRETTY_FUNCTION__)); |
2214 | return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); |
2215 | } |
2216 | |
2217 | /// Retrieve the source range that covers this offsetof node. |
2218 | /// |
2219 | /// For an array element node, the source range contains the locations of |
2220 | /// the square brackets. For a field or identifier node, the source range |
2221 | /// contains the location of the period (if there is one) and the |
2222 | /// identifier. |
2223 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; } |
2224 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); } |
2225 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); } |
2226 | }; |
2227 | |
2228 | /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form |
2229 | /// offsetof(record-type, member-designator). For example, given: |
2230 | /// @code |
2231 | /// struct S { |
2232 | /// float f; |
2233 | /// double d; |
2234 | /// }; |
2235 | /// struct T { |
2236 | /// int i; |
2237 | /// struct S s[10]; |
2238 | /// }; |
2239 | /// @endcode |
2240 | /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). |
2241 | |
2242 | class OffsetOfExpr final |
2243 | : public Expr, |
2244 | private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> { |
2245 | SourceLocation OperatorLoc, RParenLoc; |
2246 | // Base type; |
2247 | TypeSourceInfo *TSInfo; |
2248 | // Number of sub-components (i.e. instances of OffsetOfNode). |
2249 | unsigned NumComps; |
2250 | // Number of sub-expressions (i.e. array subscript expressions). |
2251 | unsigned NumExprs; |
2252 | |
2253 | size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const { |
2254 | return NumComps; |
2255 | } |
2256 | |
2257 | OffsetOfExpr(const ASTContext &C, QualType type, |
2258 | SourceLocation OperatorLoc, TypeSourceInfo *tsi, |
2259 | ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, |
2260 | SourceLocation RParenLoc); |
2261 | |
2262 | explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) |
2263 | : Expr(OffsetOfExprClass, EmptyShell()), |
2264 | TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {} |
2265 | |
2266 | public: |
2267 | |
2268 | static OffsetOfExpr *Create(const ASTContext &C, QualType type, |
2269 | SourceLocation OperatorLoc, TypeSourceInfo *tsi, |
2270 | ArrayRef<OffsetOfNode> comps, |
2271 | ArrayRef<Expr*> exprs, SourceLocation RParenLoc); |
2272 | |
2273 | static OffsetOfExpr *CreateEmpty(const ASTContext &C, |
2274 | unsigned NumComps, unsigned NumExprs); |
2275 | |
2276 | /// getOperatorLoc - Return the location of the operator. |
2277 | SourceLocation getOperatorLoc() const { return OperatorLoc; } |
2278 | void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } |
2279 | |
2280 | /// Return the location of the right parentheses. |
2281 | SourceLocation getRParenLoc() const { return RParenLoc; } |
2282 | void setRParenLoc(SourceLocation R) { RParenLoc = R; } |
2283 | |
2284 | TypeSourceInfo *getTypeSourceInfo() const { |
2285 | return TSInfo; |
2286 | } |
2287 | void setTypeSourceInfo(TypeSourceInfo *tsi) { |
2288 | TSInfo = tsi; |
2289 | } |
2290 | |
2291 | const OffsetOfNode &getComponent(unsigned Idx) const { |
2292 | assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2292, __PRETTY_FUNCTION__)); |
2293 | return getTrailingObjects<OffsetOfNode>()[Idx]; |
2294 | } |
2295 | |
2296 | void setComponent(unsigned Idx, OffsetOfNode ON) { |
2297 | assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2297, __PRETTY_FUNCTION__)); |
2298 | getTrailingObjects<OffsetOfNode>()[Idx] = ON; |
2299 | } |
2300 | |
2301 | unsigned getNumComponents() const { |
2302 | return NumComps; |
2303 | } |
2304 | |
2305 | Expr* getIndexExpr(unsigned Idx) { |
2306 | assert(Idx < NumExprs && "Subscript out of range")((Idx < NumExprs && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2306, __PRETTY_FUNCTION__)); |
2307 | return getTrailingObjects<Expr *>()[Idx]; |
2308 | } |
2309 | |
2310 | const Expr *getIndexExpr(unsigned Idx) const { |
2311 | assert(Idx < NumExprs && "Subscript out of range")((Idx < NumExprs && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2311, __PRETTY_FUNCTION__)); |
2312 | return getTrailingObjects<Expr *>()[Idx]; |
2313 | } |
2314 | |
2315 | void setIndexExpr(unsigned Idx, Expr* E) { |
2316 | assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2316, __PRETTY_FUNCTION__)); |
2317 | getTrailingObjects<Expr *>()[Idx] = E; |
2318 | } |
2319 | |
2320 | unsigned getNumExpressions() const { |
2321 | return NumExprs; |
2322 | } |
2323 | |
2324 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; } |
2325 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
2326 | |
2327 | static bool classof(const Stmt *T) { |
2328 | return T->getStmtClass() == OffsetOfExprClass; |
2329 | } |
2330 | |
2331 | // Iterators |
2332 | child_range children() { |
2333 | Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); |
2334 | return child_range(begin, begin + NumExprs); |
2335 | } |
2336 | const_child_range children() const { |
2337 | Stmt *const *begin = |
2338 | reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>()); |
2339 | return const_child_range(begin, begin + NumExprs); |
2340 | } |
2341 | friend TrailingObjects; |
2342 | }; |
2343 | |
2344 | /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) |
2345 | /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and |
2346 | /// vec_step (OpenCL 1.1 6.11.12). |
2347 | class UnaryExprOrTypeTraitExpr : public Expr { |
2348 | union { |
2349 | TypeSourceInfo *Ty; |
2350 | Stmt *Ex; |
2351 | } Argument; |
2352 | SourceLocation OpLoc, RParenLoc; |
2353 | |
2354 | public: |
2355 | UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, |
2356 | QualType resultType, SourceLocation op, |
2357 | SourceLocation rp) : |
2358 | Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, |
2359 | false, // Never type-dependent (C++ [temp.dep.expr]p3). |
2360 | // Value-dependent if the argument is type-dependent. |
2361 | TInfo->getType()->isDependentType(), |
2362 | TInfo->getType()->isInstantiationDependentType(), |
2363 | TInfo->getType()->containsUnexpandedParameterPack()), |
2364 | OpLoc(op), RParenLoc(rp) { |
2365 | UnaryExprOrTypeTraitExprBits.Kind = ExprKind; |
2366 | UnaryExprOrTypeTraitExprBits.IsType = true; |
2367 | Argument.Ty = TInfo; |
2368 | } |
2369 | |
2370 | UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, |
2371 | QualType resultType, SourceLocation op, |
2372 | SourceLocation rp); |
2373 | |
2374 | /// Construct an empty sizeof/alignof expression. |
2375 | explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) |
2376 | : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } |
2377 | |
2378 | UnaryExprOrTypeTrait getKind() const { |
2379 | return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind); |
2380 | } |
2381 | void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;} |
2382 | |
2383 | bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } |
2384 | QualType getArgumentType() const { |
2385 | return getArgumentTypeInfo()->getType(); |
2386 | } |
2387 | TypeSourceInfo *getArgumentTypeInfo() const { |
2388 | assert(isArgumentType() && "calling getArgumentType() when arg is expr")((isArgumentType() && "calling getArgumentType() when arg is expr" ) ? static_cast<void> (0) : __assert_fail ("isArgumentType() && \"calling getArgumentType() when arg is expr\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2388, __PRETTY_FUNCTION__)); |
2389 | return Argument.Ty; |
2390 | } |
2391 | Expr *getArgumentExpr() { |
2392 | assert(!isArgumentType() && "calling getArgumentExpr() when arg is type")((!isArgumentType() && "calling getArgumentExpr() when arg is type" ) ? static_cast<void> (0) : __assert_fail ("!isArgumentType() && \"calling getArgumentExpr() when arg is type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2392, __PRETTY_FUNCTION__)); |
2393 | return static_cast<Expr*>(Argument.Ex); |
2394 | } |
2395 | const Expr *getArgumentExpr() const { |
2396 | return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); |
2397 | } |
2398 | |
2399 | void setArgument(Expr *E) { |
2400 | Argument.Ex = E; |
2401 | UnaryExprOrTypeTraitExprBits.IsType = false; |
2402 | } |
2403 | void setArgument(TypeSourceInfo *TInfo) { |
2404 | Argument.Ty = TInfo; |
2405 | UnaryExprOrTypeTraitExprBits.IsType = true; |
2406 | } |
2407 | |
2408 | /// Gets the argument type, or the type of the argument expression, whichever |
2409 | /// is appropriate. |
2410 | QualType getTypeOfArgument() const { |
2411 | return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); |
2412 | } |
2413 | |
2414 | SourceLocation getOperatorLoc() const { return OpLoc; } |
2415 | void setOperatorLoc(SourceLocation L) { OpLoc = L; } |
2416 | |
2417 | SourceLocation getRParenLoc() const { return RParenLoc; } |
2418 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
2419 | |
2420 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OpLoc; } |
2421 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
2422 | |
2423 | static bool classof(const Stmt *T) { |
2424 | return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; |
2425 | } |
2426 | |
2427 | // Iterators |
2428 | child_range children(); |
2429 | const_child_range children() const; |
2430 | }; |
2431 | |
2432 | //===----------------------------------------------------------------------===// |
2433 | // Postfix Operators. |
2434 | //===----------------------------------------------------------------------===// |
2435 | |
2436 | /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. |
2437 | class ArraySubscriptExpr : public Expr { |
2438 | enum { LHS, RHS, END_EXPR }; |
2439 | Stmt *SubExprs[END_EXPR]; |
2440 | |
2441 | bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); } |
2442 | |
2443 | public: |
2444 | ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, |
2445 | ExprValueKind VK, ExprObjectKind OK, |
2446 | SourceLocation rbracketloc) |
2447 | : Expr(ArraySubscriptExprClass, t, VK, OK, |
2448 | lhs->isTypeDependent() || rhs->isTypeDependent(), |
2449 | lhs->isValueDependent() || rhs->isValueDependent(), |
2450 | (lhs->isInstantiationDependent() || |
2451 | rhs->isInstantiationDependent()), |
2452 | (lhs->containsUnexpandedParameterPack() || |
2453 | rhs->containsUnexpandedParameterPack())) { |
2454 | SubExprs[LHS] = lhs; |
2455 | SubExprs[RHS] = rhs; |
2456 | ArraySubscriptExprBits.RBracketLoc = rbracketloc; |
2457 | } |
2458 | |
2459 | /// Create an empty array subscript expression. |
2460 | explicit ArraySubscriptExpr(EmptyShell Shell) |
2461 | : Expr(ArraySubscriptExprClass, Shell) { } |
2462 | |
2463 | /// An array access can be written A[4] or 4[A] (both are equivalent). |
2464 | /// - getBase() and getIdx() always present the normalized view: A[4]. |
2465 | /// In this case getBase() returns "A" and getIdx() returns "4". |
2466 | /// - getLHS() and getRHS() present the syntactic view. e.g. for |
2467 | /// 4[A] getLHS() returns "4". |
2468 | /// Note: Because vector element access is also written A[4] we must |
2469 | /// predicate the format conversion in getBase and getIdx only on the |
2470 | /// the type of the RHS, as it is possible for the LHS to be a vector of |
2471 | /// integer type |
2472 | Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } |
2473 | const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } |
2474 | void setLHS(Expr *E) { SubExprs[LHS] = E; } |
2475 | |
2476 | Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } |
2477 | const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } |
2478 | void setRHS(Expr *E) { SubExprs[RHS] = E; } |
2479 | |
2480 | Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); } |
2481 | const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); } |
2482 | |
2483 | Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); } |
2484 | const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); } |
2485 | |
2486 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2487 | return getLHS()->getBeginLoc(); |
2488 | } |
2489 | SourceLocation getEndLoc() const { return getRBracketLoc(); } |
2490 | |
2491 | SourceLocation getRBracketLoc() const { |
2492 | return ArraySubscriptExprBits.RBracketLoc; |
2493 | } |
2494 | void setRBracketLoc(SourceLocation L) { |
2495 | ArraySubscriptExprBits.RBracketLoc = L; |
2496 | } |
2497 | |
2498 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2499 | return getBase()->getExprLoc(); |
2500 | } |
2501 | |
2502 | static bool classof(const Stmt *T) { |
2503 | return T->getStmtClass() == ArraySubscriptExprClass; |
2504 | } |
2505 | |
2506 | // Iterators |
2507 | child_range children() { |
2508 | return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); |
2509 | } |
2510 | const_child_range children() const { |
2511 | return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); |
2512 | } |
2513 | }; |
2514 | |
2515 | /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). |
2516 | /// CallExpr itself represents a normal function call, e.g., "f(x, 2)", |
2517 | /// while its subclasses may represent alternative syntax that (semantically) |
2518 | /// results in a function call. For example, CXXOperatorCallExpr is |
2519 | /// a subclass for overloaded operator calls that use operator syntax, e.g., |
2520 | /// "str1 + str2" to resolve to a function call. |
2521 | class CallExpr : public Expr { |
2522 | enum { FN = 0, PREARGS_START = 1 }; |
2523 | |
2524 | /// The number of arguments in the call expression. |
2525 | unsigned NumArgs; |
2526 | |
2527 | /// The location of the right parenthese. This has a different meaning for |
2528 | /// the derived classes of CallExpr. |
2529 | SourceLocation RParenLoc; |
2530 | |
2531 | void updateDependenciesFromArg(Expr *Arg); |
2532 | |
2533 | // CallExpr store some data in trailing objects. However since CallExpr |
2534 | // is used a base of other expression classes we cannot use |
2535 | // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic |
2536 | // and casts. |
2537 | // |
2538 | // The trailing objects are in order: |
2539 | // |
2540 | // * A single "Stmt *" for the callee expression. |
2541 | // |
2542 | // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions. |
2543 | // |
2544 | // * An array of getNumArgs() "Stmt *" for the argument expressions. |
2545 | // |
2546 | // Note that we store the offset in bytes from the this pointer to the start |
2547 | // of the trailing objects. It would be perfectly possible to compute it |
2548 | // based on the dynamic kind of the CallExpr. However 1.) we have plenty of |
2549 | // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to |
2550 | // compute this once and then load the offset from the bit-fields of Stmt, |
2551 | // instead of re-computing the offset each time the trailing objects are |
2552 | // accessed. |
2553 | |
2554 | /// Return a pointer to the start of the trailing array of "Stmt *". |
2555 | Stmt **getTrailingStmts() { |
2556 | return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) + |
2557 | CallExprBits.OffsetToTrailingObjects); |
2558 | } |
2559 | Stmt *const *getTrailingStmts() const { |
2560 | return const_cast<CallExpr *>(this)->getTrailingStmts(); |
2561 | } |
2562 | |
2563 | /// Map a statement class to the appropriate offset in bytes from the |
2564 | /// this pointer to the trailing objects. |
2565 | static unsigned offsetToTrailingObjects(StmtClass SC); |
2566 | |
2567 | public: |
2568 | enum class ADLCallKind : bool { NotADL, UsesADL }; |
2569 | static constexpr ADLCallKind NotADL = ADLCallKind::NotADL; |
2570 | static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL; |
2571 | |
2572 | protected: |
2573 | /// Build a call expression, assuming that appropriate storage has been |
2574 | /// allocated for the trailing objects. |
2575 | CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs, |
2576 | ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, |
2577 | SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL); |
2578 | |
2579 | /// Build an empty call expression, for deserialization. |
2580 | CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs, |
2581 | EmptyShell Empty); |
2582 | |
2583 | /// Return the size in bytes needed for the trailing objects. |
2584 | /// Used by the derived classes to allocate the right amount of storage. |
2585 | static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs) { |
2586 | return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *); |
2587 | } |
2588 | |
2589 | Stmt *getPreArg(unsigned I) { |
2590 | assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2590, __PRETTY_FUNCTION__)); |
2591 | return getTrailingStmts()[PREARGS_START + I]; |
2592 | } |
2593 | const Stmt *getPreArg(unsigned I) const { |
2594 | assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2594, __PRETTY_FUNCTION__)); |
2595 | return getTrailingStmts()[PREARGS_START + I]; |
2596 | } |
2597 | void setPreArg(unsigned I, Stmt *PreArg) { |
2598 | assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2598, __PRETTY_FUNCTION__)); |
2599 | getTrailingStmts()[PREARGS_START + I] = PreArg; |
2600 | } |
2601 | |
2602 | unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } |
2603 | |
2604 | public: |
2605 | /// Create a call expression. Fn is the callee expression, Args is the |
2606 | /// argument array, Ty is the type of the call expression (which is *not* |
2607 | /// the return type in general), VK is the value kind of the call expression |
2608 | /// (lvalue, rvalue, ...), and RParenLoc is the location of the right |
2609 | /// parenthese in the call expression. MinNumArgs specifies the minimum |
2610 | /// number of arguments. The actual number of arguments will be the greater |
2611 | /// of Args.size() and MinNumArgs. This is used in a few places to allocate |
2612 | /// enough storage for the default arguments. UsesADL specifies whether the |
2613 | /// callee was found through argument-dependent lookup. |
2614 | /// |
2615 | /// Note that you can use CreateTemporary if you need a temporary call |
2616 | /// expression on the stack. |
2617 | static CallExpr *Create(const ASTContext &Ctx, Expr *Fn, |
2618 | ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, |
2619 | SourceLocation RParenLoc, unsigned MinNumArgs = 0, |
2620 | ADLCallKind UsesADL = NotADL); |
2621 | |
2622 | /// Create a temporary call expression with no arguments in the memory |
2623 | /// pointed to by Mem. Mem must points to at least sizeof(CallExpr) |
2624 | /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr): |
2625 | /// |
2626 | /// \code{.cpp} |
2627 | /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; |
2628 | /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc); |
2629 | /// \endcode |
2630 | static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty, |
2631 | ExprValueKind VK, SourceLocation RParenLoc, |
2632 | ADLCallKind UsesADL = NotADL); |
2633 | |
2634 | /// Create an empty call expression, for deserialization. |
2635 | static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs, |
2636 | EmptyShell Empty); |
2637 | |
2638 | Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); } |
2639 | const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); } |
2640 | void setCallee(Expr *F) { getTrailingStmts()[FN] = F; } |
2641 | |
2642 | ADLCallKind getADLCallKind() const { |
2643 | return static_cast<ADLCallKind>(CallExprBits.UsesADL); |
2644 | } |
2645 | void setADLCallKind(ADLCallKind V = UsesADL) { |
2646 | CallExprBits.UsesADL = static_cast<bool>(V); |
2647 | } |
2648 | bool usesADL() const { return getADLCallKind() == UsesADL; } |
2649 | |
2650 | Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); } |
2651 | const Decl *getCalleeDecl() const { |
2652 | return getCallee()->getReferencedDeclOfCallee(); |
2653 | } |
2654 | |
2655 | /// If the callee is a FunctionDecl, return it. Otherwise return null. |
2656 | FunctionDecl *getDirectCallee() { |
2657 | return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); |
2658 | } |
2659 | const FunctionDecl *getDirectCallee() const { |
2660 | return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); |
2661 | } |
2662 | |
2663 | /// getNumArgs - Return the number of actual arguments to this call. |
2664 | unsigned getNumArgs() const { return NumArgs; } |
2665 | |
2666 | /// Retrieve the call arguments. |
2667 | Expr **getArgs() { |
2668 | return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START + |
2669 | getNumPreArgs()); |
2670 | } |
2671 | const Expr *const *getArgs() const { |
2672 | return reinterpret_cast<const Expr *const *>( |
2673 | getTrailingStmts() + PREARGS_START + getNumPreArgs()); |
2674 | } |
2675 | |
2676 | /// getArg - Return the specified argument. |
2677 | Expr *getArg(unsigned Arg) { |
2678 | assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2678, __PRETTY_FUNCTION__)); |
2679 | return getArgs()[Arg]; |
2680 | } |
2681 | const Expr *getArg(unsigned Arg) const { |
2682 | assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2682, __PRETTY_FUNCTION__)); |
2683 | return getArgs()[Arg]; |
2684 | } |
2685 | |
2686 | /// setArg - Set the specified argument. |
2687 | void setArg(unsigned Arg, Expr *ArgExpr) { |
2688 | assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2688, __PRETTY_FUNCTION__)); |
2689 | getArgs()[Arg] = ArgExpr; |
2690 | } |
2691 | |
2692 | /// Reduce the number of arguments in this call expression. This is used for |
2693 | /// example during error recovery to drop extra arguments. There is no way |
2694 | /// to perform the opposite because: 1.) We don't track how much storage |
2695 | /// we have for the argument array 2.) This would potentially require growing |
2696 | /// the argument array, something we cannot support since the arguments are |
2697 | /// stored in a trailing array. |
2698 | void shrinkNumArgs(unsigned NewNumArgs) { |
2699 | assert((NewNumArgs <= getNumArgs()) &&(((NewNumArgs <= getNumArgs()) && "shrinkNumArgs cannot increase the number of arguments!" ) ? static_cast<void> (0) : __assert_fail ("(NewNumArgs <= getNumArgs()) && \"shrinkNumArgs cannot increase the number of arguments!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2700, __PRETTY_FUNCTION__)) |
2700 | "shrinkNumArgs cannot increase the number of arguments!")(((NewNumArgs <= getNumArgs()) && "shrinkNumArgs cannot increase the number of arguments!" ) ? static_cast<void> (0) : __assert_fail ("(NewNumArgs <= getNumArgs()) && \"shrinkNumArgs cannot increase the number of arguments!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2700, __PRETTY_FUNCTION__)); |
2701 | NumArgs = NewNumArgs; |
2702 | } |
2703 | |
2704 | /// Bluntly set a new number of arguments without doing any checks whatsoever. |
2705 | /// Only used during construction of a CallExpr in a few places in Sema. |
2706 | /// FIXME: Find a way to remove it. |
2707 | void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; } |
2708 | |
2709 | typedef ExprIterator arg_iterator; |
2710 | typedef ConstExprIterator const_arg_iterator; |
2711 | typedef llvm::iterator_range<arg_iterator> arg_range; |
2712 | typedef llvm::iterator_range<const_arg_iterator> const_arg_range; |
2713 | |
2714 | arg_range arguments() { return arg_range(arg_begin(), arg_end()); } |
2715 | const_arg_range arguments() const { |
2716 | return const_arg_range(arg_begin(), arg_end()); |
2717 | } |
2718 | |
2719 | arg_iterator arg_begin() { |
2720 | return getTrailingStmts() + PREARGS_START + getNumPreArgs(); |
2721 | } |
2722 | arg_iterator arg_end() { return arg_begin() + getNumArgs(); } |
2723 | |
2724 | const_arg_iterator arg_begin() const { |
2725 | return getTrailingStmts() + PREARGS_START + getNumPreArgs(); |
2726 | } |
2727 | const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); } |
2728 | |
2729 | /// This method provides fast access to all the subexpressions of |
2730 | /// a CallExpr without going through the slower virtual child_iterator |
2731 | /// interface. This provides efficient reverse iteration of the |
2732 | /// subexpressions. This is currently used for CFG construction. |
2733 | ArrayRef<Stmt *> getRawSubExprs() { |
2734 | return llvm::makeArrayRef(getTrailingStmts(), |
2735 | PREARGS_START + getNumPreArgs() + getNumArgs()); |
2736 | } |
2737 | |
2738 | /// getNumCommas - Return the number of commas that must have been present in |
2739 | /// this function call. |
2740 | unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; } |
2741 | |
2742 | /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID |
2743 | /// of the callee. If not, return 0. |
2744 | unsigned getBuiltinCallee() const; |
2745 | |
2746 | /// Returns \c true if this is a call to a builtin which does not |
2747 | /// evaluate side-effects within its arguments. |
2748 | bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const; |
2749 | |
2750 | /// getCallReturnType - Get the return type of the call expr. This is not |
2751 | /// always the type of the expr itself, if the return type is a reference |
2752 | /// type. |
2753 | QualType getCallReturnType(const ASTContext &Ctx) const; |
2754 | |
2755 | /// Returns the WarnUnusedResultAttr that is either declared on the called |
2756 | /// function, or its return type declaration. |
2757 | const Attr *getUnusedResultAttr(const ASTContext &Ctx) const; |
2758 | |
2759 | /// Returns true if this call expression should warn on unused results. |
2760 | bool hasUnusedResultAttr(const ASTContext &Ctx) const { |
2761 | return getUnusedResultAttr(Ctx) != nullptr; |
2762 | } |
2763 | |
2764 | SourceLocation getRParenLoc() const { return RParenLoc; } |
2765 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
2766 | |
2767 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
2768 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
2769 | |
2770 | /// Return true if this is a call to __assume() or __builtin_assume() with |
2771 | /// a non-value-dependent constant parameter evaluating as false. |
2772 | bool isBuiltinAssumeFalse(const ASTContext &Ctx) const; |
2773 | |
2774 | bool isCallToStdMove() const { |
2775 | const FunctionDecl *FD = getDirectCallee(); |
2776 | return getNumArgs() == 1 && FD && FD->isInStdNamespace() && |
2777 | FD->getIdentifier() && FD->getIdentifier()->isStr("move"); |
2778 | } |
2779 | |
2780 | static bool classof(const Stmt *T) { |
2781 | return T->getStmtClass() >= firstCallExprConstant && |
2782 | T->getStmtClass() <= lastCallExprConstant; |
2783 | } |
2784 | |
2785 | // Iterators |
2786 | child_range children() { |
2787 | return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START + |
2788 | getNumPreArgs() + getNumArgs()); |
2789 | } |
2790 | |
2791 | const_child_range children() const { |
2792 | return const_child_range(getTrailingStmts(), |
2793 | getTrailingStmts() + PREARGS_START + |
2794 | getNumPreArgs() + getNumArgs()); |
2795 | } |
2796 | }; |
2797 | |
2798 | /// Extra data stored in some MemberExpr objects. |
2799 | struct MemberExprNameQualifier { |
2800 | /// The nested-name-specifier that qualifies the name, including |
2801 | /// source-location information. |
2802 | NestedNameSpecifierLoc QualifierLoc; |
2803 | |
2804 | /// The DeclAccessPair through which the MemberDecl was found due to |
2805 | /// name qualifiers. |
2806 | DeclAccessPair FoundDecl; |
2807 | }; |
2808 | |
2809 | /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. |
2810 | /// |
2811 | class MemberExpr final |
2812 | : public Expr, |
2813 | private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier, |
2814 | ASTTemplateKWAndArgsInfo, |
2815 | TemplateArgumentLoc> { |
2816 | friend class ASTReader; |
2817 | friend class ASTStmtReader; |
2818 | friend class ASTStmtWriter; |
2819 | friend TrailingObjects; |
2820 | |
2821 | /// Base - the expression for the base pointer or structure references. In |
2822 | /// X.F, this is "X". |
2823 | Stmt *Base; |
2824 | |
2825 | /// MemberDecl - This is the decl being referenced by the field/member name. |
2826 | /// In X.F, this is the decl referenced by F. |
2827 | ValueDecl *MemberDecl; |
2828 | |
2829 | /// MemberDNLoc - Provides source/type location info for the |
2830 | /// declaration name embedded in MemberDecl. |
2831 | DeclarationNameLoc MemberDNLoc; |
2832 | |
2833 | /// MemberLoc - This is the location of the member name. |
2834 | SourceLocation MemberLoc; |
2835 | |
2836 | size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const { |
2837 | return hasQualifierOrFoundDecl(); |
2838 | } |
2839 | |
2840 | size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { |
2841 | return hasTemplateKWAndArgsInfo(); |
2842 | } |
2843 | |
2844 | bool hasQualifierOrFoundDecl() const { |
2845 | return MemberExprBits.HasQualifierOrFoundDecl; |
2846 | } |
2847 | |
2848 | bool hasTemplateKWAndArgsInfo() const { |
2849 | return MemberExprBits.HasTemplateKWAndArgsInfo; |
2850 | } |
2851 | |
2852 | MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc, |
2853 | ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo, |
2854 | QualType T, ExprValueKind VK, ExprObjectKind OK, |
2855 | NonOdrUseReason NOUR); |
2856 | MemberExpr(EmptyShell Empty) |
2857 | : Expr(MemberExprClass, Empty), Base(), MemberDecl() {} |
2858 | |
2859 | public: |
2860 | static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow, |
2861 | SourceLocation OperatorLoc, |
2862 | NestedNameSpecifierLoc QualifierLoc, |
2863 | SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, |
2864 | DeclAccessPair FoundDecl, |
2865 | DeclarationNameInfo MemberNameInfo, |
2866 | const TemplateArgumentListInfo *TemplateArgs, |
2867 | QualType T, ExprValueKind VK, ExprObjectKind OK, |
2868 | NonOdrUseReason NOUR); |
2869 | |
2870 | /// Create an implicit MemberExpr, with no location, qualifier, template |
2871 | /// arguments, and so on. Suitable only for non-static member access. |
2872 | static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base, |
2873 | bool IsArrow, ValueDecl *MemberDecl, |
2874 | QualType T, ExprValueKind VK, |
2875 | ExprObjectKind OK) { |
2876 | return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(), |
2877 | SourceLocation(), MemberDecl, |
2878 | DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()), |
2879 | DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None); |
2880 | } |
2881 | |
2882 | static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, |
2883 | bool HasFoundDecl, |
2884 | bool HasTemplateKWAndArgsInfo, |
2885 | unsigned NumTemplateArgs); |
2886 | |
2887 | void setBase(Expr *E) { Base = E; } |
2888 | Expr *getBase() const { return cast<Expr>(Base); } |
2889 | |
2890 | /// Retrieve the member declaration to which this expression refers. |
2891 | /// |
2892 | /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for |
2893 | /// static data members), a CXXMethodDecl, or an EnumConstantDecl. |
2894 | ValueDecl *getMemberDecl() const { return MemberDecl; } |
2895 | void setMemberDecl(ValueDecl *D) { MemberDecl = D; } |
2896 | |
2897 | /// Retrieves the declaration found by lookup. |
2898 | DeclAccessPair getFoundDecl() const { |
2899 | if (!hasQualifierOrFoundDecl()) |
2900 | return DeclAccessPair::make(getMemberDecl(), |
2901 | getMemberDecl()->getAccess()); |
2902 | return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl; |
2903 | } |
2904 | |
2905 | /// Determines whether this member expression actually had |
2906 | /// a C++ nested-name-specifier prior to the name of the member, e.g., |
2907 | /// x->Base::foo. |
2908 | bool hasQualifier() const { return getQualifier() != nullptr; } |
2909 | |
2910 | /// If the member name was qualified, retrieves the |
2911 | /// nested-name-specifier that precedes the member name, with source-location |
2912 | /// information. |
2913 | NestedNameSpecifierLoc getQualifierLoc() const { |
2914 | if (!hasQualifierOrFoundDecl()) |
2915 | return NestedNameSpecifierLoc(); |
2916 | return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc; |
2917 | } |
2918 | |
2919 | /// If the member name was qualified, retrieves the |
2920 | /// nested-name-specifier that precedes the member name. Otherwise, returns |
2921 | /// NULL. |
2922 | NestedNameSpecifier *getQualifier() const { |
2923 | return getQualifierLoc().getNestedNameSpecifier(); |
2924 | } |
2925 | |
2926 | /// Retrieve the location of the template keyword preceding |
2927 | /// the member name, if any. |
2928 | SourceLocation getTemplateKeywordLoc() const { |
2929 | if (!hasTemplateKWAndArgsInfo()) |
2930 | return SourceLocation(); |
2931 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; |
2932 | } |
2933 | |
2934 | /// Retrieve the location of the left angle bracket starting the |
2935 | /// explicit template argument list following the member name, if any. |
2936 | SourceLocation getLAngleLoc() const { |
2937 | if (!hasTemplateKWAndArgsInfo()) |
2938 | return SourceLocation(); |
2939 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; |
2940 | } |
2941 | |
2942 | /// Retrieve the location of the right angle bracket ending the |
2943 | /// explicit template argument list following the member name, if any. |
2944 | SourceLocation getRAngleLoc() const { |
2945 | if (!hasTemplateKWAndArgsInfo()) |
2946 | return SourceLocation(); |
2947 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; |
2948 | } |
2949 | |
2950 | /// Determines whether the member name was preceded by the template keyword. |
2951 | bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } |
2952 | |
2953 | /// Determines whether the member name was followed by an |
2954 | /// explicit template argument list. |
2955 | bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } |
2956 | |
2957 | /// Copies the template arguments (if present) into the given |
2958 | /// structure. |
2959 | void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { |
2960 | if (hasExplicitTemplateArgs()) |
2961 | getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( |
2962 | getTrailingObjects<TemplateArgumentLoc>(), List); |
2963 | } |
2964 | |
2965 | /// Retrieve the template arguments provided as part of this |
2966 | /// template-id. |
2967 | const TemplateArgumentLoc *getTemplateArgs() const { |
2968 | if (!hasExplicitTemplateArgs()) |
2969 | return nullptr; |
2970 | |
2971 | return getTrailingObjects<TemplateArgumentLoc>(); |
2972 | } |
2973 | |
2974 | /// Retrieve the number of template arguments provided as part of this |
2975 | /// template-id. |
2976 | unsigned getNumTemplateArgs() const { |
2977 | if (!hasExplicitTemplateArgs()) |
2978 | return 0; |
2979 | |
2980 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; |
2981 | } |
2982 | |
2983 | ArrayRef<TemplateArgumentLoc> template_arguments() const { |
2984 | return {getTemplateArgs(), getNumTemplateArgs()}; |
2985 | } |
2986 | |
2987 | /// Retrieve the member declaration name info. |
2988 | DeclarationNameInfo getMemberNameInfo() const { |
2989 | return DeclarationNameInfo(MemberDecl->getDeclName(), |
2990 | MemberLoc, MemberDNLoc); |
2991 | } |
2992 | |
2993 | SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; } |
2994 | |
2995 | bool isArrow() const { return MemberExprBits.IsArrow; } |
2996 | void setArrow(bool A) { MemberExprBits.IsArrow = A; } |
2997 | |
2998 | /// getMemberLoc - Return the location of the "member", in X->F, it is the |
2999 | /// location of 'F'. |
3000 | SourceLocation getMemberLoc() const { return MemberLoc; } |
3001 | void setMemberLoc(SourceLocation L) { MemberLoc = L; } |
3002 | |
3003 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
3004 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
3005 | |
3006 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return MemberLoc; } |
3007 | |
3008 | /// Determine whether the base of this explicit is implicit. |
3009 | bool isImplicitAccess() const { |
3010 | return getBase() && getBase()->isImplicitCXXThis(); |
3011 | } |
3012 | |
3013 | /// Returns true if this member expression refers to a method that |
3014 | /// was resolved from an overloaded set having size greater than 1. |
3015 | bool hadMultipleCandidates() const { |
3016 | return MemberExprBits.HadMultipleCandidates; |
3017 | } |
3018 | /// Sets the flag telling whether this expression refers to |
3019 | /// a method that was resolved from an overloaded set having size |
3020 | /// greater than 1. |
3021 | void setHadMultipleCandidates(bool V = true) { |
3022 | MemberExprBits.HadMultipleCandidates = V; |
3023 | } |
3024 | |
3025 | /// Returns true if virtual dispatch is performed. |
3026 | /// If the member access is fully qualified, (i.e. X::f()), virtual |
3027 | /// dispatching is not performed. In -fapple-kext mode qualified |
3028 | /// calls to virtual method will still go through the vtable. |
3029 | bool performsVirtualDispatch(const LangOptions &LO) const { |
3030 | return LO.AppleKext || !hasQualifier(); |
3031 | } |
3032 | |
3033 | /// Is this expression a non-odr-use reference, and if so, why? |
3034 | /// This is only meaningful if the named member is a static member. |
3035 | NonOdrUseReason isNonOdrUse() const { |
3036 | return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason); |
3037 | } |
3038 | |
3039 | static bool classof(const Stmt *T) { |
3040 | return T->getStmtClass() == MemberExprClass; |
3041 | } |
3042 | |
3043 | // Iterators |
3044 | child_range children() { return child_range(&Base, &Base+1); } |
3045 | const_child_range children() const { |
3046 | return const_child_range(&Base, &Base + 1); |
3047 | } |
3048 | }; |
3049 | |
3050 | /// CompoundLiteralExpr - [C99 6.5.2.5] |
3051 | /// |
3052 | class CompoundLiteralExpr : public Expr { |
3053 | /// LParenLoc - If non-null, this is the location of the left paren in a |
3054 | /// compound literal like "(int){4}". This can be null if this is a |
3055 | /// synthesized compound expression. |
3056 | SourceLocation LParenLoc; |
3057 | |
3058 | /// The type as written. This can be an incomplete array type, in |
3059 | /// which case the actual expression type will be different. |
3060 | /// The int part of the pair stores whether this expr is file scope. |
3061 | llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope; |
3062 | Stmt *Init; |
3063 | public: |
3064 | CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, |
3065 | QualType T, ExprValueKind VK, Expr *init, bool fileScope) |
3066 | : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, |
3067 | tinfo->getType()->isDependentType(), |
3068 | init->isValueDependent(), |
3069 | (init->isInstantiationDependent() || |
3070 | tinfo->getType()->isInstantiationDependentType()), |
3071 | init->containsUnexpandedParameterPack()), |
3072 | LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {} |
3073 | |
3074 | /// Construct an empty compound literal. |
3075 | explicit CompoundLiteralExpr(EmptyShell Empty) |
3076 | : Expr(CompoundLiteralExprClass, Empty) { } |
3077 | |
3078 | const Expr *getInitializer() const { return cast<Expr>(Init); } |
3079 | Expr *getInitializer() { return cast<Expr>(Init); } |
3080 | void setInitializer(Expr *E) { Init = E; } |
3081 | |
3082 | bool isFileScope() const { return TInfoAndScope.getInt(); } |
3083 | void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } |
3084 | |
3085 | SourceLocation getLParenLoc() const { return LParenLoc; } |
3086 | void setLParenLoc(SourceLocation L) { LParenLoc = L; } |
3087 | |
3088 | TypeSourceInfo *getTypeSourceInfo() const { |
3089 | return TInfoAndScope.getPointer(); |
3090 | } |
3091 | void setTypeSourceInfo(TypeSourceInfo *tinfo) { |
3092 | TInfoAndScope.setPointer(tinfo); |
3093 | } |
3094 | |
3095 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3096 | // FIXME: Init should never be null. |
3097 | if (!Init) |
3098 | return SourceLocation(); |
3099 | if (LParenLoc.isInvalid()) |
3100 | return Init->getBeginLoc(); |
3101 | return LParenLoc; |
3102 | } |
3103 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3104 | // FIXME: Init should never be null. |
3105 | if (!Init) |
3106 | return SourceLocation(); |
3107 | return Init->getEndLoc(); |
3108 | } |
3109 | |
3110 | static bool classof(const Stmt *T) { |
3111 | return T->getStmtClass() == CompoundLiteralExprClass; |
3112 | } |
3113 | |
3114 | // Iterators |
3115 | child_range children() { return child_range(&Init, &Init+1); } |
3116 | const_child_range children() const { |
3117 | return const_child_range(&Init, &Init + 1); |
3118 | } |
3119 | }; |
3120 | |
3121 | /// CastExpr - Base class for type casts, including both implicit |
3122 | /// casts (ImplicitCastExpr) and explicit casts that have some |
3123 | /// representation in the source code (ExplicitCastExpr's derived |
3124 | /// classes). |
3125 | class CastExpr : public Expr { |
3126 | Stmt *Op; |
3127 | |
3128 | bool CastConsistency() const; |
3129 | |
3130 | const CXXBaseSpecifier * const *path_buffer() const { |
3131 | return const_cast<CastExpr*>(this)->path_buffer(); |
3132 | } |
3133 | CXXBaseSpecifier **path_buffer(); |
3134 | |
3135 | protected: |
3136 | CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind, |
3137 | Expr *op, unsigned BasePathSize) |
3138 | : Expr(SC, ty, VK, OK_Ordinary, |
3139 | // Cast expressions are type-dependent if the type is |
3140 | // dependent (C++ [temp.dep.expr]p3). |
3141 | ty->isDependentType(), |
3142 | // Cast expressions are value-dependent if the type is |
3143 | // dependent or if the subexpression is value-dependent. |
3144 | ty->isDependentType() || (op && op->isValueDependent()), |
3145 | (ty->isInstantiationDependentType() || |
3146 | (op && op->isInstantiationDependent())), |
3147 | // An implicit cast expression doesn't (lexically) contain an |
3148 | // unexpanded pack, even if its target type does. |
3149 | ((SC != ImplicitCastExprClass && |
3150 | ty->containsUnexpandedParameterPack()) || |
3151 | (op && op->containsUnexpandedParameterPack()))), |
3152 | Op(op) { |
3153 | CastExprBits.Kind = kind; |
3154 | CastExprBits.PartOfExplicitCast = false; |
3155 | CastExprBits.BasePathSize = BasePathSize; |
3156 | assert((CastExprBits.BasePathSize == BasePathSize) &&(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!" ) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3157, __PRETTY_FUNCTION__)) |
3157 | "BasePathSize overflow!")(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!" ) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3157, __PRETTY_FUNCTION__)); |
3158 | assert(CastConsistency())((CastConsistency()) ? static_cast<void> (0) : __assert_fail ("CastConsistency()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3158, __PRETTY_FUNCTION__)); |
3159 | } |
3160 | |
3161 | /// Construct an empty cast. |
3162 | CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) |
3163 | : Expr(SC, Empty) { |
3164 | CastExprBits.PartOfExplicitCast = false; |
3165 | CastExprBits.BasePathSize = BasePathSize; |
3166 | assert((CastExprBits.BasePathSize == BasePathSize) &&(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!" ) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3167, __PRETTY_FUNCTION__)) |
3167 | "BasePathSize overflow!")(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!" ) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3167, __PRETTY_FUNCTION__)); |
3168 | } |
3169 | |
3170 | public: |
3171 | CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } |
3172 | void setCastKind(CastKind K) { CastExprBits.Kind = K; } |
3173 | |
3174 | static const char *getCastKindName(CastKind CK); |
3175 | const char *getCastKindName() const { return getCastKindName(getCastKind()); } |
3176 | |
3177 | Expr *getSubExpr() { return cast<Expr>(Op); } |
3178 | const Expr *getSubExpr() const { return cast<Expr>(Op); } |
3179 | void setSubExpr(Expr *E) { Op = E; } |
3180 | |
3181 | /// Retrieve the cast subexpression as it was written in the source |
3182 | /// code, looking through any implicit casts or other intermediate nodes |
3183 | /// introduced by semantic analysis. |
3184 | Expr *getSubExprAsWritten(); |
3185 | const Expr *getSubExprAsWritten() const { |
3186 | return const_cast<CastExpr *>(this)->getSubExprAsWritten(); |
3187 | } |
3188 | |
3189 | /// If this cast applies a user-defined conversion, retrieve the conversion |
3190 | /// function that it invokes. |
3191 | NamedDecl *getConversionFunction() const; |
3192 | |
3193 | typedef CXXBaseSpecifier **path_iterator; |
3194 | typedef const CXXBaseSpecifier *const *path_const_iterator; |
3195 | bool path_empty() const { return path_size() == 0; } |
3196 | unsigned path_size() const { return CastExprBits.BasePathSize; } |
3197 | path_iterator path_begin() { return path_buffer(); } |
3198 | path_iterator path_end() { return path_buffer() + path_size(); } |
3199 | path_const_iterator path_begin() const { return path_buffer(); } |
3200 | path_const_iterator path_end() const { return path_buffer() + path_size(); } |
3201 | |
3202 | llvm::iterator_range<path_iterator> path() { |
3203 | return llvm::make_range(path_begin(), path_end()); |
3204 | } |
3205 | llvm::iterator_range<path_const_iterator> path() const { |
3206 | return llvm::make_range(path_begin(), path_end()); |
3207 | } |
3208 | |
3209 | const FieldDecl *getTargetUnionField() const { |
3210 | assert(getCastKind() == CK_ToUnion)((getCastKind() == CK_ToUnion) ? static_cast<void> (0) : __assert_fail ("getCastKind() == CK_ToUnion", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3210, __PRETTY_FUNCTION__)); |
3211 | return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType()); |
3212 | } |
3213 | |
3214 | static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType, |
3215 | QualType opType); |
3216 | static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD, |
3217 | QualType opType); |
3218 | |
3219 | static bool classof(const Stmt *T) { |
3220 | return T->getStmtClass() >= firstCastExprConstant && |
3221 | T->getStmtClass() <= lastCastExprConstant; |
3222 | } |
3223 | |
3224 | // Iterators |
3225 | child_range children() { return child_range(&Op, &Op+1); } |
3226 | const_child_range children() const { return const_child_range(&Op, &Op + 1); } |
3227 | }; |
3228 | |
3229 | /// ImplicitCastExpr - Allows us to explicitly represent implicit type |
3230 | /// conversions, which have no direct representation in the original |
3231 | /// source code. For example: converting T[]->T*, void f()->void |
3232 | /// (*f)(), float->double, short->int, etc. |
3233 | /// |
3234 | /// In C, implicit casts always produce rvalues. However, in C++, an |
3235 | /// implicit cast whose result is being bound to a reference will be |
3236 | /// an lvalue or xvalue. For example: |
3237 | /// |
3238 | /// @code |
3239 | /// class Base { }; |
3240 | /// class Derived : public Base { }; |
3241 | /// Derived &&ref(); |
3242 | /// void f(Derived d) { |
3243 | /// Base& b = d; // initializer is an ImplicitCastExpr |
3244 | /// // to an lvalue of type Base |
3245 | /// Base&& r = ref(); // initializer is an ImplicitCastExpr |
3246 | /// // to an xvalue of type Base |
3247 | /// } |
3248 | /// @endcode |
3249 | class ImplicitCastExpr final |
3250 | : public CastExpr, |
3251 | private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> { |
3252 | |
3253 | ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, |
3254 | unsigned BasePathLength, ExprValueKind VK) |
3255 | : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { } |
3256 | |
3257 | /// Construct an empty implicit cast. |
3258 | explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) |
3259 | : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } |
3260 | |
3261 | public: |
3262 | enum OnStack_t { OnStack }; |
3263 | ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, |
3264 | ExprValueKind VK) |
3265 | : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { |
3266 | } |
3267 | |
3268 | bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; } |
3269 | void setIsPartOfExplicitCast(bool PartOfExplicitCast) { |
3270 | CastExprBits.PartOfExplicitCast = PartOfExplicitCast; |
3271 | } |
3272 | |
3273 | static ImplicitCastExpr *Create(const ASTContext &Context, QualType T, |
3274 | CastKind Kind, Expr *Operand, |
3275 | const CXXCastPath *BasePath, |
3276 | ExprValueKind Cat); |
3277 | |
3278 | static ImplicitCastExpr *CreateEmpty(const ASTContext &Context, |
3279 | unsigned PathSize); |
3280 | |
3281 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3282 | return getSubExpr()->getBeginLoc(); |
3283 | } |
3284 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3285 | return getSubExpr()->getEndLoc(); |
3286 | } |
3287 | |
3288 | static bool classof(const Stmt *T) { |
3289 | return T->getStmtClass() == ImplicitCastExprClass; |
3290 | } |
3291 | |
3292 | friend TrailingObjects; |
3293 | friend class CastExpr; |
3294 | }; |
3295 | |
3296 | /// ExplicitCastExpr - An explicit cast written in the source |
3297 | /// code. |
3298 | /// |
3299 | /// This class is effectively an abstract class, because it provides |
3300 | /// the basic representation of an explicitly-written cast without |
3301 | /// specifying which kind of cast (C cast, functional cast, static |
3302 | /// cast, etc.) was written; specific derived classes represent the |
3303 | /// particular style of cast and its location information. |
3304 | /// |
3305 | /// Unlike implicit casts, explicit cast nodes have two different |
3306 | /// types: the type that was written into the source code, and the |
3307 | /// actual type of the expression as determined by semantic |
3308 | /// analysis. These types may differ slightly. For example, in C++ one |
3309 | /// can cast to a reference type, which indicates that the resulting |
3310 | /// expression will be an lvalue or xvalue. The reference type, however, |
3311 | /// will not be used as the type of the expression. |
3312 | class ExplicitCastExpr : public CastExpr { |
3313 | /// TInfo - Source type info for the (written) type |
3314 | /// this expression is casting to. |
3315 | TypeSourceInfo *TInfo; |
3316 | |
3317 | protected: |
3318 | ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, |
3319 | CastKind kind, Expr *op, unsigned PathSize, |
3320 | TypeSourceInfo *writtenTy) |
3321 | : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} |
3322 | |
3323 | /// Construct an empty explicit cast. |
3324 | ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) |
3325 | : CastExpr(SC, Shell, PathSize) { } |
3326 | |
3327 | public: |
3328 | /// getTypeInfoAsWritten - Returns the type source info for the type |
3329 | /// that this expression is casting to. |
3330 | TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } |
3331 | void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } |
3332 | |
3333 | /// getTypeAsWritten - Returns the type that this expression is |
3334 | /// casting to, as written in the source code. |
3335 | QualType getTypeAsWritten() const { return TInfo->getType(); } |
3336 | |
3337 | static bool classof(const Stmt *T) { |
3338 | return T->getStmtClass() >= firstExplicitCastExprConstant && |
3339 | T->getStmtClass() <= lastExplicitCastExprConstant; |
3340 | } |
3341 | }; |
3342 | |
3343 | /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style |
3344 | /// cast in C++ (C++ [expr.cast]), which uses the syntax |
3345 | /// (Type)expr. For example: @c (int)f. |
3346 | class CStyleCastExpr final |
3347 | : public ExplicitCastExpr, |
3348 | private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> { |
3349 | SourceLocation LPLoc; // the location of the left paren |
3350 | SourceLocation RPLoc; // the location of the right paren |
3351 | |
3352 | CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, |
3353 | unsigned PathSize, TypeSourceInfo *writtenTy, |
3354 | SourceLocation l, SourceLocation r) |
3355 | : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, |
3356 | writtenTy), LPLoc(l), RPLoc(r) {} |
3357 | |
3358 | /// Construct an empty C-style explicit cast. |
3359 | explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) |
3360 | : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } |
3361 | |
3362 | public: |
3363 | static CStyleCastExpr *Create(const ASTContext &Context, QualType T, |
3364 | ExprValueKind VK, CastKind K, |
3365 | Expr *Op, const CXXCastPath *BasePath, |
3366 | TypeSourceInfo *WrittenTy, SourceLocation L, |
3367 | SourceLocation R); |
3368 | |
3369 | static CStyleCastExpr *CreateEmpty(const ASTContext &Context, |
3370 | unsigned PathSize); |
3371 | |
3372 | SourceLocation getLParenLoc() const { return LPLoc; } |
3373 | void setLParenLoc(SourceLocation L) { LPLoc = L; } |
3374 | |
3375 | SourceLocation getRParenLoc() const { return RPLoc; } |
3376 | void setRParenLoc(SourceLocation L) { RPLoc = L; } |
3377 | |
3378 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LPLoc; } |
3379 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3380 | return getSubExpr()->getEndLoc(); |
3381 | } |
3382 | |
3383 | static bool classof(const Stmt *T) { |
3384 | return T->getStmtClass() == CStyleCastExprClass; |
3385 | } |
3386 | |
3387 | friend TrailingObjects; |
3388 | friend class CastExpr; |
3389 | }; |
3390 | |
3391 | /// A builtin binary operation expression such as "x + y" or "x <= y". |
3392 | /// |
3393 | /// This expression node kind describes a builtin binary operation, |
3394 | /// such as "x + y" for integer values "x" and "y". The operands will |
3395 | /// already have been converted to appropriate types (e.g., by |
3396 | /// performing promotions or conversions). |
3397 | /// |
3398 | /// In C++, where operators may be overloaded, a different kind of |
3399 | /// expression node (CXXOperatorCallExpr) is used to express the |
3400 | /// invocation of an overloaded operator with operator syntax. Within |
3401 | /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is |
3402 | /// used to store an expression "x + y" depends on the subexpressions |
3403 | /// for x and y. If neither x or y is type-dependent, and the "+" |
3404 | /// operator resolves to a built-in operation, BinaryOperator will be |
3405 | /// used to express the computation (x and y may still be |
3406 | /// value-dependent). If either x or y is type-dependent, or if the |
3407 | /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will |
3408 | /// be used to express the computation. |
3409 | class BinaryOperator : public Expr { |
3410 | enum { LHS, RHS, END_EXPR }; |
3411 | Stmt *SubExprs[END_EXPR]; |
3412 | |
3413 | public: |
3414 | typedef BinaryOperatorKind Opcode; |
3415 | |
3416 | BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, |
3417 | ExprValueKind VK, ExprObjectKind OK, |
3418 | SourceLocation opLoc, FPOptions FPFeatures) |
3419 | : Expr(BinaryOperatorClass, ResTy, VK, OK, |
3420 | lhs->isTypeDependent() || rhs->isTypeDependent(), |
3421 | lhs->isValueDependent() || rhs->isValueDependent(), |
3422 | (lhs->isInstantiationDependent() || |
3423 | rhs->isInstantiationDependent()), |
3424 | (lhs->containsUnexpandedParameterPack() || |
3425 | rhs->containsUnexpandedParameterPack())) { |
3426 | BinaryOperatorBits.Opc = opc; |
3427 | BinaryOperatorBits.FPFeatures = FPFeatures.getInt(); |
3428 | BinaryOperatorBits.OpLoc = opLoc; |
3429 | SubExprs[LHS] = lhs; |
3430 | SubExprs[RHS] = rhs; |
3431 | assert(!isCompoundAssignmentOp() &&((!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments" ) ? static_cast<void> (0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3432, __PRETTY_FUNCTION__)) |
3432 | "Use CompoundAssignOperator for compound assignments")((!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments" ) ? static_cast<void> (0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3432, __PRETTY_FUNCTION__)); |
3433 | } |
3434 | |
3435 | /// Construct an empty binary operator. |
3436 | explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) { |
3437 | BinaryOperatorBits.Opc = BO_Comma; |
3438 | } |
3439 | |
3440 | SourceLocation getExprLoc() const { return getOperatorLoc(); } |
3441 | SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; } |
3442 | void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; } |
3443 | |
3444 | Opcode getOpcode() const { |
3445 | return static_cast<Opcode>(BinaryOperatorBits.Opc); |
3446 | } |
3447 | void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; } |
3448 | |
3449 | Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } |
3450 | void setLHS(Expr *E) { SubExprs[LHS] = E; } |
3451 | Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } |
3452 | void setRHS(Expr *E) { SubExprs[RHS] = E; } |
3453 | |
3454 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3455 | return getLHS()->getBeginLoc(); |
3456 | } |
3457 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3458 | return getRHS()->getEndLoc(); |
3459 | } |
3460 | |
3461 | /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it |
3462 | /// corresponds to, e.g. "<<=". |
3463 | static StringRef getOpcodeStr(Opcode Op); |
3464 | |
3465 | StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } |
3466 | |
3467 | /// Retrieve the binary opcode that corresponds to the given |
3468 | /// overloaded operator. |
3469 | static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); |
3470 | |
3471 | /// Retrieve the overloaded operator kind that corresponds to |
3472 | /// the given binary opcode. |
3473 | static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); |
3474 | |
3475 | /// predicates to categorize the respective opcodes. |
3476 | static bool isPtrMemOp(Opcode Opc) { |
3477 | return Opc == BO_PtrMemD || Opc == BO_PtrMemI; |
3478 | } |
3479 | bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); } |
3480 | |
3481 | static bool isMultiplicativeOp(Opcode Opc) { |
3482 | return Opc >= BO_Mul && Opc <= BO_Rem; |
3483 | } |
3484 | bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); } |
3485 | static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } |
3486 | bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } |
3487 | static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } |
3488 | bool isShiftOp() const { return isShiftOp(getOpcode()); } |
3489 | |
3490 | static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } |
3491 | bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } |
3492 | |
3493 | static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } |
3494 | bool isRelationalOp() const { return isRelationalOp(getOpcode()); } |
3495 | |
3496 | static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } |
3497 | bool isEqualityOp() const { return isEqualityOp(getOpcode()); } |
3498 | |
3499 | static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; } |
3500 | bool isComparisonOp() const { return isComparisonOp(getOpcode()); } |
3501 | |
3502 | static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; } |
3503 | bool isCommaOp() const { return isCommaOp(getOpcode()); } |
3504 | |
3505 | static Opcode negateComparisonOp(Opcode Opc) { |
3506 | switch (Opc) { |
3507 | default: |
3508 | llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3508); |
3509 | case BO_LT: return BO_GE; |
3510 | case BO_GT: return BO_LE; |
3511 | case BO_LE: return BO_GT; |
3512 | case BO_GE: return BO_LT; |
3513 | case BO_EQ: return BO_NE; |
3514 | case BO_NE: return BO_EQ; |
3515 | } |
3516 | } |
3517 | |
3518 | static Opcode reverseComparisonOp(Opcode Opc) { |
3519 | switch (Opc) { |
3520 | default: |
3521 | llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3521); |
3522 | case BO_LT: return BO_GT; |
3523 | case BO_GT: return BO_LT; |
3524 | case BO_LE: return BO_GE; |
3525 | case BO_GE: return BO_LE; |
3526 | case BO_EQ: |
3527 | case BO_NE: |
3528 | return Opc; |
3529 | } |
3530 | } |
3531 | |
3532 | static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } |
3533 | bool isLogicalOp() const { return isLogicalOp(getOpcode()); } |
3534 | |
3535 | static bool isAssignmentOp(Opcode Opc) { |
3536 | return Opc >= BO_Assign && Opc <= BO_OrAssign; |
3537 | } |
3538 | bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } |
3539 | |
3540 | static bool isCompoundAssignmentOp(Opcode Opc) { |
3541 | return Opc > BO_Assign && Opc <= BO_OrAssign; |
3542 | } |
3543 | bool isCompoundAssignmentOp() const { |
3544 | return isCompoundAssignmentOp(getOpcode()); |
3545 | } |
3546 | static Opcode getOpForCompoundAssignment(Opcode Opc) { |
3547 | assert(isCompoundAssignmentOp(Opc))((isCompoundAssignmentOp(Opc)) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp(Opc)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3547, __PRETTY_FUNCTION__)); |
3548 | if (Opc >= BO_AndAssign) |
3549 | return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); |
3550 | else |
3551 | return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); |
3552 | } |
3553 | |
3554 | static bool isShiftAssignOp(Opcode Opc) { |
3555 | return Opc == BO_ShlAssign || Opc == BO_ShrAssign; |
3556 | } |
3557 | bool isShiftAssignOp() const { |
3558 | return isShiftAssignOp(getOpcode()); |
3559 | } |
3560 | |
3561 | // Return true if a binary operator using the specified opcode and operands |
3562 | // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized |
3563 | // integer to a pointer. |
3564 | static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, |
3565 | Expr *LHS, Expr *RHS); |
3566 | |
3567 | static bool classof(const Stmt *S) { |
3568 | return S->getStmtClass() >= firstBinaryOperatorConstant && |
3569 | S->getStmtClass() <= lastBinaryOperatorConstant; |
3570 | } |
3571 | |
3572 | // Iterators |
3573 | child_range children() { |
3574 | return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); |
3575 | } |
3576 | const_child_range children() const { |
3577 | return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); |
3578 | } |
3579 | |
3580 | // Set the FP contractability status of this operator. Only meaningful for |
3581 | // operations on floating point types. |
3582 | void setFPFeatures(FPOptions F) { |
3583 | BinaryOperatorBits.FPFeatures = F.getInt(); |
3584 | } |
3585 | |
3586 | FPOptions getFPFeatures() const { |
3587 | return FPOptions(BinaryOperatorBits.FPFeatures); |
3588 | } |
3589 | |
3590 | // Get the FP contractability status of this operator. Only meaningful for |
3591 | // operations on floating point types. |
3592 | bool isFPContractableWithinStatement() const { |
3593 | return getFPFeatures().allowFPContractWithinStatement(); |
3594 | } |
3595 | |
3596 | // Get the FENV_ACCESS status of this operator. Only meaningful for |
3597 | // operations on floating point types. |
3598 | bool isFEnvAccessOn() const { return getFPFeatures().allowFEnvAccess(); } |
3599 | |
3600 | protected: |
3601 | BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, |
3602 | ExprValueKind VK, ExprObjectKind OK, |
3603 | SourceLocation opLoc, FPOptions FPFeatures, bool dead2) |
3604 | : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, |
3605 | lhs->isTypeDependent() || rhs->isTypeDependent(), |
3606 | lhs->isValueDependent() || rhs->isValueDependent(), |
3607 | (lhs->isInstantiationDependent() || |
3608 | rhs->isInstantiationDependent()), |
3609 | (lhs->containsUnexpandedParameterPack() || |
3610 | rhs->containsUnexpandedParameterPack())) { |
3611 | BinaryOperatorBits.Opc = opc; |
3612 | BinaryOperatorBits.FPFeatures = FPFeatures.getInt(); |
3613 | BinaryOperatorBits.OpLoc = opLoc; |
3614 | SubExprs[LHS] = lhs; |
3615 | SubExprs[RHS] = rhs; |
3616 | } |
3617 | |
3618 | BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) { |
3619 | BinaryOperatorBits.Opc = BO_MulAssign; |
3620 | } |
3621 | }; |
3622 | |
3623 | /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep |
3624 | /// track of the type the operation is performed in. Due to the semantics of |
3625 | /// these operators, the operands are promoted, the arithmetic performed, an |
3626 | /// implicit conversion back to the result type done, then the assignment takes |
3627 | /// place. This captures the intermediate type which the computation is done |
3628 | /// in. |
3629 | class CompoundAssignOperator : public BinaryOperator { |
3630 | QualType ComputationLHSType; |
3631 | QualType ComputationResultType; |
3632 | public: |
3633 | CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, |
3634 | ExprValueKind VK, ExprObjectKind OK, |
3635 | QualType CompLHSType, QualType CompResultType, |
3636 | SourceLocation OpLoc, FPOptions FPFeatures) |
3637 | : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures, |
3638 | true), |
3639 | ComputationLHSType(CompLHSType), |
3640 | ComputationResultType(CompResultType) { |
3641 | assert(isCompoundAssignmentOp() &&((isCompoundAssignmentOp() && "Only should be used for compound assignments" ) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3642, __PRETTY_FUNCTION__)) |
3642 | "Only should be used for compound assignments")((isCompoundAssignmentOp() && "Only should be used for compound assignments" ) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3642, __PRETTY_FUNCTION__)); |
3643 | } |
3644 | |
3645 | /// Build an empty compound assignment operator expression. |
3646 | explicit CompoundAssignOperator(EmptyShell Empty) |
3647 | : BinaryOperator(CompoundAssignOperatorClass, Empty) { } |
3648 | |
3649 | // The two computation types are the type the LHS is converted |
3650 | // to for the computation and the type of the result; the two are |
3651 | // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). |
3652 | QualType getComputationLHSType() const { return ComputationLHSType; } |
3653 | void setComputationLHSType(QualType T) { ComputationLHSType = T; } |
3654 | |
3655 | QualType getComputationResultType() const { return ComputationResultType; } |
3656 | void setComputationResultType(QualType T) { ComputationResultType = T; } |
3657 | |
3658 | static bool classof(const Stmt *S) { |
3659 | return S->getStmtClass() == CompoundAssignOperatorClass; |
3660 | } |
3661 | }; |
3662 | |
3663 | /// AbstractConditionalOperator - An abstract base class for |
3664 | /// ConditionalOperator and BinaryConditionalOperator. |
3665 | class AbstractConditionalOperator : public Expr { |
3666 | SourceLocation QuestionLoc, ColonLoc; |
3667 | friend class ASTStmtReader; |
3668 | |
3669 | protected: |
3670 | AbstractConditionalOperator(StmtClass SC, QualType T, |
3671 | ExprValueKind VK, ExprObjectKind OK, |
3672 | bool TD, bool VD, bool ID, |
3673 | bool ContainsUnexpandedParameterPack, |
3674 | SourceLocation qloc, |
3675 | SourceLocation cloc) |
3676 | : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack), |
3677 | QuestionLoc(qloc), ColonLoc(cloc) {} |
3678 | |
3679 | AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) |
3680 | : Expr(SC, Empty) { } |
3681 | |
3682 | public: |
3683 | // getCond - Return the expression representing the condition for |
3684 | // the ?: operator. |
3685 | Expr *getCond() const; |
3686 | |
3687 | // getTrueExpr - Return the subexpression representing the value of |
3688 | // the expression if the condition evaluates to true. |
3689 | Expr *getTrueExpr() const; |
3690 | |
3691 | // getFalseExpr - Return the subexpression representing the value of |
3692 | // the expression if the condition evaluates to false. This is |
3693 | // the same as getRHS. |
3694 | Expr *getFalseExpr() const; |
3695 | |
3696 | SourceLocation getQuestionLoc() const { return QuestionLoc; } |
3697 | SourceLocation getColonLoc() const { return ColonLoc; } |
3698 | |
3699 | static bool classof(const Stmt *T) { |
3700 | return T->getStmtClass() == ConditionalOperatorClass || |
3701 | T->getStmtClass() == BinaryConditionalOperatorClass; |
3702 | } |
3703 | }; |
3704 | |
3705 | /// ConditionalOperator - The ?: ternary operator. The GNU "missing |
3706 | /// middle" extension is a BinaryConditionalOperator. |
3707 | class ConditionalOperator : public AbstractConditionalOperator { |
3708 | enum { COND, LHS, RHS, END_EXPR }; |
3709 | Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. |
3710 | |
3711 | friend class ASTStmtReader; |
3712 | public: |
3713 | ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, |
3714 | SourceLocation CLoc, Expr *rhs, |
3715 | QualType t, ExprValueKind VK, ExprObjectKind OK) |
3716 | : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, |
3717 | // FIXME: the type of the conditional operator doesn't |
3718 | // depend on the type of the conditional, but the standard |
3719 | // seems to imply that it could. File a bug! |
3720 | (lhs->isTypeDependent() || rhs->isTypeDependent()), |
3721 | (cond->isValueDependent() || lhs->isValueDependent() || |
3722 | rhs->isValueDependent()), |
3723 | (cond->isInstantiationDependent() || |
3724 | lhs->isInstantiationDependent() || |
3725 | rhs->isInstantiationDependent()), |
3726 | (cond->containsUnexpandedParameterPack() || |
3727 | lhs->containsUnexpandedParameterPack() || |
3728 | rhs->containsUnexpandedParameterPack()), |
3729 | QLoc, CLoc) { |
3730 | SubExprs[COND] = cond; |
3731 | SubExprs[LHS] = lhs; |
3732 | SubExprs[RHS] = rhs; |
3733 | } |
3734 | |
3735 | /// Build an empty conditional operator. |
3736 | explicit ConditionalOperator(EmptyShell Empty) |
3737 | : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } |
3738 | |
3739 | // getCond - Return the expression representing the condition for |
3740 | // the ?: operator. |
3741 | Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } |
3742 | |
3743 | // getTrueExpr - Return the subexpression representing the value of |
3744 | // the expression if the condition evaluates to true. |
3745 | Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } |
3746 | |
3747 | // getFalseExpr - Return the subexpression representing the value of |
3748 | // the expression if the condition evaluates to false. This is |
3749 | // the same as getRHS. |
3750 | Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } |
3751 | |
3752 | Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } |
3753 | Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } |
3754 | |
3755 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3756 | return getCond()->getBeginLoc(); |
3757 | } |
3758 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3759 | return getRHS()->getEndLoc(); |
3760 | } |
3761 | |
3762 | static bool classof(const Stmt *T) { |
3763 | return T->getStmtClass() == ConditionalOperatorClass; |
3764 | } |
3765 | |
3766 | // Iterators |
3767 | child_range children() { |
3768 | return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); |
3769 | } |
3770 | const_child_range children() const { |
3771 | return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); |
3772 | } |
3773 | }; |
3774 | |
3775 | /// BinaryConditionalOperator - The GNU extension to the conditional |
3776 | /// operator which allows the middle operand to be omitted. |
3777 | /// |
3778 | /// This is a different expression kind on the assumption that almost |
3779 | /// every client ends up needing to know that these are different. |
3780 | class BinaryConditionalOperator : public AbstractConditionalOperator { |
3781 | enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; |
3782 | |
3783 | /// - the common condition/left-hand-side expression, which will be |
3784 | /// evaluated as the opaque value |
3785 | /// - the condition, expressed in terms of the opaque value |
3786 | /// - the left-hand-side, expressed in terms of the opaque value |
3787 | /// - the right-hand-side |
3788 | Stmt *SubExprs[NUM_SUBEXPRS]; |
3789 | OpaqueValueExpr *OpaqueValue; |
3790 | |
3791 | friend class ASTStmtReader; |
3792 | public: |
3793 | BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, |
3794 | Expr *cond, Expr *lhs, Expr *rhs, |
3795 | SourceLocation qloc, SourceLocation cloc, |
3796 | QualType t, ExprValueKind VK, ExprObjectKind OK) |
3797 | : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, |
3798 | (common->isTypeDependent() || rhs->isTypeDependent()), |
3799 | (common->isValueDependent() || rhs->isValueDependent()), |
3800 | (common->isInstantiationDependent() || |
3801 | rhs->isInstantiationDependent()), |
3802 | (common->containsUnexpandedParameterPack() || |
3803 | rhs->containsUnexpandedParameterPack()), |
3804 | qloc, cloc), |
3805 | OpaqueValue(opaqueValue) { |
3806 | SubExprs[COMMON] = common; |
3807 | SubExprs[COND] = cond; |
3808 | SubExprs[LHS] = lhs; |
3809 | SubExprs[RHS] = rhs; |
3810 | assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value")((OpaqueValue->getSourceExpr() == common && "Wrong opaque value" ) ? static_cast<void> (0) : __assert_fail ("OpaqueValue->getSourceExpr() == common && \"Wrong opaque value\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3810, __PRETTY_FUNCTION__)); |
3811 | } |
3812 | |
3813 | /// Build an empty conditional operator. |
3814 | explicit BinaryConditionalOperator(EmptyShell Empty) |
3815 | : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } |
3816 | |
3817 | /// getCommon - Return the common expression, written to the |
3818 | /// left of the condition. The opaque value will be bound to the |
3819 | /// result of this expression. |
3820 | Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } |
3821 | |
3822 | /// getOpaqueValue - Return the opaque value placeholder. |
3823 | OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } |
3824 | |
3825 | /// getCond - Return the condition expression; this is defined |
3826 | /// in terms of the opaque value. |
3827 | Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } |
3828 | |
3829 | /// getTrueExpr - Return the subexpression which will be |
3830 | /// evaluated if the condition evaluates to true; this is defined |
3831 | /// in terms of the opaque value. |
3832 | Expr *getTrueExpr() const { |
3833 | return cast<Expr>(SubExprs[LHS]); |
3834 | } |
3835 | |
3836 | /// getFalseExpr - Return the subexpression which will be |
3837 | /// evaluated if the condnition evaluates to false; this is |
3838 | /// defined in terms of the opaque value. |
3839 | Expr *getFalseExpr() const { |
3840 | return cast<Expr>(SubExprs[RHS]); |
3841 | } |
3842 | |
3843 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3844 | return getCommon()->getBeginLoc(); |
3845 | } |
3846 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3847 | return getFalseExpr()->getEndLoc(); |
3848 | } |
3849 | |
3850 | static bool classof(const Stmt *T) { |
3851 | return T->getStmtClass() == BinaryConditionalOperatorClass; |
3852 | } |
3853 | |
3854 | // Iterators |
3855 | child_range children() { |
3856 | return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); |
3857 | } |
3858 | const_child_range children() const { |
3859 | return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS); |
3860 | } |
3861 | }; |
3862 | |
3863 | inline Expr *AbstractConditionalOperator::getCond() const { |
3864 | if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) |
3865 | return co->getCond(); |
3866 | return cast<BinaryConditionalOperator>(this)->getCond(); |
3867 | } |
3868 | |
3869 | inline Expr *AbstractConditionalOperator::getTrueExpr() const { |
3870 | if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) |
3871 | return co->getTrueExpr(); |
3872 | return cast<BinaryConditionalOperator>(this)->getTrueExpr(); |
3873 | } |
3874 | |
3875 | inline Expr *AbstractConditionalOperator::getFalseExpr() const { |
3876 | if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) |
3877 | return co->getFalseExpr(); |
3878 | return cast<BinaryConditionalOperator>(this)->getFalseExpr(); |
3879 | } |
3880 | |
3881 | /// AddrLabelExpr - The GNU address of label extension, representing &&label. |
3882 | class AddrLabelExpr : public Expr { |
3883 | SourceLocation AmpAmpLoc, LabelLoc; |
3884 | LabelDecl *Label; |
3885 | public: |
3886 | AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, |
3887 | QualType t) |
3888 | : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false, |
3889 | false), |
3890 | AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} |
3891 | |
3892 | /// Build an empty address of a label expression. |
3893 | explicit AddrLabelExpr(EmptyShell Empty) |
3894 | : Expr(AddrLabelExprClass, Empty) { } |
3895 | |
3896 | SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } |
3897 | void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } |
3898 | SourceLocation getLabelLoc() const { return LabelLoc; } |
3899 | void setLabelLoc(SourceLocation L) { LabelLoc = L; } |
3900 | |
3901 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return AmpAmpLoc; } |
3902 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return LabelLoc; } |
3903 | |
3904 | LabelDecl *getLabel() const { return Label; } |
3905 | void setLabel(LabelDecl *L) { Label = L; } |
3906 | |
3907 | static bool classof(const Stmt *T) { |
3908 | return T->getStmtClass() == AddrLabelExprClass; |
3909 | } |
3910 | |
3911 | // Iterators |
3912 | child_range children() { |
3913 | return child_range(child_iterator(), child_iterator()); |
3914 | } |
3915 | const_child_range children() const { |
3916 | return const_child_range(const_child_iterator(), const_child_iterator()); |
3917 | } |
3918 | }; |
3919 | |
3920 | /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). |
3921 | /// The StmtExpr contains a single CompoundStmt node, which it evaluates and |
3922 | /// takes the value of the last subexpression. |
3923 | /// |
3924 | /// A StmtExpr is always an r-value; values "returned" out of a |
3925 | /// StmtExpr will be copied. |
3926 | class StmtExpr : public Expr { |
3927 | Stmt *SubStmt; |
3928 | SourceLocation LParenLoc, RParenLoc; |
3929 | public: |
3930 | // FIXME: Does type-dependence need to be computed differently? |
3931 | // FIXME: Do we need to compute instantiation instantiation-dependence for |
3932 | // statements? (ugh!) |
3933 | StmtExpr(CompoundStmt *substmt, QualType T, |
3934 | SourceLocation lp, SourceLocation rp) : |
3935 | Expr(StmtExprClass, T, VK_RValue, OK_Ordinary, |
3936 | T->isDependentType(), false, false, false), |
3937 | SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } |
3938 | |
3939 | /// Build an empty statement expression. |
3940 | explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } |
3941 | |
3942 | CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } |
3943 | const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } |
3944 | void setSubStmt(CompoundStmt *S) { SubStmt = S; } |
3945 | |
3946 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LParenLoc; } |
3947 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
3948 | |
3949 | SourceLocation getLParenLoc() const { return LParenLoc; } |
3950 | void setLParenLoc(SourceLocation L) { LParenLoc = L; } |
3951 | SourceLocation getRParenLoc() const { return RParenLoc; } |
3952 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
3953 | |
3954 | static bool classof(const Stmt *T) { |
3955 | return T->getStmtClass() == StmtExprClass; |
3956 | } |
3957 | |
3958 | // Iterators |
3959 | child_range children() { return child_range(&SubStmt, &SubStmt+1); } |
3960 | const_child_range children() const { |
3961 | return const_child_range(&SubStmt, &SubStmt + 1); |
3962 | } |
3963 | }; |
3964 | |
3965 | /// ShuffleVectorExpr - clang-specific builtin-in function |
3966 | /// __builtin_shufflevector. |
3967 | /// This AST node represents a operator that does a constant |
3968 | /// shuffle, similar to LLVM's shufflevector instruction. It takes |
3969 | /// two vectors and a variable number of constant indices, |
3970 | /// and returns the appropriately shuffled vector. |
3971 | class ShuffleVectorExpr : public Expr { |
3972 | SourceLocation BuiltinLoc, RParenLoc; |
3973 | |
3974 | // SubExprs - the list of values passed to the __builtin_shufflevector |
3975 | // function. The first two are vectors, and the rest are constant |
3976 | // indices. The number of values in this list is always |
3977 | // 2+the number of indices in the vector type. |
3978 | Stmt **SubExprs; |
3979 | unsigned NumExprs; |
3980 | |
3981 | public: |
3982 | ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type, |
3983 | SourceLocation BLoc, SourceLocation RP); |
3984 | |
3985 | /// Build an empty vector-shuffle expression. |
3986 | explicit ShuffleVectorExpr(EmptyShell Empty) |
3987 | : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { } |
3988 | |
3989 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
3990 | void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } |
3991 | |
3992 | SourceLocation getRParenLoc() const { return RParenLoc; } |
3993 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
3994 | |
3995 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
3996 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
3997 | |
3998 | static bool classof(const Stmt *T) { |
3999 | return T->getStmtClass() == ShuffleVectorExprClass; |
4000 | } |
4001 | |
4002 | /// getNumSubExprs - Return the size of the SubExprs array. This includes the |
4003 | /// constant expression, the actual arguments passed in, and the function |
4004 | /// pointers. |
4005 | unsigned getNumSubExprs() const { return NumExprs; } |
4006 | |
4007 | /// Retrieve the array of expressions. |
4008 | Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } |
4009 | |
4010 | /// getExpr - Return the Expr at the specified index. |
4011 | Expr *getExpr(unsigned Index) { |
4012 | assert((Index < NumExprs) && "Arg access out of range!")(((Index < NumExprs) && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("(Index < NumExprs) && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4012, __PRETTY_FUNCTION__)); |
4013 | return cast<Expr>(SubExprs[Index]); |
4014 | } |
4015 | const Expr *getExpr(unsigned Index) const { |
4016 | assert((Index < NumExprs) && "Arg access out of range!")(((Index < NumExprs) && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("(Index < NumExprs) && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4016, __PRETTY_FUNCTION__)); |
4017 | return cast<Expr>(SubExprs[Index]); |
4018 | } |
4019 | |
4020 | void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs); |
4021 | |
4022 | llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const { |
4023 | assert((N < NumExprs - 2) && "Shuffle idx out of range!")(((N < NumExprs - 2) && "Shuffle idx out of range!" ) ? static_cast<void> (0) : __assert_fail ("(N < NumExprs - 2) && \"Shuffle idx out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4023, __PRETTY_FUNCTION__)); |
4024 | return getExpr(N+2)->EvaluateKnownConstInt(Ctx); |
4025 | } |
4026 | |
4027 | // Iterators |
4028 | child_range children() { |
4029 | return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); |
4030 | } |
4031 | const_child_range children() const { |
4032 | return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs); |
4033 | } |
4034 | }; |
4035 | |
4036 | /// ConvertVectorExpr - Clang builtin function __builtin_convertvector |
4037 | /// This AST node provides support for converting a vector type to another |
4038 | /// vector type of the same arity. |
4039 | class ConvertVectorExpr : public Expr { |
4040 | private: |
4041 | Stmt *SrcExpr; |
4042 | TypeSourceInfo *TInfo; |
4043 | SourceLocation BuiltinLoc, RParenLoc; |
4044 | |
4045 | friend class ASTReader; |
4046 | friend class ASTStmtReader; |
4047 | explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {} |
4048 | |
4049 | public: |
4050 | ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType, |
4051 | ExprValueKind VK, ExprObjectKind OK, |
4052 | SourceLocation BuiltinLoc, SourceLocation RParenLoc) |
4053 | : Expr(ConvertVectorExprClass, DstType, VK, OK, |
4054 | DstType->isDependentType(), |
4055 | DstType->isDependentType() || SrcExpr->isValueDependent(), |
4056 | (DstType->isInstantiationDependentType() || |
4057 | SrcExpr->isInstantiationDependent()), |
4058 | (DstType->containsUnexpandedParameterPack() || |
4059 | SrcExpr->containsUnexpandedParameterPack())), |
4060 | SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} |
4061 | |
4062 | /// getSrcExpr - Return the Expr to be converted. |
4063 | Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } |
4064 | |
4065 | /// getTypeSourceInfo - Return the destination type. |
4066 | TypeSourceInfo *getTypeSourceInfo() const { |
4067 | return TInfo; |
4068 | } |
4069 | void setTypeSourceInfo(TypeSourceInfo *ti) { |
4070 | TInfo = ti; |
4071 | } |
4072 | |
4073 | /// getBuiltinLoc - Return the location of the __builtin_convertvector token. |
4074 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
4075 | |
4076 | /// getRParenLoc - Return the location of final right parenthesis. |
4077 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4078 | |
4079 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
4080 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
4081 | |
4082 | static bool classof(const Stmt *T) { |
4083 | return T->getStmtClass() == ConvertVectorExprClass; |
4084 | } |
4085 | |
4086 | // Iterators |
4087 | child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } |
4088 | const_child_range children() const { |
4089 | return const_child_range(&SrcExpr, &SrcExpr + 1); |
4090 | } |
4091 | }; |
4092 | |
4093 | /// ChooseExpr - GNU builtin-in function __builtin_choose_expr. |
4094 | /// This AST node is similar to the conditional operator (?:) in C, with |
4095 | /// the following exceptions: |
4096 | /// - the test expression must be a integer constant expression. |
4097 | /// - the expression returned acts like the chosen subexpression in every |
4098 | /// visible way: the type is the same as that of the chosen subexpression, |
4099 | /// and all predicates (whether it's an l-value, whether it's an integer |
4100 | /// constant expression, etc.) return the same result as for the chosen |
4101 | /// sub-expression. |
4102 | class ChooseExpr : public Expr { |
4103 | enum { COND, LHS, RHS, END_EXPR }; |
4104 | Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. |
4105 | SourceLocation BuiltinLoc, RParenLoc; |
4106 | bool CondIsTrue; |
4107 | public: |
4108 | ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, |
4109 | QualType t, ExprValueKind VK, ExprObjectKind OK, |
4110 | SourceLocation RP, bool condIsTrue, |
4111 | bool TypeDependent, bool ValueDependent) |
4112 | : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent, |
4113 | (cond->isInstantiationDependent() || |
4114 | lhs->isInstantiationDependent() || |
4115 | rhs->isInstantiationDependent()), |
4116 | (cond->containsUnexpandedParameterPack() || |
4117 | lhs->containsUnexpandedParameterPack() || |
4118 | rhs->containsUnexpandedParameterPack())), |
4119 | BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) { |
4120 | SubExprs[COND] = cond; |
4121 | SubExprs[LHS] = lhs; |
4122 | SubExprs[RHS] = rhs; |
4123 | } |
4124 | |
4125 | /// Build an empty __builtin_choose_expr. |
4126 | explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } |
4127 | |
4128 | /// isConditionTrue - Return whether the condition is true (i.e. not |
4129 | /// equal to zero). |
4130 | bool isConditionTrue() const { |
4131 | assert(!isConditionDependent() &&((!isConditionDependent() && "Dependent condition isn't true or false" ) ? static_cast<void> (0) : __assert_fail ("!isConditionDependent() && \"Dependent condition isn't true or false\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4132, __PRETTY_FUNCTION__)) |
4132 | "Dependent condition isn't true or false")((!isConditionDependent() && "Dependent condition isn't true or false" ) ? static_cast<void> (0) : __assert_fail ("!isConditionDependent() && \"Dependent condition isn't true or false\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4132, __PRETTY_FUNCTION__)); |
4133 | return CondIsTrue; |
4134 | } |
4135 | void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; } |
4136 | |
4137 | bool isConditionDependent() const { |
4138 | return getCond()->isTypeDependent() || getCond()->isValueDependent(); |
4139 | } |
4140 | |
4141 | /// getChosenSubExpr - Return the subexpression chosen according to the |
4142 | /// condition. |
4143 | Expr *getChosenSubExpr() const { |
4144 | return isConditionTrue() ? getLHS() : getRHS(); |
4145 | } |
4146 | |
4147 | Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } |
4148 | void setCond(Expr *E) { SubExprs[COND] = E; } |
4149 | Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } |
4150 | void setLHS(Expr *E) { SubExprs[LHS] = E; } |
4151 | Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } |
4152 | void setRHS(Expr *E) { SubExprs[RHS] = E; } |
4153 | |
4154 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
4155 | void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } |
4156 | |
4157 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4158 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
4159 | |
4160 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
4161 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
4162 | |
4163 | static bool classof(const Stmt *T) { |
4164 | return T->getStmtClass() == ChooseExprClass; |
4165 | } |
4166 | |
4167 | // Iterators |
4168 | child_range children() { |
4169 | return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); |
4170 | } |
4171 | const_child_range children() const { |
4172 | return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); |
4173 | } |
4174 | }; |
4175 | |
4176 | /// GNUNullExpr - Implements the GNU __null extension, which is a name |
4177 | /// for a null pointer constant that has integral type (e.g., int or |
4178 | /// long) and is the same size and alignment as a pointer. The __null |
4179 | /// extension is typically only used by system headers, which define |
4180 | /// NULL as __null in C++ rather than using 0 (which is an integer |
4181 | /// that may not match the size of a pointer). |
4182 | class GNUNullExpr : public Expr { |
4183 | /// TokenLoc - The location of the __null keyword. |
4184 | SourceLocation TokenLoc; |
4185 | |
4186 | public: |
4187 | GNUNullExpr(QualType Ty, SourceLocation Loc) |
4188 | : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false, |
4189 | false), |
4190 | TokenLoc(Loc) { } |
4191 | |
4192 | /// Build an empty GNU __null expression. |
4193 | explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } |
4194 | |
4195 | /// getTokenLocation - The location of the __null token. |
4196 | SourceLocation getTokenLocation() const { return TokenLoc; } |
4197 | void setTokenLocation(SourceLocation L) { TokenLoc = L; } |
4198 | |
4199 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; } |
4200 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; } |
4201 | |
4202 | static bool classof(const Stmt *T) { |
4203 | return T->getStmtClass() == GNUNullExprClass; |
4204 | } |
4205 | |
4206 | // Iterators |
4207 | child_range children() { |
4208 | return child_range(child_iterator(), child_iterator()); |
4209 | } |
4210 | const_child_range children() const { |
4211 | return const_child_range(const_child_iterator(), const_child_iterator()); |
4212 | } |
4213 | }; |
4214 | |
4215 | /// Represents a call to the builtin function \c __builtin_va_arg. |
4216 | class VAArgExpr : public Expr { |
4217 | Stmt *Val; |
4218 | llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo; |
4219 | SourceLocation BuiltinLoc, RParenLoc; |
4220 | public: |
4221 | VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo, |
4222 | SourceLocation RPLoc, QualType t, bool IsMS) |
4223 | : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(), |
4224 | false, (TInfo->getType()->isInstantiationDependentType() || |
4225 | e->isInstantiationDependent()), |
4226 | (TInfo->getType()->containsUnexpandedParameterPack() || |
4227 | e->containsUnexpandedParameterPack())), |
4228 | Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {} |
4229 | |
4230 | /// Create an empty __builtin_va_arg expression. |
4231 | explicit VAArgExpr(EmptyShell Empty) |
4232 | : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {} |
4233 | |
4234 | const Expr *getSubExpr() const { return cast<Expr>(Val); } |
4235 | Expr *getSubExpr() { return cast<Expr>(Val); } |
4236 | void setSubExpr(Expr *E) { Val = E; } |
4237 | |
4238 | /// Returns whether this is really a Win64 ABI va_arg expression. |
4239 | bool isMicrosoftABI() const { return TInfo.getInt(); } |
4240 | void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); } |
4241 | |
4242 | TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); } |
4243 | void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); } |
4244 | |
4245 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
4246 | void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } |
4247 | |
4248 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4249 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
4250 | |
4251 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
4252 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
4253 | |
4254 | static bool classof(const Stmt *T) { |
4255 | return T->getStmtClass() == VAArgExprClass; |
4256 | } |
4257 | |
4258 | // Iterators |
4259 | child_range children() { return child_range(&Val, &Val+1); } |
4260 | const_child_range children() const { |
4261 | return const_child_range(&Val, &Val + 1); |
4262 | } |
4263 | }; |
4264 | |
4265 | /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), |
4266 | /// __builtin_FUNCTION(), or __builtin_FILE(). |
4267 | class SourceLocExpr final : public Expr { |
4268 | SourceLocation BuiltinLoc, RParenLoc; |
4269 | DeclContext *ParentContext; |
4270 | |
4271 | public: |
4272 | enum IdentKind { Function, File, Line, Column }; |
4273 | |
4274 | SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc, |
4275 | SourceLocation RParenLoc, DeclContext *Context); |
4276 | |
4277 | /// Build an empty call expression. |
4278 | explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {} |
4279 | |
4280 | /// Return the result of evaluating this SourceLocExpr in the specified |
4281 | /// (and possibly null) default argument or initialization context. |
4282 | APValue EvaluateInContext(const ASTContext &Ctx, |
4283 | const Expr *DefaultExpr) const; |
4284 | |
4285 | /// Return a string representing the name of the specific builtin function. |
4286 | StringRef getBuiltinStr() const; |
4287 | |
4288 | IdentKind getIdentKind() const { |
4289 | return static_cast<IdentKind>(SourceLocExprBits.Kind); |
4290 | } |
4291 | |
4292 | bool isStringType() const { |
4293 | switch (getIdentKind()) { |
4294 | case File: |
4295 | case Function: |
4296 | return true; |
4297 | case Line: |
4298 | case Column: |
4299 | return false; |
4300 | } |
4301 | llvm_unreachable("unknown source location expression kind")::llvm::llvm_unreachable_internal("unknown source location expression kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4301); |
4302 | } |
4303 | bool isIntType() const LLVM_READONLY__attribute__((__pure__)) { return !isStringType(); } |
4304 | |
4305 | /// If the SourceLocExpr has been resolved return the subexpression |
4306 | /// representing the resolved value. Otherwise return null. |
4307 | const DeclContext *getParentContext() const { return ParentContext; } |
4308 | DeclContext *getParentContext() { return ParentContext; } |
4309 | |
4310 | SourceLocation getLocation() const { return BuiltinLoc; } |
4311 | SourceLocation getBeginLoc() const { return BuiltinLoc; } |
4312 | SourceLocation getEndLoc() const { return RParenLoc; } |
4313 | |
4314 | child_range children() { |
4315 | return child_range(child_iterator(), child_iterator()); |
4316 | } |
4317 | |
4318 | const_child_range children() const { |
4319 | return const_child_range(child_iterator(), child_iterator()); |
4320 | } |
4321 | |
4322 | static bool classof(const Stmt *T) { |
4323 | return T->getStmtClass() == SourceLocExprClass; |
4324 | } |
4325 | |
4326 | private: |
4327 | friend class ASTStmtReader; |
4328 | }; |
4329 | |
4330 | /// Describes an C or C++ initializer list. |
4331 | /// |
4332 | /// InitListExpr describes an initializer list, which can be used to |
4333 | /// initialize objects of different types, including |
4334 | /// struct/class/union types, arrays, and vectors. For example: |
4335 | /// |
4336 | /// @code |
4337 | /// struct foo x = { 1, { 2, 3 } }; |
4338 | /// @endcode |
4339 | /// |
4340 | /// Prior to semantic analysis, an initializer list will represent the |
4341 | /// initializer list as written by the user, but will have the |
4342 | /// placeholder type "void". This initializer list is called the |
4343 | /// syntactic form of the initializer, and may contain C99 designated |
4344 | /// initializers (represented as DesignatedInitExprs), initializations |
4345 | /// of subobject members without explicit braces, and so on. Clients |
4346 | /// interested in the original syntax of the initializer list should |
4347 | /// use the syntactic form of the initializer list. |
4348 | /// |
4349 | /// After semantic analysis, the initializer list will represent the |
4350 | /// semantic form of the initializer, where the initializations of all |
4351 | /// subobjects are made explicit with nested InitListExpr nodes and |
4352 | /// C99 designators have been eliminated by placing the designated |
4353 | /// initializations into the subobject they initialize. Additionally, |
4354 | /// any "holes" in the initialization, where no initializer has been |
4355 | /// specified for a particular subobject, will be replaced with |
4356 | /// implicitly-generated ImplicitValueInitExpr expressions that |
4357 | /// value-initialize the subobjects. Note, however, that the |
4358 | /// initializer lists may still have fewer initializers than there are |
4359 | /// elements to initialize within the object. |
4360 | /// |
4361 | /// After semantic analysis has completed, given an initializer list, |
4362 | /// method isSemanticForm() returns true if and only if this is the |
4363 | /// semantic form of the initializer list (note: the same AST node |
4364 | /// may at the same time be the syntactic form). |
4365 | /// Given the semantic form of the initializer list, one can retrieve |
4366 | /// the syntactic form of that initializer list (when different) |
4367 | /// using method getSyntacticForm(); the method returns null if applied |
4368 | /// to a initializer list which is already in syntactic form. |
4369 | /// Similarly, given the syntactic form (i.e., an initializer list such |
4370 | /// that isSemanticForm() returns false), one can retrieve the semantic |
4371 | /// form using method getSemanticForm(). |
4372 | /// Since many initializer lists have the same syntactic and semantic forms, |
4373 | /// getSyntacticForm() may return NULL, indicating that the current |
4374 | /// semantic initializer list also serves as its syntactic form. |
4375 | class InitListExpr : public Expr { |
4376 | // FIXME: Eliminate this vector in favor of ASTContext allocation |
4377 | typedef ASTVector<Stmt *> InitExprsTy; |
4378 | InitExprsTy InitExprs; |
4379 | SourceLocation LBraceLoc, RBraceLoc; |
4380 | |
4381 | /// The alternative form of the initializer list (if it exists). |
4382 | /// The int part of the pair stores whether this initializer list is |
4383 | /// in semantic form. If not null, the pointer points to: |
4384 | /// - the syntactic form, if this is in semantic form; |
4385 | /// - the semantic form, if this is in syntactic form. |
4386 | llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm; |
4387 | |
4388 | /// Either: |
4389 | /// If this initializer list initializes an array with more elements than |
4390 | /// there are initializers in the list, specifies an expression to be used |
4391 | /// for value initialization of the rest of the elements. |
4392 | /// Or |
4393 | /// If this initializer list initializes a union, specifies which |
4394 | /// field within the union will be initialized. |
4395 | llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; |
4396 | |
4397 | public: |
4398 | InitListExpr(const ASTContext &C, SourceLocation lbraceloc, |
4399 | ArrayRef<Expr*> initExprs, SourceLocation rbraceloc); |
4400 | |
4401 | /// Build an empty initializer list. |
4402 | explicit InitListExpr(EmptyShell Empty) |
4403 | : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { } |
4404 | |
4405 | unsigned getNumInits() const { return InitExprs.size(); } |
4406 | |
4407 | /// Retrieve the set of initializers. |
4408 | Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } |
4409 | |
4410 | /// Retrieve the set of initializers. |
4411 | Expr * const *getInits() const { |
4412 | return reinterpret_cast<Expr * const *>(InitExprs.data()); |
4413 | } |
4414 | |
4415 | ArrayRef<Expr *> inits() { |
4416 | return llvm::makeArrayRef(getInits(), getNumInits()); |
4417 | } |
4418 | |
4419 | ArrayRef<Expr *> inits() const { |
4420 | return llvm::makeArrayRef(getInits(), getNumInits()); |
4421 | } |
4422 | |
4423 | const Expr *getInit(unsigned Init) const { |
4424 | assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4424, __PRETTY_FUNCTION__)); |
4425 | return cast_or_null<Expr>(InitExprs[Init]); |
4426 | } |
4427 | |
4428 | Expr *getInit(unsigned Init) { |
4429 | assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4429, __PRETTY_FUNCTION__)); |
4430 | return cast_or_null<Expr>(InitExprs[Init]); |
4431 | } |
4432 | |
4433 | void setInit(unsigned Init, Expr *expr) { |
4434 | assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4434, __PRETTY_FUNCTION__)); |
4435 | InitExprs[Init] = expr; |
4436 | |
4437 | if (expr) { |
4438 | ExprBits.TypeDependent |= expr->isTypeDependent(); |
4439 | ExprBits.ValueDependent |= expr->isValueDependent(); |
4440 | ExprBits.InstantiationDependent |= expr->isInstantiationDependent(); |
4441 | ExprBits.ContainsUnexpandedParameterPack |= |
4442 | expr->containsUnexpandedParameterPack(); |
4443 | } |
4444 | } |
4445 | |
4446 | /// Reserve space for some number of initializers. |
4447 | void reserveInits(const ASTContext &C, unsigned NumInits); |
4448 | |
4449 | /// Specify the number of initializers |
4450 | /// |
4451 | /// If there are more than @p NumInits initializers, the remaining |
4452 | /// initializers will be destroyed. If there are fewer than @p |
4453 | /// NumInits initializers, NULL expressions will be added for the |
4454 | /// unknown initializers. |
4455 | void resizeInits(const ASTContext &Context, unsigned NumInits); |
4456 | |
4457 | /// Updates the initializer at index @p Init with the new |
4458 | /// expression @p expr, and returns the old expression at that |
4459 | /// location. |
4460 | /// |
4461 | /// When @p Init is out of range for this initializer list, the |
4462 | /// initializer list will be extended with NULL expressions to |
4463 | /// accommodate the new entry. |
4464 | Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr); |
4465 | |
4466 | /// If this initializer list initializes an array with more elements |
4467 | /// than there are initializers in the list, specifies an expression to be |
4468 | /// used for value initialization of the rest of the elements. |
4469 | Expr *getArrayFiller() { |
4470 | return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); |
4471 | } |
4472 | const Expr *getArrayFiller() const { |
4473 | return const_cast<InitListExpr *>(this)->getArrayFiller(); |
4474 | } |
4475 | void setArrayFiller(Expr *filler); |
4476 | |
4477 | /// Return true if this is an array initializer and its array "filler" |
4478 | /// has been set. |
4479 | bool hasArrayFiller() const { return getArrayFiller(); } |
4480 | |
4481 | /// If this initializes a union, specifies which field in the |
4482 | /// union to initialize. |
4483 | /// |
4484 | /// Typically, this field is the first named field within the |
4485 | /// union. However, a designated initializer can specify the |
4486 | /// initialization of a different field within the union. |
4487 | FieldDecl *getInitializedFieldInUnion() { |
4488 | return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); |
4489 | } |
4490 | const FieldDecl *getInitializedFieldInUnion() const { |
4491 | return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); |
4492 | } |
4493 | void setInitializedFieldInUnion(FieldDecl *FD) { |
4494 | assert((FD == nullptr(((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!" ) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4497, __PRETTY_FUNCTION__)) |
4495 | || getInitializedFieldInUnion() == nullptr(((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!" ) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4497, __PRETTY_FUNCTION__)) |
4496 | || getInitializedFieldInUnion() == FD)(((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!" ) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4497, __PRETTY_FUNCTION__)) |
4497 | && "Only one field of a union may be initialized at a time!")(((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!" ) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4497, __PRETTY_FUNCTION__)); |
4498 | ArrayFillerOrUnionFieldInit = FD; |
4499 | } |
4500 | |
4501 | // Explicit InitListExpr's originate from source code (and have valid source |
4502 | // locations). Implicit InitListExpr's are created by the semantic analyzer. |
4503 | // FIXME: This is wrong; InitListExprs created by semantic analysis have |
4504 | // valid source locations too! |
4505 | bool isExplicit() const { |
4506 | return LBraceLoc.isValid() && RBraceLoc.isValid(); |
4507 | } |
4508 | |
4509 | // Is this an initializer for an array of characters, initialized by a string |
4510 | // literal or an @encode? |
4511 | bool isStringLiteralInit() const; |
4512 | |
4513 | /// Is this a transparent initializer list (that is, an InitListExpr that is |
4514 | /// purely syntactic, and whose semantics are that of the sole contained |
4515 | /// initializer)? |
4516 | bool isTransparent() const; |
4517 | |
4518 | /// Is this the zero initializer {0} in a language which considers it |
4519 | /// idiomatic? |
4520 | bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const; |
4521 | |
4522 | SourceLocation getLBraceLoc() const { return LBraceLoc; } |
4523 | void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } |
4524 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
4525 | void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } |
4526 | |
4527 | bool isSemanticForm() const { return AltForm.getInt(); } |
4528 | InitListExpr *getSemanticForm() const { |
4529 | return isSemanticForm() ? nullptr : AltForm.getPointer(); |
4530 | } |
4531 | bool isSyntacticForm() const { |
4532 | return !AltForm.getInt() || !AltForm.getPointer(); |
4533 | } |
4534 | InitListExpr *getSyntacticForm() const { |
4535 | return isSemanticForm() ? AltForm.getPointer() : nullptr; |
4536 | } |
4537 | |
4538 | void setSyntacticForm(InitListExpr *Init) { |
4539 | AltForm.setPointer(Init); |
4540 | AltForm.setInt(true); |
4541 | Init->AltForm.setPointer(this); |
4542 | Init->AltForm.setInt(false); |
4543 | } |
4544 | |
4545 | bool hadArrayRangeDesignator() const { |
4546 | return InitListExprBits.HadArrayRangeDesignator != 0; |
4547 | } |
4548 | void sawArrayRangeDesignator(bool ARD = true) { |
4549 | InitListExprBits.HadArrayRangeDesignator = ARD; |
4550 | } |
4551 | |
4552 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
4553 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
4554 | |
4555 | static bool classof(const Stmt *T) { |
4556 | return T->getStmtClass() == InitListExprClass; |
4557 | } |
4558 | |
4559 | // Iterators |
4560 | child_range children() { |
4561 | const_child_range CCR = const_cast<const InitListExpr *>(this)->children(); |
4562 | return child_range(cast_away_const(CCR.begin()), |
4563 | cast_away_const(CCR.end())); |
4564 | } |
4565 | |
4566 | const_child_range children() const { |
4567 | // FIXME: This does not include the array filler expression. |
4568 | if (InitExprs.empty()) |
4569 | return const_child_range(const_child_iterator(), const_child_iterator()); |
4570 | return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); |
4571 | } |
4572 | |
4573 | typedef InitExprsTy::iterator iterator; |
4574 | typedef InitExprsTy::const_iterator const_iterator; |
4575 | typedef InitExprsTy::reverse_iterator reverse_iterator; |
4576 | typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; |
4577 | |
4578 | iterator begin() { return InitExprs.begin(); } |
4579 | const_iterator begin() const { return InitExprs.begin(); } |
4580 | iterator end() { return InitExprs.end(); } |
4581 | const_iterator end() const { return InitExprs.end(); } |
4582 | reverse_iterator rbegin() { return InitExprs.rbegin(); } |
4583 | const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } |
4584 | reverse_iterator rend() { return InitExprs.rend(); } |
4585 | const_reverse_iterator rend() const { return InitExprs.rend(); } |
4586 | |
4587 | friend class ASTStmtReader; |
4588 | friend class ASTStmtWriter; |
4589 | }; |
4590 | |
4591 | /// Represents a C99 designated initializer expression. |
4592 | /// |
4593 | /// A designated initializer expression (C99 6.7.8) contains one or |
4594 | /// more designators (which can be field designators, array |
4595 | /// designators, or GNU array-range designators) followed by an |
4596 | /// expression that initializes the field or element(s) that the |
4597 | /// designators refer to. For example, given: |
4598 | /// |
4599 | /// @code |
4600 | /// struct point { |
4601 | /// double x; |
4602 | /// double y; |
4603 | /// }; |
4604 | /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; |
4605 | /// @endcode |
4606 | /// |
4607 | /// The InitListExpr contains three DesignatedInitExprs, the first of |
4608 | /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two |
4609 | /// designators, one array designator for @c [2] followed by one field |
4610 | /// designator for @c .y. The initialization expression will be 1.0. |
4611 | class DesignatedInitExpr final |
4612 | : public Expr, |
4613 | private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> { |
4614 | public: |
4615 | /// Forward declaration of the Designator class. |
4616 | class Designator; |
4617 | |
4618 | private: |
4619 | /// The location of the '=' or ':' prior to the actual initializer |
4620 | /// expression. |
4621 | SourceLocation EqualOrColonLoc; |
4622 | |
4623 | /// Whether this designated initializer used the GNU deprecated |
4624 | /// syntax rather than the C99 '=' syntax. |
4625 | unsigned GNUSyntax : 1; |
4626 | |
4627 | /// The number of designators in this initializer expression. |
4628 | unsigned NumDesignators : 15; |
4629 | |
4630 | /// The number of subexpressions of this initializer expression, |
4631 | /// which contains both the initializer and any additional |
4632 | /// expressions used by array and array-range designators. |
4633 | unsigned NumSubExprs : 16; |
4634 | |
4635 | /// The designators in this designated initialization |
4636 | /// expression. |
4637 | Designator *Designators; |
4638 | |
4639 | DesignatedInitExpr(const ASTContext &C, QualType Ty, |
4640 | llvm::ArrayRef<Designator> Designators, |
4641 | SourceLocation EqualOrColonLoc, bool GNUSyntax, |
4642 | ArrayRef<Expr *> IndexExprs, Expr *Init); |
4643 | |
4644 | explicit DesignatedInitExpr(unsigned NumSubExprs) |
4645 | : Expr(DesignatedInitExprClass, EmptyShell()), |
4646 | NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { } |
4647 | |
4648 | public: |
4649 | /// A field designator, e.g., ".x". |
4650 | struct FieldDesignator { |
4651 | /// Refers to the field that is being initialized. The low bit |
4652 | /// of this field determines whether this is actually a pointer |
4653 | /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When |
4654 | /// initially constructed, a field designator will store an |
4655 | /// IdentifierInfo*. After semantic analysis has resolved that |
4656 | /// name, the field designator will instead store a FieldDecl*. |
4657 | uintptr_t NameOrField; |
4658 | |
4659 | /// The location of the '.' in the designated initializer. |
4660 | unsigned DotLoc; |
4661 | |
4662 | /// The location of the field name in the designated initializer. |
4663 | unsigned FieldLoc; |
4664 | }; |
4665 | |
4666 | /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". |
4667 | struct ArrayOrRangeDesignator { |
4668 | /// Location of the first index expression within the designated |
4669 | /// initializer expression's list of subexpressions. |
4670 | unsigned Index; |
4671 | /// The location of the '[' starting the array range designator. |
4672 | unsigned LBracketLoc; |
4673 | /// The location of the ellipsis separating the start and end |
4674 | /// indices. Only valid for GNU array-range designators. |
4675 | unsigned EllipsisLoc; |
4676 | /// The location of the ']' terminating the array range designator. |
4677 | unsigned RBracketLoc; |
4678 | }; |
4679 | |
4680 | /// Represents a single C99 designator. |
4681 | /// |
4682 | /// @todo This class is infuriatingly similar to clang::Designator, |
4683 | /// but minor differences (storing indices vs. storing pointers) |
4684 | /// keep us from reusing it. Try harder, later, to rectify these |
4685 | /// differences. |
4686 | class Designator { |
4687 | /// The kind of designator this describes. |
4688 | enum { |
4689 | FieldDesignator, |
4690 | ArrayDesignator, |
4691 | ArrayRangeDesignator |
4692 | } Kind; |
4693 | |
4694 | union { |
4695 | /// A field designator, e.g., ".x". |
4696 | struct FieldDesignator Field; |
4697 | /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". |
4698 | struct ArrayOrRangeDesignator ArrayOrRange; |
4699 | }; |
4700 | friend class DesignatedInitExpr; |
4701 | |
4702 | public: |
4703 | Designator() {} |
4704 | |
4705 | /// Initializes a field designator. |
4706 | Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, |
4707 | SourceLocation FieldLoc) |
4708 | : Kind(FieldDesignator) { |
4709 | Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; |
4710 | Field.DotLoc = DotLoc.getRawEncoding(); |
4711 | Field.FieldLoc = FieldLoc.getRawEncoding(); |
4712 | } |
4713 | |
4714 | /// Initializes an array designator. |
4715 | Designator(unsigned Index, SourceLocation LBracketLoc, |
4716 | SourceLocation RBracketLoc) |
4717 | : Kind(ArrayDesignator) { |
4718 | ArrayOrRange.Index = Index; |
4719 | ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); |
4720 | ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); |
4721 | ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); |
4722 | } |
4723 | |
4724 | /// Initializes a GNU array-range designator. |
4725 | Designator(unsigned Index, SourceLocation LBracketLoc, |
4726 | SourceLocation EllipsisLoc, SourceLocation RBracketLoc) |
4727 | : Kind(ArrayRangeDesignator) { |
4728 | ArrayOrRange.Index = Index; |
4729 | ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); |
4730 | ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); |
4731 | ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); |
4732 | } |
4733 | |
4734 | bool isFieldDesignator() const { return Kind == FieldDesignator; } |
4735 | bool isArrayDesignator() const { return Kind == ArrayDesignator; } |
4736 | bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } |
4737 | |
4738 | IdentifierInfo *getFieldName() const; |
4739 | |
4740 | FieldDecl *getField() const { |
4741 | assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4741, __PRETTY_FUNCTION__)); |
4742 | if (Field.NameOrField & 0x01) |
4743 | return nullptr; |
4744 | else |
4745 | return reinterpret_cast<FieldDecl *>(Field.NameOrField); |
4746 | } |
4747 | |
4748 | void setField(FieldDecl *FD) { |
4749 | assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4749, __PRETTY_FUNCTION__)); |
4750 | Field.NameOrField = reinterpret_cast<uintptr_t>(FD); |
4751 | } |
4752 | |
4753 | SourceLocation getDotLoc() const { |
4754 | assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4754, __PRETTY_FUNCTION__)); |
4755 | return SourceLocation::getFromRawEncoding(Field.DotLoc); |
4756 | } |
4757 | |
4758 | SourceLocation getFieldLoc() const { |
4759 | assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4759, __PRETTY_FUNCTION__)); |
4760 | return SourceLocation::getFromRawEncoding(Field.FieldLoc); |
4761 | } |
4762 | |
4763 | SourceLocation getLBracketLoc() const { |
4764 | assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4765, __PRETTY_FUNCTION__)) |
4765 | "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4765, __PRETTY_FUNCTION__)); |
4766 | return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); |
4767 | } |
4768 | |
4769 | SourceLocation getRBracketLoc() const { |
4770 | assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4771, __PRETTY_FUNCTION__)) |
4771 | "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4771, __PRETTY_FUNCTION__)); |
4772 | return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); |
4773 | } |
4774 | |
4775 | SourceLocation getEllipsisLoc() const { |
4776 | assert(Kind == ArrayRangeDesignator &&((Kind == ArrayRangeDesignator && "Only valid on an array-range designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == ArrayRangeDesignator && \"Only valid on an array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4777, __PRETTY_FUNCTION__)) |
4777 | "Only valid on an array-range designator")((Kind == ArrayRangeDesignator && "Only valid on an array-range designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == ArrayRangeDesignator && \"Only valid on an array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4777, __PRETTY_FUNCTION__)); |
4778 | return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); |
4779 | } |
4780 | |
4781 | unsigned getFirstExprIndex() const { |
4782 | assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4783, __PRETTY_FUNCTION__)) |
4783 | "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4783, __PRETTY_FUNCTION__)); |
4784 | return ArrayOrRange.Index; |
4785 | } |
4786 | |
4787 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
4788 | if (Kind == FieldDesignator) |
4789 | return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); |
4790 | else |
4791 | return getLBracketLoc(); |
4792 | } |
4793 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
4794 | return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); |
4795 | } |
4796 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { |
4797 | return SourceRange(getBeginLoc(), getEndLoc()); |
4798 | } |
4799 | }; |
4800 | |
4801 | static DesignatedInitExpr *Create(const ASTContext &C, |
4802 | llvm::ArrayRef<Designator> Designators, |
4803 | ArrayRef<Expr*> IndexExprs, |
4804 | SourceLocation EqualOrColonLoc, |
4805 | bool GNUSyntax, Expr *Init); |
4806 | |
4807 | static DesignatedInitExpr *CreateEmpty(const ASTContext &C, |
4808 | unsigned NumIndexExprs); |
4809 | |
4810 | /// Returns the number of designators in this initializer. |
4811 | unsigned size() const { return NumDesignators; } |
4812 | |
4813 | // Iterator access to the designators. |
4814 | llvm::MutableArrayRef<Designator> designators() { |
4815 | return {Designators, NumDesignators}; |
4816 | } |
4817 | |
4818 | llvm::ArrayRef<Designator> designators() const { |
4819 | return {Designators, NumDesignators}; |
4820 | } |
4821 | |
4822 | Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; } |
4823 | const Designator *getDesignator(unsigned Idx) const { |
4824 | return &designators()[Idx]; |
4825 | } |
4826 | |
4827 | void setDesignators(const ASTContext &C, const Designator *Desigs, |
4828 | unsigned NumDesigs); |
4829 | |
4830 | Expr *getArrayIndex(const Designator &D) const; |
4831 | Expr *getArrayRangeStart(const Designator &D) const; |
4832 | Expr *getArrayRangeEnd(const Designator &D) const; |
4833 | |
4834 | /// Retrieve the location of the '=' that precedes the |
4835 | /// initializer value itself, if present. |
4836 | SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } |
4837 | void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } |
4838 | |
4839 | /// Whether this designated initializer should result in direct-initialization |
4840 | /// of the designated subobject (eg, '{.foo{1, 2, 3}}'). |
4841 | bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); } |
4842 | |
4843 | /// Determines whether this designated initializer used the |
4844 | /// deprecated GNU syntax for designated initializers. |
4845 | bool usesGNUSyntax() const { return GNUSyntax; } |
4846 | void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } |
4847 | |
4848 | /// Retrieve the initializer value. |
4849 | Expr *getInit() const { |
4850 | return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); |
4851 | } |
4852 | |
4853 | void setInit(Expr *init) { |
4854 | *child_begin() = init; |
4855 | } |
4856 | |
4857 | /// Retrieve the total number of subexpressions in this |
4858 | /// designated initializer expression, including the actual |
4859 | /// initialized value and any expressions that occur within array |
4860 | /// and array-range designators. |
4861 | unsigned getNumSubExprs() const { return NumSubExprs; } |
4862 | |
4863 | Expr *getSubExpr(unsigned Idx) const { |
4864 | assert(Idx < NumSubExprs && "Subscript out of range")((Idx < NumSubExprs && "Subscript out of range") ? static_cast<void> (0) : __assert_fail ("Idx < NumSubExprs && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4864, __PRETTY_FUNCTION__)); |
4865 | return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]); |
4866 | } |
4867 | |
4868 | void setSubExpr(unsigned Idx, Expr *E) { |
4869 | assert(Idx < NumSubExprs && "Subscript out of range")((Idx < NumSubExprs && "Subscript out of range") ? static_cast<void> (0) : __assert_fail ("Idx < NumSubExprs && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4869, __PRETTY_FUNCTION__)); |
4870 | getTrailingObjects<Stmt *>()[Idx] = E; |
4871 | } |
4872 | |
4873 | /// Replaces the designator at index @p Idx with the series |
4874 | /// of designators in [First, Last). |
4875 | void ExpandDesignator(const ASTContext &C, unsigned Idx, |
4876 | const Designator *First, const Designator *Last); |
4877 | |
4878 | SourceRange getDesignatorsSourceRange() const; |
4879 | |
4880 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
4881 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
4882 | |
4883 | static bool classof(const Stmt *T) { |
4884 | return T->getStmtClass() == DesignatedInitExprClass; |
4885 | } |
4886 | |
4887 | // Iterators |
4888 | child_range children() { |
4889 | Stmt **begin = getTrailingObjects<Stmt *>(); |
4890 | return child_range(begin, begin + NumSubExprs); |
4891 | } |
4892 | const_child_range children() const { |
4893 | Stmt * const *begin = getTrailingObjects<Stmt *>(); |
4894 | return const_child_range(begin, begin + NumSubExprs); |
4895 | } |
4896 | |
4897 | friend TrailingObjects; |
4898 | }; |
4899 | |
4900 | /// Represents a place-holder for an object not to be initialized by |
4901 | /// anything. |
4902 | /// |
4903 | /// This only makes sense when it appears as part of an updater of a |
4904 | /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE |
4905 | /// initializes a big object, and the NoInitExpr's mark the spots within the |
4906 | /// big object not to be overwritten by the updater. |
4907 | /// |
4908 | /// \see DesignatedInitUpdateExpr |
4909 | class NoInitExpr : public Expr { |
4910 | public: |
4911 | explicit NoInitExpr(QualType ty) |
4912 | : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary, |
4913 | false, false, ty->isInstantiationDependentType(), false) { } |
4914 | |
4915 | explicit NoInitExpr(EmptyShell Empty) |
4916 | : Expr(NoInitExprClass, Empty) { } |
4917 | |
4918 | static bool classof(const Stmt *T) { |
4919 | return T->getStmtClass() == NoInitExprClass; |
4920 | } |
4921 | |
4922 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
4923 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
4924 | |
4925 | // Iterators |
4926 | child_range children() { |
4927 | return child_range(child_iterator(), child_iterator()); |
4928 | } |
4929 | const_child_range children() const { |
4930 | return const_child_range(const_child_iterator(), const_child_iterator()); |
4931 | } |
4932 | }; |
4933 | |
4934 | // In cases like: |
4935 | // struct Q { int a, b, c; }; |
4936 | // Q *getQ(); |
4937 | // void foo() { |
4938 | // struct A { Q q; } a = { *getQ(), .q.b = 3 }; |
4939 | // } |
4940 | // |
4941 | // We will have an InitListExpr for a, with type A, and then a |
4942 | // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE |
4943 | // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3" |
4944 | // |
4945 | class DesignatedInitUpdateExpr : public Expr { |
4946 | // BaseAndUpdaterExprs[0] is the base expression; |
4947 | // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base. |
4948 | Stmt *BaseAndUpdaterExprs[2]; |
4949 | |
4950 | public: |
4951 | DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, |
4952 | Expr *baseExprs, SourceLocation rBraceLoc); |
4953 | |
4954 | explicit DesignatedInitUpdateExpr(EmptyShell Empty) |
4955 | : Expr(DesignatedInitUpdateExprClass, Empty) { } |
4956 | |
4957 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
4958 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
4959 | |
4960 | static bool classof(const Stmt *T) { |
4961 | return T->getStmtClass() == DesignatedInitUpdateExprClass; |
4962 | } |
4963 | |
4964 | Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); } |
4965 | void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; } |
4966 | |
4967 | InitListExpr *getUpdater() const { |
4968 | return cast<InitListExpr>(BaseAndUpdaterExprs[1]); |
4969 | } |
4970 | void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; } |
4971 | |
4972 | // Iterators |
4973 | // children = the base and the updater |
4974 | child_range children() { |
4975 | return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2); |
4976 | } |
4977 | const_child_range children() const { |
4978 | return const_child_range(&BaseAndUpdaterExprs[0], |
4979 | &BaseAndUpdaterExprs[0] + 2); |
4980 | } |
4981 | }; |
4982 | |
4983 | /// Represents a loop initializing the elements of an array. |
4984 | /// |
4985 | /// The need to initialize the elements of an array occurs in a number of |
4986 | /// contexts: |
4987 | /// |
4988 | /// * in the implicit copy/move constructor for a class with an array member |
4989 | /// * when a lambda-expression captures an array by value |
4990 | /// * when a decomposition declaration decomposes an array |
4991 | /// |
4992 | /// There are two subexpressions: a common expression (the source array) |
4993 | /// that is evaluated once up-front, and a per-element initializer that |
4994 | /// runs once for each array element. |
4995 | /// |
4996 | /// Within the per-element initializer, the common expression may be referenced |
4997 | /// via an OpaqueValueExpr, and the current index may be obtained via an |
4998 | /// ArrayInitIndexExpr. |
4999 | class ArrayInitLoopExpr : public Expr { |
5000 | Stmt *SubExprs[2]; |
5001 | |
5002 | explicit ArrayInitLoopExpr(EmptyShell Empty) |
5003 | : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {} |
5004 | |
5005 | public: |
5006 | explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit) |
5007 | : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false, |
5008 | CommonInit->isValueDependent() || ElementInit->isValueDependent(), |
5009 | T->isInstantiationDependentType(), |
5010 | CommonInit->containsUnexpandedParameterPack() || |
5011 | ElementInit->containsUnexpandedParameterPack()), |
5012 | SubExprs{CommonInit, ElementInit} {} |
5013 | |
5014 | /// Get the common subexpression shared by all initializations (the source |
5015 | /// array). |
5016 | OpaqueValueExpr *getCommonExpr() const { |
5017 | return cast<OpaqueValueExpr>(SubExprs[0]); |
5018 | } |
5019 | |
5020 | /// Get the initializer to use for each array element. |
5021 | Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); } |
5022 | |
5023 | llvm::APInt getArraySize() const { |
5024 | return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe()) |
5025 | ->getSize(); |
5026 | } |
5027 | |
5028 | static bool classof(const Stmt *S) { |
5029 | return S->getStmtClass() == ArrayInitLoopExprClass; |
5030 | } |
5031 | |
5032 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5033 | return getCommonExpr()->getBeginLoc(); |
5034 | } |
5035 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5036 | return getCommonExpr()->getEndLoc(); |
5037 | } |
5038 | |
5039 | child_range children() { |
5040 | return child_range(SubExprs, SubExprs + 2); |
5041 | } |
5042 | const_child_range children() const { |
5043 | return const_child_range(SubExprs, SubExprs + 2); |
5044 | } |
5045 | |
5046 | friend class ASTReader; |
5047 | friend class ASTStmtReader; |
5048 | friend class ASTStmtWriter; |
5049 | }; |
5050 | |
5051 | /// Represents the index of the current element of an array being |
5052 | /// initialized by an ArrayInitLoopExpr. This can only appear within the |
5053 | /// subexpression of an ArrayInitLoopExpr. |
5054 | class ArrayInitIndexExpr : public Expr { |
5055 | explicit ArrayInitIndexExpr(EmptyShell Empty) |
5056 | : Expr(ArrayInitIndexExprClass, Empty) {} |
5057 | |
5058 | public: |
5059 | explicit ArrayInitIndexExpr(QualType T) |
5060 | : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary, |
5061 | false, false, false, false) {} |
5062 | |
5063 | static bool classof(const Stmt *S) { |
5064 | return S->getStmtClass() == ArrayInitIndexExprClass; |
5065 | } |
5066 | |
5067 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5068 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5069 | |
5070 | child_range children() { |
5071 | return child_range(child_iterator(), child_iterator()); |
5072 | } |
5073 | const_child_range children() const { |
5074 | return const_child_range(const_child_iterator(), const_child_iterator()); |
5075 | } |
5076 | |
5077 | friend class ASTReader; |
5078 | friend class ASTStmtReader; |
5079 | }; |
5080 | |
5081 | /// Represents an implicitly-generated value initialization of |
5082 | /// an object of a given type. |
5083 | /// |
5084 | /// Implicit value initializations occur within semantic initializer |
5085 | /// list expressions (InitListExpr) as placeholders for subobject |
5086 | /// initializations not explicitly specified by the user. |
5087 | /// |
5088 | /// \see InitListExpr |
5089 | class ImplicitValueInitExpr : public Expr { |
5090 | public: |
5091 | explicit ImplicitValueInitExpr(QualType ty) |
5092 | : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary, |
5093 | false, false, ty->isInstantiationDependentType(), false) { } |
5094 | |
5095 | /// Construct an empty implicit value initialization. |
5096 | explicit ImplicitValueInitExpr(EmptyShell Empty) |
5097 | : Expr(ImplicitValueInitExprClass, Empty) { } |
5098 | |
5099 | static bool classof(const Stmt *T) { |
5100 | return T->getStmtClass() == ImplicitValueInitExprClass; |
5101 | } |
5102 | |
5103 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5104 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5105 | |
5106 | // Iterators |
5107 | child_range children() { |
5108 | return child_range(child_iterator(), child_iterator()); |
5109 | } |
5110 | const_child_range children() const { |
5111 | return const_child_range(const_child_iterator(), const_child_iterator()); |
5112 | } |
5113 | }; |
5114 | |
5115 | class ParenListExpr final |
5116 | : public Expr, |
5117 | private llvm::TrailingObjects<ParenListExpr, Stmt *> { |
5118 | friend class ASTStmtReader; |
5119 | friend TrailingObjects; |
5120 | |
5121 | /// The location of the left and right parentheses. |
5122 | SourceLocation LParenLoc, RParenLoc; |
5123 | |
5124 | /// Build a paren list. |
5125 | ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs, |
5126 | SourceLocation RParenLoc); |
5127 | |
5128 | /// Build an empty paren list. |
5129 | ParenListExpr(EmptyShell Empty, unsigned NumExprs); |
5130 | |
5131 | public: |
5132 | /// Create a paren list. |
5133 | static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc, |
5134 | ArrayRef<Expr *> Exprs, |
5135 | SourceLocation RParenLoc); |
5136 | |
5137 | /// Create an empty paren list. |
5138 | static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs); |
5139 | |
5140 | /// Return the number of expressions in this paren list. |
5141 | unsigned getNumExprs() const { return ParenListExprBits.NumExprs; } |
5142 | |
5143 | Expr *getExpr(unsigned Init) { |
5144 | assert(Init < getNumExprs() && "Initializer access out of range!")((Init < getNumExprs() && "Initializer access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Init < getNumExprs() && \"Initializer access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5144, __PRETTY_FUNCTION__)); |
5145 | return getExprs()[Init]; |
5146 | } |
5147 | |
5148 | const Expr *getExpr(unsigned Init) const { |
5149 | return const_cast<ParenListExpr *>(this)->getExpr(Init); |
5150 | } |
5151 | |
5152 | Expr **getExprs() { |
5153 | return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>()); |
5154 | } |
5155 | |
5156 | ArrayRef<Expr *> exprs() { |
5157 | return llvm::makeArrayRef(getExprs(), getNumExprs()); |
5158 | } |
5159 | |
5160 | SourceLocation getLParenLoc() const { return LParenLoc; } |
5161 | SourceLocation getRParenLoc() const { return RParenLoc; } |
5162 | SourceLocation getBeginLoc() const { return getLParenLoc(); } |
5163 | SourceLocation getEndLoc() const { return getRParenLoc(); } |
5164 | |
5165 | static bool classof(const Stmt *T) { |
5166 | return T->getStmtClass() == ParenListExprClass; |
5167 | } |
5168 | |
5169 | // Iterators |
5170 | child_range children() { |
5171 | return child_range(getTrailingObjects<Stmt *>(), |
5172 | getTrailingObjects<Stmt *>() + getNumExprs()); |
5173 | } |
5174 | const_child_range children() const { |
5175 | return const_child_range(getTrailingObjects<Stmt *>(), |
5176 | getTrailingObjects<Stmt *>() + getNumExprs()); |
5177 | } |
5178 | }; |
5179 | |
5180 | /// Represents a C11 generic selection. |
5181 | /// |
5182 | /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling |
5183 | /// expression, followed by one or more generic associations. Each generic |
5184 | /// association specifies a type name and an expression, or "default" and an |
5185 | /// expression (in which case it is known as a default generic association). |
5186 | /// The type and value of the generic selection are identical to those of its |
5187 | /// result expression, which is defined as the expression in the generic |
5188 | /// association with a type name that is compatible with the type of the |
5189 | /// controlling expression, or the expression in the default generic association |
5190 | /// if no types are compatible. For example: |
5191 | /// |
5192 | /// @code |
5193 | /// _Generic(X, double: 1, float: 2, default: 3) |
5194 | /// @endcode |
5195 | /// |
5196 | /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f |
5197 | /// or 3 if "hello". |
5198 | /// |
5199 | /// As an extension, generic selections are allowed in C++, where the following |
5200 | /// additional semantics apply: |
5201 | /// |
5202 | /// Any generic selection whose controlling expression is type-dependent or |
5203 | /// which names a dependent type in its association list is result-dependent, |
5204 | /// which means that the choice of result expression is dependent. |
5205 | /// Result-dependent generic associations are both type- and value-dependent. |
5206 | class GenericSelectionExpr final |
5207 | : public Expr, |
5208 | private llvm::TrailingObjects<GenericSelectionExpr, Stmt *, |
5209 | TypeSourceInfo *> { |
5210 | friend class ASTStmtReader; |
5211 | friend class ASTStmtWriter; |
5212 | friend TrailingObjects; |
5213 | |
5214 | /// The number of association expressions and the index of the result |
5215 | /// expression in the case where the generic selection expression is not |
5216 | /// result-dependent. The result index is equal to ResultDependentIndex |
5217 | /// if and only if the generic selection expression is result-dependent. |
5218 | unsigned NumAssocs, ResultIndex; |
5219 | enum : unsigned { |
5220 | ResultDependentIndex = std::numeric_limits<unsigned>::max(), |
5221 | ControllingIndex = 0, |
5222 | AssocExprStartIndex = 1 |
5223 | }; |
5224 | |
5225 | /// The location of the "default" and of the right parenthesis. |
5226 | SourceLocation DefaultLoc, RParenLoc; |
5227 | |
5228 | // GenericSelectionExpr is followed by several trailing objects. |
5229 | // They are (in order): |
5230 | // |
5231 | // * A single Stmt * for the controlling expression. |
5232 | // * An array of getNumAssocs() Stmt * for the association expressions. |
5233 | // * An array of getNumAssocs() TypeSourceInfo *, one for each of the |
5234 | // association expressions. |
5235 | unsigned numTrailingObjects(OverloadToken<Stmt *>) const { |
5236 | // Add one to account for the controlling expression; the remainder |
5237 | // are the associated expressions. |
5238 | return 1 + getNumAssocs(); |
5239 | } |
5240 | |
5241 | unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const { |
5242 | return getNumAssocs(); |
5243 | } |
5244 | |
5245 | template <bool Const> class AssociationIteratorTy; |
5246 | /// Bundle together an association expression and its TypeSourceInfo. |
5247 | /// The Const template parameter is for the const and non-const versions |
5248 | /// of AssociationTy. |
5249 | template <bool Const> class AssociationTy { |
5250 | friend class GenericSelectionExpr; |
5251 | template <bool OtherConst> friend class AssociationIteratorTy; |
5252 | using ExprPtrTy = |
5253 | typename std::conditional<Const, const Expr *, Expr *>::type; |
5254 | using TSIPtrTy = typename std::conditional<Const, const TypeSourceInfo *, |
5255 | TypeSourceInfo *>::type; |
5256 | ExprPtrTy E; |
5257 | TSIPtrTy TSI; |
5258 | bool Selected; |
5259 | AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected) |
5260 | : E(E), TSI(TSI), Selected(Selected) {} |
5261 | |
5262 | public: |
5263 | ExprPtrTy getAssociationExpr() const { return E; } |
5264 | TSIPtrTy getTypeSourceInfo() const { return TSI; } |
5265 | QualType getType() const { return TSI ? TSI->getType() : QualType(); } |
5266 | bool isSelected() const { return Selected; } |
5267 | AssociationTy *operator->() { return this; } |
5268 | const AssociationTy *operator->() const { return this; } |
5269 | }; // class AssociationTy |
5270 | |
5271 | /// Iterator over const and non-const Association objects. The Association |
5272 | /// objects are created on the fly when the iterator is dereferenced. |
5273 | /// This abstract over how exactly the association expressions and the |
5274 | /// corresponding TypeSourceInfo * are stored. |
5275 | template <bool Const> |
5276 | class AssociationIteratorTy |
5277 | : public llvm::iterator_facade_base< |
5278 | AssociationIteratorTy<Const>, std::input_iterator_tag, |
5279 | AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>, |
5280 | AssociationTy<Const>> { |
5281 | friend class GenericSelectionExpr; |
5282 | // FIXME: This iterator could conceptually be a random access iterator, and |
5283 | // it would be nice if we could strengthen the iterator category someday. |
5284 | // However this iterator does not satisfy two requirements of forward |
5285 | // iterators: |
5286 | // a) reference = T& or reference = const T& |
5287 | // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only |
5288 | // if *It1 and *It2 are bound to the same objects. |
5289 | // An alternative design approach was discussed during review; |
5290 | // store an Association object inside the iterator, and return a reference |
5291 | // to it when dereferenced. This idea was discarded beacuse of nasty |
5292 | // lifetime issues: |
5293 | // AssociationIterator It = ...; |
5294 | // const Association &Assoc = *It++; // Oops, Assoc is dangling. |
5295 | using BaseTy = typename AssociationIteratorTy::iterator_facade_base; |
5296 | using StmtPtrPtrTy = |
5297 | typename std::conditional<Const, const Stmt *const *, Stmt **>::type; |
5298 | using TSIPtrPtrTy = |
5299 | typename std::conditional<Const, const TypeSourceInfo *const *, |
5300 | TypeSourceInfo **>::type; |
5301 | StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped. |
5302 | TSIPtrPtrTy TSI; // Kept in sync with E. |
5303 | unsigned Offset = 0, SelectedOffset = 0; |
5304 | AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset, |
5305 | unsigned SelectedOffset) |
5306 | : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {} |
5307 | |
5308 | public: |
5309 | AssociationIteratorTy() : E(nullptr), TSI(nullptr) {} |
5310 | typename BaseTy::reference operator*() const { |
5311 | return AssociationTy<Const>(cast<Expr>(*E), *TSI, |
5312 | Offset == SelectedOffset); |
5313 | } |
5314 | typename BaseTy::pointer operator->() const { return **this; } |
5315 | using BaseTy::operator++; |
5316 | AssociationIteratorTy &operator++() { |
5317 | ++E; |
5318 | ++TSI; |
5319 | ++Offset; |
5320 | return *this; |
5321 | } |
5322 | bool operator==(AssociationIteratorTy Other) const { return E == Other.E; } |
5323 | }; // class AssociationIterator |
5324 | |
5325 | /// Build a non-result-dependent generic selection expression. |
5326 | GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, |
5327 | Expr *ControllingExpr, |
5328 | ArrayRef<TypeSourceInfo *> AssocTypes, |
5329 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
5330 | SourceLocation RParenLoc, |
5331 | bool ContainsUnexpandedParameterPack, |
5332 | unsigned ResultIndex); |
5333 | |
5334 | /// Build a result-dependent generic selection expression. |
5335 | GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, |
5336 | Expr *ControllingExpr, |
5337 | ArrayRef<TypeSourceInfo *> AssocTypes, |
5338 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
5339 | SourceLocation RParenLoc, |
5340 | bool ContainsUnexpandedParameterPack); |
5341 | |
5342 | /// Build an empty generic selection expression for deserialization. |
5343 | explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs); |
5344 | |
5345 | public: |
5346 | /// Create a non-result-dependent generic selection expression. |
5347 | static GenericSelectionExpr * |
5348 | Create(const ASTContext &Context, SourceLocation GenericLoc, |
5349 | Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, |
5350 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
5351 | SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, |
5352 | unsigned ResultIndex); |
5353 | |
5354 | /// Create a result-dependent generic selection expression. |
5355 | static GenericSelectionExpr * |
5356 | Create(const ASTContext &Context, SourceLocation GenericLoc, |
5357 | Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, |
5358 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
5359 | SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack); |
5360 | |
5361 | /// Create an empty generic selection expression for deserialization. |
5362 | static GenericSelectionExpr *CreateEmpty(const ASTContext &Context, |
5363 | unsigned NumAssocs); |
5364 | |
5365 | using Association = AssociationTy<false>; |
5366 | using ConstAssociation = AssociationTy<true>; |
5367 | using AssociationIterator = AssociationIteratorTy<false>; |
5368 | using ConstAssociationIterator = AssociationIteratorTy<true>; |
5369 | using association_range = llvm::iterator_range<AssociationIterator>; |
5370 | using const_association_range = |
5371 | llvm::iterator_range<ConstAssociationIterator>; |
5372 | |
5373 | /// The number of association expressions. |
5374 | unsigned getNumAssocs() const { return NumAssocs; } |
5375 | |
5376 | /// The zero-based index of the result expression's generic association in |
5377 | /// the generic selection's association list. Defined only if the |
5378 | /// generic selection is not result-dependent. |
5379 | unsigned getResultIndex() const { |
5380 | assert(!isResultDependent() &&((!isResultDependent() && "Generic selection is result-dependent but getResultIndex called!" ) ? static_cast<void> (0) : __assert_fail ("!isResultDependent() && \"Generic selection is result-dependent but getResultIndex called!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5381, __PRETTY_FUNCTION__)) |
5381 | "Generic selection is result-dependent but getResultIndex called!")((!isResultDependent() && "Generic selection is result-dependent but getResultIndex called!" ) ? static_cast<void> (0) : __assert_fail ("!isResultDependent() && \"Generic selection is result-dependent but getResultIndex called!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5381, __PRETTY_FUNCTION__)); |
5382 | return ResultIndex; |
5383 | } |
5384 | |
5385 | /// Whether this generic selection is result-dependent. |
5386 | bool isResultDependent() const { return ResultIndex == ResultDependentIndex; } |
5387 | |
5388 | /// Return the controlling expression of this generic selection expression. |
5389 | Expr *getControllingExpr() { |
5390 | return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]); |
5391 | } |
5392 | const Expr *getControllingExpr() const { |
5393 | return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]); |
5394 | } |
5395 | |
5396 | /// Return the result expression of this controlling expression. Defined if |
5397 | /// and only if the generic selection expression is not result-dependent. |
5398 | Expr *getResultExpr() { |
5399 | return cast<Expr>( |
5400 | getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]); |
5401 | } |
5402 | const Expr *getResultExpr() const { |
5403 | return cast<Expr>( |
5404 | getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]); |
5405 | } |
5406 | |
5407 | ArrayRef<Expr *> getAssocExprs() const { |
5408 | return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() + |
5409 | AssocExprStartIndex), |
5410 | NumAssocs}; |
5411 | } |
5412 | ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const { |
5413 | return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs}; |
5414 | } |
5415 | |
5416 | /// Return the Ith association expression with its TypeSourceInfo, |
5417 | /// bundled together in GenericSelectionExpr::(Const)Association. |
5418 | Association getAssociation(unsigned I) { |
5419 | assert(I < getNumAssocs() &&((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5420, __PRETTY_FUNCTION__)) |
5420 | "Out-of-range index in GenericSelectionExpr::getAssociation!")((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5420, __PRETTY_FUNCTION__)); |
5421 | return Association( |
5422 | cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]), |
5423 | getTrailingObjects<TypeSourceInfo *>()[I], |
5424 | !isResultDependent() && (getResultIndex() == I)); |
5425 | } |
5426 | ConstAssociation getAssociation(unsigned I) const { |
5427 | assert(I < getNumAssocs() &&((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5428, __PRETTY_FUNCTION__)) |
5428 | "Out-of-range index in GenericSelectionExpr::getAssociation!")((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5428, __PRETTY_FUNCTION__)); |
5429 | return ConstAssociation( |
5430 | cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]), |
5431 | getTrailingObjects<TypeSourceInfo *>()[I], |
5432 | !isResultDependent() && (getResultIndex() == I)); |
5433 | } |
5434 | |
5435 | association_range associations() { |
5436 | AssociationIterator Begin(getTrailingObjects<Stmt *>() + |
5437 | AssocExprStartIndex, |
5438 | getTrailingObjects<TypeSourceInfo *>(), |
5439 | /*Offset=*/0, ResultIndex); |
5440 | AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, |
5441 | /*Offset=*/NumAssocs, ResultIndex); |
5442 | return llvm::make_range(Begin, End); |
5443 | } |
5444 | |
5445 | const_association_range associations() const { |
5446 | ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() + |
5447 | AssocExprStartIndex, |
5448 | getTrailingObjects<TypeSourceInfo *>(), |
5449 | /*Offset=*/0, ResultIndex); |
5450 | ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, |
5451 | /*Offset=*/NumAssocs, ResultIndex); |
5452 | return llvm::make_range(Begin, End); |
5453 | } |
5454 | |
5455 | SourceLocation getGenericLoc() const { |
5456 | return GenericSelectionExprBits.GenericLoc; |
5457 | } |
5458 | SourceLocation getDefaultLoc() const { return DefaultLoc; } |
5459 | SourceLocation getRParenLoc() const { return RParenLoc; } |
5460 | SourceLocation getBeginLoc() const { return getGenericLoc(); } |
5461 | SourceLocation getEndLoc() const { return getRParenLoc(); } |
5462 | |
5463 | static bool classof(const Stmt *T) { |
5464 | return T->getStmtClass() == GenericSelectionExprClass; |
5465 | } |
5466 | |
5467 | child_range children() { |
5468 | return child_range(getTrailingObjects<Stmt *>(), |
5469 | getTrailingObjects<Stmt *>() + |
5470 | numTrailingObjects(OverloadToken<Stmt *>())); |
5471 | } |
5472 | const_child_range children() const { |
5473 | return const_child_range(getTrailingObjects<Stmt *>(), |
5474 | getTrailingObjects<Stmt *>() + |
5475 | numTrailingObjects(OverloadToken<Stmt *>())); |
5476 | } |
5477 | }; |
5478 | |
5479 | //===----------------------------------------------------------------------===// |
5480 | // Clang Extensions |
5481 | //===----------------------------------------------------------------------===// |
5482 | |
5483 | /// ExtVectorElementExpr - This represents access to specific elements of a |
5484 | /// vector, and may occur on the left hand side or right hand side. For example |
5485 | /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. |
5486 | /// |
5487 | /// Note that the base may have either vector or pointer to vector type, just |
5488 | /// like a struct field reference. |
5489 | /// |
5490 | class ExtVectorElementExpr : public Expr { |
5491 | Stmt *Base; |
5492 | IdentifierInfo *Accessor; |
5493 | SourceLocation AccessorLoc; |
5494 | public: |
5495 | ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, |
5496 | IdentifierInfo &accessor, SourceLocation loc) |
5497 | : Expr(ExtVectorElementExprClass, ty, VK, |
5498 | (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent), |
5499 | base->isTypeDependent(), base->isValueDependent(), |
5500 | base->isInstantiationDependent(), |
5501 | base->containsUnexpandedParameterPack()), |
5502 | Base(base), Accessor(&accessor), AccessorLoc(loc) {} |
5503 | |
5504 | /// Build an empty vector element expression. |
5505 | explicit ExtVectorElementExpr(EmptyShell Empty) |
5506 | : Expr(ExtVectorElementExprClass, Empty) { } |
5507 | |
5508 | const Expr *getBase() const { return cast<Expr>(Base); } |
5509 | Expr *getBase() { return cast<Expr>(Base); } |
5510 | void setBase(Expr *E) { Base = E; } |
5511 | |
5512 | IdentifierInfo &getAccessor() const { return *Accessor; } |
5513 | void setAccessor(IdentifierInfo *II) { Accessor = II; } |
5514 | |
5515 | SourceLocation getAccessorLoc() const { return AccessorLoc; } |
5516 | void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } |
5517 | |
5518 | /// getNumElements - Get the number of components being selected. |
5519 | unsigned getNumElements() const; |
5520 | |
5521 | /// containsDuplicateElements - Return true if any element access is |
5522 | /// repeated. |
5523 | bool containsDuplicateElements() const; |
5524 | |
5525 | /// getEncodedElementAccess - Encode the elements accessed into an llvm |
5526 | /// aggregate Constant of ConstantInt(s). |
5527 | void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const; |
5528 | |
5529 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5530 | return getBase()->getBeginLoc(); |
5531 | } |
5532 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return AccessorLoc; } |
5533 | |
5534 | /// isArrow - Return true if the base expression is a pointer to vector, |
5535 | /// return false if the base expression is a vector. |
5536 | bool isArrow() const; |
5537 | |
5538 | static bool classof(const Stmt *T) { |
5539 | return T->getStmtClass() == ExtVectorElementExprClass; |
5540 | } |
5541 | |
5542 | // Iterators |
5543 | child_range children() { return child_range(&Base, &Base+1); } |
5544 | const_child_range children() const { |
5545 | return const_child_range(&Base, &Base + 1); |
5546 | } |
5547 | }; |
5548 | |
5549 | /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. |
5550 | /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } |
5551 | class BlockExpr : public Expr { |
5552 | protected: |
5553 | BlockDecl *TheBlock; |
5554 | public: |
5555 | BlockExpr(BlockDecl *BD, QualType ty) |
5556 | : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary, |
5557 | ty->isDependentType(), ty->isDependentType(), |
5558 | ty->isInstantiationDependentType() || BD->isDependentContext(), |
5559 | false), |
5560 | TheBlock(BD) {} |
5561 | |
5562 | /// Build an empty block expression. |
5563 | explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } |
5564 | |
5565 | const BlockDecl *getBlockDecl() const { return TheBlock; } |
5566 | BlockDecl *getBlockDecl() { return TheBlock; } |
5567 | void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } |
5568 | |
5569 | // Convenience functions for probing the underlying BlockDecl. |
5570 | SourceLocation getCaretLocation() const; |
5571 | const Stmt *getBody() const; |
5572 | Stmt *getBody(); |
5573 | |
5574 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5575 | return getCaretLocation(); |
5576 | } |
5577 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5578 | return getBody()->getEndLoc(); |
5579 | } |
5580 | |
5581 | /// getFunctionType - Return the underlying function type for this block. |
5582 | const FunctionProtoType *getFunctionType() const; |
5583 | |
5584 | static bool classof(const Stmt *T) { |
5585 | return T->getStmtClass() == BlockExprClass; |
5586 | } |
5587 | |
5588 | // Iterators |
5589 | child_range children() { |
5590 | return child_range(child_iterator(), child_iterator()); |
5591 | } |
5592 | const_child_range children() const { |
5593 | return const_child_range(const_child_iterator(), const_child_iterator()); |
5594 | } |
5595 | }; |
5596 | |
5597 | /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] |
5598 | /// This AST node provides support for reinterpreting a type to another |
5599 | /// type of the same size. |
5600 | class AsTypeExpr : public Expr { |
5601 | private: |
5602 | Stmt *SrcExpr; |
5603 | SourceLocation BuiltinLoc, RParenLoc; |
5604 | |
5605 | friend class ASTReader; |
5606 | friend class ASTStmtReader; |
5607 | explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} |
5608 | |
5609 | public: |
5610 | AsTypeExpr(Expr* SrcExpr, QualType DstType, |
5611 | ExprValueKind VK, ExprObjectKind OK, |
5612 | SourceLocation BuiltinLoc, SourceLocation RParenLoc) |
5613 | : Expr(AsTypeExprClass, DstType, VK, OK, |
5614 | DstType->isDependentType(), |
5615 | DstType->isDependentType() || SrcExpr->isValueDependent(), |
5616 | (DstType->isInstantiationDependentType() || |
5617 | SrcExpr->isInstantiationDependent()), |
5618 | (DstType->containsUnexpandedParameterPack() || |
5619 | SrcExpr->containsUnexpandedParameterPack())), |
5620 | SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} |
5621 | |
5622 | /// getSrcExpr - Return the Expr to be converted. |
5623 | Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } |
5624 | |
5625 | /// getBuiltinLoc - Return the location of the __builtin_astype token. |
5626 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
5627 | |
5628 | /// getRParenLoc - Return the location of final right parenthesis. |
5629 | SourceLocation getRParenLoc() const { return RParenLoc; } |
5630 | |
5631 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
5632 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
5633 | |
5634 | static bool classof(const Stmt *T) { |
5635 | return T->getStmtClass() == AsTypeExprClass; |
5636 | } |
5637 | |
5638 | // Iterators |
5639 | child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } |
5640 | const_child_range children() const { |
5641 | return const_child_range(&SrcExpr, &SrcExpr + 1); |
5642 | } |
5643 | }; |
5644 | |
5645 | /// PseudoObjectExpr - An expression which accesses a pseudo-object |
5646 | /// l-value. A pseudo-object is an abstract object, accesses to which |
5647 | /// are translated to calls. The pseudo-object expression has a |
5648 | /// syntactic form, which shows how the expression was actually |
5649 | /// written in the source code, and a semantic form, which is a series |
5650 | /// of expressions to be executed in order which detail how the |
5651 | /// operation is actually evaluated. Optionally, one of the semantic |
5652 | /// forms may also provide a result value for the expression. |
5653 | /// |
5654 | /// If any of the semantic-form expressions is an OpaqueValueExpr, |
5655 | /// that OVE is required to have a source expression, and it is bound |
5656 | /// to the result of that source expression. Such OVEs may appear |
5657 | /// only in subsequent semantic-form expressions and as |
5658 | /// sub-expressions of the syntactic form. |
5659 | /// |
5660 | /// PseudoObjectExpr should be used only when an operation can be |
5661 | /// usefully described in terms of fairly simple rewrite rules on |
5662 | /// objects and functions that are meant to be used by end-developers. |
5663 | /// For example, under the Itanium ABI, dynamic casts are implemented |
5664 | /// as a call to a runtime function called __dynamic_cast; using this |
5665 | /// class to describe that would be inappropriate because that call is |
5666 | /// not really part of the user-visible semantics, and instead the |
5667 | /// cast is properly reflected in the AST and IR-generation has been |
5668 | /// taught to generate the call as necessary. In contrast, an |
5669 | /// Objective-C property access is semantically defined to be |
5670 | /// equivalent to a particular message send, and this is very much |
5671 | /// part of the user model. The name of this class encourages this |
5672 | /// modelling design. |
5673 | class PseudoObjectExpr final |
5674 | : public Expr, |
5675 | private llvm::TrailingObjects<PseudoObjectExpr, Expr *> { |
5676 | // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions. |
5677 | // Always at least two, because the first sub-expression is the |
5678 | // syntactic form. |
5679 | |
5680 | // PseudoObjectExprBits.ResultIndex - The index of the |
5681 | // sub-expression holding the result. 0 means the result is void, |
5682 | // which is unambiguous because it's the index of the syntactic |
5683 | // form. Note that this is therefore 1 higher than the value passed |
5684 | // in to Create, which is an index within the semantic forms. |
5685 | // Note also that ASTStmtWriter assumes this encoding. |
5686 | |
5687 | Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); } |
5688 | const Expr * const *getSubExprsBuffer() const { |
5689 | return getTrailingObjects<Expr *>(); |
5690 | } |
5691 | |
5692 | PseudoObjectExpr(QualType type, ExprValueKind VK, |
5693 | Expr *syntactic, ArrayRef<Expr*> semantic, |
5694 | unsigned resultIndex); |
5695 | |
5696 | PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs); |
5697 | |
5698 | unsigned getNumSubExprs() const { |
5699 | return PseudoObjectExprBits.NumSubExprs; |
5700 | } |
5701 | |
5702 | public: |
5703 | /// NoResult - A value for the result index indicating that there is |
5704 | /// no semantic result. |
5705 | enum : unsigned { NoResult = ~0U }; |
5706 | |
5707 | static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic, |
5708 | ArrayRef<Expr*> semantic, |
5709 | unsigned resultIndex); |
5710 | |
5711 | static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell, |
5712 | unsigned numSemanticExprs); |
5713 | |
5714 | /// Return the syntactic form of this expression, i.e. the |
5715 | /// expression it actually looks like. Likely to be expressed in |
5716 | /// terms of OpaqueValueExprs bound in the semantic form. |
5717 | Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; } |
5718 | const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; } |
5719 | |
5720 | /// Return the index of the result-bearing expression into the semantics |
5721 | /// expressions, or PseudoObjectExpr::NoResult if there is none. |
5722 | unsigned getResultExprIndex() const { |
5723 | if (PseudoObjectExprBits.ResultIndex == 0) return NoResult; |
5724 | return PseudoObjectExprBits.ResultIndex - 1; |
5725 | } |
5726 | |
5727 | /// Return the result-bearing expression, or null if there is none. |
5728 | Expr *getResultExpr() { |
5729 | if (PseudoObjectExprBits.ResultIndex == 0) |
5730 | return nullptr; |
5731 | return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex]; |
5732 | } |
5733 | const Expr *getResultExpr() const { |
5734 | return const_cast<PseudoObjectExpr*>(this)->getResultExpr(); |
5735 | } |
5736 | |
5737 | unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; } |
5738 | |
5739 | typedef Expr * const *semantics_iterator; |
5740 | typedef const Expr * const *const_semantics_iterator; |
5741 | semantics_iterator semantics_begin() { |
5742 | return getSubExprsBuffer() + 1; |
5743 | } |
5744 | const_semantics_iterator semantics_begin() const { |
5745 | return getSubExprsBuffer() + 1; |
5746 | } |
5747 | semantics_iterator semantics_end() { |
5748 | return getSubExprsBuffer() + getNumSubExprs(); |
5749 | } |
5750 | const_semantics_iterator semantics_end() const { |
5751 | return getSubExprsBuffer() + getNumSubExprs(); |
5752 | } |
5753 | |
5754 | llvm::iterator_range<semantics_iterator> semantics() { |
5755 | return llvm::make_range(semantics_begin(), semantics_end()); |
5756 | } |
5757 | llvm::iterator_range<const_semantics_iterator> semantics() const { |
5758 | return llvm::make_range(semantics_begin(), semantics_end()); |
5759 | } |
5760 | |
5761 | Expr *getSemanticExpr(unsigned index) { |
5762 | assert(index + 1 < getNumSubExprs())((index + 1 < getNumSubExprs()) ? static_cast<void> ( 0) : __assert_fail ("index + 1 < getNumSubExprs()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5762, __PRETTY_FUNCTION__)); |
5763 | return getSubExprsBuffer()[index + 1]; |
5764 | } |
5765 | const Expr *getSemanticExpr(unsigned index) const { |
5766 | return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index); |
5767 | } |
5768 | |
5769 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5770 | return getSyntacticForm()->getExprLoc(); |
5771 | } |
5772 | |
5773 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5774 | return getSyntacticForm()->getBeginLoc(); |
5775 | } |
5776 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5777 | return getSyntacticForm()->getEndLoc(); |
5778 | } |
5779 | |
5780 | child_range children() { |
5781 | const_child_range CCR = |
5782 | const_cast<const PseudoObjectExpr *>(this)->children(); |
5783 | return child_range(cast_away_const(CCR.begin()), |
5784 | cast_away_const(CCR.end())); |
5785 | } |
5786 | const_child_range children() const { |
5787 | Stmt *const *cs = const_cast<Stmt *const *>( |
5788 | reinterpret_cast<const Stmt *const *>(getSubExprsBuffer())); |
5789 | return const_child_range(cs, cs + getNumSubExprs()); |
5790 | } |
5791 | |
5792 | static bool classof(const Stmt *T) { |
5793 | return T->getStmtClass() == PseudoObjectExprClass; |
5794 | } |
5795 | |
5796 | friend TrailingObjects; |
5797 | friend class ASTStmtReader; |
5798 | }; |
5799 | |
5800 | /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, |
5801 | /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the |
5802 | /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, |
5803 | /// and corresponding __opencl_atomic_* for OpenCL 2.0. |
5804 | /// All of these instructions take one primary pointer, at least one memory |
5805 | /// order. The instructions for which getScopeModel returns non-null value |
5806 | /// take one synch scope. |
5807 | class AtomicExpr : public Expr { |
5808 | public: |
5809 | enum AtomicOp { |
5810 | #define BUILTIN(ID, TYPE, ATTRS) |
5811 | #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID, |
5812 | #include "clang/Basic/Builtins.def" |
5813 | // Avoid trailing comma |
5814 | BI_First = 0 |
5815 | }; |
5816 | |
5817 | private: |
5818 | /// Location of sub-expressions. |
5819 | /// The location of Scope sub-expression is NumSubExprs - 1, which is |
5820 | /// not fixed, therefore is not defined in enum. |
5821 | enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR }; |
5822 | Stmt *SubExprs[END_EXPR + 1]; |
5823 | unsigned NumSubExprs; |
5824 | SourceLocation BuiltinLoc, RParenLoc; |
5825 | AtomicOp Op; |
5826 | |
5827 | friend class ASTStmtReader; |
5828 | public: |
5829 | AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t, |
5830 | AtomicOp op, SourceLocation RP); |
5831 | |
5832 | /// Determine the number of arguments the specified atomic builtin |
5833 | /// should have. |
5834 | static unsigned getNumSubExprs(AtomicOp Op); |
5835 | |
5836 | /// Build an empty AtomicExpr. |
5837 | explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } |
5838 | |
5839 | Expr *getPtr() const { |
5840 | return cast<Expr>(SubExprs[PTR]); |
5841 | } |
5842 | Expr *getOrder() const { |
5843 | return cast<Expr>(SubExprs[ORDER]); |
5844 | } |
5845 | Expr *getScope() const { |
5846 | assert(getScopeModel() && "No scope")((getScopeModel() && "No scope") ? static_cast<void > (0) : __assert_fail ("getScopeModel() && \"No scope\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5846, __PRETTY_FUNCTION__)); |
5847 | return cast<Expr>(SubExprs[NumSubExprs - 1]); |
5848 | } |
5849 | Expr *getVal1() const { |
5850 | if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init) |
5851 | return cast<Expr>(SubExprs[ORDER]); |
5852 | assert(NumSubExprs > VAL1)((NumSubExprs > VAL1) ? static_cast<void> (0) : __assert_fail ("NumSubExprs > VAL1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5852, __PRETTY_FUNCTION__)); |
5853 | return cast<Expr>(SubExprs[VAL1]); |
5854 | } |
5855 | Expr *getOrderFail() const { |
5856 | assert(NumSubExprs > ORDER_FAIL)((NumSubExprs > ORDER_FAIL) ? static_cast<void> (0) : __assert_fail ("NumSubExprs > ORDER_FAIL", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5856, __PRETTY_FUNCTION__)); |
5857 | return cast<Expr>(SubExprs[ORDER_FAIL]); |
5858 | } |
5859 | Expr *getVal2() const { |
5860 | if (Op == AO__atomic_exchange) |
5861 | return cast<Expr>(SubExprs[ORDER_FAIL]); |
5862 | assert(NumSubExprs > VAL2)((NumSubExprs > VAL2) ? static_cast<void> (0) : __assert_fail ("NumSubExprs > VAL2", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5862, __PRETTY_FUNCTION__)); |
5863 | return cast<Expr>(SubExprs[VAL2]); |
5864 | } |
5865 | Expr *getWeak() const { |
5866 | assert(NumSubExprs > WEAK)((NumSubExprs > WEAK) ? static_cast<void> (0) : __assert_fail ("NumSubExprs > WEAK", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5866, __PRETTY_FUNCTION__)); |
5867 | return cast<Expr>(SubExprs[WEAK]); |
5868 | } |
5869 | QualType getValueType() const; |
5870 | |
5871 | AtomicOp getOp() const { return Op; } |
5872 | unsigned getNumSubExprs() const { return NumSubExprs; } |
5873 | |
5874 | Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } |
5875 | const Expr * const *getSubExprs() const { |
5876 | return reinterpret_cast<Expr * const *>(SubExprs); |
5877 | } |
5878 | |
5879 | bool isVolatile() const { |
5880 | return getPtr()->getType()->getPointeeType().isVolatileQualified(); |
5881 | } |
5882 | |
5883 | bool isCmpXChg() const { |
5884 | return getOp() == AO__c11_atomic_compare_exchange_strong || |
5885 | getOp() == AO__c11_atomic_compare_exchange_weak || |
5886 | getOp() == AO__opencl_atomic_compare_exchange_strong || |
5887 | getOp() == AO__opencl_atomic_compare_exchange_weak || |
5888 | getOp() == AO__atomic_compare_exchange || |
5889 | getOp() == AO__atomic_compare_exchange_n; |
5890 | } |
5891 | |
5892 | bool isOpenCL() const { |
5893 | return getOp() >= AO__opencl_atomic_init && |
5894 | getOp() <= AO__opencl_atomic_fetch_max; |
5895 | } |
5896 | |
5897 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
5898 | SourceLocation getRParenLoc() const { return RParenLoc; } |
5899 | |
5900 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
5901 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
5902 | |
5903 | static bool classof(const Stmt *T) { |
5904 | return T->getStmtClass() == AtomicExprClass; |
5905 | } |
5906 | |
5907 | // Iterators |
5908 | child_range children() { |
5909 | return child_range(SubExprs, SubExprs+NumSubExprs); |
5910 | } |
5911 | const_child_range children() const { |
5912 | return const_child_range(SubExprs, SubExprs + NumSubExprs); |
5913 | } |
5914 | |
5915 | /// Get atomic scope model for the atomic op code. |
5916 | /// \return empty atomic scope model if the atomic op code does not have |
5917 | /// scope operand. |
5918 | static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) { |
5919 | auto Kind = |
5920 | (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max) |
5921 | ? AtomicScopeModelKind::OpenCL |
5922 | : AtomicScopeModelKind::None; |
5923 | return AtomicScopeModel::create(Kind); |
5924 | } |
5925 | |
5926 | /// Get atomic scope model. |
5927 | /// \return empty atomic scope model if this atomic expression does not have |
5928 | /// scope operand. |
5929 | std::unique_ptr<AtomicScopeModel> getScopeModel() const { |
5930 | return getScopeModel(getOp()); |
5931 | } |
5932 | }; |
5933 | |
5934 | /// TypoExpr - Internal placeholder for expressions where typo correction |
5935 | /// still needs to be performed and/or an error diagnostic emitted. |
5936 | class TypoExpr : public Expr { |
5937 | public: |
5938 | TypoExpr(QualType T) |
5939 | : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary, |
5940 | /*isTypeDependent*/ true, |
5941 | /*isValueDependent*/ true, |
5942 | /*isInstantiationDependent*/ true, |
5943 | /*containsUnexpandedParameterPack*/ false) { |
5944 | assert(T->isDependentType() && "TypoExpr given a non-dependent type")((T->isDependentType() && "TypoExpr given a non-dependent type" ) ? static_cast<void> (0) : __assert_fail ("T->isDependentType() && \"TypoExpr given a non-dependent type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5944, __PRETTY_FUNCTION__)); |
5945 | } |
5946 | |
5947 | child_range children() { |
5948 | return child_range(child_iterator(), child_iterator()); |
5949 | } |
5950 | const_child_range children() const { |
5951 | return const_child_range(const_child_iterator(), const_child_iterator()); |
5952 | } |
5953 | |
5954 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5955 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5956 | |
5957 | static bool classof(const Stmt *T) { |
5958 | return T->getStmtClass() == TypoExprClass; |
5959 | } |
5960 | |
5961 | }; |
5962 | } // end namespace clang |
5963 | |
5964 | #endif // LLVM_CLANG_AST_EXPR_H |
1 | //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | /// \file |
10 | /// C Language Family Type Representation |
11 | /// |
12 | /// This file defines the clang::Type interface and subclasses, used to |
13 | /// represent types for languages in the C family. |
14 | // |
15 | //===----------------------------------------------------------------------===// |
16 | |
17 | #ifndef LLVM_CLANG_AST_TYPE_H |
18 | #define LLVM_CLANG_AST_TYPE_H |
19 | |
20 | #include "clang/AST/NestedNameSpecifier.h" |
21 | #include "clang/AST/TemplateName.h" |
22 | #include "clang/Basic/AddressSpaces.h" |
23 | #include "clang/Basic/AttrKinds.h" |
24 | #include "clang/Basic/Diagnostic.h" |
25 | #include "clang/Basic/ExceptionSpecificationType.h" |
26 | #include "clang/Basic/LLVM.h" |
27 | #include "clang/Basic/Linkage.h" |
28 | #include "clang/Basic/PartialDiagnostic.h" |
29 | #include "clang/Basic/SourceLocation.h" |
30 | #include "clang/Basic/Specifiers.h" |
31 | #include "clang/Basic/Visibility.h" |
32 | #include "llvm/ADT/APInt.h" |
33 | #include "llvm/ADT/APSInt.h" |
34 | #include "llvm/ADT/ArrayRef.h" |
35 | #include "llvm/ADT/FoldingSet.h" |
36 | #include "llvm/ADT/None.h" |
37 | #include "llvm/ADT/Optional.h" |
38 | #include "llvm/ADT/PointerIntPair.h" |
39 | #include "llvm/ADT/PointerUnion.h" |
40 | #include "llvm/ADT/StringRef.h" |
41 | #include "llvm/ADT/Twine.h" |
42 | #include "llvm/ADT/iterator_range.h" |
43 | #include "llvm/Support/Casting.h" |
44 | #include "llvm/Support/Compiler.h" |
45 | #include "llvm/Support/ErrorHandling.h" |
46 | #include "llvm/Support/PointerLikeTypeTraits.h" |
47 | #include "llvm/Support/type_traits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include <cassert> |
50 | #include <cstddef> |
51 | #include <cstdint> |
52 | #include <cstring> |
53 | #include <string> |
54 | #include <type_traits> |
55 | #include <utility> |
56 | |
57 | namespace clang { |
58 | |
59 | class ExtQuals; |
60 | class QualType; |
61 | class TagDecl; |
62 | class Type; |
63 | |
64 | enum { |
65 | TypeAlignmentInBits = 4, |
66 | TypeAlignment = 1 << TypeAlignmentInBits |
67 | }; |
68 | |
69 | } // namespace clang |
70 | |
71 | namespace llvm { |
72 | |
73 | template <typename T> |
74 | struct PointerLikeTypeTraits; |
75 | template<> |
76 | struct PointerLikeTypeTraits< ::clang::Type*> { |
77 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
78 | |
79 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
80 | return static_cast< ::clang::Type*>(P); |
81 | } |
82 | |
83 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
84 | }; |
85 | |
86 | template<> |
87 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
88 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
89 | |
90 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
91 | return static_cast< ::clang::ExtQuals*>(P); |
92 | } |
93 | |
94 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
95 | }; |
96 | |
97 | } // namespace llvm |
98 | |
99 | namespace clang { |
100 | |
101 | class ASTContext; |
102 | template <typename> class CanQual; |
103 | class CXXRecordDecl; |
104 | class DeclContext; |
105 | class EnumDecl; |
106 | class Expr; |
107 | class ExtQualsTypeCommonBase; |
108 | class FunctionDecl; |
109 | class IdentifierInfo; |
110 | class NamedDecl; |
111 | class ObjCInterfaceDecl; |
112 | class ObjCProtocolDecl; |
113 | class ObjCTypeParamDecl; |
114 | struct PrintingPolicy; |
115 | class RecordDecl; |
116 | class Stmt; |
117 | class TagDecl; |
118 | class TemplateArgument; |
119 | class TemplateArgumentListInfo; |
120 | class TemplateArgumentLoc; |
121 | class TemplateTypeParmDecl; |
122 | class TypedefNameDecl; |
123 | class UnresolvedUsingTypenameDecl; |
124 | |
125 | using CanQualType = CanQual<Type>; |
126 | |
127 | // Provide forward declarations for all of the *Type classes. |
128 | #define TYPE(Class, Base) class Class##Type; |
129 | #include "clang/AST/TypeNodes.inc" |
130 | |
131 | /// The collection of all-type qualifiers we support. |
132 | /// Clang supports five independent qualifiers: |
133 | /// * C99: const, volatile, and restrict |
134 | /// * MS: __unaligned |
135 | /// * Embedded C (TR18037): address spaces |
136 | /// * Objective C: the GC attributes (none, weak, or strong) |
137 | class Qualifiers { |
138 | public: |
139 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
140 | Const = 0x1, |
141 | Restrict = 0x2, |
142 | Volatile = 0x4, |
143 | CVRMask = Const | Volatile | Restrict |
144 | }; |
145 | |
146 | enum GC { |
147 | GCNone = 0, |
148 | Weak, |
149 | Strong |
150 | }; |
151 | |
152 | enum ObjCLifetime { |
153 | /// There is no lifetime qualification on this type. |
154 | OCL_None, |
155 | |
156 | /// This object can be modified without requiring retains or |
157 | /// releases. |
158 | OCL_ExplicitNone, |
159 | |
160 | /// Assigning into this object requires the old value to be |
161 | /// released and the new value to be retained. The timing of the |
162 | /// release of the old value is inexact: it may be moved to |
163 | /// immediately after the last known point where the value is |
164 | /// live. |
165 | OCL_Strong, |
166 | |
167 | /// Reading or writing from this object requires a barrier call. |
168 | OCL_Weak, |
169 | |
170 | /// Assigning into this object requires a lifetime extension. |
171 | OCL_Autoreleasing |
172 | }; |
173 | |
174 | enum { |
175 | /// The maximum supported address space number. |
176 | /// 23 bits should be enough for anyone. |
177 | MaxAddressSpace = 0x7fffffu, |
178 | |
179 | /// The width of the "fast" qualifier mask. |
180 | FastWidth = 3, |
181 | |
182 | /// The fast qualifier mask. |
183 | FastMask = (1 << FastWidth) - 1 |
184 | }; |
185 | |
186 | /// Returns the common set of qualifiers while removing them from |
187 | /// the given sets. |
188 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
189 | // If both are only CVR-qualified, bit operations are sufficient. |
190 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
191 | Qualifiers Q; |
192 | Q.Mask = L.Mask & R.Mask; |
193 | L.Mask &= ~Q.Mask; |
194 | R.Mask &= ~Q.Mask; |
195 | return Q; |
196 | } |
197 | |
198 | Qualifiers Q; |
199 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
200 | Q.addCVRQualifiers(CommonCRV); |
201 | L.removeCVRQualifiers(CommonCRV); |
202 | R.removeCVRQualifiers(CommonCRV); |
203 | |
204 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
205 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
206 | L.removeObjCGCAttr(); |
207 | R.removeObjCGCAttr(); |
208 | } |
209 | |
210 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
211 | Q.setObjCLifetime(L.getObjCLifetime()); |
212 | L.removeObjCLifetime(); |
213 | R.removeObjCLifetime(); |
214 | } |
215 | |
216 | if (L.getAddressSpace() == R.getAddressSpace()) { |
217 | Q.setAddressSpace(L.getAddressSpace()); |
218 | L.removeAddressSpace(); |
219 | R.removeAddressSpace(); |
220 | } |
221 | return Q; |
222 | } |
223 | |
224 | static Qualifiers fromFastMask(unsigned Mask) { |
225 | Qualifiers Qs; |
226 | Qs.addFastQualifiers(Mask); |
227 | return Qs; |
228 | } |
229 | |
230 | static Qualifiers fromCVRMask(unsigned CVR) { |
231 | Qualifiers Qs; |
232 | Qs.addCVRQualifiers(CVR); |
233 | return Qs; |
234 | } |
235 | |
236 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
237 | Qualifiers Qs; |
238 | Qs.addCVRUQualifiers(CVRU); |
239 | return Qs; |
240 | } |
241 | |
242 | // Deserialize qualifiers from an opaque representation. |
243 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
244 | Qualifiers Qs; |
245 | Qs.Mask = opaque; |
246 | return Qs; |
247 | } |
248 | |
249 | // Serialize these qualifiers into an opaque representation. |
250 | unsigned getAsOpaqueValue() const { |
251 | return Mask; |
252 | } |
253 | |
254 | bool hasConst() const { return Mask & Const; } |
255 | bool hasOnlyConst() const { return Mask == Const; } |
256 | void removeConst() { Mask &= ~Const; } |
257 | void addConst() { Mask |= Const; } |
258 | |
259 | bool hasVolatile() const { return Mask & Volatile; } |
260 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
261 | void removeVolatile() { Mask &= ~Volatile; } |
262 | void addVolatile() { Mask |= Volatile; } |
263 | |
264 | bool hasRestrict() const { return Mask & Restrict; } |
265 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
266 | void removeRestrict() { Mask &= ~Restrict; } |
267 | void addRestrict() { Mask |= Restrict; } |
268 | |
269 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
270 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
271 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
272 | |
273 | void setCVRQualifiers(unsigned mask) { |
274 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 274, __PRETTY_FUNCTION__)); |
275 | Mask = (Mask & ~CVRMask) | mask; |
276 | } |
277 | void removeCVRQualifiers(unsigned mask) { |
278 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 278, __PRETTY_FUNCTION__)); |
279 | Mask &= ~mask; |
280 | } |
281 | void removeCVRQualifiers() { |
282 | removeCVRQualifiers(CVRMask); |
283 | } |
284 | void addCVRQualifiers(unsigned mask) { |
285 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 285, __PRETTY_FUNCTION__)); |
286 | Mask |= mask; |
287 | } |
288 | void addCVRUQualifiers(unsigned mask) { |
289 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 289, __PRETTY_FUNCTION__)); |
290 | Mask |= mask; |
291 | } |
292 | |
293 | bool hasUnaligned() const { return Mask & UMask; } |
294 | void setUnaligned(bool flag) { |
295 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
296 | } |
297 | void removeUnaligned() { Mask &= ~UMask; } |
298 | void addUnaligned() { Mask |= UMask; } |
299 | |
300 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
301 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
302 | void setObjCGCAttr(GC type) { |
303 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
304 | } |
305 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
306 | void addObjCGCAttr(GC type) { |
307 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 307, __PRETTY_FUNCTION__)); |
308 | setObjCGCAttr(type); |
309 | } |
310 | Qualifiers withoutObjCGCAttr() const { |
311 | Qualifiers qs = *this; |
312 | qs.removeObjCGCAttr(); |
313 | return qs; |
314 | } |
315 | Qualifiers withoutObjCLifetime() const { |
316 | Qualifiers qs = *this; |
317 | qs.removeObjCLifetime(); |
318 | return qs; |
319 | } |
320 | Qualifiers withoutAddressSpace() const { |
321 | Qualifiers qs = *this; |
322 | qs.removeAddressSpace(); |
323 | return qs; |
324 | } |
325 | |
326 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
327 | ObjCLifetime getObjCLifetime() const { |
328 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
329 | } |
330 | void setObjCLifetime(ObjCLifetime type) { |
331 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
332 | } |
333 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
334 | void addObjCLifetime(ObjCLifetime type) { |
335 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 335, __PRETTY_FUNCTION__)); |
336 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 336, __PRETTY_FUNCTION__)); |
337 | Mask |= (type << LifetimeShift); |
338 | } |
339 | |
340 | /// True if the lifetime is neither None or ExplicitNone. |
341 | bool hasNonTrivialObjCLifetime() const { |
342 | ObjCLifetime lifetime = getObjCLifetime(); |
343 | return (lifetime > OCL_ExplicitNone); |
344 | } |
345 | |
346 | /// True if the lifetime is either strong or weak. |
347 | bool hasStrongOrWeakObjCLifetime() const { |
348 | ObjCLifetime lifetime = getObjCLifetime(); |
349 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
350 | } |
351 | |
352 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
353 | LangAS getAddressSpace() const { |
354 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
355 | } |
356 | bool hasTargetSpecificAddressSpace() const { |
357 | return isTargetAddressSpace(getAddressSpace()); |
358 | } |
359 | /// Get the address space attribute value to be printed by diagnostics. |
360 | unsigned getAddressSpaceAttributePrintValue() const { |
361 | auto Addr = getAddressSpace(); |
362 | // This function is not supposed to be used with language specific |
363 | // address spaces. If that happens, the diagnostic message should consider |
364 | // printing the QualType instead of the address space value. |
365 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 365, __PRETTY_FUNCTION__)); |
366 | if (Addr != LangAS::Default) |
367 | return toTargetAddressSpace(Addr); |
368 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
369 | // since it cannot differentiate the situation where 0 denotes the default |
370 | // address space or user specified __attribute__((address_space(0))). |
371 | return 0; |
372 | } |
373 | void setAddressSpace(LangAS space) { |
374 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 374, __PRETTY_FUNCTION__)); |
375 | Mask = (Mask & ~AddressSpaceMask) |
376 | | (((uint32_t) space) << AddressSpaceShift); |
377 | } |
378 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
379 | void addAddressSpace(LangAS space) { |
380 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 380, __PRETTY_FUNCTION__)); |
381 | setAddressSpace(space); |
382 | } |
383 | |
384 | // Fast qualifiers are those that can be allocated directly |
385 | // on a QualType object. |
386 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
387 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
388 | void setFastQualifiers(unsigned mask) { |
389 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 389, __PRETTY_FUNCTION__)); |
390 | Mask = (Mask & ~FastMask) | mask; |
391 | } |
392 | void removeFastQualifiers(unsigned mask) { |
393 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 393, __PRETTY_FUNCTION__)); |
394 | Mask &= ~mask; |
395 | } |
396 | void removeFastQualifiers() { |
397 | removeFastQualifiers(FastMask); |
398 | } |
399 | void addFastQualifiers(unsigned mask) { |
400 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 400, __PRETTY_FUNCTION__)); |
401 | Mask |= mask; |
402 | } |
403 | |
404 | /// Return true if the set contains any qualifiers which require an ExtQuals |
405 | /// node to be allocated. |
406 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
407 | Qualifiers getNonFastQualifiers() const { |
408 | Qualifiers Quals = *this; |
409 | Quals.setFastQualifiers(0); |
410 | return Quals; |
411 | } |
412 | |
413 | /// Return true if the set contains any qualifiers. |
414 | bool hasQualifiers() const { return Mask; } |
415 | bool empty() const { return !Mask; } |
416 | |
417 | /// Add the qualifiers from the given set to this set. |
418 | void addQualifiers(Qualifiers Q) { |
419 | // If the other set doesn't have any non-boolean qualifiers, just |
420 | // bit-or it in. |
421 | if (!(Q.Mask & ~CVRMask)) |
422 | Mask |= Q.Mask; |
423 | else { |
424 | Mask |= (Q.Mask & CVRMask); |
425 | if (Q.hasAddressSpace()) |
426 | addAddressSpace(Q.getAddressSpace()); |
427 | if (Q.hasObjCGCAttr()) |
428 | addObjCGCAttr(Q.getObjCGCAttr()); |
429 | if (Q.hasObjCLifetime()) |
430 | addObjCLifetime(Q.getObjCLifetime()); |
431 | } |
432 | } |
433 | |
434 | /// Remove the qualifiers from the given set from this set. |
435 | void removeQualifiers(Qualifiers Q) { |
436 | // If the other set doesn't have any non-boolean qualifiers, just |
437 | // bit-and the inverse in. |
438 | if (!(Q.Mask & ~CVRMask)) |
439 | Mask &= ~Q.Mask; |
440 | else { |
441 | Mask &= ~(Q.Mask & CVRMask); |
442 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
443 | removeObjCGCAttr(); |
444 | if (getObjCLifetime() == Q.getObjCLifetime()) |
445 | removeObjCLifetime(); |
446 | if (getAddressSpace() == Q.getAddressSpace()) |
447 | removeAddressSpace(); |
448 | } |
449 | } |
450 | |
451 | /// Add the qualifiers from the given set to this set, given that |
452 | /// they don't conflict. |
453 | void addConsistentQualifiers(Qualifiers qs) { |
454 | assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 455, __PRETTY_FUNCTION__)) |
455 | !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 455, __PRETTY_FUNCTION__)); |
456 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 457, __PRETTY_FUNCTION__)) |
457 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 457, __PRETTY_FUNCTION__)); |
458 | assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 459, __PRETTY_FUNCTION__)) |
459 | !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 459, __PRETTY_FUNCTION__)); |
460 | Mask |= qs.Mask; |
461 | } |
462 | |
463 | /// Returns true if address space A is equal to or a superset of B. |
464 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
465 | /// overlapping address spaces. |
466 | /// CL1.1 or CL1.2: |
467 | /// every address space is a superset of itself. |
468 | /// CL2.0 adds: |
469 | /// __generic is a superset of any address space except for __constant. |
470 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
471 | // Address spaces must match exactly. |
472 | return A == B || |
473 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
474 | // for __constant can be used as __generic. |
475 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant); |
476 | } |
477 | |
478 | /// Returns true if the address space in these qualifiers is equal to or |
479 | /// a superset of the address space in the argument qualifiers. |
480 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
481 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
482 | } |
483 | |
484 | /// Determines if these qualifiers compatibly include another set. |
485 | /// Generally this answers the question of whether an object with the other |
486 | /// qualifiers can be safely used as an object with these qualifiers. |
487 | bool compatiblyIncludes(Qualifiers other) const { |
488 | return isAddressSpaceSupersetOf(other) && |
489 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
490 | // be changed. |
491 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
492 | !other.hasObjCGCAttr()) && |
493 | // ObjC lifetime qualifiers must match exactly. |
494 | getObjCLifetime() == other.getObjCLifetime() && |
495 | // CVR qualifiers may subset. |
496 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
497 | // U qualifier may superset. |
498 | (!other.hasUnaligned() || hasUnaligned()); |
499 | } |
500 | |
501 | /// Determines if these qualifiers compatibly include another set of |
502 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
503 | /// |
504 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
505 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
506 | /// including set also contains the 'const' qualifier, or both are non-__weak |
507 | /// and one is None (which can only happen in non-ARC modes). |
508 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
509 | if (getObjCLifetime() == other.getObjCLifetime()) |
510 | return true; |
511 | |
512 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
513 | return false; |
514 | |
515 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
516 | return true; |
517 | |
518 | return hasConst(); |
519 | } |
520 | |
521 | /// Determine whether this set of qualifiers is a strict superset of |
522 | /// another set of qualifiers, not considering qualifier compatibility. |
523 | bool isStrictSupersetOf(Qualifiers Other) const; |
524 | |
525 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
526 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
527 | |
528 | explicit operator bool() const { return hasQualifiers(); } |
529 | |
530 | Qualifiers &operator+=(Qualifiers R) { |
531 | addQualifiers(R); |
532 | return *this; |
533 | } |
534 | |
535 | // Union two qualifier sets. If an enumerated qualifier appears |
536 | // in both sets, use the one from the right. |
537 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
538 | L += R; |
539 | return L; |
540 | } |
541 | |
542 | Qualifiers &operator-=(Qualifiers R) { |
543 | removeQualifiers(R); |
544 | return *this; |
545 | } |
546 | |
547 | /// Compute the difference between two qualifier sets. |
548 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
549 | L -= R; |
550 | return L; |
551 | } |
552 | |
553 | std::string getAsString() const; |
554 | std::string getAsString(const PrintingPolicy &Policy) const; |
555 | |
556 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
557 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
558 | bool appendSpaceIfNonEmpty = false) const; |
559 | |
560 | void Profile(llvm::FoldingSetNodeID &ID) const { |
561 | ID.AddInteger(Mask); |
562 | } |
563 | |
564 | private: |
565 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
566 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
567 | uint32_t Mask = 0; |
568 | |
569 | static const uint32_t UMask = 0x8; |
570 | static const uint32_t UShift = 3; |
571 | static const uint32_t GCAttrMask = 0x30; |
572 | static const uint32_t GCAttrShift = 4; |
573 | static const uint32_t LifetimeMask = 0x1C0; |
574 | static const uint32_t LifetimeShift = 6; |
575 | static const uint32_t AddressSpaceMask = |
576 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
577 | static const uint32_t AddressSpaceShift = 9; |
578 | }; |
579 | |
580 | /// A std::pair-like structure for storing a qualified type split |
581 | /// into its local qualifiers and its locally-unqualified type. |
582 | struct SplitQualType { |
583 | /// The locally-unqualified type. |
584 | const Type *Ty = nullptr; |
585 | |
586 | /// The local qualifiers. |
587 | Qualifiers Quals; |
588 | |
589 | SplitQualType() = default; |
590 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
591 | |
592 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
593 | |
594 | // Make std::tie work. |
595 | std::pair<const Type *,Qualifiers> asPair() const { |
596 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
597 | } |
598 | |
599 | friend bool operator==(SplitQualType a, SplitQualType b) { |
600 | return a.Ty == b.Ty && a.Quals == b.Quals; |
601 | } |
602 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
603 | return a.Ty != b.Ty || a.Quals != b.Quals; |
604 | } |
605 | }; |
606 | |
607 | /// The kind of type we are substituting Objective-C type arguments into. |
608 | /// |
609 | /// The kind of substitution affects the replacement of type parameters when |
610 | /// no concrete type information is provided, e.g., when dealing with an |
611 | /// unspecialized type. |
612 | enum class ObjCSubstitutionContext { |
613 | /// An ordinary type. |
614 | Ordinary, |
615 | |
616 | /// The result type of a method or function. |
617 | Result, |
618 | |
619 | /// The parameter type of a method or function. |
620 | Parameter, |
621 | |
622 | /// The type of a property. |
623 | Property, |
624 | |
625 | /// The superclass of a type. |
626 | Superclass, |
627 | }; |
628 | |
629 | /// A (possibly-)qualified type. |
630 | /// |
631 | /// For efficiency, we don't store CV-qualified types as nodes on their |
632 | /// own: instead each reference to a type stores the qualifiers. This |
633 | /// greatly reduces the number of nodes we need to allocate for types (for |
634 | /// example we only need one for 'int', 'const int', 'volatile int', |
635 | /// 'const volatile int', etc). |
636 | /// |
637 | /// As an added efficiency bonus, instead of making this a pair, we |
638 | /// just store the two bits we care about in the low bits of the |
639 | /// pointer. To handle the packing/unpacking, we make QualType be a |
640 | /// simple wrapper class that acts like a smart pointer. A third bit |
641 | /// indicates whether there are extended qualifiers present, in which |
642 | /// case the pointer points to a special structure. |
643 | class QualType { |
644 | friend class QualifierCollector; |
645 | |
646 | // Thankfully, these are efficiently composable. |
647 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
648 | Qualifiers::FastWidth> Value; |
649 | |
650 | const ExtQuals *getExtQualsUnsafe() const { |
651 | return Value.getPointer().get<const ExtQuals*>(); |
652 | } |
653 | |
654 | const Type *getTypePtrUnsafe() const { |
655 | return Value.getPointer().get<const Type*>(); |
656 | } |
657 | |
658 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
659 | assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer") ? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 659, __PRETTY_FUNCTION__)); |
660 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
661 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
662 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
663 | } |
664 | |
665 | public: |
666 | QualType() = default; |
667 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
668 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
669 | |
670 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
671 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
672 | |
673 | /// Retrieves a pointer to the underlying (unqualified) type. |
674 | /// |
675 | /// This function requires that the type not be NULL. If the type might be |
676 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
677 | const Type *getTypePtr() const; |
678 | |
679 | const Type *getTypePtrOrNull() const; |
680 | |
681 | /// Retrieves a pointer to the name of the base type. |
682 | const IdentifierInfo *getBaseTypeIdentifier() const; |
683 | |
684 | /// Divides a QualType into its unqualified type and a set of local |
685 | /// qualifiers. |
686 | SplitQualType split() const; |
687 | |
688 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
689 | |
690 | static QualType getFromOpaquePtr(const void *Ptr) { |
691 | QualType T; |
692 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
693 | return T; |
694 | } |
695 | |
696 | const Type &operator*() const { |
697 | return *getTypePtr(); |
698 | } |
699 | |
700 | const Type *operator->() const { |
701 | return getTypePtr(); |
702 | } |
703 | |
704 | bool isCanonical() const; |
705 | bool isCanonicalAsParam() const; |
706 | |
707 | /// Return true if this QualType doesn't point to a type yet. |
708 | bool isNull() const { |
709 | return Value.getPointer().isNull(); |
710 | } |
711 | |
712 | /// Determine whether this particular QualType instance has the |
713 | /// "const" qualifier set, without looking through typedefs that may have |
714 | /// added "const" at a different level. |
715 | bool isLocalConstQualified() const { |
716 | return (getLocalFastQualifiers() & Qualifiers::Const); |
717 | } |
718 | |
719 | /// Determine whether this type is const-qualified. |
720 | bool isConstQualified() const; |
721 | |
722 | /// Determine whether this particular QualType instance has the |
723 | /// "restrict" qualifier set, without looking through typedefs that may have |
724 | /// added "restrict" at a different level. |
725 | bool isLocalRestrictQualified() const { |
726 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
727 | } |
728 | |
729 | /// Determine whether this type is restrict-qualified. |
730 | bool isRestrictQualified() const; |
731 | |
732 | /// Determine whether this particular QualType instance has the |
733 | /// "volatile" qualifier set, without looking through typedefs that may have |
734 | /// added "volatile" at a different level. |
735 | bool isLocalVolatileQualified() const { |
736 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
737 | } |
738 | |
739 | /// Determine whether this type is volatile-qualified. |
740 | bool isVolatileQualified() const; |
741 | |
742 | /// Determine whether this particular QualType instance has any |
743 | /// qualifiers, without looking through any typedefs that might add |
744 | /// qualifiers at a different level. |
745 | bool hasLocalQualifiers() const { |
746 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
747 | } |
748 | |
749 | /// Determine whether this type has any qualifiers. |
750 | bool hasQualifiers() const; |
751 | |
752 | /// Determine whether this particular QualType instance has any |
753 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
754 | /// instance. |
755 | bool hasLocalNonFastQualifiers() const { |
756 | return Value.getPointer().is<const ExtQuals*>(); |
757 | } |
758 | |
759 | /// Retrieve the set of qualifiers local to this particular QualType |
760 | /// instance, not including any qualifiers acquired through typedefs or |
761 | /// other sugar. |
762 | Qualifiers getLocalQualifiers() const; |
763 | |
764 | /// Retrieve the set of qualifiers applied to this type. |
765 | Qualifiers getQualifiers() const; |
766 | |
767 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
768 | /// local to this particular QualType instance, not including any qualifiers |
769 | /// acquired through typedefs or other sugar. |
770 | unsigned getLocalCVRQualifiers() const { |
771 | return getLocalFastQualifiers(); |
772 | } |
773 | |
774 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
775 | /// applied to this type. |
776 | unsigned getCVRQualifiers() const; |
777 | |
778 | bool isConstant(const ASTContext& Ctx) const { |
779 | return QualType::isConstant(*this, Ctx); |
780 | } |
781 | |
782 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
783 | bool isPODType(const ASTContext &Context) const; |
784 | |
785 | /// Return true if this is a POD type according to the rules of the C++98 |
786 | /// standard, regardless of the current compilation's language. |
787 | bool isCXX98PODType(const ASTContext &Context) const; |
788 | |
789 | /// Return true if this is a POD type according to the more relaxed rules |
790 | /// of the C++11 standard, regardless of the current compilation's language. |
791 | /// (C++0x [basic.types]p9). Note that, unlike |
792 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
793 | bool isCXX11PODType(const ASTContext &Context) const; |
794 | |
795 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
796 | bool isTrivialType(const ASTContext &Context) const; |
797 | |
798 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
799 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
800 | |
801 | |
802 | /// Returns true if it is a class and it might be dynamic. |
803 | bool mayBeDynamicClass() const; |
804 | |
805 | /// Returns true if it is not a class or if the class might not be dynamic. |
806 | bool mayBeNotDynamicClass() const; |
807 | |
808 | // Don't promise in the API that anything besides 'const' can be |
809 | // easily added. |
810 | |
811 | /// Add the `const` type qualifier to this QualType. |
812 | void addConst() { |
813 | addFastQualifiers(Qualifiers::Const); |
814 | } |
815 | QualType withConst() const { |
816 | return withFastQualifiers(Qualifiers::Const); |
817 | } |
818 | |
819 | /// Add the `volatile` type qualifier to this QualType. |
820 | void addVolatile() { |
821 | addFastQualifiers(Qualifiers::Volatile); |
822 | } |
823 | QualType withVolatile() const { |
824 | return withFastQualifiers(Qualifiers::Volatile); |
825 | } |
826 | |
827 | /// Add the `restrict` qualifier to this QualType. |
828 | void addRestrict() { |
829 | addFastQualifiers(Qualifiers::Restrict); |
830 | } |
831 | QualType withRestrict() const { |
832 | return withFastQualifiers(Qualifiers::Restrict); |
833 | } |
834 | |
835 | QualType withCVRQualifiers(unsigned CVR) const { |
836 | return withFastQualifiers(CVR); |
837 | } |
838 | |
839 | void addFastQualifiers(unsigned TQs) { |
840 | assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 841, __PRETTY_FUNCTION__)) |
841 | && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 841, __PRETTY_FUNCTION__)); |
842 | Value.setInt(Value.getInt() | TQs); |
843 | } |
844 | |
845 | void removeLocalConst(); |
846 | void removeLocalVolatile(); |
847 | void removeLocalRestrict(); |
848 | void removeLocalCVRQualifiers(unsigned Mask); |
849 | |
850 | void removeLocalFastQualifiers() { Value.setInt(0); } |
851 | void removeLocalFastQualifiers(unsigned Mask) { |
852 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 852, __PRETTY_FUNCTION__)); |
853 | Value.setInt(Value.getInt() & ~Mask); |
854 | } |
855 | |
856 | // Creates a type with the given qualifiers in addition to any |
857 | // qualifiers already on this type. |
858 | QualType withFastQualifiers(unsigned TQs) const { |
859 | QualType T = *this; |
860 | T.addFastQualifiers(TQs); |
861 | return T; |
862 | } |
863 | |
864 | // Creates a type with exactly the given fast qualifiers, removing |
865 | // any existing fast qualifiers. |
866 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
867 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
868 | } |
869 | |
870 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
871 | QualType withoutLocalFastQualifiers() const { |
872 | QualType T = *this; |
873 | T.removeLocalFastQualifiers(); |
874 | return T; |
875 | } |
876 | |
877 | QualType getCanonicalType() const; |
878 | |
879 | /// Return this type with all of the instance-specific qualifiers |
880 | /// removed, but without removing any qualifiers that may have been applied |
881 | /// through typedefs. |
882 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
883 | |
884 | /// Retrieve the unqualified variant of the given type, |
885 | /// removing as little sugar as possible. |
886 | /// |
887 | /// This routine looks through various kinds of sugar to find the |
888 | /// least-desugared type that is unqualified. For example, given: |
889 | /// |
890 | /// \code |
891 | /// typedef int Integer; |
892 | /// typedef const Integer CInteger; |
893 | /// typedef CInteger DifferenceType; |
894 | /// \endcode |
895 | /// |
896 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
897 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
898 | /// |
899 | /// The resulting type might still be qualified if it's sugar for an array |
900 | /// type. To strip qualifiers even from within a sugared array type, use |
901 | /// ASTContext::getUnqualifiedArrayType. |
902 | inline QualType getUnqualifiedType() const; |
903 | |
904 | /// Retrieve the unqualified variant of the given type, removing as little |
905 | /// sugar as possible. |
906 | /// |
907 | /// Like getUnqualifiedType(), but also returns the set of |
908 | /// qualifiers that were built up. |
909 | /// |
910 | /// The resulting type might still be qualified if it's sugar for an array |
911 | /// type. To strip qualifiers even from within a sugared array type, use |
912 | /// ASTContext::getUnqualifiedArrayType. |
913 | inline SplitQualType getSplitUnqualifiedType() const; |
914 | |
915 | /// Determine whether this type is more qualified than the other |
916 | /// given type, requiring exact equality for non-CVR qualifiers. |
917 | bool isMoreQualifiedThan(QualType Other) const; |
918 | |
919 | /// Determine whether this type is at least as qualified as the other |
920 | /// given type, requiring exact equality for non-CVR qualifiers. |
921 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
922 | |
923 | QualType getNonReferenceType() const; |
924 | |
925 | /// Determine the type of a (typically non-lvalue) expression with the |
926 | /// specified result type. |
927 | /// |
928 | /// This routine should be used for expressions for which the return type is |
929 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
930 | /// an lvalue. It removes a top-level reference (since there are no |
931 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
932 | /// from non-class types (in C++) or all types (in C). |
933 | QualType getNonLValueExprType(const ASTContext &Context) const; |
934 | |
935 | /// Return the specified type with any "sugar" removed from |
936 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
937 | /// the type is already concrete, it returns it unmodified. This is similar |
938 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
939 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
940 | /// concrete. |
941 | /// |
942 | /// Qualifiers are left in place. |
943 | QualType getDesugaredType(const ASTContext &Context) const { |
944 | return getDesugaredType(*this, Context); |
945 | } |
946 | |
947 | SplitQualType getSplitDesugaredType() const { |
948 | return getSplitDesugaredType(*this); |
949 | } |
950 | |
951 | /// Return the specified type with one level of "sugar" removed from |
952 | /// the type. |
953 | /// |
954 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
955 | /// of the type is already concrete, it returns it unmodified. |
956 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
957 | return getSingleStepDesugaredTypeImpl(*this, Context); |
958 | } |
959 | |
960 | /// Returns the specified type after dropping any |
961 | /// outer-level parentheses. |
962 | QualType IgnoreParens() const { |
963 | if (isa<ParenType>(*this)) |
964 | return QualType::IgnoreParens(*this); |
965 | return *this; |
966 | } |
967 | |
968 | /// Indicate whether the specified types and qualifiers are identical. |
969 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
970 | return LHS.Value == RHS.Value; |
971 | } |
972 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
973 | return LHS.Value != RHS.Value; |
974 | } |
975 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
976 | return LHS.Value < RHS.Value; |
977 | } |
978 | |
979 | static std::string getAsString(SplitQualType split, |
980 | const PrintingPolicy &Policy) { |
981 | return getAsString(split.Ty, split.Quals, Policy); |
982 | } |
983 | static std::string getAsString(const Type *ty, Qualifiers qs, |
984 | const PrintingPolicy &Policy); |
985 | |
986 | std::string getAsString() const; |
987 | std::string getAsString(const PrintingPolicy &Policy) const; |
988 | |
989 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
990 | const Twine &PlaceHolder = Twine(), |
991 | unsigned Indentation = 0) const; |
992 | |
993 | static void print(SplitQualType split, raw_ostream &OS, |
994 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
995 | unsigned Indentation = 0) { |
996 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
997 | } |
998 | |
999 | static void print(const Type *ty, Qualifiers qs, |
1000 | raw_ostream &OS, const PrintingPolicy &policy, |
1001 | const Twine &PlaceHolder, |
1002 | unsigned Indentation = 0); |
1003 | |
1004 | void getAsStringInternal(std::string &Str, |
1005 | const PrintingPolicy &Policy) const; |
1006 | |
1007 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1008 | const PrintingPolicy &policy) { |
1009 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1010 | } |
1011 | |
1012 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1013 | std::string &out, |
1014 | const PrintingPolicy &policy); |
1015 | |
1016 | class StreamedQualTypeHelper { |
1017 | const QualType &T; |
1018 | const PrintingPolicy &Policy; |
1019 | const Twine &PlaceHolder; |
1020 | unsigned Indentation; |
1021 | |
1022 | public: |
1023 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1024 | const Twine &PlaceHolder, unsigned Indentation) |
1025 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1026 | Indentation(Indentation) {} |
1027 | |
1028 | friend raw_ostream &operator<<(raw_ostream &OS, |
1029 | const StreamedQualTypeHelper &SQT) { |
1030 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1031 | return OS; |
1032 | } |
1033 | }; |
1034 | |
1035 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1036 | const Twine &PlaceHolder = Twine(), |
1037 | unsigned Indentation = 0) const { |
1038 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1039 | } |
1040 | |
1041 | void dump(const char *s) const; |
1042 | void dump() const; |
1043 | void dump(llvm::raw_ostream &OS) const; |
1044 | |
1045 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1046 | ID.AddPointer(getAsOpaquePtr()); |
1047 | } |
1048 | |
1049 | /// Return the address space of this type. |
1050 | inline LangAS getAddressSpace() const; |
1051 | |
1052 | /// Returns gc attribute of this type. |
1053 | inline Qualifiers::GC getObjCGCAttr() const; |
1054 | |
1055 | /// true when Type is objc's weak. |
1056 | bool isObjCGCWeak() const { |
1057 | return getObjCGCAttr() == Qualifiers::Weak; |
1058 | } |
1059 | |
1060 | /// true when Type is objc's strong. |
1061 | bool isObjCGCStrong() const { |
1062 | return getObjCGCAttr() == Qualifiers::Strong; |
1063 | } |
1064 | |
1065 | /// Returns lifetime attribute of this type. |
1066 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1067 | return getQualifiers().getObjCLifetime(); |
1068 | } |
1069 | |
1070 | bool hasNonTrivialObjCLifetime() const { |
1071 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1072 | } |
1073 | |
1074 | bool hasStrongOrWeakObjCLifetime() const { |
1075 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1076 | } |
1077 | |
1078 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1079 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1080 | |
1081 | enum PrimitiveDefaultInitializeKind { |
1082 | /// The type does not fall into any of the following categories. Note that |
1083 | /// this case is zero-valued so that values of this enum can be used as a |
1084 | /// boolean condition for non-triviality. |
1085 | PDIK_Trivial, |
1086 | |
1087 | /// The type is an Objective-C retainable pointer type that is qualified |
1088 | /// with the ARC __strong qualifier. |
1089 | PDIK_ARCStrong, |
1090 | |
1091 | /// The type is an Objective-C retainable pointer type that is qualified |
1092 | /// with the ARC __weak qualifier. |
1093 | PDIK_ARCWeak, |
1094 | |
1095 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1096 | PDIK_Struct |
1097 | }; |
1098 | |
1099 | /// Functions to query basic properties of non-trivial C struct types. |
1100 | |
1101 | /// Check if this is a non-trivial type that would cause a C struct |
1102 | /// transitively containing this type to be non-trivial to default initialize |
1103 | /// and return the kind. |
1104 | PrimitiveDefaultInitializeKind |
1105 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1106 | |
1107 | enum PrimitiveCopyKind { |
1108 | /// The type does not fall into any of the following categories. Note that |
1109 | /// this case is zero-valued so that values of this enum can be used as a |
1110 | /// boolean condition for non-triviality. |
1111 | PCK_Trivial, |
1112 | |
1113 | /// The type would be trivial except that it is volatile-qualified. Types |
1114 | /// that fall into one of the other non-trivial cases may additionally be |
1115 | /// volatile-qualified. |
1116 | PCK_VolatileTrivial, |
1117 | |
1118 | /// The type is an Objective-C retainable pointer type that is qualified |
1119 | /// with the ARC __strong qualifier. |
1120 | PCK_ARCStrong, |
1121 | |
1122 | /// The type is an Objective-C retainable pointer type that is qualified |
1123 | /// with the ARC __weak qualifier. |
1124 | PCK_ARCWeak, |
1125 | |
1126 | /// The type is a struct containing a field whose type is neither |
1127 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1128 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1129 | /// semantics are too complex to express here, in part because they depend |
1130 | /// on the exact constructor or assignment operator that is chosen by |
1131 | /// overload resolution to do the copy. |
1132 | PCK_Struct |
1133 | }; |
1134 | |
1135 | /// Check if this is a non-trivial type that would cause a C struct |
1136 | /// transitively containing this type to be non-trivial to copy and return the |
1137 | /// kind. |
1138 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1139 | |
1140 | /// Check if this is a non-trivial type that would cause a C struct |
1141 | /// transitively containing this type to be non-trivial to destructively |
1142 | /// move and return the kind. Destructive move in this context is a C++-style |
1143 | /// move in which the source object is placed in a valid but unspecified state |
1144 | /// after it is moved, as opposed to a truly destructive move in which the |
1145 | /// source object is placed in an uninitialized state. |
1146 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1147 | |
1148 | enum DestructionKind { |
1149 | DK_none, |
1150 | DK_cxx_destructor, |
1151 | DK_objc_strong_lifetime, |
1152 | DK_objc_weak_lifetime, |
1153 | DK_nontrivial_c_struct |
1154 | }; |
1155 | |
1156 | /// Returns a nonzero value if objects of this type require |
1157 | /// non-trivial work to clean up after. Non-zero because it's |
1158 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1159 | /// something require destruction. |
1160 | DestructionKind isDestructedType() const { |
1161 | return isDestructedTypeImpl(*this); |
1162 | } |
1163 | |
1164 | /// Check if this is or contains a C union that is non-trivial to |
1165 | /// default-initialize, which is a union that has a member that is non-trivial |
1166 | /// to default-initialize. If this returns true, |
1167 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1168 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1169 | |
1170 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1171 | /// which is a union that has a member that is non-trivial to destruct. If |
1172 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1173 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1174 | |
1175 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1176 | /// is a union that has a member that is non-trivial to copy. If this returns |
1177 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1178 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1179 | |
1180 | /// Determine whether expressions of the given type are forbidden |
1181 | /// from being lvalues in C. |
1182 | /// |
1183 | /// The expression types that are forbidden to be lvalues are: |
1184 | /// - 'void', but not qualified void |
1185 | /// - function types |
1186 | /// |
1187 | /// The exact rule here is C99 6.3.2.1: |
1188 | /// An lvalue is an expression with an object type or an incomplete |
1189 | /// type other than void. |
1190 | bool isCForbiddenLValueType() const; |
1191 | |
1192 | /// Substitute type arguments for the Objective-C type parameters used in the |
1193 | /// subject type. |
1194 | /// |
1195 | /// \param ctx ASTContext in which the type exists. |
1196 | /// |
1197 | /// \param typeArgs The type arguments that will be substituted for the |
1198 | /// Objective-C type parameters in the subject type, which are generally |
1199 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1200 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1201 | /// for the context. |
1202 | /// |
1203 | /// \param context The context in which the subject type was written. |
1204 | /// |
1205 | /// \returns the resulting type. |
1206 | QualType substObjCTypeArgs(ASTContext &ctx, |
1207 | ArrayRef<QualType> typeArgs, |
1208 | ObjCSubstitutionContext context) const; |
1209 | |
1210 | /// Substitute type arguments from an object type for the Objective-C type |
1211 | /// parameters used in the subject type. |
1212 | /// |
1213 | /// This operation combines the computation of type arguments for |
1214 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1215 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1216 | /// callers that need to perform a single substitution in isolation. |
1217 | /// |
1218 | /// \param objectType The type of the object whose member type we're |
1219 | /// substituting into. For example, this might be the receiver of a message |
1220 | /// or the base of a property access. |
1221 | /// |
1222 | /// \param dc The declaration context from which the subject type was |
1223 | /// retrieved, which indicates (for example) which type parameters should |
1224 | /// be substituted. |
1225 | /// |
1226 | /// \param context The context in which the subject type was written. |
1227 | /// |
1228 | /// \returns the subject type after replacing all of the Objective-C type |
1229 | /// parameters with their corresponding arguments. |
1230 | QualType substObjCMemberType(QualType objectType, |
1231 | const DeclContext *dc, |
1232 | ObjCSubstitutionContext context) const; |
1233 | |
1234 | /// Strip Objective-C "__kindof" types from the given type. |
1235 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1236 | |
1237 | /// Remove all qualifiers including _Atomic. |
1238 | QualType getAtomicUnqualifiedType() const; |
1239 | |
1240 | private: |
1241 | // These methods are implemented in a separate translation unit; |
1242 | // "static"-ize them to avoid creating temporary QualTypes in the |
1243 | // caller. |
1244 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1245 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1246 | static SplitQualType getSplitDesugaredType(QualType T); |
1247 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1248 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1249 | const ASTContext &C); |
1250 | static QualType IgnoreParens(QualType T); |
1251 | static DestructionKind isDestructedTypeImpl(QualType type); |
1252 | |
1253 | /// Check if \param RD is or contains a non-trivial C union. |
1254 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1255 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1256 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1257 | }; |
1258 | |
1259 | } // namespace clang |
1260 | |
1261 | namespace llvm { |
1262 | |
1263 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1264 | /// to a specific Type class. |
1265 | template<> struct simplify_type< ::clang::QualType> { |
1266 | using SimpleType = const ::clang::Type *; |
1267 | |
1268 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1269 | return Val.getTypePtr(); |
1270 | } |
1271 | }; |
1272 | |
1273 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1274 | template<> |
1275 | struct PointerLikeTypeTraits<clang::QualType> { |
1276 | static inline void *getAsVoidPointer(clang::QualType P) { |
1277 | return P.getAsOpaquePtr(); |
1278 | } |
1279 | |
1280 | static inline clang::QualType getFromVoidPointer(void *P) { |
1281 | return clang::QualType::getFromOpaquePtr(P); |
1282 | } |
1283 | |
1284 | // Various qualifiers go in low bits. |
1285 | enum { NumLowBitsAvailable = 0 }; |
1286 | }; |
1287 | |
1288 | } // namespace llvm |
1289 | |
1290 | namespace clang { |
1291 | |
1292 | /// Base class that is common to both the \c ExtQuals and \c Type |
1293 | /// classes, which allows \c QualType to access the common fields between the |
1294 | /// two. |
1295 | class ExtQualsTypeCommonBase { |
1296 | friend class ExtQuals; |
1297 | friend class QualType; |
1298 | friend class Type; |
1299 | |
1300 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1301 | /// a self-referential pointer (for \c Type). |
1302 | /// |
1303 | /// This pointer allows an efficient mapping from a QualType to its |
1304 | /// underlying type pointer. |
1305 | const Type *const BaseType; |
1306 | |
1307 | /// The canonical type of this type. A QualType. |
1308 | QualType CanonicalType; |
1309 | |
1310 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1311 | : BaseType(baseType), CanonicalType(canon) {} |
1312 | }; |
1313 | |
1314 | /// We can encode up to four bits in the low bits of a |
1315 | /// type pointer, but there are many more type qualifiers that we want |
1316 | /// to be able to apply to an arbitrary type. Therefore we have this |
1317 | /// struct, intended to be heap-allocated and used by QualType to |
1318 | /// store qualifiers. |
1319 | /// |
1320 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1321 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1322 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1323 | /// Objective-C GC attributes) are much more rare. |
1324 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1325 | // NOTE: changing the fast qualifiers should be straightforward as |
1326 | // long as you don't make 'const' non-fast. |
1327 | // 1. Qualifiers: |
1328 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1329 | // Fast qualifiers must occupy the low-order bits. |
1330 | // b) Update Qualifiers::FastWidth and FastMask. |
1331 | // 2. QualType: |
1332 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1333 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1334 | // this header. |
1335 | // 3. ASTContext: |
1336 | // a) Update get{Volatile,Restrict}Type. |
1337 | |
1338 | /// The immutable set of qualifiers applied by this node. Always contains |
1339 | /// extended qualifiers. |
1340 | Qualifiers Quals; |
1341 | |
1342 | ExtQuals *this_() { return this; } |
1343 | |
1344 | public: |
1345 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1346 | : ExtQualsTypeCommonBase(baseType, |
1347 | canon.isNull() ? QualType(this_(), 0) : canon), |
1348 | Quals(quals) { |
1349 | assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1350, __PRETTY_FUNCTION__)) |
1350 | && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1350, __PRETTY_FUNCTION__)); |
1351 | assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1352, __PRETTY_FUNCTION__)) |
1352 | && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1352, __PRETTY_FUNCTION__)); |
1353 | } |
1354 | |
1355 | Qualifiers getQualifiers() const { return Quals; } |
1356 | |
1357 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1358 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1359 | |
1360 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1361 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1362 | return Quals.getObjCLifetime(); |
1363 | } |
1364 | |
1365 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1366 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1367 | |
1368 | const Type *getBaseType() const { return BaseType; } |
1369 | |
1370 | public: |
1371 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1372 | Profile(ID, getBaseType(), Quals); |
1373 | } |
1374 | |
1375 | static void Profile(llvm::FoldingSetNodeID &ID, |
1376 | const Type *BaseType, |
1377 | Qualifiers Quals) { |
1378 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1378, __PRETTY_FUNCTION__)); |
1379 | ID.AddPointer(BaseType); |
1380 | Quals.Profile(ID); |
1381 | } |
1382 | }; |
1383 | |
1384 | /// The kind of C++11 ref-qualifier associated with a function type. |
1385 | /// This determines whether a member function's "this" object can be an |
1386 | /// lvalue, rvalue, or neither. |
1387 | enum RefQualifierKind { |
1388 | /// No ref-qualifier was provided. |
1389 | RQ_None = 0, |
1390 | |
1391 | /// An lvalue ref-qualifier was provided (\c &). |
1392 | RQ_LValue, |
1393 | |
1394 | /// An rvalue ref-qualifier was provided (\c &&). |
1395 | RQ_RValue |
1396 | }; |
1397 | |
1398 | /// Which keyword(s) were used to create an AutoType. |
1399 | enum class AutoTypeKeyword { |
1400 | /// auto |
1401 | Auto, |
1402 | |
1403 | /// decltype(auto) |
1404 | DecltypeAuto, |
1405 | |
1406 | /// __auto_type (GNU extension) |
1407 | GNUAutoType |
1408 | }; |
1409 | |
1410 | /// The base class of the type hierarchy. |
1411 | /// |
1412 | /// A central concept with types is that each type always has a canonical |
1413 | /// type. A canonical type is the type with any typedef names stripped out |
1414 | /// of it or the types it references. For example, consider: |
1415 | /// |
1416 | /// typedef int foo; |
1417 | /// typedef foo* bar; |
1418 | /// 'int *' 'foo *' 'bar' |
1419 | /// |
1420 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1421 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1422 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1423 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1424 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1425 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1426 | /// is also 'int*'. |
1427 | /// |
1428 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1429 | /// information about typedefs being used. Canonical types are useful for type |
1430 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1431 | /// about whether something has a particular form (e.g. is a function type), |
1432 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1433 | /// |
1434 | /// Types, once created, are immutable. |
1435 | /// |
1436 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1437 | public: |
1438 | enum TypeClass { |
1439 | #define TYPE(Class, Base) Class, |
1440 | #define LAST_TYPE(Class) TypeLast = Class |
1441 | #define ABSTRACT_TYPE(Class, Base) |
1442 | #include "clang/AST/TypeNodes.inc" |
1443 | }; |
1444 | |
1445 | private: |
1446 | /// Bitfields required by the Type class. |
1447 | class TypeBitfields { |
1448 | friend class Type; |
1449 | template <class T> friend class TypePropertyCache; |
1450 | |
1451 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1452 | unsigned TC : 8; |
1453 | |
1454 | /// Whether this type is a dependent type (C++ [temp.dep.type]). |
1455 | unsigned Dependent : 1; |
1456 | |
1457 | /// Whether this type somehow involves a template parameter, even |
1458 | /// if the resolution of the type does not depend on a template parameter. |
1459 | unsigned InstantiationDependent : 1; |
1460 | |
1461 | /// Whether this type is a variably-modified type (C99 6.7.5). |
1462 | unsigned VariablyModified : 1; |
1463 | |
1464 | /// Whether this type contains an unexpanded parameter pack |
1465 | /// (for C++11 variadic templates). |
1466 | unsigned ContainsUnexpandedParameterPack : 1; |
1467 | |
1468 | /// True if the cache (i.e. the bitfields here starting with |
1469 | /// 'Cache') is valid. |
1470 | mutable unsigned CacheValid : 1; |
1471 | |
1472 | /// Linkage of this type. |
1473 | mutable unsigned CachedLinkage : 3; |
1474 | |
1475 | /// Whether this type involves and local or unnamed types. |
1476 | mutable unsigned CachedLocalOrUnnamed : 1; |
1477 | |
1478 | /// Whether this type comes from an AST file. |
1479 | mutable unsigned FromAST : 1; |
1480 | |
1481 | bool isCacheValid() const { |
1482 | return CacheValid; |
1483 | } |
1484 | |
1485 | Linkage getLinkage() const { |
1486 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1486, __PRETTY_FUNCTION__)); |
1487 | return static_cast<Linkage>(CachedLinkage); |
1488 | } |
1489 | |
1490 | bool hasLocalOrUnnamedType() const { |
1491 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1491, __PRETTY_FUNCTION__)); |
1492 | return CachedLocalOrUnnamed; |
1493 | } |
1494 | }; |
1495 | enum { NumTypeBits = 18 }; |
1496 | |
1497 | protected: |
1498 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1499 | // into Type. |
1500 | |
1501 | class ArrayTypeBitfields { |
1502 | friend class ArrayType; |
1503 | |
1504 | unsigned : NumTypeBits; |
1505 | |
1506 | /// CVR qualifiers from declarations like |
1507 | /// 'int X[static restrict 4]'. For function parameters only. |
1508 | unsigned IndexTypeQuals : 3; |
1509 | |
1510 | /// Storage class qualifiers from declarations like |
1511 | /// 'int X[static restrict 4]'. For function parameters only. |
1512 | /// Actually an ArrayType::ArraySizeModifier. |
1513 | unsigned SizeModifier : 3; |
1514 | }; |
1515 | |
1516 | class BuiltinTypeBitfields { |
1517 | friend class BuiltinType; |
1518 | |
1519 | unsigned : NumTypeBits; |
1520 | |
1521 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1522 | unsigned Kind : 8; |
1523 | }; |
1524 | |
1525 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1526 | /// Only common bits are stored here. Additional uncommon bits are stored |
1527 | /// in a trailing object after FunctionProtoType. |
1528 | class FunctionTypeBitfields { |
1529 | friend class FunctionProtoType; |
1530 | friend class FunctionType; |
1531 | |
1532 | unsigned : NumTypeBits; |
1533 | |
1534 | /// Extra information which affects how the function is called, like |
1535 | /// regparm and the calling convention. |
1536 | unsigned ExtInfo : 12; |
1537 | |
1538 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1539 | /// |
1540 | /// This is a value of type \c RefQualifierKind. |
1541 | unsigned RefQualifier : 2; |
1542 | |
1543 | /// Used only by FunctionProtoType, put here to pack with the |
1544 | /// other bitfields. |
1545 | /// The qualifiers are part of FunctionProtoType because... |
1546 | /// |
1547 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1548 | /// cv-qualifier-seq, [...], are part of the function type. |
1549 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1550 | /// Whether this function has extended Qualifiers. |
1551 | unsigned HasExtQuals : 1; |
1552 | |
1553 | /// The number of parameters this function has, not counting '...'. |
1554 | /// According to [implimits] 8 bits should be enough here but this is |
1555 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1556 | /// keep NumParams as wide as reasonably possible. |
1557 | unsigned NumParams : 16; |
1558 | |
1559 | /// The type of exception specification this function has. |
1560 | unsigned ExceptionSpecType : 4; |
1561 | |
1562 | /// Whether this function has extended parameter information. |
1563 | unsigned HasExtParameterInfos : 1; |
1564 | |
1565 | /// Whether the function is variadic. |
1566 | unsigned Variadic : 1; |
1567 | |
1568 | /// Whether this function has a trailing return type. |
1569 | unsigned HasTrailingReturn : 1; |
1570 | }; |
1571 | |
1572 | class ObjCObjectTypeBitfields { |
1573 | friend class ObjCObjectType; |
1574 | |
1575 | unsigned : NumTypeBits; |
1576 | |
1577 | /// The number of type arguments stored directly on this object type. |
1578 | unsigned NumTypeArgs : 7; |
1579 | |
1580 | /// The number of protocols stored directly on this object type. |
1581 | unsigned NumProtocols : 6; |
1582 | |
1583 | /// Whether this is a "kindof" type. |
1584 | unsigned IsKindOf : 1; |
1585 | }; |
1586 | |
1587 | class ReferenceTypeBitfields { |
1588 | friend class ReferenceType; |
1589 | |
1590 | unsigned : NumTypeBits; |
1591 | |
1592 | /// True if the type was originally spelled with an lvalue sigil. |
1593 | /// This is never true of rvalue references but can also be false |
1594 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1595 | /// as follows: |
1596 | /// |
1597 | /// typedef int &ref; // lvalue, spelled lvalue |
1598 | /// typedef int &&rvref; // rvalue |
1599 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1600 | /// ref &&a; // lvalue, inner ref |
1601 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1602 | /// rvref &&a; // rvalue, inner ref |
1603 | unsigned SpelledAsLValue : 1; |
1604 | |
1605 | /// True if the inner type is a reference type. This only happens |
1606 | /// in non-canonical forms. |
1607 | unsigned InnerRef : 1; |
1608 | }; |
1609 | |
1610 | class TypeWithKeywordBitfields { |
1611 | friend class TypeWithKeyword; |
1612 | |
1613 | unsigned : NumTypeBits; |
1614 | |
1615 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1616 | unsigned Keyword : 8; |
1617 | }; |
1618 | |
1619 | enum { NumTypeWithKeywordBits = 8 }; |
1620 | |
1621 | class ElaboratedTypeBitfields { |
1622 | friend class ElaboratedType; |
1623 | |
1624 | unsigned : NumTypeBits; |
1625 | unsigned : NumTypeWithKeywordBits; |
1626 | |
1627 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1628 | unsigned HasOwnedTagDecl : 1; |
1629 | }; |
1630 | |
1631 | class VectorTypeBitfields { |
1632 | friend class VectorType; |
1633 | friend class DependentVectorType; |
1634 | |
1635 | unsigned : NumTypeBits; |
1636 | |
1637 | /// The kind of vector, either a generic vector type or some |
1638 | /// target-specific vector type such as for AltiVec or Neon. |
1639 | unsigned VecKind : 3; |
1640 | |
1641 | /// The number of elements in the vector. |
1642 | unsigned NumElements : 29 - NumTypeBits; |
1643 | |
1644 | enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 }; |
1645 | }; |
1646 | |
1647 | class AttributedTypeBitfields { |
1648 | friend class AttributedType; |
1649 | |
1650 | unsigned : NumTypeBits; |
1651 | |
1652 | /// An AttributedType::Kind |
1653 | unsigned AttrKind : 32 - NumTypeBits; |
1654 | }; |
1655 | |
1656 | class AutoTypeBitfields { |
1657 | friend class AutoType; |
1658 | |
1659 | unsigned : NumTypeBits; |
1660 | |
1661 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1662 | /// or '__auto_type'? AutoTypeKeyword value. |
1663 | unsigned Keyword : 2; |
1664 | }; |
1665 | |
1666 | class SubstTemplateTypeParmPackTypeBitfields { |
1667 | friend class SubstTemplateTypeParmPackType; |
1668 | |
1669 | unsigned : NumTypeBits; |
1670 | |
1671 | /// The number of template arguments in \c Arguments, which is |
1672 | /// expected to be able to hold at least 1024 according to [implimits]. |
1673 | /// However as this limit is somewhat easy to hit with template |
1674 | /// metaprogramming we'd prefer to keep it as large as possible. |
1675 | /// At the moment it has been left as a non-bitfield since this type |
1676 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1677 | /// introduce the performance impact of a bitfield. |
1678 | unsigned NumArgs; |
1679 | }; |
1680 | |
1681 | class TemplateSpecializationTypeBitfields { |
1682 | friend class TemplateSpecializationType; |
1683 | |
1684 | unsigned : NumTypeBits; |
1685 | |
1686 | /// Whether this template specialization type is a substituted type alias. |
1687 | unsigned TypeAlias : 1; |
1688 | |
1689 | /// The number of template arguments named in this class template |
1690 | /// specialization, which is expected to be able to hold at least 1024 |
1691 | /// according to [implimits]. However, as this limit is somewhat easy to |
1692 | /// hit with template metaprogramming we'd prefer to keep it as large |
1693 | /// as possible. At the moment it has been left as a non-bitfield since |
1694 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1695 | /// to introduce the performance impact of a bitfield. |
1696 | unsigned NumArgs; |
1697 | }; |
1698 | |
1699 | class DependentTemplateSpecializationTypeBitfields { |
1700 | friend class DependentTemplateSpecializationType; |
1701 | |
1702 | unsigned : NumTypeBits; |
1703 | unsigned : NumTypeWithKeywordBits; |
1704 | |
1705 | /// The number of template arguments named in this class template |
1706 | /// specialization, which is expected to be able to hold at least 1024 |
1707 | /// according to [implimits]. However, as this limit is somewhat easy to |
1708 | /// hit with template metaprogramming we'd prefer to keep it as large |
1709 | /// as possible. At the moment it has been left as a non-bitfield since |
1710 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1711 | /// to introduce the performance impact of a bitfield. |
1712 | unsigned NumArgs; |
1713 | }; |
1714 | |
1715 | class PackExpansionTypeBitfields { |
1716 | friend class PackExpansionType; |
1717 | |
1718 | unsigned : NumTypeBits; |
1719 | |
1720 | /// The number of expansions that this pack expansion will |
1721 | /// generate when substituted (+1), which is expected to be able to |
1722 | /// hold at least 1024 according to [implimits]. However, as this limit |
1723 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1724 | /// keep it as large as possible. At the moment it has been left as a |
1725 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1726 | /// there is no reason to introduce the performance impact of a bitfield. |
1727 | /// |
1728 | /// This field will only have a non-zero value when some of the parameter |
1729 | /// packs that occur within the pattern have been substituted but others |
1730 | /// have not. |
1731 | unsigned NumExpansions; |
1732 | }; |
1733 | |
1734 | union { |
1735 | TypeBitfields TypeBits; |
1736 | ArrayTypeBitfields ArrayTypeBits; |
1737 | AttributedTypeBitfields AttributedTypeBits; |
1738 | AutoTypeBitfields AutoTypeBits; |
1739 | BuiltinTypeBitfields BuiltinTypeBits; |
1740 | FunctionTypeBitfields FunctionTypeBits; |
1741 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1742 | ReferenceTypeBitfields ReferenceTypeBits; |
1743 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1744 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1745 | VectorTypeBitfields VectorTypeBits; |
1746 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1747 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1748 | DependentTemplateSpecializationTypeBitfields |
1749 | DependentTemplateSpecializationTypeBits; |
1750 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1751 | |
1752 | static_assert(sizeof(TypeBitfields) <= 8, |
1753 | "TypeBitfields is larger than 8 bytes!"); |
1754 | static_assert(sizeof(ArrayTypeBitfields) <= 8, |
1755 | "ArrayTypeBitfields is larger than 8 bytes!"); |
1756 | static_assert(sizeof(AttributedTypeBitfields) <= 8, |
1757 | "AttributedTypeBitfields is larger than 8 bytes!"); |
1758 | static_assert(sizeof(AutoTypeBitfields) <= 8, |
1759 | "AutoTypeBitfields is larger than 8 bytes!"); |
1760 | static_assert(sizeof(BuiltinTypeBitfields) <= 8, |
1761 | "BuiltinTypeBitfields is larger than 8 bytes!"); |
1762 | static_assert(sizeof(FunctionTypeBitfields) <= 8, |
1763 | "FunctionTypeBitfields is larger than 8 bytes!"); |
1764 | static_assert(sizeof(ObjCObjectTypeBitfields) <= 8, |
1765 | "ObjCObjectTypeBitfields is larger than 8 bytes!"); |
1766 | static_assert(sizeof(ReferenceTypeBitfields) <= 8, |
1767 | "ReferenceTypeBitfields is larger than 8 bytes!"); |
1768 | static_assert(sizeof(TypeWithKeywordBitfields) <= 8, |
1769 | "TypeWithKeywordBitfields is larger than 8 bytes!"); |
1770 | static_assert(sizeof(ElaboratedTypeBitfields) <= 8, |
1771 | "ElaboratedTypeBitfields is larger than 8 bytes!"); |
1772 | static_assert(sizeof(VectorTypeBitfields) <= 8, |
1773 | "VectorTypeBitfields is larger than 8 bytes!"); |
1774 | static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8, |
1775 | "SubstTemplateTypeParmPackTypeBitfields is larger" |
1776 | " than 8 bytes!"); |
1777 | static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8, |
1778 | "TemplateSpecializationTypeBitfields is larger" |
1779 | " than 8 bytes!"); |
1780 | static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8, |
1781 | "DependentTemplateSpecializationTypeBitfields is larger" |
1782 | " than 8 bytes!"); |
1783 | static_assert(sizeof(PackExpansionTypeBitfields) <= 8, |
1784 | "PackExpansionTypeBitfields is larger than 8 bytes"); |
1785 | }; |
1786 | |
1787 | private: |
1788 | template <class T> friend class TypePropertyCache; |
1789 | |
1790 | /// Set whether this type comes from an AST file. |
1791 | void setFromAST(bool V = true) const { |
1792 | TypeBits.FromAST = V; |
1793 | } |
1794 | |
1795 | protected: |
1796 | friend class ASTContext; |
1797 | |
1798 | Type(TypeClass tc, QualType canon, bool Dependent, |
1799 | bool InstantiationDependent, bool VariablyModified, |
1800 | bool ContainsUnexpandedParameterPack) |
1801 | : ExtQualsTypeCommonBase(this, |
1802 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1803 | TypeBits.TC = tc; |
1804 | TypeBits.Dependent = Dependent; |
1805 | TypeBits.InstantiationDependent = Dependent || InstantiationDependent; |
1806 | TypeBits.VariablyModified = VariablyModified; |
1807 | TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
1808 | TypeBits.CacheValid = false; |
1809 | TypeBits.CachedLocalOrUnnamed = false; |
1810 | TypeBits.CachedLinkage = NoLinkage; |
1811 | TypeBits.FromAST = false; |
1812 | } |
1813 | |
1814 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1815 | Type *this_() { return this; } |
1816 | |
1817 | void setDependent(bool D = true) { |
1818 | TypeBits.Dependent = D; |
1819 | if (D) |
1820 | TypeBits.InstantiationDependent = true; |
1821 | } |
1822 | |
1823 | void setInstantiationDependent(bool D = true) { |
1824 | TypeBits.InstantiationDependent = D; } |
1825 | |
1826 | void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; } |
1827 | |
1828 | void setContainsUnexpandedParameterPack(bool PP = true) { |
1829 | TypeBits.ContainsUnexpandedParameterPack = PP; |
1830 | } |
1831 | |
1832 | public: |
1833 | friend class ASTReader; |
1834 | friend class ASTWriter; |
1835 | |
1836 | Type(const Type &) = delete; |
1837 | Type(Type &&) = delete; |
1838 | Type &operator=(const Type &) = delete; |
1839 | Type &operator=(Type &&) = delete; |
1840 | |
1841 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1842 | |
1843 | /// Whether this type comes from an AST file. |
1844 | bool isFromAST() const { return TypeBits.FromAST; } |
1845 | |
1846 | /// Whether this type is or contains an unexpanded parameter |
1847 | /// pack, used to support C++0x variadic templates. |
1848 | /// |
1849 | /// A type that contains a parameter pack shall be expanded by the |
1850 | /// ellipsis operator at some point. For example, the typedef in the |
1851 | /// following example contains an unexpanded parameter pack 'T': |
1852 | /// |
1853 | /// \code |
1854 | /// template<typename ...T> |
1855 | /// struct X { |
1856 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1857 | /// }; |
1858 | /// \endcode |
1859 | /// |
1860 | /// Note that this routine does not specify which |
1861 | bool containsUnexpandedParameterPack() const { |
1862 | return TypeBits.ContainsUnexpandedParameterPack; |
1863 | } |
1864 | |
1865 | /// Determines if this type would be canonical if it had no further |
1866 | /// qualification. |
1867 | bool isCanonicalUnqualified() const { |
1868 | return CanonicalType == QualType(this, 0); |
1869 | } |
1870 | |
1871 | /// Pull a single level of sugar off of this locally-unqualified type. |
1872 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1873 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1874 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1875 | |
1876 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1877 | /// object types, function types, and incomplete types. |
1878 | |
1879 | /// Return true if this is an incomplete type. |
1880 | /// A type that can describe objects, but which lacks information needed to |
1881 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1882 | /// routine will need to determine if the size is actually required. |
1883 | /// |
1884 | /// Def If non-null, and the type refers to some kind of declaration |
1885 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1886 | /// class), will be set to the declaration. |
1887 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1888 | |
1889 | /// Return true if this is an incomplete or object |
1890 | /// type, in other words, not a function type. |
1891 | bool isIncompleteOrObjectType() const { |
1892 | return !isFunctionType(); |
1893 | } |
1894 | |
1895 | /// Determine whether this type is an object type. |
1896 | bool isObjectType() const { |
1897 | // C++ [basic.types]p8: |
1898 | // An object type is a (possibly cv-qualified) type that is not a |
1899 | // function type, not a reference type, and not a void type. |
1900 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1901 | } |
1902 | |
1903 | /// Return true if this is a literal type |
1904 | /// (C++11 [basic.types]p10) |
1905 | bool isLiteralType(const ASTContext &Ctx) const; |
1906 | |
1907 | /// Test if this type is a standard-layout type. |
1908 | /// (C++0x [basic.type]p9) |
1909 | bool isStandardLayoutType() const; |
1910 | |
1911 | /// Helper methods to distinguish type categories. All type predicates |
1912 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1913 | |
1914 | /// Returns true if the type is a builtin type. |
1915 | bool isBuiltinType() const; |
1916 | |
1917 | /// Test for a particular builtin type. |
1918 | bool isSpecificBuiltinType(unsigned K) const; |
1919 | |
1920 | /// Test for a type which does not represent an actual type-system type but |
1921 | /// is instead used as a placeholder for various convenient purposes within |
1922 | /// Clang. All such types are BuiltinTypes. |
1923 | bool isPlaceholderType() const; |
1924 | const BuiltinType *getAsPlaceholderType() const; |
1925 | |
1926 | /// Test for a specific placeholder type. |
1927 | bool isSpecificPlaceholderType(unsigned K) const; |
1928 | |
1929 | /// Test for a placeholder type other than Overload; see |
1930 | /// BuiltinType::isNonOverloadPlaceholderType. |
1931 | bool isNonOverloadPlaceholderType() const; |
1932 | |
1933 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1934 | /// isComplexIntegerType() can be used to test for complex integers. |
1935 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1936 | bool isEnumeralType() const; |
1937 | |
1938 | /// Determine whether this type is a scoped enumeration type. |
1939 | bool isScopedEnumeralType() const; |
1940 | bool isBooleanType() const; |
1941 | bool isCharType() const; |
1942 | bool isWideCharType() const; |
1943 | bool isChar8Type() const; |
1944 | bool isChar16Type() const; |
1945 | bool isChar32Type() const; |
1946 | bool isAnyCharacterType() const; |
1947 | bool isIntegralType(const ASTContext &Ctx) const; |
1948 | |
1949 | /// Determine whether this type is an integral or enumeration type. |
1950 | bool isIntegralOrEnumerationType() const; |
1951 | |
1952 | /// Determine whether this type is an integral or unscoped enumeration type. |
1953 | bool isIntegralOrUnscopedEnumerationType() const; |
1954 | |
1955 | /// Floating point categories. |
1956 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1957 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1958 | /// isComplexIntegerType() can be used to test for complex integers. |
1959 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1960 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1961 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1962 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1963 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1964 | bool isFloat128Type() const; |
1965 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1966 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1967 | bool isVoidType() const; // C99 6.2.5p19 |
1968 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1969 | bool isAggregateType() const; |
1970 | bool isFundamentalType() const; |
1971 | bool isCompoundType() const; |
1972 | |
1973 | // Type Predicates: Check to see if this type is structurally the specified |
1974 | // type, ignoring typedefs and qualifiers. |
1975 | bool isFunctionType() const; |
1976 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
1977 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
1978 | bool isPointerType() const; |
1979 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
1980 | bool isBlockPointerType() const; |
1981 | bool isVoidPointerType() const; |
1982 | bool isReferenceType() const; |
1983 | bool isLValueReferenceType() const; |
1984 | bool isRValueReferenceType() const; |
1985 | bool isFunctionPointerType() const; |
1986 | bool isFunctionReferenceType() const; |
1987 | bool isMemberPointerType() const; |
1988 | bool isMemberFunctionPointerType() const; |
1989 | bool isMemberDataPointerType() const; |
1990 | bool isArrayType() const; |
1991 | bool isConstantArrayType() const; |
1992 | bool isIncompleteArrayType() const; |
1993 | bool isVariableArrayType() const; |
1994 | bool isDependentSizedArrayType() const; |
1995 | bool isRecordType() const; |
1996 | bool isClassType() const; |
1997 | bool isStructureType() const; |
1998 | bool isObjCBoxableRecordType() const; |
1999 | bool isInterfaceType() const; |
2000 | bool isStructureOrClassType() const; |
2001 | bool isUnionType() const; |
2002 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2003 | bool isVectorType() const; // GCC vector type. |
2004 | bool isExtVectorType() const; // Extended vector type. |
2005 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2006 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2007 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2008 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2009 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2010 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2011 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2012 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2013 | // for the common case. |
2014 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2015 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2016 | bool isObjCQualifiedIdType() const; // id<foo> |
2017 | bool isObjCQualifiedClassType() const; // Class<foo> |
2018 | bool isObjCObjectOrInterfaceType() const; |
2019 | bool isObjCIdType() const; // id |
2020 | bool isDecltypeType() const; |
2021 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2022 | /// qualifier? |
2023 | /// |
2024 | /// This approximates the answer to the following question: if this |
2025 | /// translation unit were compiled in ARC, would this type be qualified |
2026 | /// with __unsafe_unretained? |
2027 | bool isObjCInertUnsafeUnretainedType() const { |
2028 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2029 | } |
2030 | |
2031 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2032 | /// object type, e.g., __kindof NSView * or __kindof id |
2033 | /// <NSCopying>. |
2034 | /// |
2035 | /// \param bound Will be set to the bound on non-id subtype types, |
2036 | /// which will be (possibly specialized) Objective-C class type, or |
2037 | /// null for 'id. |
2038 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2039 | const ObjCObjectType *&bound) const; |
2040 | |
2041 | bool isObjCClassType() const; // Class |
2042 | |
2043 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2044 | /// Class type, e.g., __kindof Class <NSCopying>. |
2045 | /// |
2046 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2047 | /// here because Objective-C's type system cannot express "a class |
2048 | /// object for a subclass of NSFoo". |
2049 | bool isObjCClassOrClassKindOfType() const; |
2050 | |
2051 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2052 | bool isObjCSelType() const; // Class |
2053 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2054 | bool isObjCARCBridgableType() const; |
2055 | bool isCARCBridgableType() const; |
2056 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2057 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2058 | bool isNothrowT() const; // C++ std::nothrow_t |
2059 | bool isAlignValT() const; // C++17 std::align_val_t |
2060 | bool isStdByteType() const; // C++17 std::byte |
2061 | bool isAtomicType() const; // C11 _Atomic() |
2062 | |
2063 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2064 | bool is##Id##Type() const; |
2065 | #include "clang/Basic/OpenCLImageTypes.def" |
2066 | |
2067 | bool isImageType() const; // Any OpenCL image type |
2068 | |
2069 | bool isSamplerT() const; // OpenCL sampler_t |
2070 | bool isEventT() const; // OpenCL event_t |
2071 | bool isClkEventT() const; // OpenCL clk_event_t |
2072 | bool isQueueT() const; // OpenCL queue_t |
2073 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2074 | |
2075 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2076 | bool is##Id##Type() const; |
2077 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2078 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2079 | bool isOCLIntelSubgroupAVCType() const; |
2080 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2081 | |
2082 | bool isPipeType() const; // OpenCL pipe type |
2083 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2084 | |
2085 | /// Determines if this type, which must satisfy |
2086 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2087 | /// than implicitly __strong. |
2088 | bool isObjCARCImplicitlyUnretainedType() const; |
2089 | |
2090 | /// Return the implicit lifetime for this type, which must not be dependent. |
2091 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2092 | |
2093 | enum ScalarTypeKind { |
2094 | STK_CPointer, |
2095 | STK_BlockPointer, |
2096 | STK_ObjCObjectPointer, |
2097 | STK_MemberPointer, |
2098 | STK_Bool, |
2099 | STK_Integral, |
2100 | STK_Floating, |
2101 | STK_IntegralComplex, |
2102 | STK_FloatingComplex, |
2103 | STK_FixedPoint |
2104 | }; |
2105 | |
2106 | /// Given that this is a scalar type, classify it. |
2107 | ScalarTypeKind getScalarTypeKind() const; |
2108 | |
2109 | /// Whether this type is a dependent type, meaning that its definition |
2110 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2111 | bool isDependentType() const { return TypeBits.Dependent; } |
2112 | |
2113 | /// Determine whether this type is an instantiation-dependent type, |
2114 | /// meaning that the type involves a template parameter (even if the |
2115 | /// definition does not actually depend on the type substituted for that |
2116 | /// template parameter). |
2117 | bool isInstantiationDependentType() const { |
2118 | return TypeBits.InstantiationDependent; |
2119 | } |
2120 | |
2121 | /// Determine whether this type is an undeduced type, meaning that |
2122 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2123 | /// deduced. |
2124 | bool isUndeducedType() const; |
2125 | |
2126 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2127 | bool isVariablyModifiedType() const { return TypeBits.VariablyModified; } |
2128 | |
2129 | /// Whether this type involves a variable-length array type |
2130 | /// with a definite size. |
2131 | bool hasSizedVLAType() const; |
2132 | |
2133 | /// Whether this type is or contains a local or unnamed type. |
2134 | bool hasUnnamedOrLocalType() const; |
2135 | |
2136 | bool isOverloadableType() const; |
2137 | |
2138 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2139 | bool isElaboratedTypeSpecifier() const; |
2140 | |
2141 | bool canDecayToPointerType() const; |
2142 | |
2143 | /// Whether this type is represented natively as a pointer. This includes |
2144 | /// pointers, references, block pointers, and Objective-C interface, |
2145 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2146 | bool hasPointerRepresentation() const; |
2147 | |
2148 | /// Whether this type can represent an objective pointer type for the |
2149 | /// purpose of GC'ability |
2150 | bool hasObjCPointerRepresentation() const; |
2151 | |
2152 | /// Determine whether this type has an integer representation |
2153 | /// of some sort, e.g., it is an integer type or a vector. |
2154 | bool hasIntegerRepresentation() const; |
2155 | |
2156 | /// Determine whether this type has an signed integer representation |
2157 | /// of some sort, e.g., it is an signed integer type or a vector. |
2158 | bool hasSignedIntegerRepresentation() const; |
2159 | |
2160 | /// Determine whether this type has an unsigned integer representation |
2161 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2162 | bool hasUnsignedIntegerRepresentation() const; |
2163 | |
2164 | /// Determine whether this type has a floating-point representation |
2165 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2166 | bool hasFloatingRepresentation() const; |
2167 | |
2168 | // Type Checking Functions: Check to see if this type is structurally the |
2169 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2170 | // the best type we can. |
2171 | const RecordType *getAsStructureType() const; |
2172 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2173 | const RecordType *getAsUnionType() const; |
2174 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2175 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2176 | |
2177 | // The following is a convenience method that returns an ObjCObjectPointerType |
2178 | // for object declared using an interface. |
2179 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2180 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2181 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2182 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2183 | |
2184 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2185 | /// because the type is a RecordType or because it is the injected-class-name |
2186 | /// type of a class template or class template partial specialization. |
2187 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2188 | |
2189 | /// Retrieves the RecordDecl this type refers to. |
2190 | RecordDecl *getAsRecordDecl() const; |
2191 | |
2192 | /// Retrieves the TagDecl that this type refers to, either |
2193 | /// because the type is a TagType or because it is the injected-class-name |
2194 | /// type of a class template or class template partial specialization. |
2195 | TagDecl *getAsTagDecl() const; |
2196 | |
2197 | /// If this is a pointer or reference to a RecordType, return the |
2198 | /// CXXRecordDecl that the type refers to. |
2199 | /// |
2200 | /// If this is not a pointer or reference, or the type being pointed to does |
2201 | /// not refer to a CXXRecordDecl, returns NULL. |
2202 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2203 | |
2204 | /// Get the DeducedType whose type will be deduced for a variable with |
2205 | /// an initializer of this type. This looks through declarators like pointer |
2206 | /// types, but not through decltype or typedefs. |
2207 | DeducedType *getContainedDeducedType() const; |
2208 | |
2209 | /// Get the AutoType whose type will be deduced for a variable with |
2210 | /// an initializer of this type. This looks through declarators like pointer |
2211 | /// types, but not through decltype or typedefs. |
2212 | AutoType *getContainedAutoType() const { |
2213 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2214 | } |
2215 | |
2216 | /// Determine whether this type was written with a leading 'auto' |
2217 | /// corresponding to a trailing return type (possibly for a nested |
2218 | /// function type within a pointer to function type or similar). |
2219 | bool hasAutoForTrailingReturnType() const; |
2220 | |
2221 | /// Member-template getAs<specific type>'. Look through sugar for |
2222 | /// an instance of \<specific type>. This scheme will eventually |
2223 | /// replace the specific getAsXXXX methods above. |
2224 | /// |
2225 | /// There are some specializations of this member template listed |
2226 | /// immediately following this class. |
2227 | template <typename T> const T *getAs() const; |
2228 | |
2229 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2230 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2231 | /// This is used when you need to walk over sugar nodes that represent some |
2232 | /// kind of type adjustment from a type that was written as a \<specific type> |
2233 | /// to another type that is still canonically a \<specific type>. |
2234 | template <typename T> const T *getAsAdjusted() const; |
2235 | |
2236 | /// A variant of getAs<> for array types which silently discards |
2237 | /// qualifiers from the outermost type. |
2238 | const ArrayType *getAsArrayTypeUnsafe() const; |
2239 | |
2240 | /// Member-template castAs<specific type>. Look through sugar for |
2241 | /// the underlying instance of \<specific type>. |
2242 | /// |
2243 | /// This method has the same relationship to getAs<T> as cast<T> has |
2244 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2245 | /// have the intended type, and this method will never return null. |
2246 | template <typename T> const T *castAs() const; |
2247 | |
2248 | /// A variant of castAs<> for array type which silently discards |
2249 | /// qualifiers from the outermost type. |
2250 | const ArrayType *castAsArrayTypeUnsafe() const; |
2251 | |
2252 | /// Determine whether this type had the specified attribute applied to it |
2253 | /// (looking through top-level type sugar). |
2254 | bool hasAttr(attr::Kind AK) const; |
2255 | |
2256 | /// Get the base element type of this type, potentially discarding type |
2257 | /// qualifiers. This should never be used when type qualifiers |
2258 | /// are meaningful. |
2259 | const Type *getBaseElementTypeUnsafe() const; |
2260 | |
2261 | /// If this is an array type, return the element type of the array, |
2262 | /// potentially with type qualifiers missing. |
2263 | /// This should never be used when type qualifiers are meaningful. |
2264 | const Type *getArrayElementTypeNoTypeQual() const; |
2265 | |
2266 | /// If this is a pointer type, return the pointee type. |
2267 | /// If this is an array type, return the array element type. |
2268 | /// This should never be used when type qualifiers are meaningful. |
2269 | const Type *getPointeeOrArrayElementType() const; |
2270 | |
2271 | /// If this is a pointer, ObjC object pointer, or block |
2272 | /// pointer, this returns the respective pointee. |
2273 | QualType getPointeeType() const; |
2274 | |
2275 | /// Return the specified type with any "sugar" removed from the type, |
2276 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2277 | const Type *getUnqualifiedDesugaredType() const; |
2278 | |
2279 | /// More type predicates useful for type checking/promotion |
2280 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2281 | |
2282 | /// Return true if this is an integer type that is |
2283 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2284 | /// or an enum decl which has a signed representation. |
2285 | bool isSignedIntegerType() const; |
2286 | |
2287 | /// Return true if this is an integer type that is |
2288 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2289 | /// or an enum decl which has an unsigned representation. |
2290 | bool isUnsignedIntegerType() const; |
2291 | |
2292 | /// Determines whether this is an integer type that is signed or an |
2293 | /// enumeration types whose underlying type is a signed integer type. |
2294 | bool isSignedIntegerOrEnumerationType() const; |
2295 | |
2296 | /// Determines whether this is an integer type that is unsigned or an |
2297 | /// enumeration types whose underlying type is a unsigned integer type. |
2298 | bool isUnsignedIntegerOrEnumerationType() const; |
2299 | |
2300 | /// Return true if this is a fixed point type according to |
2301 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2302 | bool isFixedPointType() const; |
2303 | |
2304 | /// Return true if this is a fixed point or integer type. |
2305 | bool isFixedPointOrIntegerType() const; |
2306 | |
2307 | /// Return true if this is a saturated fixed point type according to |
2308 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2309 | bool isSaturatedFixedPointType() const; |
2310 | |
2311 | /// Return true if this is a saturated fixed point type according to |
2312 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2313 | bool isUnsaturatedFixedPointType() const; |
2314 | |
2315 | /// Return true if this is a fixed point type that is signed according |
2316 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2317 | bool isSignedFixedPointType() const; |
2318 | |
2319 | /// Return true if this is a fixed point type that is unsigned according |
2320 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2321 | bool isUnsignedFixedPointType() const; |
2322 | |
2323 | /// Return true if this is not a variable sized type, |
2324 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2325 | /// incomplete types. |
2326 | bool isConstantSizeType() const; |
2327 | |
2328 | /// Returns true if this type can be represented by some |
2329 | /// set of type specifiers. |
2330 | bool isSpecifierType() const; |
2331 | |
2332 | /// Determine the linkage of this type. |
2333 | Linkage getLinkage() const; |
2334 | |
2335 | /// Determine the visibility of this type. |
2336 | Visibility getVisibility() const { |
2337 | return getLinkageAndVisibility().getVisibility(); |
2338 | } |
2339 | |
2340 | /// Return true if the visibility was explicitly set is the code. |
2341 | bool isVisibilityExplicit() const { |
2342 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2343 | } |
2344 | |
2345 | /// Determine the linkage and visibility of this type. |
2346 | LinkageInfo getLinkageAndVisibility() const; |
2347 | |
2348 | /// True if the computed linkage is valid. Used for consistency |
2349 | /// checking. Should always return true. |
2350 | bool isLinkageValid() const; |
2351 | |
2352 | /// Determine the nullability of the given type. |
2353 | /// |
2354 | /// Note that nullability is only captured as sugar within the type |
2355 | /// system, not as part of the canonical type, so nullability will |
2356 | /// be lost by canonicalization and desugaring. |
2357 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2358 | |
2359 | /// Determine whether the given type can have a nullability |
2360 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2361 | /// |
2362 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2363 | /// this type can have nullability because it is dependent. |
2364 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2365 | |
2366 | /// Retrieve the set of substitutions required when accessing a member |
2367 | /// of the Objective-C receiver type that is declared in the given context. |
2368 | /// |
2369 | /// \c *this is the type of the object we're operating on, e.g., the |
2370 | /// receiver for a message send or the base of a property access, and is |
2371 | /// expected to be of some object or object pointer type. |
2372 | /// |
2373 | /// \param dc The declaration context for which we are building up a |
2374 | /// substitution mapping, which should be an Objective-C class, extension, |
2375 | /// category, or method within. |
2376 | /// |
2377 | /// \returns an array of type arguments that can be substituted for |
2378 | /// the type parameters of the given declaration context in any type described |
2379 | /// within that context, or an empty optional to indicate that no |
2380 | /// substitution is required. |
2381 | Optional<ArrayRef<QualType>> |
2382 | getObjCSubstitutions(const DeclContext *dc) const; |
2383 | |
2384 | /// Determines if this is an ObjC interface type that may accept type |
2385 | /// parameters. |
2386 | bool acceptsObjCTypeParams() const; |
2387 | |
2388 | const char *getTypeClassName() const; |
2389 | |
2390 | QualType getCanonicalTypeInternal() const { |
2391 | return CanonicalType; |
2392 | } |
2393 | |
2394 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2395 | void dump() const; |
2396 | void dump(llvm::raw_ostream &OS) const; |
2397 | }; |
2398 | |
2399 | /// This will check for a TypedefType by removing any existing sugar |
2400 | /// until it reaches a TypedefType or a non-sugared type. |
2401 | template <> const TypedefType *Type::getAs() const; |
2402 | |
2403 | /// This will check for a TemplateSpecializationType by removing any |
2404 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2405 | /// non-sugared type. |
2406 | template <> const TemplateSpecializationType *Type::getAs() const; |
2407 | |
2408 | /// This will check for an AttributedType by removing any existing sugar |
2409 | /// until it reaches an AttributedType or a non-sugared type. |
2410 | template <> const AttributedType *Type::getAs() const; |
2411 | |
2412 | // We can do canonical leaf types faster, because we don't have to |
2413 | // worry about preserving child type decoration. |
2414 | #define TYPE(Class, Base) |
2415 | #define LEAF_TYPE(Class) \ |
2416 | template <> inline const Class##Type *Type::getAs() const { \ |
2417 | return dyn_cast<Class##Type>(CanonicalType); \ |
2418 | } \ |
2419 | template <> inline const Class##Type *Type::castAs() const { \ |
2420 | return cast<Class##Type>(CanonicalType); \ |
2421 | } |
2422 | #include "clang/AST/TypeNodes.inc" |
2423 | |
2424 | /// This class is used for builtin types like 'int'. Builtin |
2425 | /// types are always canonical and have a literal name field. |
2426 | class BuiltinType : public Type { |
2427 | public: |
2428 | enum Kind { |
2429 | // OpenCL image types |
2430 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2431 | #include "clang/Basic/OpenCLImageTypes.def" |
2432 | // OpenCL extension types |
2433 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2434 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2435 | // SVE Types |
2436 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2437 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2438 | // All other builtin types |
2439 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2440 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2441 | #include "clang/AST/BuiltinTypes.def" |
2442 | }; |
2443 | |
2444 | private: |
2445 | friend class ASTContext; // ASTContext creates these. |
2446 | |
2447 | BuiltinType(Kind K) |
2448 | : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent), |
2449 | /*InstantiationDependent=*/(K == Dependent), |
2450 | /*VariablyModified=*/false, |
2451 | /*Unexpanded parameter pack=*/false) { |
2452 | BuiltinTypeBits.Kind = K; |
2453 | } |
2454 | |
2455 | public: |
2456 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2457 | StringRef getName(const PrintingPolicy &Policy) const; |
2458 | |
2459 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2460 | // The StringRef is null-terminated. |
2461 | StringRef str = getName(Policy); |
2462 | assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast <void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 2462, __PRETTY_FUNCTION__)); |
2463 | return str.data(); |
2464 | } |
2465 | |
2466 | bool isSugared() const { return false; } |
2467 | QualType desugar() const { return QualType(this, 0); } |
2468 | |
2469 | bool isInteger() const { |
2470 | return getKind() >= Bool && getKind() <= Int128; |
2471 | } |
2472 | |
2473 | bool isSignedInteger() const { |
2474 | return getKind() >= Char_S && getKind() <= Int128; |
2475 | } |
2476 | |
2477 | bool isUnsignedInteger() const { |
2478 | return getKind() >= Bool && getKind() <= UInt128; |
2479 | } |
2480 | |
2481 | bool isFloatingPoint() const { |
2482 | return getKind() >= Half && getKind() <= Float128; |
2483 | } |
2484 | |
2485 | /// Determines whether the given kind corresponds to a placeholder type. |
2486 | static bool isPlaceholderTypeKind(Kind K) { |
2487 | return K >= Overload; |
2488 | } |
2489 | |
2490 | /// Determines whether this type is a placeholder type, i.e. a type |
2491 | /// which cannot appear in arbitrary positions in a fully-formed |
2492 | /// expression. |
2493 | bool isPlaceholderType() const { |
2494 | return isPlaceholderTypeKind(getKind()); |
2495 | } |
2496 | |
2497 | /// Determines whether this type is a placeholder type other than |
2498 | /// Overload. Most placeholder types require only syntactic |
2499 | /// information about their context in order to be resolved (e.g. |
2500 | /// whether it is a call expression), which means they can (and |
2501 | /// should) be resolved in an earlier "phase" of analysis. |
2502 | /// Overload expressions sometimes pick up further information |
2503 | /// from their context, like whether the context expects a |
2504 | /// specific function-pointer type, and so frequently need |
2505 | /// special treatment. |
2506 | bool isNonOverloadPlaceholderType() const { |
2507 | return getKind() > Overload; |
2508 | } |
2509 | |
2510 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2511 | }; |
2512 | |
2513 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2514 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2515 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2516 | friend class ASTContext; // ASTContext creates these. |
2517 | |
2518 | QualType ElementType; |
2519 | |
2520 | ComplexType(QualType Element, QualType CanonicalPtr) |
2521 | : Type(Complex, CanonicalPtr, Element->isDependentType(), |
2522 | Element->isInstantiationDependentType(), |
2523 | Element->isVariablyModifiedType(), |
2524 | Element->containsUnexpandedParameterPack()), |
2525 | ElementType(Element) {} |
2526 | |
2527 | public: |
2528 | QualType getElementType() const { return ElementType; } |
2529 | |
2530 | bool isSugared() const { return false; } |
2531 | QualType desugar() const { return QualType(this, 0); } |
2532 | |
2533 | void Profile(llvm::FoldingSetNodeID &ID) { |
2534 | Profile(ID, getElementType()); |
2535 | } |
2536 | |
2537 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2538 | ID.AddPointer(Element.getAsOpaquePtr()); |
2539 | } |
2540 | |
2541 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2542 | }; |
2543 | |
2544 | /// Sugar for parentheses used when specifying types. |
2545 | class ParenType : public Type, public llvm::FoldingSetNode { |
2546 | friend class ASTContext; // ASTContext creates these. |
2547 | |
2548 | QualType Inner; |
2549 | |
2550 | ParenType(QualType InnerType, QualType CanonType) |
2551 | : Type(Paren, CanonType, InnerType->isDependentType(), |
2552 | InnerType->isInstantiationDependentType(), |
2553 | InnerType->isVariablyModifiedType(), |
2554 | InnerType->containsUnexpandedParameterPack()), |
2555 | Inner(InnerType) {} |
2556 | |
2557 | public: |
2558 | QualType getInnerType() const { return Inner; } |
2559 | |
2560 | bool isSugared() const { return true; } |
2561 | QualType desugar() const { return getInnerType(); } |
2562 | |
2563 | void Profile(llvm::FoldingSetNodeID &ID) { |
2564 | Profile(ID, getInnerType()); |
2565 | } |
2566 | |
2567 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2568 | Inner.Profile(ID); |
2569 | } |
2570 | |
2571 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2572 | }; |
2573 | |
2574 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2575 | class PointerType : public Type, public llvm::FoldingSetNode { |
2576 | friend class ASTContext; // ASTContext creates these. |
2577 | |
2578 | QualType PointeeType; |
2579 | |
2580 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2581 | : Type(Pointer, CanonicalPtr, Pointee->isDependentType(), |
2582 | Pointee->isInstantiationDependentType(), |
2583 | Pointee->isVariablyModifiedType(), |
2584 | Pointee->containsUnexpandedParameterPack()), |
2585 | PointeeType(Pointee) {} |
2586 | |
2587 | public: |
2588 | QualType getPointeeType() const { return PointeeType; } |
2589 | |
2590 | /// Returns true if address spaces of pointers overlap. |
2591 | /// OpenCL v2.0 defines conversion rules for pointers to different |
2592 | /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping |
2593 | /// address spaces. |
2594 | /// CL1.1 or CL1.2: |
2595 | /// address spaces overlap iff they are they same. |
2596 | /// CL2.0 adds: |
2597 | /// __generic overlaps with any address space except for __constant. |
2598 | bool isAddressSpaceOverlapping(const PointerType &other) const { |
2599 | Qualifiers thisQuals = PointeeType.getQualifiers(); |
2600 | Qualifiers otherQuals = other.getPointeeType().getQualifiers(); |
2601 | // Address spaces overlap if at least one of them is a superset of another |
2602 | return thisQuals.isAddressSpaceSupersetOf(otherQuals) || |
2603 | otherQuals.isAddressSpaceSupersetOf(thisQuals); |
2604 | } |
2605 | |
2606 | bool isSugared() const { return false; } |
2607 | QualType desugar() const { return QualType(this, 0); } |
2608 | |
2609 | void Profile(llvm::FoldingSetNodeID &ID) { |
2610 | Profile(ID, getPointeeType()); |
2611 | } |
2612 | |
2613 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2614 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2615 | } |
2616 | |
2617 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2618 | }; |
2619 | |
2620 | /// Represents a type which was implicitly adjusted by the semantic |
2621 | /// engine for arbitrary reasons. For example, array and function types can |
2622 | /// decay, and function types can have their calling conventions adjusted. |
2623 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2624 | QualType OriginalTy; |
2625 | QualType AdjustedTy; |
2626 | |
2627 | protected: |
2628 | friend class ASTContext; // ASTContext creates these. |
2629 | |
2630 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2631 | QualType CanonicalPtr) |
2632 | : Type(TC, CanonicalPtr, OriginalTy->isDependentType(), |
2633 | OriginalTy->isInstantiationDependentType(), |
2634 | OriginalTy->isVariablyModifiedType(), |
2635 | OriginalTy->containsUnexpandedParameterPack()), |
2636 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2637 | |
2638 | public: |
2639 | QualType getOriginalType() const { return OriginalTy; } |
2640 | QualType getAdjustedType() const { return AdjustedTy; } |
2641 | |
2642 | bool isSugared() const { return true; } |
2643 | QualType desugar() const { return AdjustedTy; } |
2644 | |
2645 | void Profile(llvm::FoldingSetNodeID &ID) { |
2646 | Profile(ID, OriginalTy, AdjustedTy); |
2647 | } |
2648 | |
2649 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2650 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2651 | ID.AddPointer(New.getAsOpaquePtr()); |
2652 | } |
2653 | |
2654 | static bool classof(const Type *T) { |
2655 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2656 | } |
2657 | }; |
2658 | |
2659 | /// Represents a pointer type decayed from an array or function type. |
2660 | class DecayedType : public AdjustedType { |
2661 | friend class ASTContext; // ASTContext creates these. |
2662 | |
2663 | inline |
2664 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2665 | |
2666 | public: |
2667 | QualType getDecayedType() const { return getAdjustedType(); } |
2668 | |
2669 | inline QualType getPointeeType() const; |
2670 | |
2671 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2672 | }; |
2673 | |
2674 | /// Pointer to a block type. |
2675 | /// This type is to represent types syntactically represented as |
2676 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2677 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2678 | friend class ASTContext; // ASTContext creates these. |
2679 | |
2680 | // Block is some kind of pointer type |
2681 | QualType PointeeType; |
2682 | |
2683 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2684 | : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(), |
2685 | Pointee->isInstantiationDependentType(), |
2686 | Pointee->isVariablyModifiedType(), |
2687 | Pointee->containsUnexpandedParameterPack()), |
2688 | PointeeType(Pointee) {} |
2689 | |
2690 | public: |
2691 | // Get the pointee type. Pointee is required to always be a function type. |
2692 | QualType getPointeeType() const { return PointeeType; } |
2693 | |
2694 | bool isSugared() const { return false; } |
2695 | QualType desugar() const { return QualType(this, 0); } |
2696 | |
2697 | void Profile(llvm::FoldingSetNodeID &ID) { |
2698 | Profile(ID, getPointeeType()); |
2699 | } |
2700 | |
2701 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2702 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2703 | } |
2704 | |
2705 | static bool classof(const Type *T) { |
2706 | return T->getTypeClass() == BlockPointer; |
2707 | } |
2708 | }; |
2709 | |
2710 | /// Base for LValueReferenceType and RValueReferenceType |
2711 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2712 | QualType PointeeType; |
2713 | |
2714 | protected: |
2715 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2716 | bool SpelledAsLValue) |
2717 | : Type(tc, CanonicalRef, Referencee->isDependentType(), |
2718 | Referencee->isInstantiationDependentType(), |
2719 | Referencee->isVariablyModifiedType(), |
2720 | Referencee->containsUnexpandedParameterPack()), |
2721 | PointeeType(Referencee) { |
2722 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2723 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2724 | } |
2725 | |
2726 | public: |
2727 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2728 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2729 | |
2730 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2731 | |
2732 | QualType getPointeeType() const { |
2733 | // FIXME: this might strip inner qualifiers; okay? |
2734 | const ReferenceType *T = this; |
2735 | while (T->isInnerRef()) |
2736 | T = T->PointeeType->castAs<ReferenceType>(); |
2737 | return T->PointeeType; |
2738 | } |
2739 | |
2740 | void Profile(llvm::FoldingSetNodeID &ID) { |
2741 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2742 | } |
2743 | |
2744 | static void Profile(llvm::FoldingSetNodeID &ID, |
2745 | QualType Referencee, |
2746 | bool SpelledAsLValue) { |
2747 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2748 | ID.AddBoolean(SpelledAsLValue); |
2749 | } |
2750 | |
2751 | static bool classof(const Type *T) { |
2752 | return T->getTypeClass() == LValueReference || |
2753 | T->getTypeClass() == RValueReference; |
2754 | } |
2755 | }; |
2756 | |
2757 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2758 | class LValueReferenceType : public ReferenceType { |
2759 | friend class ASTContext; // ASTContext creates these |
2760 | |
2761 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2762 | bool SpelledAsLValue) |
2763 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2764 | SpelledAsLValue) {} |
2765 | |
2766 | public: |
2767 | bool isSugared() const { return false; } |
2768 | QualType desugar() const { return QualType(this, 0); } |
2769 | |
2770 | static bool classof(const Type *T) { |
2771 | return T->getTypeClass() == LValueReference; |
2772 | } |
2773 | }; |
2774 | |
2775 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2776 | class RValueReferenceType : public ReferenceType { |
2777 | friend class ASTContext; // ASTContext creates these |
2778 | |
2779 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2780 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2781 | |
2782 | public: |
2783 | bool isSugared() const { return false; } |
2784 | QualType desugar() const { return QualType(this, 0); } |
2785 | |
2786 | static bool classof(const Type *T) { |
2787 | return T->getTypeClass() == RValueReference; |
2788 | } |
2789 | }; |
2790 | |
2791 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2792 | /// |
2793 | /// This includes both pointers to data members and pointer to member functions. |
2794 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2795 | friend class ASTContext; // ASTContext creates these. |
2796 | |
2797 | QualType PointeeType; |
2798 | |
2799 | /// The class of which the pointee is a member. Must ultimately be a |
2800 | /// RecordType, but could be a typedef or a template parameter too. |
2801 | const Type *Class; |
2802 | |
2803 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2804 | : Type(MemberPointer, CanonicalPtr, |
2805 | Cls->isDependentType() || Pointee->isDependentType(), |
2806 | (Cls->isInstantiationDependentType() || |
2807 | Pointee->isInstantiationDependentType()), |
2808 | Pointee->isVariablyModifiedType(), |
2809 | (Cls->containsUnexpandedParameterPack() || |
2810 | Pointee->containsUnexpandedParameterPack())), |
2811 | PointeeType(Pointee), Class(Cls) {} |
2812 | |
2813 | public: |
2814 | QualType getPointeeType() const { return PointeeType; } |
2815 | |
2816 | /// Returns true if the member type (i.e. the pointee type) is a |
2817 | /// function type rather than a data-member type. |
2818 | bool isMemberFunctionPointer() const { |
2819 | return PointeeType->isFunctionProtoType(); |
2820 | } |
2821 | |
2822 | /// Returns true if the member type (i.e. the pointee type) is a |
2823 | /// data type rather than a function type. |
2824 | bool isMemberDataPointer() const { |
2825 | return !PointeeType->isFunctionProtoType(); |
2826 | } |
2827 | |
2828 | const Type *getClass() const { return Class; } |
2829 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2830 | |
2831 | bool isSugared() const { return false; } |
2832 | QualType desugar() const { return QualType(this, 0); } |
2833 | |
2834 | void Profile(llvm::FoldingSetNodeID &ID) { |
2835 | Profile(ID, getPointeeType(), getClass()); |
2836 | } |
2837 | |
2838 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2839 | const Type *Class) { |
2840 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2841 | ID.AddPointer(Class); |
2842 | } |
2843 | |
2844 | static bool classof(const Type *T) { |
2845 | return T->getTypeClass() == MemberPointer; |
2846 | } |
2847 | }; |
2848 | |
2849 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2850 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2851 | public: |
2852 | /// Capture whether this is a normal array (e.g. int X[4]) |
2853 | /// an array with a static size (e.g. int X[static 4]), or an array |
2854 | /// with a star size (e.g. int X[*]). |
2855 | /// 'static' is only allowed on function parameters. |
2856 | enum ArraySizeModifier { |
2857 | Normal, Static, Star |
2858 | }; |
2859 | |
2860 | private: |
2861 | /// The element type of the array. |
2862 | QualType ElementType; |
2863 | |
2864 | protected: |
2865 | friend class ASTContext; // ASTContext creates these. |
2866 | |
2867 | // C++ [temp.dep.type]p1: |
2868 | // A type is dependent if it is... |
2869 | // - an array type constructed from any dependent type or whose |
2870 | // size is specified by a constant expression that is |
2871 | // value-dependent, |
2872 | ArrayType(TypeClass tc, QualType et, QualType can, |
2873 | ArraySizeModifier sm, unsigned tq, |
2874 | bool ContainsUnexpandedParameterPack) |
2875 | : Type(tc, can, et->isDependentType() || tc == DependentSizedArray, |
2876 | et->isInstantiationDependentType() || tc == DependentSizedArray, |
2877 | (tc == VariableArray || et->isVariablyModifiedType()), |
2878 | ContainsUnexpandedParameterPack), |
2879 | ElementType(et) { |
2880 | ArrayTypeBits.IndexTypeQuals = tq; |
2881 | ArrayTypeBits.SizeModifier = sm; |
2882 | } |
2883 | |
2884 | public: |
2885 | QualType getElementType() const { return ElementType; } |
2886 | |
2887 | ArraySizeModifier getSizeModifier() const { |
2888 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2889 | } |
2890 | |
2891 | Qualifiers getIndexTypeQualifiers() const { |
2892 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2893 | } |
2894 | |
2895 | unsigned getIndexTypeCVRQualifiers() const { |
2896 | return ArrayTypeBits.IndexTypeQuals; |
2897 | } |
2898 | |
2899 | static bool classof(const Type *T) { |
2900 | return T->getTypeClass() == ConstantArray || |
2901 | T->getTypeClass() == VariableArray || |
2902 | T->getTypeClass() == IncompleteArray || |
2903 | T->getTypeClass() == DependentSizedArray; |
2904 | } |
2905 | }; |
2906 | |
2907 | /// Represents the canonical version of C arrays with a specified constant size. |
2908 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2909 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2910 | class ConstantArrayType : public ArrayType { |
2911 | llvm::APInt Size; // Allows us to unique the type. |
2912 | |
2913 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2914 | ArraySizeModifier sm, unsigned tq) |
2915 | : ArrayType(ConstantArray, et, can, sm, tq, |
2916 | et->containsUnexpandedParameterPack()), |
2917 | Size(size) {} |
2918 | |
2919 | protected: |
2920 | friend class ASTContext; // ASTContext creates these. |
2921 | |
2922 | ConstantArrayType(TypeClass tc, QualType et, QualType can, |
2923 | const llvm::APInt &size, ArraySizeModifier sm, unsigned tq) |
2924 | : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()), |
2925 | Size(size) {} |
2926 | |
2927 | public: |
2928 | const llvm::APInt &getSize() const { return Size; } |
2929 | bool isSugared() const { return false; } |
2930 | QualType desugar() const { return QualType(this, 0); } |
2931 | |
2932 | /// Determine the number of bits required to address a member of |
2933 | // an array with the given element type and number of elements. |
2934 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2935 | QualType ElementType, |
2936 | const llvm::APInt &NumElements); |
2937 | |
2938 | /// Determine the maximum number of active bits that an array's size |
2939 | /// can require, which limits the maximum size of the array. |
2940 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2941 | |
2942 | void Profile(llvm::FoldingSetNodeID &ID) { |
2943 | Profile(ID, getElementType(), getSize(), |
2944 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2945 | } |
2946 | |
2947 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2948 | const llvm::APInt &ArraySize, ArraySizeModifier SizeMod, |
2949 | unsigned TypeQuals) { |
2950 | ID.AddPointer(ET.getAsOpaquePtr()); |
2951 | ID.AddInteger(ArraySize.getZExtValue()); |
2952 | ID.AddInteger(SizeMod); |
2953 | ID.AddInteger(TypeQuals); |
2954 | } |
2955 | |
2956 | static bool classof(const Type *T) { |
2957 | return T->getTypeClass() == ConstantArray; |
2958 | } |
2959 | }; |
2960 | |
2961 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2962 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2963 | /// unspecified. |
2964 | class IncompleteArrayType : public ArrayType { |
2965 | friend class ASTContext; // ASTContext creates these. |
2966 | |
2967 | IncompleteArrayType(QualType et, QualType can, |
2968 | ArraySizeModifier sm, unsigned tq) |
2969 | : ArrayType(IncompleteArray, et, can, sm, tq, |
2970 | et->containsUnexpandedParameterPack()) {} |
2971 | |
2972 | public: |
2973 | friend class StmtIteratorBase; |
2974 | |
2975 | bool isSugared() const { return false; } |
2976 | QualType desugar() const { return QualType(this, 0); } |
2977 | |
2978 | static bool classof(const Type *T) { |
2979 | return T->getTypeClass() == IncompleteArray; |
2980 | } |
2981 | |
2982 | void Profile(llvm::FoldingSetNodeID &ID) { |
2983 | Profile(ID, getElementType(), getSizeModifier(), |
2984 | getIndexTypeCVRQualifiers()); |
2985 | } |
2986 | |
2987 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2988 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
2989 | ID.AddPointer(ET.getAsOpaquePtr()); |
2990 | ID.AddInteger(SizeMod); |
2991 | ID.AddInteger(TypeQuals); |
2992 | } |
2993 | }; |
2994 | |
2995 | /// Represents a C array with a specified size that is not an |
2996 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
2997 | /// Since the size expression is an arbitrary expression, we store it as such. |
2998 | /// |
2999 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3000 | /// should not be: two lexically equivalent variable array types could mean |
3001 | /// different things, for example, these variables do not have the same type |
3002 | /// dynamically: |
3003 | /// |
3004 | /// void foo(int x) { |
3005 | /// int Y[x]; |
3006 | /// ++x; |
3007 | /// int Z[x]; |
3008 | /// } |
3009 | class VariableArrayType : public ArrayType { |
3010 | friend class ASTContext; // ASTContext creates these. |
3011 | |
3012 | /// An assignment-expression. VLA's are only permitted within |
3013 | /// a function block. |
3014 | Stmt *SizeExpr; |
3015 | |
3016 | /// The range spanned by the left and right array brackets. |
3017 | SourceRange Brackets; |
3018 | |
3019 | VariableArrayType(QualType et, QualType can, Expr *e, |
3020 | ArraySizeModifier sm, unsigned tq, |
3021 | SourceRange brackets) |
3022 | : ArrayType(VariableArray, et, can, sm, tq, |
3023 | et->containsUnexpandedParameterPack()), |
3024 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3025 | |
3026 | public: |
3027 | friend class StmtIteratorBase; |
3028 | |
3029 | Expr *getSizeExpr() const { |
3030 | // We use C-style casts instead of cast<> here because we do not wish |
3031 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3032 | return (Expr*) SizeExpr; |
3033 | } |
3034 | |
3035 | SourceRange getBracketsRange() const { return Brackets; } |
3036 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3037 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3038 | |
3039 | bool isSugared() const { return false; } |
3040 | QualType desugar() const { return QualType(this, 0); } |
3041 | |
3042 | static bool classof(const Type *T) { |
3043 | return T->getTypeClass() == VariableArray; |
3044 | } |
3045 | |
3046 | void Profile(llvm::FoldingSetNodeID &ID) { |
3047 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3047); |
3048 | } |
3049 | }; |
3050 | |
3051 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3052 | /// |
3053 | /// For example: |
3054 | /// \code |
3055 | /// template<typename T, int Size> |
3056 | /// class array { |
3057 | /// T data[Size]; |
3058 | /// }; |
3059 | /// \endcode |
3060 | /// |
3061 | /// For these types, we won't actually know what the array bound is |
3062 | /// until template instantiation occurs, at which point this will |
3063 | /// become either a ConstantArrayType or a VariableArrayType. |
3064 | class DependentSizedArrayType : public ArrayType { |
3065 | friend class ASTContext; // ASTContext creates these. |
3066 | |
3067 | const ASTContext &Context; |
3068 | |
3069 | /// An assignment expression that will instantiate to the |
3070 | /// size of the array. |
3071 | /// |
3072 | /// The expression itself might be null, in which case the array |
3073 | /// type will have its size deduced from an initializer. |
3074 | Stmt *SizeExpr; |
3075 | |
3076 | /// The range spanned by the left and right array brackets. |
3077 | SourceRange Brackets; |
3078 | |
3079 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3080 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3081 | SourceRange brackets); |
3082 | |
3083 | public: |
3084 | friend class StmtIteratorBase; |
3085 | |
3086 | Expr *getSizeExpr() const { |
3087 | // We use C-style casts instead of cast<> here because we do not wish |
3088 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3089 | return (Expr*) SizeExpr; |
3090 | } |
3091 | |
3092 | SourceRange getBracketsRange() const { return Brackets; } |
3093 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3094 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3095 | |
3096 | bool isSugared() const { return false; } |
3097 | QualType desugar() const { return QualType(this, 0); } |
3098 | |
3099 | static bool classof(const Type *T) { |
3100 | return T->getTypeClass() == DependentSizedArray; |
3101 | } |
3102 | |
3103 | void Profile(llvm::FoldingSetNodeID &ID) { |
3104 | Profile(ID, Context, getElementType(), |
3105 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3106 | } |
3107 | |
3108 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3109 | QualType ET, ArraySizeModifier SizeMod, |
3110 | unsigned TypeQuals, Expr *E); |
3111 | }; |
3112 | |
3113 | /// Represents an extended address space qualifier where the input address space |
3114 | /// value is dependent. Non-dependent address spaces are not represented with a |
3115 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3116 | /// |
3117 | /// For example: |
3118 | /// \code |
3119 | /// template<typename T, int AddrSpace> |
3120 | /// class AddressSpace { |
3121 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3122 | /// } |
3123 | /// \endcode |
3124 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3125 | friend class ASTContext; |
3126 | |
3127 | const ASTContext &Context; |
3128 | Expr *AddrSpaceExpr; |
3129 | QualType PointeeType; |
3130 | SourceLocation loc; |
3131 | |
3132 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3133 | QualType can, Expr *AddrSpaceExpr, |
3134 | SourceLocation loc); |
3135 | |
3136 | public: |
3137 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3138 | QualType getPointeeType() const { return PointeeType; } |
3139 | SourceLocation getAttributeLoc() const { return loc; } |
3140 | |
3141 | bool isSugared() const { return false; } |
3142 | QualType desugar() const { return QualType(this, 0); } |
3143 | |
3144 | static bool classof(const Type *T) { |
3145 | return T->getTypeClass() == DependentAddressSpace; |
3146 | } |
3147 | |
3148 | void Profile(llvm::FoldingSetNodeID &ID) { |
3149 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3150 | } |
3151 | |
3152 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3153 | QualType PointeeType, Expr *AddrSpaceExpr); |
3154 | }; |
3155 | |
3156 | /// Represents an extended vector type where either the type or size is |
3157 | /// dependent. |
3158 | /// |
3159 | /// For example: |
3160 | /// \code |
3161 | /// template<typename T, int Size> |
3162 | /// class vector { |
3163 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3164 | /// } |
3165 | /// \endcode |
3166 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3167 | friend class ASTContext; |
3168 | |
3169 | const ASTContext &Context; |
3170 | Expr *SizeExpr; |
3171 | |
3172 | /// The element type of the array. |
3173 | QualType ElementType; |
3174 | |
3175 | SourceLocation loc; |
3176 | |
3177 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3178 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3179 | |
3180 | public: |
3181 | Expr *getSizeExpr() const { return SizeExpr; } |
3182 | QualType getElementType() const { return ElementType; } |
3183 | SourceLocation getAttributeLoc() const { return loc; } |
3184 | |
3185 | bool isSugared() const { return false; } |
3186 | QualType desugar() const { return QualType(this, 0); } |
3187 | |
3188 | static bool classof(const Type *T) { |
3189 | return T->getTypeClass() == DependentSizedExtVector; |
3190 | } |
3191 | |
3192 | void Profile(llvm::FoldingSetNodeID &ID) { |
3193 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3194 | } |
3195 | |
3196 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3197 | QualType ElementType, Expr *SizeExpr); |
3198 | }; |
3199 | |
3200 | |
3201 | /// Represents a GCC generic vector type. This type is created using |
3202 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3203 | /// bytes; or from an Altivec __vector or vector declaration. |
3204 | /// Since the constructor takes the number of vector elements, the |
3205 | /// client is responsible for converting the size into the number of elements. |
3206 | class VectorType : public Type, public llvm::FoldingSetNode { |
3207 | public: |
3208 | enum VectorKind { |
3209 | /// not a target-specific vector type |
3210 | GenericVector, |
3211 | |
3212 | /// is AltiVec vector |
3213 | AltiVecVector, |
3214 | |
3215 | /// is AltiVec 'vector Pixel' |
3216 | AltiVecPixel, |
3217 | |
3218 | /// is AltiVec 'vector bool ...' |
3219 | AltiVecBool, |
3220 | |
3221 | /// is ARM Neon vector |
3222 | NeonVector, |
3223 | |
3224 | /// is ARM Neon polynomial vector |
3225 | NeonPolyVector |
3226 | }; |
3227 | |
3228 | protected: |
3229 | friend class ASTContext; // ASTContext creates these. |
3230 | |
3231 | /// The element type of the vector. |
3232 | QualType ElementType; |
3233 | |
3234 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3235 | VectorKind vecKind); |
3236 | |
3237 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3238 | QualType canonType, VectorKind vecKind); |
3239 | |
3240 | public: |
3241 | QualType getElementType() const { return ElementType; } |
3242 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3243 | |
3244 | static bool isVectorSizeTooLarge(unsigned NumElements) { |
3245 | return NumElements > VectorTypeBitfields::MaxNumElements; |
3246 | } |
3247 | |
3248 | bool isSugared() const { return false; } |
3249 | QualType desugar() const { return QualType(this, 0); } |
3250 | |
3251 | VectorKind getVectorKind() const { |
3252 | return VectorKind(VectorTypeBits.VecKind); |
3253 | } |
3254 | |
3255 | void Profile(llvm::FoldingSetNodeID &ID) { |
3256 | Profile(ID, getElementType(), getNumElements(), |
3257 | getTypeClass(), getVectorKind()); |
3258 | } |
3259 | |
3260 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3261 | unsigned NumElements, TypeClass TypeClass, |
3262 | VectorKind VecKind) { |
3263 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3264 | ID.AddInteger(NumElements); |
3265 | ID.AddInteger(TypeClass); |
3266 | ID.AddInteger(VecKind); |
3267 | } |
3268 | |
3269 | static bool classof(const Type *T) { |
3270 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3271 | } |
3272 | }; |
3273 | |
3274 | /// Represents a vector type where either the type or size is dependent. |
3275 | //// |
3276 | /// For example: |
3277 | /// \code |
3278 | /// template<typename T, int Size> |
3279 | /// class vector { |
3280 | /// typedef T __attribute__((vector_size(Size))) type; |
3281 | /// } |
3282 | /// \endcode |
3283 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3284 | friend class ASTContext; |
3285 | |
3286 | const ASTContext &Context; |
3287 | QualType ElementType; |
3288 | Expr *SizeExpr; |
3289 | SourceLocation Loc; |
3290 | |
3291 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3292 | QualType CanonType, Expr *SizeExpr, |
3293 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3294 | |
3295 | public: |
3296 | Expr *getSizeExpr() const { return SizeExpr; } |
3297 | QualType getElementType() const { return ElementType; } |
3298 | SourceLocation getAttributeLoc() const { return Loc; } |
3299 | VectorType::VectorKind getVectorKind() const { |
3300 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3301 | } |
3302 | |
3303 | bool isSugared() const { return false; } |
3304 | QualType desugar() const { return QualType(this, 0); } |
3305 | |
3306 | static bool classof(const Type *T) { |
3307 | return T->getTypeClass() == DependentVector; |
3308 | } |
3309 | |
3310 | void Profile(llvm::FoldingSetNodeID &ID) { |
3311 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3312 | } |
3313 | |
3314 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3315 | QualType ElementType, const Expr *SizeExpr, |
3316 | VectorType::VectorKind VecKind); |
3317 | }; |
3318 | |
3319 | /// ExtVectorType - Extended vector type. This type is created using |
3320 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3321 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3322 | /// class enables syntactic extensions, like Vector Components for accessing |
3323 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3324 | /// Shading Language). |
3325 | class ExtVectorType : public VectorType { |
3326 | friend class ASTContext; // ASTContext creates these. |
3327 | |
3328 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3329 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3330 | |
3331 | public: |
3332 | static int getPointAccessorIdx(char c) { |
3333 | switch (c) { |
3334 | default: return -1; |
3335 | case 'x': case 'r': return 0; |
3336 | case 'y': case 'g': return 1; |
3337 | case 'z': case 'b': return 2; |
3338 | case 'w': case 'a': return 3; |
3339 | } |
3340 | } |
3341 | |
3342 | static int getNumericAccessorIdx(char c) { |
3343 | switch (c) { |
3344 | default: return -1; |
3345 | case '0': return 0; |
3346 | case '1': return 1; |
3347 | case '2': return 2; |
3348 | case '3': return 3; |
3349 | case '4': return 4; |
3350 | case '5': return 5; |
3351 | case '6': return 6; |
3352 | case '7': return 7; |
3353 | case '8': return 8; |
3354 | case '9': return 9; |
3355 | case 'A': |
3356 | case 'a': return 10; |
3357 | case 'B': |
3358 | case 'b': return 11; |
3359 | case 'C': |
3360 | case 'c': return 12; |
3361 | case 'D': |
3362 | case 'd': return 13; |
3363 | case 'E': |
3364 | case 'e': return 14; |
3365 | case 'F': |
3366 | case 'f': return 15; |
3367 | } |
3368 | } |
3369 | |
3370 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3371 | if (isNumericAccessor) |
3372 | return getNumericAccessorIdx(c); |
3373 | else |
3374 | return getPointAccessorIdx(c); |
3375 | } |
3376 | |
3377 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3378 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3379 | return unsigned(idx-1) < getNumElements(); |
3380 | return false; |
3381 | } |
3382 | |
3383 | bool isSugared() const { return false; } |
3384 | QualType desugar() const { return QualType(this, 0); } |
3385 | |
3386 | static bool classof(const Type *T) { |
3387 | return T->getTypeClass() == ExtVector; |
3388 | } |
3389 | }; |
3390 | |
3391 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3392 | /// class of FunctionNoProtoType and FunctionProtoType. |
3393 | class FunctionType : public Type { |
3394 | // The type returned by the function. |
3395 | QualType ResultType; |
3396 | |
3397 | public: |
3398 | /// Interesting information about a specific parameter that can't simply |
3399 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3400 | /// but is in FunctionType to make this class available during the |
3401 | /// specification of the bases of FunctionProtoType. |
3402 | /// |
3403 | /// It makes sense to model language features this way when there's some |
3404 | /// sort of parameter-specific override (such as an attribute) that |
3405 | /// affects how the function is called. For example, the ARC ns_consumed |
3406 | /// attribute changes whether a parameter is passed at +0 (the default) |
3407 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3408 | /// but isn't really a change to the parameter type. |
3409 | /// |
3410 | /// One serious disadvantage of modelling language features this way is |
3411 | /// that they generally do not work with language features that attempt |
3412 | /// to destructure types. For example, template argument deduction will |
3413 | /// not be able to match a parameter declared as |
3414 | /// T (*)(U) |
3415 | /// against an argument of type |
3416 | /// void (*)(__attribute__((ns_consumed)) id) |
3417 | /// because the substitution of T=void, U=id into the former will |
3418 | /// not produce the latter. |
3419 | class ExtParameterInfo { |
3420 | enum { |
3421 | ABIMask = 0x0F, |
3422 | IsConsumed = 0x10, |
3423 | HasPassObjSize = 0x20, |
3424 | IsNoEscape = 0x40, |
3425 | }; |
3426 | unsigned char Data = 0; |
3427 | |
3428 | public: |
3429 | ExtParameterInfo() = default; |
3430 | |
3431 | /// Return the ABI treatment of this parameter. |
3432 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3433 | ExtParameterInfo withABI(ParameterABI kind) const { |
3434 | ExtParameterInfo copy = *this; |
3435 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3436 | return copy; |
3437 | } |
3438 | |
3439 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3440 | /// Consumed parameters must have retainable object type. |
3441 | bool isConsumed() const { return (Data & IsConsumed); } |
3442 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3443 | ExtParameterInfo copy = *this; |
3444 | if (consumed) |
3445 | copy.Data |= IsConsumed; |
3446 | else |
3447 | copy.Data &= ~IsConsumed; |
3448 | return copy; |
3449 | } |
3450 | |
3451 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3452 | ExtParameterInfo withHasPassObjectSize() const { |
3453 | ExtParameterInfo Copy = *this; |
3454 | Copy.Data |= HasPassObjSize; |
3455 | return Copy; |
3456 | } |
3457 | |
3458 | bool isNoEscape() const { return Data & IsNoEscape; } |
3459 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3460 | ExtParameterInfo Copy = *this; |
3461 | if (NoEscape) |
3462 | Copy.Data |= IsNoEscape; |
3463 | else |
3464 | Copy.Data &= ~IsNoEscape; |
3465 | return Copy; |
3466 | } |
3467 | |
3468 | unsigned char getOpaqueValue() const { return Data; } |
3469 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3470 | ExtParameterInfo result; |
3471 | result.Data = data; |
3472 | return result; |
3473 | } |
3474 | |
3475 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3476 | return lhs.Data == rhs.Data; |
3477 | } |
3478 | |
3479 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3480 | return lhs.Data != rhs.Data; |
3481 | } |
3482 | }; |
3483 | |
3484 | /// A class which abstracts out some details necessary for |
3485 | /// making a call. |
3486 | /// |
3487 | /// It is not actually used directly for storing this information in |
3488 | /// a FunctionType, although FunctionType does currently use the |
3489 | /// same bit-pattern. |
3490 | /// |
3491 | // If you add a field (say Foo), other than the obvious places (both, |
3492 | // constructors, compile failures), what you need to update is |
3493 | // * Operator== |
3494 | // * getFoo |
3495 | // * withFoo |
3496 | // * functionType. Add Foo, getFoo. |
3497 | // * ASTContext::getFooType |
3498 | // * ASTContext::mergeFunctionTypes |
3499 | // * FunctionNoProtoType::Profile |
3500 | // * FunctionProtoType::Profile |
3501 | // * TypePrinter::PrintFunctionProto |
3502 | // * AST read and write |
3503 | // * Codegen |
3504 | class ExtInfo { |
3505 | friend class FunctionType; |
3506 | |
3507 | // Feel free to rearrange or add bits, but if you go over 12, |
3508 | // you'll need to adjust both the Bits field below and |
3509 | // Type::FunctionTypeBitfields. |
3510 | |
3511 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck| |
3512 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | |
3513 | // |
3514 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3515 | enum { CallConvMask = 0x1F }; |
3516 | enum { NoReturnMask = 0x20 }; |
3517 | enum { ProducesResultMask = 0x40 }; |
3518 | enum { NoCallerSavedRegsMask = 0x80 }; |
3519 | enum { NoCfCheckMask = 0x800 }; |
3520 | enum { |
3521 | RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask | |
3522 | NoCallerSavedRegsMask | NoCfCheckMask), |
3523 | RegParmOffset = 8 |
3524 | }; // Assumed to be the last field |
3525 | uint16_t Bits = CC_C; |
3526 | |
3527 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3528 | |
3529 | public: |
3530 | // Constructor with no defaults. Use this when you know that you |
3531 | // have all the elements (when reading an AST file for example). |
3532 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3533 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) { |
3534 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value" ) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3534, __PRETTY_FUNCTION__)); |
3535 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3536 | (producesResult ? ProducesResultMask : 0) | |
3537 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3538 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3539 | (NoCfCheck ? NoCfCheckMask : 0); |
3540 | } |
3541 | |
3542 | // Constructor with all defaults. Use when for example creating a |
3543 | // function known to use defaults. |
3544 | ExtInfo() = default; |
3545 | |
3546 | // Constructor with just the calling convention, which is an important part |
3547 | // of the canonical type. |
3548 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3549 | |
3550 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3551 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3552 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3553 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3554 | bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; } |
3555 | |
3556 | unsigned getRegParm() const { |
3557 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3558 | if (RegParm > 0) |
3559 | --RegParm; |
3560 | return RegParm; |
3561 | } |
3562 | |
3563 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3564 | |
3565 | bool operator==(ExtInfo Other) const { |
3566 | return Bits == Other.Bits; |
3567 | } |
3568 | bool operator!=(ExtInfo Other) const { |
3569 | return Bits != Other.Bits; |
3570 | } |
3571 | |
3572 | // Note that we don't have setters. That is by design, use |
3573 | // the following with methods instead of mutating these objects. |
3574 | |
3575 | ExtInfo withNoReturn(bool noReturn) const { |
3576 | if (noReturn) |
3577 | return ExtInfo(Bits | NoReturnMask); |
3578 | else |
3579 | return ExtInfo(Bits & ~NoReturnMask); |
3580 | } |
3581 | |
3582 | ExtInfo withProducesResult(bool producesResult) const { |
3583 | if (producesResult) |
3584 | return ExtInfo(Bits | ProducesResultMask); |
3585 | else |
3586 | return ExtInfo(Bits & ~ProducesResultMask); |
3587 | } |
3588 | |
3589 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3590 | if (noCallerSavedRegs) |
3591 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3592 | else |
3593 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3594 | } |
3595 | |
3596 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3597 | if (noCfCheck) |
3598 | return ExtInfo(Bits | NoCfCheckMask); |
3599 | else |
3600 | return ExtInfo(Bits & ~NoCfCheckMask); |
3601 | } |
3602 | |
3603 | ExtInfo withRegParm(unsigned RegParm) const { |
3604 | assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast <void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3604, __PRETTY_FUNCTION__)); |
3605 | return ExtInfo((Bits & ~RegParmMask) | |
3606 | ((RegParm + 1) << RegParmOffset)); |
3607 | } |
3608 | |
3609 | ExtInfo withCallingConv(CallingConv cc) const { |
3610 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3611 | } |
3612 | |
3613 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3614 | ID.AddInteger(Bits); |
3615 | } |
3616 | }; |
3617 | |
3618 | /// A simple holder for a QualType representing a type in an |
3619 | /// exception specification. Unfortunately needed by FunctionProtoType |
3620 | /// because TrailingObjects cannot handle repeated types. |
3621 | struct ExceptionType { QualType Type; }; |
3622 | |
3623 | /// A simple holder for various uncommon bits which do not fit in |
3624 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3625 | /// alignment of subsequent objects in TrailingObjects. You must update |
3626 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3627 | struct alignas(void *) FunctionTypeExtraBitfields { |
3628 | /// The number of types in the exception specification. |
3629 | /// A whole unsigned is not needed here and according to |
3630 | /// [implimits] 8 bits would be enough here. |
3631 | unsigned NumExceptionType; |
3632 | }; |
3633 | |
3634 | protected: |
3635 | FunctionType(TypeClass tc, QualType res, |
3636 | QualType Canonical, bool Dependent, |
3637 | bool InstantiationDependent, |
3638 | bool VariablyModified, bool ContainsUnexpandedParameterPack, |
3639 | ExtInfo Info) |
3640 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
3641 | ContainsUnexpandedParameterPack), |
3642 | ResultType(res) { |
3643 | FunctionTypeBits.ExtInfo = Info.Bits; |
3644 | } |
3645 | |
3646 | Qualifiers getFastTypeQuals() const { |
3647 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3648 | } |
3649 | |
3650 | public: |
3651 | QualType getReturnType() const { return ResultType; } |
3652 | |
3653 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3654 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3655 | |
3656 | /// Determine whether this function type includes the GNU noreturn |
3657 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3658 | /// type. |
3659 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3660 | |
3661 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3662 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3663 | |
3664 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3665 | "Const, volatile and restrict are assumed to be a subset of " |
3666 | "the fast qualifiers."); |
3667 | |
3668 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3669 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3670 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3671 | |
3672 | /// Determine the type of an expression that calls a function of |
3673 | /// this type. |
3674 | QualType getCallResultType(const ASTContext &Context) const { |
3675 | return getReturnType().getNonLValueExprType(Context); |
3676 | } |
3677 | |
3678 | static StringRef getNameForCallConv(CallingConv CC); |
3679 | |
3680 | static bool classof(const Type *T) { |
3681 | return T->getTypeClass() == FunctionNoProto || |
3682 | T->getTypeClass() == FunctionProto; |
3683 | } |
3684 | }; |
3685 | |
3686 | /// Represents a K&R-style 'int foo()' function, which has |
3687 | /// no information available about its arguments. |
3688 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3689 | friend class ASTContext; // ASTContext creates these. |
3690 | |
3691 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3692 | : FunctionType(FunctionNoProto, Result, Canonical, |
3693 | /*Dependent=*/false, /*InstantiationDependent=*/false, |
3694 | Result->isVariablyModifiedType(), |
3695 | /*ContainsUnexpandedParameterPack=*/false, Info) {} |
3696 | |
3697 | public: |
3698 | // No additional state past what FunctionType provides. |
3699 | |
3700 | bool isSugared() const { return false; } |
3701 | QualType desugar() const { return QualType(this, 0); } |
3702 | |
3703 | void Profile(llvm::FoldingSetNodeID &ID) { |
3704 | Profile(ID, getReturnType(), getExtInfo()); |
3705 | } |
3706 | |
3707 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3708 | ExtInfo Info) { |
3709 | Info.Profile(ID); |
3710 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3711 | } |
3712 | |
3713 | static bool classof(const Type *T) { |
3714 | return T->getTypeClass() == FunctionNoProto; |
3715 | } |
3716 | }; |
3717 | |
3718 | /// Represents a prototype with parameter type info, e.g. |
3719 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3720 | /// parameters, not as having a single void parameter. Such a type can have |
3721 | /// an exception specification, but this specification is not part of the |
3722 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3723 | /// which optional. For more information about the trailing objects see |
3724 | /// the first comment inside FunctionProtoType. |
3725 | class FunctionProtoType final |
3726 | : public FunctionType, |
3727 | public llvm::FoldingSetNode, |
3728 | private llvm::TrailingObjects< |
3729 | FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields, |
3730 | FunctionType::ExceptionType, Expr *, FunctionDecl *, |
3731 | FunctionType::ExtParameterInfo, Qualifiers> { |
3732 | friend class ASTContext; // ASTContext creates these. |
3733 | friend TrailingObjects; |
3734 | |
3735 | // FunctionProtoType is followed by several trailing objects, some of |
3736 | // which optional. They are in order: |
3737 | // |
3738 | // * An array of getNumParams() QualType holding the parameter types. |
3739 | // Always present. Note that for the vast majority of FunctionProtoType, |
3740 | // these will be the only trailing objects. |
3741 | // |
3742 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3743 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3744 | // a single FunctionTypeExtraBitfields. Present if and only if |
3745 | // hasExtraBitfields() is true. |
3746 | // |
3747 | // * Optionally exactly one of: |
3748 | // * an array of getNumExceptions() ExceptionType, |
3749 | // * a single Expr *, |
3750 | // * a pair of FunctionDecl *, |
3751 | // * a single FunctionDecl * |
3752 | // used to store information about the various types of exception |
3753 | // specification. See getExceptionSpecSize for the details. |
3754 | // |
3755 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3756 | // an ExtParameterInfo for each of the parameters. Present if and |
3757 | // only if hasExtParameterInfos() is true. |
3758 | // |
3759 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3760 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3761 | // if hasExtQualifiers() is true. |
3762 | // |
3763 | // The optional FunctionTypeExtraBitfields has to be before the data |
3764 | // related to the exception specification since it contains the number |
3765 | // of exception types. |
3766 | // |
3767 | // We put the ExtParameterInfos last. If all were equal, it would make |
3768 | // more sense to put these before the exception specification, because |
3769 | // it's much easier to skip past them compared to the elaborate switch |
3770 | // required to skip the exception specification. However, all is not |
3771 | // equal; ExtParameterInfos are used to model very uncommon features, |
3772 | // and it's better not to burden the more common paths. |
3773 | |
3774 | public: |
3775 | /// Holds information about the various types of exception specification. |
3776 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3777 | /// used to group together the various bits of information about the |
3778 | /// exception specification. |
3779 | struct ExceptionSpecInfo { |
3780 | /// The kind of exception specification this is. |
3781 | ExceptionSpecificationType Type = EST_None; |
3782 | |
3783 | /// Explicitly-specified list of exception types. |
3784 | ArrayRef<QualType> Exceptions; |
3785 | |
3786 | /// Noexcept expression, if this is a computed noexcept specification. |
3787 | Expr *NoexceptExpr = nullptr; |
3788 | |
3789 | /// The function whose exception specification this is, for |
3790 | /// EST_Unevaluated and EST_Uninstantiated. |
3791 | FunctionDecl *SourceDecl = nullptr; |
3792 | |
3793 | /// The function template whose exception specification this is instantiated |
3794 | /// from, for EST_Uninstantiated. |
3795 | FunctionDecl *SourceTemplate = nullptr; |
3796 | |
3797 | ExceptionSpecInfo() = default; |
3798 | |
3799 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3800 | }; |
3801 | |
3802 | /// Extra information about a function prototype. ExtProtoInfo is not |
3803 | /// stored as such in FunctionProtoType but is used to group together |
3804 | /// the various bits of extra information about a function prototype. |
3805 | struct ExtProtoInfo { |
3806 | FunctionType::ExtInfo ExtInfo; |
3807 | bool Variadic : 1; |
3808 | bool HasTrailingReturn : 1; |
3809 | Qualifiers TypeQuals; |
3810 | RefQualifierKind RefQualifier = RQ_None; |
3811 | ExceptionSpecInfo ExceptionSpec; |
3812 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3813 | |
3814 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3815 | |
3816 | ExtProtoInfo(CallingConv CC) |
3817 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3818 | |
3819 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3820 | ExtProtoInfo Result(*this); |
3821 | Result.ExceptionSpec = ESI; |
3822 | return Result; |
3823 | } |
3824 | }; |
3825 | |
3826 | private: |
3827 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3828 | return getNumParams(); |
3829 | } |
3830 | |
3831 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
3832 | return hasExtraBitfields(); |
3833 | } |
3834 | |
3835 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
3836 | return getExceptionSpecSize().NumExceptionType; |
3837 | } |
3838 | |
3839 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
3840 | return getExceptionSpecSize().NumExprPtr; |
3841 | } |
3842 | |
3843 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
3844 | return getExceptionSpecSize().NumFunctionDeclPtr; |
3845 | } |
3846 | |
3847 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
3848 | return hasExtParameterInfos() ? getNumParams() : 0; |
3849 | } |
3850 | |
3851 | /// Determine whether there are any argument types that |
3852 | /// contain an unexpanded parameter pack. |
3853 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
3854 | unsigned numArgs) { |
3855 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
3856 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
3857 | return true; |
3858 | |
3859 | return false; |
3860 | } |
3861 | |
3862 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
3863 | QualType canonical, const ExtProtoInfo &epi); |
3864 | |
3865 | /// This struct is returned by getExceptionSpecSize and is used to |
3866 | /// translate an ExceptionSpecificationType to the number and kind |
3867 | /// of trailing objects related to the exception specification. |
3868 | struct ExceptionSpecSizeHolder { |
3869 | unsigned NumExceptionType; |
3870 | unsigned NumExprPtr; |
3871 | unsigned NumFunctionDeclPtr; |
3872 | }; |
3873 | |
3874 | /// Return the number and kind of trailing objects |
3875 | /// related to the exception specification. |
3876 | static ExceptionSpecSizeHolder |
3877 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
3878 | switch (EST) { |
3879 | case EST_None: |
3880 | case EST_DynamicNone: |
3881 | case EST_MSAny: |
3882 | case EST_BasicNoexcept: |
3883 | case EST_Unparsed: |
3884 | case EST_NoThrow: |
3885 | return {0, 0, 0}; |
3886 | |
3887 | case EST_Dynamic: |
3888 | return {NumExceptions, 0, 0}; |
3889 | |
3890 | case EST_DependentNoexcept: |
3891 | case EST_NoexceptFalse: |
3892 | case EST_NoexceptTrue: |
3893 | return {0, 1, 0}; |
3894 | |
3895 | case EST_Uninstantiated: |
3896 | return {0, 0, 2}; |
3897 | |
3898 | case EST_Unevaluated: |
3899 | return {0, 0, 1}; |
3900 | } |
3901 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3901); |
3902 | } |
3903 | |
3904 | /// Return the number and kind of trailing objects |
3905 | /// related to the exception specification. |
3906 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
3907 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
3908 | } |
3909 | |
3910 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
3911 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
3912 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
3913 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
3914 | return EST == EST_Dynamic; |
3915 | } |
3916 | |
3917 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
3918 | bool hasExtraBitfields() const { |
3919 | return hasExtraBitfields(getExceptionSpecType()); |
3920 | } |
3921 | |
3922 | bool hasExtQualifiers() const { |
3923 | return FunctionTypeBits.HasExtQuals; |
3924 | } |
3925 | |
3926 | public: |
3927 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
3928 | |
3929 | QualType getParamType(unsigned i) const { |
3930 | assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index") ? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3930, __PRETTY_FUNCTION__)); |
3931 | return param_type_begin()[i]; |
3932 | } |
3933 | |
3934 | ArrayRef<QualType> getParamTypes() const { |
3935 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
3936 | } |
3937 | |
3938 | ExtProtoInfo getExtProtoInfo() const { |
3939 | ExtProtoInfo EPI; |
3940 | EPI.ExtInfo = getExtInfo(); |
3941 | EPI.Variadic = isVariadic(); |
3942 | EPI.HasTrailingReturn = hasTrailingReturn(); |
3943 | EPI.ExceptionSpec.Type = getExceptionSpecType(); |
3944 | EPI.TypeQuals = getMethodQuals(); |
3945 | EPI.RefQualifier = getRefQualifier(); |
3946 | if (EPI.ExceptionSpec.Type == EST_Dynamic) { |
3947 | EPI.ExceptionSpec.Exceptions = exceptions(); |
3948 | } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) { |
3949 | EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr(); |
3950 | } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) { |
3951 | EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl(); |
3952 | EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate(); |
3953 | } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) { |
3954 | EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl(); |
3955 | } |
3956 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
3957 | return EPI; |
3958 | } |
3959 | |
3960 | /// Get the kind of exception specification on this function. |
3961 | ExceptionSpecificationType getExceptionSpecType() const { |
3962 | return static_cast<ExceptionSpecificationType>( |
3963 | FunctionTypeBits.ExceptionSpecType); |
3964 | } |
3965 | |
3966 | /// Return whether this function has any kind of exception spec. |
3967 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
3968 | |
3969 | /// Return whether this function has a dynamic (throw) exception spec. |
3970 | bool hasDynamicExceptionSpec() const { |
3971 | return isDynamicExceptionSpec(getExceptionSpecType()); |
3972 | } |
3973 | |
3974 | /// Return whether this function has a noexcept exception spec. |
3975 | bool hasNoexceptExceptionSpec() const { |
3976 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
3977 | } |
3978 | |
3979 | /// Return whether this function has a dependent exception spec. |
3980 | bool hasDependentExceptionSpec() const; |
3981 | |
3982 | /// Return whether this function has an instantiation-dependent exception |
3983 | /// spec. |
3984 | bool hasInstantiationDependentExceptionSpec() const; |
3985 | |
3986 | /// Return the number of types in the exception specification. |
3987 | unsigned getNumExceptions() const { |
3988 | return getExceptionSpecType() == EST_Dynamic |
3989 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
3990 | ->NumExceptionType |
3991 | : 0; |
3992 | } |
3993 | |
3994 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
3995 | QualType getExceptionType(unsigned i) const { |
3996 | assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3996, __PRETTY_FUNCTION__)); |
3997 | return exception_begin()[i]; |
3998 | } |
3999 | |
4000 | /// Return the expression inside noexcept(expression), or a null pointer |
4001 | /// if there is none (because the exception spec is not of this form). |
4002 | Expr *getNoexceptExpr() const { |
4003 | if (!isComputedNoexcept(getExceptionSpecType())) |
4004 | return nullptr; |
4005 | return *getTrailingObjects<Expr *>(); |
4006 | } |
4007 | |
4008 | /// If this function type has an exception specification which hasn't |
4009 | /// been determined yet (either because it has not been evaluated or because |
4010 | /// it has not been instantiated), this is the function whose exception |
4011 | /// specification is represented by this type. |
4012 | FunctionDecl *getExceptionSpecDecl() const { |
4013 | if (getExceptionSpecType() != EST_Uninstantiated && |
4014 | getExceptionSpecType() != EST_Unevaluated) |
4015 | return nullptr; |
4016 | return getTrailingObjects<FunctionDecl *>()[0]; |
4017 | } |
4018 | |
4019 | /// If this function type has an uninstantiated exception |
4020 | /// specification, this is the function whose exception specification |
4021 | /// should be instantiated to find the exception specification for |
4022 | /// this type. |
4023 | FunctionDecl *getExceptionSpecTemplate() const { |
4024 | if (getExceptionSpecType() != EST_Uninstantiated) |
4025 | return nullptr; |
4026 | return getTrailingObjects<FunctionDecl *>()[1]; |
4027 | } |
4028 | |
4029 | /// Determine whether this function type has a non-throwing exception |
4030 | /// specification. |
4031 | CanThrowResult canThrow() const; |
4032 | |
4033 | /// Determine whether this function type has a non-throwing exception |
4034 | /// specification. If this depends on template arguments, returns |
4035 | /// \c ResultIfDependent. |
4036 | bool isNothrow(bool ResultIfDependent = false) const { |
4037 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4038 | } |
4039 | |
4040 | /// Whether this function prototype is variadic. |
4041 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4042 | |
4043 | /// Determines whether this function prototype contains a |
4044 | /// parameter pack at the end. |
4045 | /// |
4046 | /// A function template whose last parameter is a parameter pack can be |
4047 | /// called with an arbitrary number of arguments, much like a variadic |
4048 | /// function. |
4049 | bool isTemplateVariadic() const; |
4050 | |
4051 | /// Whether this function prototype has a trailing return type. |
4052 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4053 | |
4054 | Qualifiers getMethodQuals() const { |
4055 | if (hasExtQualifiers()) |
4056 | return *getTrailingObjects<Qualifiers>(); |
4057 | else |
4058 | return getFastTypeQuals(); |
4059 | } |
4060 | |
4061 | /// Retrieve the ref-qualifier associated with this function type. |
4062 | RefQualifierKind getRefQualifier() const { |
4063 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4064 | } |
4065 | |
4066 | using param_type_iterator = const QualType *; |
4067 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4068 | |
4069 | param_type_range param_types() const { |
4070 | return param_type_range(param_type_begin(), param_type_end()); |
4071 | } |
4072 | |
4073 | param_type_iterator param_type_begin() const { |
4074 | return getTrailingObjects<QualType>(); |
4075 | } |
4076 | |
4077 | param_type_iterator param_type_end() const { |
4078 | return param_type_begin() + getNumParams(); |
4079 | } |
4080 | |
4081 | using exception_iterator = const QualType *; |
4082 | |
4083 | ArrayRef<QualType> exceptions() const { |
4084 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4085 | } |
4086 | |
4087 | exception_iterator exception_begin() const { |
4088 | return reinterpret_cast<exception_iterator>( |
4089 | getTrailingObjects<ExceptionType>()); |
4090 | } |
4091 | |
4092 | exception_iterator exception_end() const { |
4093 | return exception_begin() + getNumExceptions(); |
4094 | } |
4095 | |
4096 | /// Is there any interesting extra information for any of the parameters |
4097 | /// of this function type? |
4098 | bool hasExtParameterInfos() const { |
4099 | return FunctionTypeBits.HasExtParameterInfos; |
4100 | } |
4101 | |
4102 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4103 | assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4103, __PRETTY_FUNCTION__)); |
4104 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4105 | getNumParams()); |
4106 | } |
4107 | |
4108 | /// Return a pointer to the beginning of the array of extra parameter |
4109 | /// information, if present, or else null if none of the parameters |
4110 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4111 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4112 | if (!hasExtParameterInfos()) |
4113 | return nullptr; |
4114 | return getTrailingObjects<ExtParameterInfo>(); |
4115 | } |
4116 | |
4117 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4118 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4118, __PRETTY_FUNCTION__)); |
4119 | if (hasExtParameterInfos()) |
4120 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4121 | return ExtParameterInfo(); |
4122 | } |
4123 | |
4124 | ParameterABI getParameterABI(unsigned I) const { |
4125 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4125, __PRETTY_FUNCTION__)); |
4126 | if (hasExtParameterInfos()) |
4127 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4128 | return ParameterABI::Ordinary; |
4129 | } |
4130 | |
4131 | bool isParamConsumed(unsigned I) const { |
4132 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4132, __PRETTY_FUNCTION__)); |
4133 | if (hasExtParameterInfos()) |
4134 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4135 | return false; |
4136 | } |
4137 | |
4138 | bool isSugared() const { return false; } |
4139 | QualType desugar() const { return QualType(this, 0); } |
4140 | |
4141 | void printExceptionSpecification(raw_ostream &OS, |
4142 | const PrintingPolicy &Policy) const; |
4143 | |
4144 | static bool classof(const Type *T) { |
4145 | return T->getTypeClass() == FunctionProto; |
4146 | } |
4147 | |
4148 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
4149 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
4150 | param_type_iterator ArgTys, unsigned NumArgs, |
4151 | const ExtProtoInfo &EPI, const ASTContext &Context, |
4152 | bool Canonical); |
4153 | }; |
4154 | |
4155 | /// Represents the dependent type named by a dependently-scoped |
4156 | /// typename using declaration, e.g. |
4157 | /// using typename Base<T>::foo; |
4158 | /// |
4159 | /// Template instantiation turns these into the underlying type. |
4160 | class UnresolvedUsingType : public Type { |
4161 | friend class ASTContext; // ASTContext creates these. |
4162 | |
4163 | UnresolvedUsingTypenameDecl *Decl; |
4164 | |
4165 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
4166 | : Type(UnresolvedUsing, QualType(), true, true, false, |
4167 | /*ContainsUnexpandedParameterPack=*/false), |
4168 | Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {} |
4169 | |
4170 | public: |
4171 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
4172 | |
4173 | bool isSugared() const { return false; } |
4174 | QualType desugar() const { return QualType(this, 0); } |
4175 | |
4176 | static bool classof(const Type *T) { |
4177 | return T->getTypeClass() == UnresolvedUsing; |
4178 | } |
4179 | |
4180 | void Profile(llvm::FoldingSetNodeID &ID) { |
4181 | return Profile(ID, Decl); |
4182 | } |
4183 | |
4184 | static void Profile(llvm::FoldingSetNodeID &ID, |
4185 | UnresolvedUsingTypenameDecl *D) { |
4186 | ID.AddPointer(D); |
4187 | } |
4188 | }; |
4189 | |
4190 | class TypedefType : public Type { |
4191 | TypedefNameDecl *Decl; |
4192 | |
4193 | protected: |
4194 | friend class ASTContext; // ASTContext creates these. |
4195 | |
4196 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can) |
4197 | : Type(tc, can, can->isDependentType(), |
4198 | can->isInstantiationDependentType(), |
4199 | can->isVariablyModifiedType(), |
4200 | /*ContainsUnexpandedParameterPack=*/false), |
4201 | Decl(const_cast<TypedefNameDecl*>(D)) { |
4202 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4202, __PRETTY_FUNCTION__)); |
4203 | } |
4204 | |
4205 | public: |
4206 | TypedefNameDecl *getDecl() const { return Decl; } |
4207 | |
4208 | bool isSugared() const { return true; } |
4209 | QualType desugar() const; |
4210 | |
4211 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
4212 | }; |
4213 | |
4214 | /// Sugar type that represents a type that was qualified by a qualifier written |
4215 | /// as a macro invocation. |
4216 | class MacroQualifiedType : public Type { |
4217 | friend class ASTContext; // ASTContext creates these. |
4218 | |
4219 | QualType UnderlyingTy; |
4220 | const IdentifierInfo *MacroII; |
4221 | |
4222 | MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, |
4223 | const IdentifierInfo *MacroII) |
4224 | : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(), |
4225 | UnderlyingTy->isInstantiationDependentType(), |
4226 | UnderlyingTy->isVariablyModifiedType(), |
4227 | UnderlyingTy->containsUnexpandedParameterPack()), |
4228 | UnderlyingTy(UnderlyingTy), MacroII(MacroII) { |
4229 | assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4230, __PRETTY_FUNCTION__)) |
4230 | "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4230, __PRETTY_FUNCTION__)); |
4231 | } |
4232 | |
4233 | public: |
4234 | const IdentifierInfo *getMacroIdentifier() const { return MacroII; } |
4235 | QualType getUnderlyingType() const { return UnderlyingTy; } |
4236 | |
4237 | /// Return this attributed type's modified type with no qualifiers attached to |
4238 | /// it. |
4239 | QualType getModifiedType() const; |
4240 | |
4241 | bool isSugared() const { return true; } |
4242 | QualType desugar() const; |
4243 | |
4244 | static bool classof(const Type *T) { |
4245 | return T->getTypeClass() == MacroQualified; |
4246 | } |
4247 | }; |
4248 | |
4249 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
4250 | class TypeOfExprType : public Type { |
4251 | Expr *TOExpr; |
4252 | |
4253 | protected: |
4254 | friend class ASTContext; // ASTContext creates these. |
4255 | |
4256 | TypeOfExprType(Expr *E, QualType can = QualType()); |
4257 | |
4258 | public: |
4259 | Expr *getUnderlyingExpr() const { return TOExpr; } |
4260 | |
4261 | /// Remove a single level of sugar. |
4262 | QualType desugar() const; |
4263 | |
4264 | /// Returns whether this type directly provides sugar. |
4265 | bool isSugared() const; |
4266 | |
4267 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
4268 | }; |
4269 | |
4270 | /// Internal representation of canonical, dependent |
4271 | /// `typeof(expr)` types. |
4272 | /// |
4273 | /// This class is used internally by the ASTContext to manage |
4274 | /// canonical, dependent types, only. Clients will only see instances |
4275 | /// of this class via TypeOfExprType nodes. |
4276 | class DependentTypeOfExprType |
4277 | : public TypeOfExprType, public llvm::FoldingSetNode { |
4278 | const ASTContext &Context; |
4279 | |
4280 | public: |
4281 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
4282 | : TypeOfExprType(E), Context(Context) {} |
4283 | |
4284 | void Profile(llvm::FoldingSetNodeID &ID) { |
4285 | Profile(ID, Context, getUnderlyingExpr()); |
4286 | } |
4287 | |
4288 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4289 | Expr *E); |
4290 | }; |
4291 | |
4292 | /// Represents `typeof(type)`, a GCC extension. |
4293 | class TypeOfType : public Type { |
4294 | friend class ASTContext; // ASTContext creates these. |
4295 | |
4296 | QualType TOType; |
4297 | |
4298 | TypeOfType(QualType T, QualType can) |
4299 | : Type(TypeOf, can, T->isDependentType(), |
4300 | T->isInstantiationDependentType(), |
4301 | T->isVariablyModifiedType(), |
4302 | T->containsUnexpandedParameterPack()), |
4303 | TOType(T) { |
4304 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4304, __PRETTY_FUNCTION__)); |
4305 | } |
4306 | |
4307 | public: |
4308 | QualType getUnderlyingType() const { return TOType; } |
4309 | |
4310 | /// Remove a single level of sugar. |
4311 | QualType desugar() const { return getUnderlyingType(); } |
4312 | |
4313 | /// Returns whether this type directly provides sugar. |
4314 | bool isSugared() const { return true; } |
4315 | |
4316 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
4317 | }; |
4318 | |
4319 | /// Represents the type `decltype(expr)` (C++11). |
4320 | class DecltypeType : public Type { |
4321 | Expr *E; |
4322 | QualType UnderlyingType; |
4323 | |
4324 | protected: |
4325 | friend class ASTContext; // ASTContext creates these. |
4326 | |
4327 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
4328 | |
4329 | public: |
4330 | Expr *getUnderlyingExpr() const { return E; } |
4331 | QualType getUnderlyingType() const { return UnderlyingType; } |
4332 | |
4333 | /// Remove a single level of sugar. |
4334 | QualType desugar() const; |
4335 | |
4336 | /// Returns whether this type directly provides sugar. |
4337 | bool isSugared() const; |
4338 | |
4339 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
4340 | }; |
4341 | |
4342 | /// Internal representation of canonical, dependent |
4343 | /// decltype(expr) types. |
4344 | /// |
4345 | /// This class is used internally by the ASTContext to manage |
4346 | /// canonical, dependent types, only. Clients will only see instances |
4347 | /// of this class via DecltypeType nodes. |
4348 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
4349 | const ASTContext &Context; |
4350 | |
4351 | public: |
4352 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
4353 | |
4354 | void Profile(llvm::FoldingSetNodeID &ID) { |
4355 | Profile(ID, Context, getUnderlyingExpr()); |
4356 | } |
4357 | |
4358 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4359 | Expr *E); |
4360 | }; |
4361 | |
4362 | /// A unary type transform, which is a type constructed from another. |
4363 | class UnaryTransformType : public Type { |
4364 | public: |
4365 | enum UTTKind { |
4366 | EnumUnderlyingType |
4367 | }; |
4368 | |
4369 | private: |
4370 | /// The untransformed type. |
4371 | QualType BaseType; |
4372 | |
4373 | /// The transformed type if not dependent, otherwise the same as BaseType. |
4374 | QualType UnderlyingType; |
4375 | |
4376 | UTTKind UKind; |
4377 | |
4378 | protected: |
4379 | friend class ASTContext; |
4380 | |
4381 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
4382 | QualType CanonicalTy); |
4383 | |
4384 | public: |
4385 | bool isSugared() const { return !isDependentType(); } |
4386 | QualType desugar() const { return UnderlyingType; } |
4387 | |
4388 | QualType getUnderlyingType() const { return UnderlyingType; } |
4389 | QualType getBaseType() const { return BaseType; } |
4390 | |
4391 | UTTKind getUTTKind() const { return UKind; } |
4392 | |
4393 | static bool classof(const Type *T) { |
4394 | return T->getTypeClass() == UnaryTransform; |
4395 | } |
4396 | }; |
4397 | |
4398 | /// Internal representation of canonical, dependent |
4399 | /// __underlying_type(type) types. |
4400 | /// |
4401 | /// This class is used internally by the ASTContext to manage |
4402 | /// canonical, dependent types, only. Clients will only see instances |
4403 | /// of this class via UnaryTransformType nodes. |
4404 | class DependentUnaryTransformType : public UnaryTransformType, |
4405 | public llvm::FoldingSetNode { |
4406 | public: |
4407 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
4408 | UTTKind UKind); |
4409 | |
4410 | void Profile(llvm::FoldingSetNodeID &ID) { |
4411 | Profile(ID, getBaseType(), getUTTKind()); |
4412 | } |
4413 | |
4414 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
4415 | UTTKind UKind) { |
4416 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
4417 | ID.AddInteger((unsigned)UKind); |
4418 | } |
4419 | }; |
4420 | |
4421 | class TagType : public Type { |
4422 | friend class ASTReader; |
4423 | |
4424 | /// Stores the TagDecl associated with this type. The decl may point to any |
4425 | /// TagDecl that declares the entity. |
4426 | TagDecl *decl; |
4427 | |
4428 | protected: |
4429 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
4430 | |
4431 | public: |
4432 | TagDecl *getDecl() const; |
4433 | |
4434 | /// Determines whether this type is in the process of being defined. |
4435 | bool isBeingDefined() const; |
4436 | |
4437 | static bool classof(const Type *T) { |
4438 | return T->getTypeClass() == Enum || T->getTypeClass() == Record; |
4439 | } |
4440 | }; |
4441 | |
4442 | /// A helper class that allows the use of isa/cast/dyncast |
4443 | /// to detect TagType objects of structs/unions/classes. |
4444 | class RecordType : public TagType { |
4445 | protected: |
4446 | friend class ASTContext; // ASTContext creates these. |
4447 | |
4448 | explicit RecordType(const RecordDecl *D) |
4449 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4450 | explicit RecordType(TypeClass TC, RecordDecl *D) |
4451 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4452 | |
4453 | public: |
4454 | RecordDecl *getDecl() const { |
4455 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
4456 | } |
4457 | |
4458 | /// Recursively check all fields in the record for const-ness. If any field |
4459 | /// is declared const, return true. Otherwise, return false. |
4460 | bool hasConstFields() const; |
4461 | |
4462 | bool isSugared() const { return false; } |
4463 | QualType desugar() const { return QualType(this, 0); } |
4464 | |
4465 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4466 | }; |
4467 | |
4468 | /// A helper class that allows the use of isa/cast/dyncast |
4469 | /// to detect TagType objects of enums. |
4470 | class EnumType : public TagType { |
4471 | friend class ASTContext; // ASTContext creates these. |
4472 | |
4473 | explicit EnumType(const EnumDecl *D) |
4474 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4475 | |
4476 | public: |
4477 | EnumDecl *getDecl() const { |
4478 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4479 | } |
4480 | |
4481 | bool isSugared() const { return false; } |
4482 | QualType desugar() const { return QualType(this, 0); } |
4483 | |
4484 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4485 | }; |
4486 | |
4487 | /// An attributed type is a type to which a type attribute has been applied. |
4488 | /// |
4489 | /// The "modified type" is the fully-sugared type to which the attributed |
4490 | /// type was applied; generally it is not canonically equivalent to the |
4491 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4492 | /// which the type is canonically equivalent to. |
4493 | /// |
4494 | /// For example, in the following attributed type: |
4495 | /// int32_t __attribute__((vector_size(16))) |
4496 | /// - the modified type is the TypedefType for int32_t |
4497 | /// - the equivalent type is VectorType(16, int32_t) |
4498 | /// - the canonical type is VectorType(16, int) |
4499 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4500 | public: |
4501 | using Kind = attr::Kind; |
4502 | |
4503 | private: |
4504 | friend class ASTContext; // ASTContext creates these |
4505 | |
4506 | QualType ModifiedType; |
4507 | QualType EquivalentType; |
4508 | |
4509 | AttributedType(QualType canon, attr::Kind attrKind, QualType modified, |
4510 | QualType equivalent) |
4511 | : Type(Attributed, canon, equivalent->isDependentType(), |
4512 | equivalent->isInstantiationDependentType(), |
4513 | equivalent->isVariablyModifiedType(), |
4514 | equivalent->containsUnexpandedParameterPack()), |
4515 | ModifiedType(modified), EquivalentType(equivalent) { |
4516 | AttributedTypeBits.AttrKind = attrKind; |
4517 | } |
4518 | |
4519 | public: |
4520 | Kind getAttrKind() const { |
4521 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4522 | } |
4523 | |
4524 | QualType getModifiedType() const { return ModifiedType; } |
4525 | QualType getEquivalentType() const { return EquivalentType; } |
4526 | |
4527 | bool isSugared() const { return true; } |
4528 | QualType desugar() const { return getEquivalentType(); } |
4529 | |
4530 | /// Does this attribute behave like a type qualifier? |
4531 | /// |
4532 | /// A type qualifier adjusts a type to provide specialized rules for |
4533 | /// a specific object, like the standard const and volatile qualifiers. |
4534 | /// This includes attributes controlling things like nullability, |
4535 | /// address spaces, and ARC ownership. The value of the object is still |
4536 | /// largely described by the modified type. |
4537 | /// |
4538 | /// In contrast, many type attributes "rewrite" their modified type to |
4539 | /// produce a fundamentally different type, not necessarily related in any |
4540 | /// formalizable way to the original type. For example, calling convention |
4541 | /// and vector attributes are not simple type qualifiers. |
4542 | /// |
4543 | /// Type qualifiers are often, but not always, reflected in the canonical |
4544 | /// type. |
4545 | bool isQualifier() const; |
4546 | |
4547 | bool isMSTypeSpec() const; |
4548 | |
4549 | bool isCallingConv() const; |
4550 | |
4551 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4552 | |
4553 | /// Retrieve the attribute kind corresponding to the given |
4554 | /// nullability kind. |
4555 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4556 | switch (kind) { |
4557 | case NullabilityKind::NonNull: |
4558 | return attr::TypeNonNull; |
4559 | |
4560 | case NullabilityKind::Nullable: |
4561 | return attr::TypeNullable; |
4562 | |
4563 | case NullabilityKind::Unspecified: |
4564 | return attr::TypeNullUnspecified; |
4565 | } |
4566 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4566); |
4567 | } |
4568 | |
4569 | /// Strip off the top-level nullability annotation on the given |
4570 | /// type, if it's there. |
4571 | /// |
4572 | /// \param T The type to strip. If the type is exactly an |
4573 | /// AttributedType specifying nullability (without looking through |
4574 | /// type sugar), the nullability is returned and this type changed |
4575 | /// to the underlying modified type. |
4576 | /// |
4577 | /// \returns the top-level nullability, if present. |
4578 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4579 | |
4580 | void Profile(llvm::FoldingSetNodeID &ID) { |
4581 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4582 | } |
4583 | |
4584 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4585 | QualType modified, QualType equivalent) { |
4586 | ID.AddInteger(attrKind); |
4587 | ID.AddPointer(modified.getAsOpaquePtr()); |
4588 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4589 | } |
4590 | |
4591 | static bool classof(const Type *T) { |
4592 | return T->getTypeClass() == Attributed; |
4593 | } |
4594 | }; |
4595 | |
4596 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4597 | friend class ASTContext; // ASTContext creates these |
4598 | |
4599 | // Helper data collector for canonical types. |
4600 | struct CanonicalTTPTInfo { |
4601 | unsigned Depth : 15; |
4602 | unsigned ParameterPack : 1; |
4603 | unsigned Index : 16; |
4604 | }; |
4605 | |
4606 | union { |
4607 | // Info for the canonical type. |
4608 | CanonicalTTPTInfo CanTTPTInfo; |
4609 | |
4610 | // Info for the non-canonical type. |
4611 | TemplateTypeParmDecl *TTPDecl; |
4612 | }; |
4613 | |
4614 | /// Build a non-canonical type. |
4615 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4616 | : Type(TemplateTypeParm, Canon, /*Dependent=*/true, |
4617 | /*InstantiationDependent=*/true, |
4618 | /*VariablyModified=*/false, |
4619 | Canon->containsUnexpandedParameterPack()), |
4620 | TTPDecl(TTPDecl) {} |
4621 | |
4622 | /// Build the canonical type. |
4623 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4624 | : Type(TemplateTypeParm, QualType(this, 0), |
4625 | /*Dependent=*/true, |
4626 | /*InstantiationDependent=*/true, |
4627 | /*VariablyModified=*/false, PP) { |
4628 | CanTTPTInfo.Depth = D; |
4629 | CanTTPTInfo.Index = I; |
4630 | CanTTPTInfo.ParameterPack = PP; |
4631 | } |
4632 | |
4633 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4634 | QualType Can = getCanonicalTypeInternal(); |
4635 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4636 | } |
4637 | |
4638 | public: |
4639 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4640 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4641 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4642 | |
4643 | TemplateTypeParmDecl *getDecl() const { |
4644 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4645 | } |
4646 | |
4647 | IdentifierInfo *getIdentifier() const; |
4648 | |
4649 | bool isSugared() const { return false; } |
4650 | QualType desugar() const { return QualType(this, 0); } |
4651 | |
4652 | void Profile(llvm::FoldingSetNodeID &ID) { |
4653 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4654 | } |
4655 | |
4656 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4657 | unsigned Index, bool ParameterPack, |
4658 | TemplateTypeParmDecl *TTPDecl) { |
4659 | ID.AddInteger(Depth); |
4660 | ID.AddInteger(Index); |
4661 | ID.AddBoolean(ParameterPack); |
4662 | ID.AddPointer(TTPDecl); |
4663 | } |
4664 | |
4665 | static bool classof(const Type *T) { |
4666 | return T->getTypeClass() == TemplateTypeParm; |
4667 | } |
4668 | }; |
4669 | |
4670 | /// Represents the result of substituting a type for a template |
4671 | /// type parameter. |
4672 | /// |
4673 | /// Within an instantiated template, all template type parameters have |
4674 | /// been replaced with these. They are used solely to record that a |
4675 | /// type was originally written as a template type parameter; |
4676 | /// therefore they are never canonical. |
4677 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4678 | friend class ASTContext; |
4679 | |
4680 | // The original type parameter. |
4681 | const TemplateTypeParmType *Replaced; |
4682 | |
4683 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4684 | : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(), |
4685 | Canon->isInstantiationDependentType(), |
4686 | Canon->isVariablyModifiedType(), |
4687 | Canon->containsUnexpandedParameterPack()), |
4688 | Replaced(Param) {} |
4689 | |
4690 | public: |
4691 | /// Gets the template parameter that was substituted for. |
4692 | const TemplateTypeParmType *getReplacedParameter() const { |
4693 | return Replaced; |
4694 | } |
4695 | |
4696 | /// Gets the type that was substituted for the template |
4697 | /// parameter. |
4698 | QualType getReplacementType() const { |
4699 | return getCanonicalTypeInternal(); |
4700 | } |
4701 | |
4702 | bool isSugared() const { return true; } |
4703 | QualType desugar() const { return getReplacementType(); } |
4704 | |
4705 | void Profile(llvm::FoldingSetNodeID &ID) { |
4706 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4707 | } |
4708 | |
4709 | static void Profile(llvm::FoldingSetNodeID &ID, |
4710 | const TemplateTypeParmType *Replaced, |
4711 | QualType Replacement) { |
4712 | ID.AddPointer(Replaced); |
4713 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4714 | } |
4715 | |
4716 | static bool classof(const Type *T) { |
4717 | return T->getTypeClass() == SubstTemplateTypeParm; |
4718 | } |
4719 | }; |
4720 | |
4721 | /// Represents the result of substituting a set of types for a template |
4722 | /// type parameter pack. |
4723 | /// |
4724 | /// When a pack expansion in the source code contains multiple parameter packs |
4725 | /// and those parameter packs correspond to different levels of template |
4726 | /// parameter lists, this type node is used to represent a template type |
4727 | /// parameter pack from an outer level, which has already had its argument pack |
4728 | /// substituted but that still lives within a pack expansion that itself |
4729 | /// could not be instantiated. When actually performing a substitution into |
4730 | /// that pack expansion (e.g., when all template parameters have corresponding |
4731 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4732 | /// at the current pack substitution index. |
4733 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4734 | friend class ASTContext; |
4735 | |
4736 | /// The original type parameter. |
4737 | const TemplateTypeParmType *Replaced; |
4738 | |
4739 | /// A pointer to the set of template arguments that this |
4740 | /// parameter pack is instantiated with. |
4741 | const TemplateArgument *Arguments; |
4742 | |
4743 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4744 | QualType Canon, |
4745 | const TemplateArgument &ArgPack); |
4746 | |
4747 | public: |
4748 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4749 | |
4750 | /// Gets the template parameter that was substituted for. |
4751 | const TemplateTypeParmType *getReplacedParameter() const { |
4752 | return Replaced; |
4753 | } |
4754 | |
4755 | unsigned getNumArgs() const { |
4756 | return SubstTemplateTypeParmPackTypeBits.NumArgs; |
4757 | } |
4758 | |
4759 | bool isSugared() const { return false; } |
4760 | QualType desugar() const { return QualType(this, 0); } |
4761 | |
4762 | TemplateArgument getArgumentPack() const; |
4763 | |
4764 | void Profile(llvm::FoldingSetNodeID &ID); |
4765 | static void Profile(llvm::FoldingSetNodeID &ID, |
4766 | const TemplateTypeParmType *Replaced, |
4767 | const TemplateArgument &ArgPack); |
4768 | |
4769 | static bool classof(const Type *T) { |
4770 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4771 | } |
4772 | }; |
4773 | |
4774 | /// Common base class for placeholders for types that get replaced by |
4775 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4776 | /// class template types, and (eventually) constrained type names from the C++ |
4777 | /// Concepts TS. |
4778 | /// |
4779 | /// These types are usually a placeholder for a deduced type. However, before |
4780 | /// the initializer is attached, or (usually) if the initializer is |
4781 | /// type-dependent, there is no deduced type and the type is canonical. In |
4782 | /// the latter case, it is also a dependent type. |
4783 | class DeducedType : public Type { |
4784 | protected: |
4785 | DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent, |
4786 | bool IsInstantiationDependent, bool ContainsParameterPack) |
4787 | : Type(TC, |
4788 | // FIXME: Retain the sugared deduced type? |
4789 | DeducedAsType.isNull() ? QualType(this, 0) |
4790 | : DeducedAsType.getCanonicalType(), |
4791 | IsDependent, IsInstantiationDependent, |
4792 | /*VariablyModified=*/false, ContainsParameterPack) { |
4793 | if (!DeducedAsType.isNull()) { |
4794 | if (DeducedAsType->isDependentType()) |
4795 | setDependent(); |
4796 | if (DeducedAsType->isInstantiationDependentType()) |
4797 | setInstantiationDependent(); |
4798 | if (DeducedAsType->containsUnexpandedParameterPack()) |
4799 | setContainsUnexpandedParameterPack(); |
4800 | } |
4801 | } |
4802 | |
4803 | public: |
4804 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4805 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4806 | |
4807 | /// Get the type deduced for this placeholder type, or null if it's |
4808 | /// either not been deduced or was deduced to a dependent type. |
4809 | QualType getDeducedType() const { |
4810 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4811 | } |
4812 | bool isDeduced() const { |
4813 | return !isCanonicalUnqualified() || isDependentType(); |
4814 | } |
4815 | |
4816 | static bool classof(const Type *T) { |
4817 | return T->getTypeClass() == Auto || |
4818 | T->getTypeClass() == DeducedTemplateSpecialization; |
4819 | } |
4820 | }; |
4821 | |
4822 | /// Represents a C++11 auto or C++14 decltype(auto) type. |
4823 | class AutoType : public DeducedType, public llvm::FoldingSetNode { |
4824 | friend class ASTContext; // ASTContext creates these |
4825 | |
4826 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4827 | bool IsDeducedAsDependent, bool IsDeducedAsPack) |
4828 | : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent, |
4829 | IsDeducedAsDependent, IsDeducedAsPack) { |
4830 | AutoTypeBits.Keyword = (unsigned)Keyword; |
4831 | } |
4832 | |
4833 | public: |
4834 | bool isDecltypeAuto() const { |
4835 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
4836 | } |
4837 | |
4838 | AutoTypeKeyword getKeyword() const { |
4839 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
4840 | } |
4841 | |
4842 | void Profile(llvm::FoldingSetNodeID &ID) { |
4843 | Profile(ID, getDeducedType(), getKeyword(), isDependentType(), |
4844 | containsUnexpandedParameterPack()); |
4845 | } |
4846 | |
4847 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced, |
4848 | AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) { |
4849 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4850 | ID.AddInteger((unsigned)Keyword); |
4851 | ID.AddBoolean(IsDependent); |
4852 | ID.AddBoolean(IsPack); |
4853 | } |
4854 | |
4855 | static bool classof(const Type *T) { |
4856 | return T->getTypeClass() == Auto; |
4857 | } |
4858 | }; |
4859 | |
4860 | /// Represents a C++17 deduced template specialization type. |
4861 | class DeducedTemplateSpecializationType : public DeducedType, |
4862 | public llvm::FoldingSetNode { |
4863 | friend class ASTContext; // ASTContext creates these |
4864 | |
4865 | /// The name of the template whose arguments will be deduced. |
4866 | TemplateName Template; |
4867 | |
4868 | DeducedTemplateSpecializationType(TemplateName Template, |
4869 | QualType DeducedAsType, |
4870 | bool IsDeducedAsDependent) |
4871 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
4872 | IsDeducedAsDependent || Template.isDependent(), |
4873 | IsDeducedAsDependent || Template.isInstantiationDependent(), |
4874 | Template.containsUnexpandedParameterPack()), |
4875 | Template(Template) {} |
4876 | |
4877 | public: |
4878 | /// Retrieve the name of the template that we are deducing. |
4879 | TemplateName getTemplateName() const { return Template;} |
4880 | |
4881 | void Profile(llvm::FoldingSetNodeID &ID) { |
4882 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
4883 | } |
4884 | |
4885 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
4886 | QualType Deduced, bool IsDependent) { |
4887 | Template.Profile(ID); |
4888 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4889 | ID.AddBoolean(IsDependent); |
4890 | } |
4891 | |
4892 | static bool classof(const Type *T) { |
4893 | return T->getTypeClass() == DeducedTemplateSpecialization; |
4894 | } |
4895 | }; |
4896 | |
4897 | /// Represents a type template specialization; the template |
4898 | /// must be a class template, a type alias template, or a template |
4899 | /// template parameter. A template which cannot be resolved to one of |
4900 | /// these, e.g. because it is written with a dependent scope |
4901 | /// specifier, is instead represented as a |
4902 | /// @c DependentTemplateSpecializationType. |
4903 | /// |
4904 | /// A non-dependent template specialization type is always "sugar", |
4905 | /// typically for a \c RecordType. For example, a class template |
4906 | /// specialization type of \c vector<int> will refer to a tag type for |
4907 | /// the instantiation \c std::vector<int, std::allocator<int>> |
4908 | /// |
4909 | /// Template specializations are dependent if either the template or |
4910 | /// any of the template arguments are dependent, in which case the |
4911 | /// type may also be canonical. |
4912 | /// |
4913 | /// Instances of this type are allocated with a trailing array of |
4914 | /// TemplateArguments, followed by a QualType representing the |
4915 | /// non-canonical aliased type when the template is a type alias |
4916 | /// template. |
4917 | class alignas(8) TemplateSpecializationType |
4918 | : public Type, |
4919 | public llvm::FoldingSetNode { |
4920 | friend class ASTContext; // ASTContext creates these |
4921 | |
4922 | /// The name of the template being specialized. This is |
4923 | /// either a TemplateName::Template (in which case it is a |
4924 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
4925 | /// TypeAliasTemplateDecl*), a |
4926 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
4927 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
4928 | /// replacement must, recursively, be one of these). |
4929 | TemplateName Template; |
4930 | |
4931 | TemplateSpecializationType(TemplateName T, |
4932 | ArrayRef<TemplateArgument> Args, |
4933 | QualType Canon, |
4934 | QualType Aliased); |
4935 | |
4936 | public: |
4937 | /// Determine whether any of the given template arguments are dependent. |
4938 | static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
4939 | bool &InstantiationDependent); |
4940 | |
4941 | static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
4942 | bool &InstantiationDependent); |
4943 | |
4944 | /// True if this template specialization type matches a current |
4945 | /// instantiation in the context in which it is found. |
4946 | bool isCurrentInstantiation() const { |
4947 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
4948 | } |
4949 | |
4950 | /// Determine if this template specialization type is for a type alias |
4951 | /// template that has been substituted. |
4952 | /// |
4953 | /// Nearly every template specialization type whose template is an alias |
4954 | /// template will be substituted. However, this is not the case when |
4955 | /// the specialization contains a pack expansion but the template alias |
4956 | /// does not have a corresponding parameter pack, e.g., |
4957 | /// |
4958 | /// \code |
4959 | /// template<typename T, typename U, typename V> struct S; |
4960 | /// template<typename T, typename U> using A = S<T, int, U>; |
4961 | /// template<typename... Ts> struct X { |
4962 | /// typedef A<Ts...> type; // not a type alias |
4963 | /// }; |
4964 | /// \endcode |
4965 | bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } |
4966 | |
4967 | /// Get the aliased type, if this is a specialization of a type alias |
4968 | /// template. |
4969 | QualType getAliasedType() const { |
4970 | assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization" ) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4970, __PRETTY_FUNCTION__)); |
4971 | return *reinterpret_cast<const QualType*>(end()); |
4972 | } |
4973 | |
4974 | using iterator = const TemplateArgument *; |
4975 | |
4976 | iterator begin() const { return getArgs(); } |
4977 | iterator end() const; // defined inline in TemplateBase.h |
4978 | |
4979 | /// Retrieve the name of the template that we are specializing. |
4980 | TemplateName getTemplateName() const { return Template; } |
4981 | |
4982 | /// Retrieve the template arguments. |
4983 | const TemplateArgument *getArgs() const { |
4984 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
4985 | } |
4986 | |
4987 | /// Retrieve the number of template arguments. |
4988 | unsigned getNumArgs() const { |
4989 | return TemplateSpecializationTypeBits.NumArgs; |
4990 | } |
4991 | |
4992 | /// Retrieve a specific template argument as a type. |
4993 | /// \pre \c isArgType(Arg) |
4994 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
4995 | |
4996 | ArrayRef<TemplateArgument> template_arguments() const { |
4997 | return {getArgs(), getNumArgs()}; |
4998 | } |
4999 | |
5000 | bool isSugared() const { |
5001 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
5002 | } |
5003 | |
5004 | QualType desugar() const { |
5005 | return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); |
5006 | } |
5007 | |
5008 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
5009 | Profile(ID, Template, template_arguments(), Ctx); |
5010 | if (isTypeAlias()) |
5011 | getAliasedType().Profile(ID); |
5012 | } |
5013 | |
5014 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
5015 | ArrayRef<TemplateArgument> Args, |
5016 | const ASTContext &Context); |
5017 | |
5018 | static bool classof(const Type *T) { |
5019 | return T->getTypeClass() == TemplateSpecialization; |
5020 | } |
5021 | }; |
5022 | |
5023 | /// Print a template argument list, including the '<' and '>' |
5024 | /// enclosing the template arguments. |
5025 | void printTemplateArgumentList(raw_ostream &OS, |
5026 | ArrayRef<TemplateArgument> Args, |
5027 | const PrintingPolicy &Policy); |
5028 | |
5029 | void printTemplateArgumentList(raw_ostream &OS, |
5030 | ArrayRef<TemplateArgumentLoc> Args, |
5031 | const PrintingPolicy &Policy); |
5032 | |
5033 | void printTemplateArgumentList(raw_ostream &OS, |
5034 | const TemplateArgumentListInfo &Args, |
5035 | const PrintingPolicy &Policy); |
5036 | |
5037 | /// The injected class name of a C++ class template or class |
5038 | /// template partial specialization. Used to record that a type was |
5039 | /// spelled with a bare identifier rather than as a template-id; the |
5040 | /// equivalent for non-templated classes is just RecordType. |
5041 | /// |
5042 | /// Injected class name types are always dependent. Template |
5043 | /// instantiation turns these into RecordTypes. |
5044 | /// |
5045 | /// Injected class name types are always canonical. This works |
5046 | /// because it is impossible to compare an injected class name type |
5047 | /// with the corresponding non-injected template type, for the same |
5048 | /// reason that it is impossible to directly compare template |
5049 | /// parameters from different dependent contexts: injected class name |
5050 | /// types can only occur within the scope of a particular templated |
5051 | /// declaration, and within that scope every template specialization |
5052 | /// will canonicalize to the injected class name (when appropriate |
5053 | /// according to the rules of the language). |
5054 | class InjectedClassNameType : public Type { |
5055 | friend class ASTContext; // ASTContext creates these. |
5056 | friend class ASTNodeImporter; |
5057 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
5058 | // currently suitable for AST reading, too much |
5059 | // interdependencies. |
5060 | |
5061 | CXXRecordDecl *Decl; |
5062 | |
5063 | /// The template specialization which this type represents. |
5064 | /// For example, in |
5065 | /// template <class T> class A { ... }; |
5066 | /// this is A<T>, whereas in |
5067 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
5068 | /// this is A<B<X,Y> >. |
5069 | /// |
5070 | /// It is always unqualified, always a template specialization type, |
5071 | /// and always dependent. |
5072 | QualType InjectedType; |
5073 | |
5074 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
5075 | : Type(InjectedClassName, QualType(), /*Dependent=*/true, |
5076 | /*InstantiationDependent=*/true, |
5077 | /*VariablyModified=*/false, |
5078 | /*ContainsUnexpandedParameterPack=*/false), |
5079 | Decl(D), InjectedType(TST) { |
5080 | assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast< void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5080, __PRETTY_FUNCTION__)); |
5081 | assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5081, __PRETTY_FUNCTION__)); |
5082 | assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5082, __PRETTY_FUNCTION__)); |
5083 | } |
5084 | |
5085 | public: |
5086 | QualType getInjectedSpecializationType() const { return InjectedType; } |
5087 | |
5088 | const TemplateSpecializationType *getInjectedTST() const { |
5089 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
5090 | } |
5091 | |
5092 | TemplateName getTemplateName() const { |
5093 | return getInjectedTST()->getTemplateName(); |
5094 | } |
5095 | |
5096 | CXXRecordDecl *getDecl() const; |
5097 | |
5098 | bool isSugared() const { return false; } |
5099 | QualType desugar() const { return QualType(this, 0); } |
5100 | |
5101 | static bool classof(const Type *T) { |
5102 | return T->getTypeClass() == InjectedClassName; |
5103 | } |
5104 | }; |
5105 | |
5106 | /// The kind of a tag type. |
5107 | enum TagTypeKind { |
5108 | /// The "struct" keyword. |
5109 | TTK_Struct, |
5110 | |
5111 | /// The "__interface" keyword. |
5112 | TTK_Interface, |
5113 | |
5114 | /// The "union" keyword. |
5115 | TTK_Union, |
5116 | |
5117 | /// The "class" keyword. |
5118 | TTK_Class, |
5119 | |
5120 | /// The "enum" keyword. |
5121 | TTK_Enum |
5122 | }; |
5123 | |
5124 | /// The elaboration keyword that precedes a qualified type name or |
5125 | /// introduces an elaborated-type-specifier. |
5126 | enum ElaboratedTypeKeyword { |
5127 | /// The "struct" keyword introduces the elaborated-type-specifier. |
5128 | ETK_Struct, |
5129 | |
5130 | /// The "__interface" keyword introduces the elaborated-type-specifier. |
5131 | ETK_Interface, |
5132 | |
5133 | /// The "union" keyword introduces the elaborated-type-specifier. |
5134 | ETK_Union, |
5135 | |
5136 | /// The "class" keyword introduces the elaborated-type-specifier. |
5137 | ETK_Class, |
5138 | |
5139 | /// The "enum" keyword introduces the elaborated-type-specifier. |
5140 | ETK_Enum, |
5141 | |
5142 | /// The "typename" keyword precedes the qualified type name, e.g., |
5143 | /// \c typename T::type. |
5144 | ETK_Typename, |
5145 | |
5146 | /// No keyword precedes the qualified type name. |
5147 | ETK_None |
5148 | }; |
5149 | |
5150 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
5151 | /// The keyword in stored in the free bits of the base class. |
5152 | /// Also provides a few static helpers for converting and printing |
5153 | /// elaborated type keyword and tag type kind enumerations. |
5154 | class TypeWithKeyword : public Type { |
5155 | protected: |
5156 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
5157 | QualType Canonical, bool Dependent, |
5158 | bool InstantiationDependent, bool VariablyModified, |
5159 | bool ContainsUnexpandedParameterPack) |
5160 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
5161 | ContainsUnexpandedParameterPack) { |
5162 | TypeWithKeywordBits.Keyword = Keyword; |
5163 | } |
5164 | |
5165 | public: |
5166 | ElaboratedTypeKeyword getKeyword() const { |
5167 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
5168 | } |
5169 | |
5170 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
5171 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
5172 | |
5173 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
5174 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
5175 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
5176 | |
5177 | /// Converts a TagTypeKind into an elaborated type keyword. |
5178 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
5179 | |
5180 | /// Converts an elaborated type keyword into a TagTypeKind. |
5181 | /// It is an error to provide an elaborated type keyword |
5182 | /// which *isn't* a tag kind here. |
5183 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
5184 | |
5185 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
5186 | |
5187 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
5188 | |
5189 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
5190 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
5191 | } |
5192 | |
5193 | class CannotCastToThisType {}; |
5194 | static CannotCastToThisType classof(const Type *); |
5195 | }; |
5196 | |
5197 | /// Represents a type that was referred to using an elaborated type |
5198 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
5199 | /// or both. |
5200 | /// |
5201 | /// This type is used to keep track of a type name as written in the |
5202 | /// source code, including tag keywords and any nested-name-specifiers. |
5203 | /// The type itself is always "sugar", used to express what was written |
5204 | /// in the source code but containing no additional semantic information. |
5205 | class ElaboratedType final |
5206 | : public TypeWithKeyword, |
5207 | public llvm::FoldingSetNode, |
5208 | private llvm::TrailingObjects<ElaboratedType, TagDecl *> { |
5209 | friend class ASTContext; // ASTContext creates these |
5210 | friend TrailingObjects; |
5211 | |
5212 | /// The nested name specifier containing the qualifier. |
5213 | NestedNameSpecifier *NNS; |
5214 | |
5215 | /// The type that this qualified name refers to. |
5216 | QualType NamedType; |
5217 | |
5218 | /// The (re)declaration of this tag type owned by this occurrence is stored |
5219 | /// as a trailing object if there is one. Use getOwnedTagDecl to obtain |
5220 | /// it, or obtain a null pointer if there is none. |
5221 | |
5222 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5223 | QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) |
5224 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
5225 | NamedType->isDependentType(), |
5226 | NamedType->isInstantiationDependentType(), |
5227 | NamedType->isVariablyModifiedType(), |
5228 | NamedType->containsUnexpandedParameterPack()), |
5229 | NNS(NNS), NamedType(NamedType) { |
5230 | ElaboratedTypeBits.HasOwnedTagDecl = false; |
5231 | if (OwnedTagDecl) { |
5232 | ElaboratedTypeBits.HasOwnedTagDecl = true; |
5233 | *getTrailingObjects<TagDecl *>() = OwnedTagDecl; |
5234 | } |
5235 | assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)) |
5236 | "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)) |
5237 | "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)); |
5238 | } |
5239 | |
5240 | public: |
5241 | /// Retrieve the qualification on this type. |
5242 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5243 | |
5244 | /// Retrieve the type named by the qualified-id. |
5245 | QualType getNamedType() const { return NamedType; } |
5246 | |
5247 | /// Remove a single level of sugar. |
5248 | QualType desugar() const { return getNamedType(); } |
5249 | |
5250 | /// Returns whether this type directly provides sugar. |
5251 | bool isSugared() const { return true; } |
5252 | |
5253 | /// Return the (re)declaration of this type owned by this occurrence of this |
5254 | /// type, or nullptr if there is none. |
5255 | TagDecl *getOwnedTagDecl() const { |
5256 | return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() |
5257 | : nullptr; |
5258 | } |
5259 | |
5260 | void Profile(llvm::FoldingSetNodeID &ID) { |
5261 | Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); |
5262 | } |
5263 | |
5264 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5265 | NestedNameSpecifier *NNS, QualType NamedType, |
5266 | TagDecl *OwnedTagDecl) { |
5267 | ID.AddInteger(Keyword); |
5268 | ID.AddPointer(NNS); |
5269 | NamedType.Profile(ID); |
5270 | ID.AddPointer(OwnedTagDecl); |
5271 | } |
5272 | |
5273 | static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } |
5274 | }; |
5275 | |
5276 | /// Represents a qualified type name for which the type name is |
5277 | /// dependent. |
5278 | /// |
5279 | /// DependentNameType represents a class of dependent types that involve a |
5280 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
5281 | /// name of a type. The DependentNameType may start with a "typename" (for a |
5282 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
5283 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
5284 | /// know that we must be referring to a type, e.g., in a base class specifier). |
5285 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
5286 | /// mode, this type is used with non-dependent names to delay name lookup until |
5287 | /// instantiation. |
5288 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
5289 | friend class ASTContext; // ASTContext creates these |
5290 | |
5291 | /// The nested name specifier containing the qualifier. |
5292 | NestedNameSpecifier *NNS; |
5293 | |
5294 | /// The type that this typename specifier refers to. |
5295 | const IdentifierInfo *Name; |
5296 | |
5297 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5298 | const IdentifierInfo *Name, QualType CanonType) |
5299 | : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true, |
5300 | /*InstantiationDependent=*/true, |
5301 | /*VariablyModified=*/false, |
5302 | NNS->containsUnexpandedParameterPack()), |
5303 | NNS(NNS), Name(Name) {} |
5304 | |
5305 | public: |
5306 | /// Retrieve the qualification on this type. |
5307 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5308 | |
5309 | /// Retrieve the type named by the typename specifier as an identifier. |
5310 | /// |
5311 | /// This routine will return a non-NULL identifier pointer when the |
5312 | /// form of the original typename was terminated by an identifier, |
5313 | /// e.g., "typename T::type". |
5314 | const IdentifierInfo *getIdentifier() const { |
5315 | return Name; |
5316 | } |
5317 | |
5318 | bool isSugared() const { return false; } |
5319 | QualType desugar() const { return QualType(this, 0); } |
5320 | |
5321 | void Profile(llvm::FoldingSetNodeID &ID) { |
5322 | Profile(ID, getKeyword(), NNS, Name); |
5323 | } |
5324 | |
5325 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5326 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
5327 | ID.AddInteger(Keyword); |
5328 | ID.AddPointer(NNS); |
5329 | ID.AddPointer(Name); |
5330 | } |
5331 | |
5332 | static bool classof(const Type *T) { |
5333 | return T->getTypeClass() == DependentName; |
5334 | } |
5335 | }; |
5336 | |
5337 | /// Represents a template specialization type whose template cannot be |
5338 | /// resolved, e.g. |
5339 | /// A<T>::template B<T> |
5340 | class alignas(8) DependentTemplateSpecializationType |
5341 | : public TypeWithKeyword, |
5342 | public llvm::FoldingSetNode { |
5343 | friend class ASTContext; // ASTContext creates these |
5344 | |
5345 | /// The nested name specifier containing the qualifier. |
5346 | NestedNameSpecifier *NNS; |
5347 | |
5348 | /// The identifier of the template. |
5349 | const IdentifierInfo *Name; |
5350 | |
5351 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
5352 | NestedNameSpecifier *NNS, |
5353 | const IdentifierInfo *Name, |
5354 | ArrayRef<TemplateArgument> Args, |
5355 | QualType Canon); |
5356 | |
5357 | const TemplateArgument *getArgBuffer() const { |
5358 | return reinterpret_cast<const TemplateArgument*>(this+1); |
5359 | } |
5360 | |
5361 | TemplateArgument *getArgBuffer() { |
5362 | return reinterpret_cast<TemplateArgument*>(this+1); |
5363 | } |
5364 | |
5365 | public: |
5366 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5367 | const IdentifierInfo *getIdentifier() const { return Name; } |
5368 | |
5369 | /// Retrieve the template arguments. |
5370 | const TemplateArgument *getArgs() const { |
5371 | return getArgBuffer(); |
5372 | } |
5373 | |
5374 | /// Retrieve the number of template arguments. |
5375 | unsigned getNumArgs() const { |
5376 | return DependentTemplateSpecializationTypeBits.NumArgs; |
5377 | } |
5378 | |
5379 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5380 | |
5381 | ArrayRef<TemplateArgument> template_arguments() const { |
5382 | return {getArgs(), getNumArgs()}; |
5383 | } |
5384 | |
5385 | using iterator = const TemplateArgument *; |
5386 | |
5387 | iterator begin() const { return getArgs(); } |
5388 | iterator end() const; // inline in TemplateBase.h |
5389 | |
5390 | bool isSugared() const { return false; } |
5391 | QualType desugar() const { return QualType(this, 0); } |
5392 | |
5393 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5394 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); |
5395 | } |
5396 | |
5397 | static void Profile(llvm::FoldingSetNodeID &ID, |
5398 | const ASTContext &Context, |
5399 | ElaboratedTypeKeyword Keyword, |
5400 | NestedNameSpecifier *Qualifier, |
5401 | const IdentifierInfo *Name, |
5402 | ArrayRef<TemplateArgument> Args); |
5403 | |
5404 | static bool classof(const Type *T) { |
5405 | return T->getTypeClass() == DependentTemplateSpecialization; |
5406 | } |
5407 | }; |
5408 | |
5409 | /// Represents a pack expansion of types. |
5410 | /// |
5411 | /// Pack expansions are part of C++11 variadic templates. A pack |
5412 | /// expansion contains a pattern, which itself contains one or more |
5413 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
5414 | /// produces a series of types, each instantiated from the pattern of |
5415 | /// the expansion, where the Ith instantiation of the pattern uses the |
5416 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
5417 | /// pack expansion is considered to "expand" these unexpanded |
5418 | /// parameter packs. |
5419 | /// |
5420 | /// \code |
5421 | /// template<typename ...Types> struct tuple; |
5422 | /// |
5423 | /// template<typename ...Types> |
5424 | /// struct tuple_of_references { |
5425 | /// typedef tuple<Types&...> type; |
5426 | /// }; |
5427 | /// \endcode |
5428 | /// |
5429 | /// Here, the pack expansion \c Types&... is represented via a |
5430 | /// PackExpansionType whose pattern is Types&. |
5431 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5432 | friend class ASTContext; // ASTContext creates these |
5433 | |
5434 | /// The pattern of the pack expansion. |
5435 | QualType Pattern; |
5436 | |
5437 | PackExpansionType(QualType Pattern, QualType Canon, |
5438 | Optional<unsigned> NumExpansions) |
5439 | : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(), |
5440 | /*InstantiationDependent=*/true, |
5441 | /*VariablyModified=*/Pattern->isVariablyModifiedType(), |
5442 | /*ContainsUnexpandedParameterPack=*/false), |
5443 | Pattern(Pattern) { |
5444 | PackExpansionTypeBits.NumExpansions = |
5445 | NumExpansions ? *NumExpansions + 1 : 0; |
5446 | } |
5447 | |
5448 | public: |
5449 | /// Retrieve the pattern of this pack expansion, which is the |
5450 | /// type that will be repeatedly instantiated when instantiating the |
5451 | /// pack expansion itself. |
5452 | QualType getPattern() const { return Pattern; } |
5453 | |
5454 | /// Retrieve the number of expansions that this pack expansion will |
5455 | /// generate, if known. |
5456 | Optional<unsigned> getNumExpansions() const { |
5457 | if (PackExpansionTypeBits.NumExpansions) |
5458 | return PackExpansionTypeBits.NumExpansions - 1; |
5459 | return None; |
5460 | } |
5461 | |
5462 | bool isSugared() const { return !Pattern->isDependentType(); } |
5463 | QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); } |
5464 | |
5465 | void Profile(llvm::FoldingSetNodeID &ID) { |
5466 | Profile(ID, getPattern(), getNumExpansions()); |
5467 | } |
5468 | |
5469 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5470 | Optional<unsigned> NumExpansions) { |
5471 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5472 | ID.AddBoolean(NumExpansions.hasValue()); |
5473 | if (NumExpansions) |
5474 | ID.AddInteger(*NumExpansions); |
5475 | } |
5476 | |
5477 | static bool classof(const Type *T) { |
5478 | return T->getTypeClass() == PackExpansion; |
5479 | } |
5480 | }; |
5481 | |
5482 | /// This class wraps the list of protocol qualifiers. For types that can |
5483 | /// take ObjC protocol qualifers, they can subclass this class. |
5484 | template <class T> |
5485 | class ObjCProtocolQualifiers { |
5486 | protected: |
5487 | ObjCProtocolQualifiers() = default; |
5488 | |
5489 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5490 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5491 | } |
5492 | |
5493 | ObjCProtocolDecl **getProtocolStorage() { |
5494 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5495 | } |
5496 | |
5497 | void setNumProtocols(unsigned N) { |
5498 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5499 | } |
5500 | |
5501 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5502 | setNumProtocols(protocols.size()); |
5503 | assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5504, __PRETTY_FUNCTION__)) |
5504 | "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5504, __PRETTY_FUNCTION__)); |
5505 | if (!protocols.empty()) |
5506 | memcpy(getProtocolStorage(), protocols.data(), |
5507 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5508 | } |
5509 | |
5510 | public: |
5511 | using qual_iterator = ObjCProtocolDecl * const *; |
5512 | using qual_range = llvm::iterator_range<qual_iterator>; |
5513 | |
5514 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5515 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5516 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5517 | |
5518 | bool qual_empty() const { return getNumProtocols() == 0; } |
5519 | |
5520 | /// Return the number of qualifying protocols in this type, or 0 if |
5521 | /// there are none. |
5522 | unsigned getNumProtocols() const { |
5523 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5524 | } |
5525 | |
5526 | /// Fetch a protocol by index. |
5527 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5528 | assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access" ) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5528, __PRETTY_FUNCTION__)); |
5529 | return qual_begin()[I]; |
5530 | } |
5531 | |
5532 | /// Retrieve all of the protocol qualifiers. |
5533 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5534 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5535 | } |
5536 | }; |
5537 | |
5538 | /// Represents a type parameter type in Objective C. It can take |
5539 | /// a list of protocols. |
5540 | class ObjCTypeParamType : public Type, |
5541 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5542 | public llvm::FoldingSetNode { |
5543 | friend class ASTContext; |
5544 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5545 | |
5546 | /// The number of protocols stored on this type. |
5547 | unsigned NumProtocols : 6; |
5548 | |
5549 | ObjCTypeParamDecl *OTPDecl; |
5550 | |
5551 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5552 | /// canonical type, the list of protocols are sorted alphabetically |
5553 | /// and uniqued. |
5554 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5555 | |
5556 | /// Return the number of qualifying protocols in this interface type, |
5557 | /// or 0 if there are none. |
5558 | unsigned getNumProtocolsImpl() const { |
5559 | return NumProtocols; |
5560 | } |
5561 | |
5562 | void setNumProtocolsImpl(unsigned N) { |
5563 | NumProtocols = N; |
5564 | } |
5565 | |
5566 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5567 | QualType can, |
5568 | ArrayRef<ObjCProtocolDecl *> protocols); |
5569 | |
5570 | public: |
5571 | bool isSugared() const { return true; } |
5572 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5573 | |
5574 | static bool classof(const Type *T) { |
5575 | return T->getTypeClass() == ObjCTypeParam; |
5576 | } |
5577 | |
5578 | void Profile(llvm::FoldingSetNodeID &ID); |
5579 | static void Profile(llvm::FoldingSetNodeID &ID, |
5580 | const ObjCTypeParamDecl *OTPDecl, |
5581 | ArrayRef<ObjCProtocolDecl *> protocols); |
5582 | |
5583 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5584 | }; |
5585 | |
5586 | /// Represents a class type in Objective C. |
5587 | /// |
5588 | /// Every Objective C type is a combination of a base type, a set of |
5589 | /// type arguments (optional, for parameterized classes) and a list of |
5590 | /// protocols. |
5591 | /// |
5592 | /// Given the following declarations: |
5593 | /// \code |
5594 | /// \@class C<T>; |
5595 | /// \@protocol P; |
5596 | /// \endcode |
5597 | /// |
5598 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5599 | /// with base C and no protocols. |
5600 | /// |
5601 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5602 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5603 | /// protocol list. |
5604 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5605 | /// and protocol list [P]. |
5606 | /// |
5607 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5608 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5609 | /// and no protocols. |
5610 | /// |
5611 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5612 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5613 | /// this should get its own sugar class to better represent the source. |
5614 | class ObjCObjectType : public Type, |
5615 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5616 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5617 | |
5618 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5619 | // after the ObjCObjectPointerType node. |
5620 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5621 | // after the type arguments of ObjCObjectPointerType node. |
5622 | // |
5623 | // These protocols are those written directly on the type. If |
5624 | // protocol qualifiers ever become additive, the iterators will need |
5625 | // to get kindof complicated. |
5626 | // |
5627 | // In the canonical object type, these are sorted alphabetically |
5628 | // and uniqued. |
5629 | |
5630 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5631 | QualType BaseType; |
5632 | |
5633 | /// Cached superclass type. |
5634 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5635 | CachedSuperClassType; |
5636 | |
5637 | QualType *getTypeArgStorage(); |
5638 | const QualType *getTypeArgStorage() const { |
5639 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5640 | } |
5641 | |
5642 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5643 | /// Return the number of qualifying protocols in this interface type, |
5644 | /// or 0 if there are none. |
5645 | unsigned getNumProtocolsImpl() const { |
5646 | return ObjCObjectTypeBits.NumProtocols; |
5647 | } |
5648 | void setNumProtocolsImpl(unsigned N) { |
5649 | ObjCObjectTypeBits.NumProtocols = N; |
5650 | } |
5651 | |
5652 | protected: |
5653 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5654 | |
5655 | ObjCObjectType(QualType Canonical, QualType Base, |
5656 | ArrayRef<QualType> typeArgs, |
5657 | ArrayRef<ObjCProtocolDecl *> protocols, |
5658 | bool isKindOf); |
5659 | |
5660 | ObjCObjectType(enum Nonce_ObjCInterface) |
5661 | : Type(ObjCInterface, QualType(), false, false, false, false), |
5662 | BaseType(QualType(this_(), 0)) { |
5663 | ObjCObjectTypeBits.NumProtocols = 0; |
5664 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5665 | ObjCObjectTypeBits.IsKindOf = 0; |
5666 | } |
5667 | |
5668 | void computeSuperClassTypeSlow() const; |
5669 | |
5670 | public: |
5671 | /// Gets the base type of this object type. This is always (possibly |
5672 | /// sugar for) one of: |
5673 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5674 | /// user, which is a typedef for an ObjCObjectPointerType) |
5675 | /// - the 'Class' builtin type (same caveat) |
5676 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5677 | QualType getBaseType() const { return BaseType; } |
5678 | |
5679 | bool isObjCId() const { |
5680 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5681 | } |
5682 | |
5683 | bool isObjCClass() const { |
5684 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5685 | } |
5686 | |
5687 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5688 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5689 | bool isObjCUnqualifiedIdOrClass() const { |
5690 | if (!qual_empty()) return false; |
5691 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5692 | return T->getKind() == BuiltinType::ObjCId || |
5693 | T->getKind() == BuiltinType::ObjCClass; |
5694 | return false; |
5695 | } |
5696 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5697 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5698 | |
5699 | /// Gets the interface declaration for this object type, if the base type |
5700 | /// really is an interface. |
5701 | ObjCInterfaceDecl *getInterface() const; |
5702 | |
5703 | /// Determine whether this object type is "specialized", meaning |
5704 | /// that it has type arguments. |
5705 | bool isSpecialized() const; |
5706 | |
5707 | /// Determine whether this object type was written with type arguments. |
5708 | bool isSpecializedAsWritten() const { |
5709 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5710 | } |
5711 | |
5712 | /// Determine whether this object type is "unspecialized", meaning |
5713 | /// that it has no type arguments. |
5714 | bool isUnspecialized() const { return !isSpecialized(); } |
5715 | |
5716 | /// Determine whether this object type is "unspecialized" as |
5717 | /// written, meaning that it has no type arguments. |
5718 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5719 | |
5720 | /// Retrieve the type arguments of this object type (semantically). |
5721 | ArrayRef<QualType> getTypeArgs() const; |
5722 | |
5723 | /// Retrieve the type arguments of this object type as they were |
5724 | /// written. |
5725 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5726 | return llvm::makeArrayRef(getTypeArgStorage(), |
5727 | ObjCObjectTypeBits.NumTypeArgs); |
5728 | } |
5729 | |
5730 | /// Whether this is a "__kindof" type as written. |
5731 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5732 | |
5733 | /// Whether this ia a "__kindof" type (semantically). |
5734 | bool isKindOfType() const; |
5735 | |
5736 | /// Retrieve the type of the superclass of this object type. |
5737 | /// |
5738 | /// This operation substitutes any type arguments into the |
5739 | /// superclass of the current class type, potentially producing a |
5740 | /// specialization of the superclass type. Produces a null type if |
5741 | /// there is no superclass. |
5742 | QualType getSuperClassType() const { |
5743 | if (!CachedSuperClassType.getInt()) |
5744 | computeSuperClassTypeSlow(); |
5745 | |
5746 | assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?" ) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5746, __PRETTY_FUNCTION__)); |
5747 | return QualType(CachedSuperClassType.getPointer(), 0); |
5748 | } |
5749 | |
5750 | /// Strip off the Objective-C "kindof" type and (with it) any |
5751 | /// protocol qualifiers. |
5752 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5753 | |
5754 | bool isSugared() const { return false; } |
5755 | QualType desugar() const { return QualType(this, 0); } |
5756 | |
5757 | static bool classof(const Type *T) { |
5758 | return T->getTypeClass() == ObjCObject || |
5759 | T->getTypeClass() == ObjCInterface; |
5760 | } |
5761 | }; |
5762 | |
5763 | /// A class providing a concrete implementation |
5764 | /// of ObjCObjectType, so as to not increase the footprint of |
5765 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5766 | /// system should not reference this type. |
5767 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5768 | friend class ASTContext; |
5769 | |
5770 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5771 | // will need to be modified. |
5772 | |
5773 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5774 | ArrayRef<QualType> typeArgs, |
5775 | ArrayRef<ObjCProtocolDecl *> protocols, |
5776 | bool isKindOf) |
5777 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5778 | |
5779 | public: |
5780 | void Profile(llvm::FoldingSetNodeID &ID); |
5781 | static void Profile(llvm::FoldingSetNodeID &ID, |
5782 | QualType Base, |
5783 | ArrayRef<QualType> typeArgs, |
5784 | ArrayRef<ObjCProtocolDecl *> protocols, |
5785 | bool isKindOf); |
5786 | }; |
5787 | |
5788 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5789 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5790 | } |
5791 | |
5792 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5793 | return reinterpret_cast<ObjCProtocolDecl**>( |
5794 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
5795 | } |
5796 | |
5797 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
5798 | return reinterpret_cast<ObjCProtocolDecl**>( |
5799 | static_cast<ObjCTypeParamType*>(this)+1); |
5800 | } |
5801 | |
5802 | /// Interfaces are the core concept in Objective-C for object oriented design. |
5803 | /// They basically correspond to C++ classes. There are two kinds of interface |
5804 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
5805 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
5806 | /// |
5807 | /// ObjCInterfaceType guarantees the following properties when considered |
5808 | /// as a subtype of its superclass, ObjCObjectType: |
5809 | /// - There are no protocol qualifiers. To reinforce this, code which |
5810 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
5811 | /// fail to compile. |
5812 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
5813 | /// T->getBaseType() == QualType(T, 0). |
5814 | class ObjCInterfaceType : public ObjCObjectType { |
5815 | friend class ASTContext; // ASTContext creates these. |
5816 | friend class ASTReader; |
5817 | friend class ObjCInterfaceDecl; |
5818 | |
5819 | mutable ObjCInterfaceDecl *Decl; |
5820 | |
5821 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
5822 | : ObjCObjectType(Nonce_ObjCInterface), |
5823 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
5824 | |
5825 | public: |
5826 | /// Get the declaration of this interface. |
5827 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
5828 | |
5829 | bool isSugared() const { return false; } |
5830 | QualType desugar() const { return QualType(this, 0); } |
5831 | |
5832 | static bool classof(const Type *T) { |
5833 | return T->getTypeClass() == ObjCInterface; |
5834 | } |
5835 | |
5836 | // Nonsense to "hide" certain members of ObjCObjectType within this |
5837 | // class. People asking for protocols on an ObjCInterfaceType are |
5838 | // not going to get what they want: ObjCInterfaceTypes are |
5839 | // guaranteed to have no protocols. |
5840 | enum { |
5841 | qual_iterator, |
5842 | qual_begin, |
5843 | qual_end, |
5844 | getNumProtocols, |
5845 | getProtocol |
5846 | }; |
5847 | }; |
5848 | |
5849 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
5850 | QualType baseType = getBaseType(); |
5851 | while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { |
5852 | if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
5853 | return T->getDecl(); |
5854 | |
5855 | baseType = ObjT->getBaseType(); |
5856 | } |
5857 | |
5858 | return nullptr; |
5859 | } |
5860 | |
5861 | /// Represents a pointer to an Objective C object. |
5862 | /// |
5863 | /// These are constructed from pointer declarators when the pointee type is |
5864 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
5865 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
5866 | /// and 'Class<P>' are translated into these. |
5867 | /// |
5868 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
5869 | /// only the first level of pointer gets it own type implementation. |
5870 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
5871 | friend class ASTContext; // ASTContext creates these. |
5872 | |
5873 | QualType PointeeType; |
5874 | |
5875 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
5876 | : Type(ObjCObjectPointer, Canonical, |
5877 | Pointee->isDependentType(), |
5878 | Pointee->isInstantiationDependentType(), |
5879 | Pointee->isVariablyModifiedType(), |
5880 | Pointee->containsUnexpandedParameterPack()), |
5881 | PointeeType(Pointee) {} |
5882 | |
5883 | public: |
5884 | /// Gets the type pointed to by this ObjC pointer. |
5885 | /// The result will always be an ObjCObjectType or sugar thereof. |
5886 | QualType getPointeeType() const { return PointeeType; } |
5887 | |
5888 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
5889 | /// |
5890 | /// This method is equivalent to getPointeeType() except that |
5891 | /// it discards any typedefs (or other sugar) between this |
5892 | /// type and the "outermost" object type. So for: |
5893 | /// \code |
5894 | /// \@class A; \@protocol P; \@protocol Q; |
5895 | /// typedef A<P> AP; |
5896 | /// typedef A A1; |
5897 | /// typedef A1<P> A1P; |
5898 | /// typedef A1P<Q> A1PQ; |
5899 | /// \endcode |
5900 | /// For 'A*', getObjectType() will return 'A'. |
5901 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
5902 | /// For 'AP*', getObjectType() will return 'A<P>'. |
5903 | /// For 'A1*', getObjectType() will return 'A'. |
5904 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
5905 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
5906 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
5907 | /// adding protocols to a protocol-qualified base discards the |
5908 | /// old qualifiers (for now). But if it didn't, getObjectType() |
5909 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
5910 | /// qualifiers more complicated). |
5911 | const ObjCObjectType *getObjectType() const { |
5912 | return PointeeType->castAs<ObjCObjectType>(); |
5913 | } |
5914 | |
5915 | /// If this pointer points to an Objective C |
5916 | /// \@interface type, gets the type for that interface. Any protocol |
5917 | /// qualifiers on the interface are ignored. |
5918 | /// |
5919 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5920 | const ObjCInterfaceType *getInterfaceType() const; |
5921 | |
5922 | /// If this pointer points to an Objective \@interface |
5923 | /// type, gets the declaration for that interface. |
5924 | /// |
5925 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5926 | ObjCInterfaceDecl *getInterfaceDecl() const { |
5927 | return getObjectType()->getInterface(); |
5928 | } |
5929 | |
5930 | /// True if this is equivalent to the 'id' type, i.e. if |
5931 | /// its object type is the primitive 'id' type with no protocols. |
5932 | bool isObjCIdType() const { |
5933 | return getObjectType()->isObjCUnqualifiedId(); |
5934 | } |
5935 | |
5936 | /// True if this is equivalent to the 'Class' type, |
5937 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
5938 | bool isObjCClassType() const { |
5939 | return getObjectType()->isObjCUnqualifiedClass(); |
5940 | } |
5941 | |
5942 | /// True if this is equivalent to the 'id' or 'Class' type, |
5943 | bool isObjCIdOrClassType() const { |
5944 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
5945 | } |
5946 | |
5947 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
5948 | /// protocols. |
5949 | bool isObjCQualifiedIdType() const { |
5950 | return getObjectType()->isObjCQualifiedId(); |
5951 | } |
5952 | |
5953 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
5954 | /// protocols. |
5955 | bool isObjCQualifiedClassType() const { |
5956 | return getObjectType()->isObjCQualifiedClass(); |
5957 | } |
5958 | |
5959 | /// Whether this is a "__kindof" type. |
5960 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
5961 | |
5962 | /// Whether this type is specialized, meaning that it has type arguments. |
5963 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
5964 | |
5965 | /// Whether this type is specialized, meaning that it has type arguments. |
5966 | bool isSpecializedAsWritten() const { |
5967 | return getObjectType()->isSpecializedAsWritten(); |
5968 | } |
5969 | |
5970 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
5971 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
5972 | |
5973 | /// Determine whether this object type is "unspecialized" as |
5974 | /// written, meaning that it has no type arguments. |
5975 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5976 | |
5977 | /// Retrieve the type arguments for this type. |
5978 | ArrayRef<QualType> getTypeArgs() const { |
5979 | return getObjectType()->getTypeArgs(); |
5980 | } |
5981 | |
5982 | /// Retrieve the type arguments for this type. |
5983 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5984 | return getObjectType()->getTypeArgsAsWritten(); |
5985 | } |
5986 | |
5987 | /// An iterator over the qualifiers on the object type. Provided |
5988 | /// for convenience. This will always iterate over the full set of |
5989 | /// protocols on a type, not just those provided directly. |
5990 | using qual_iterator = ObjCObjectType::qual_iterator; |
5991 | using qual_range = llvm::iterator_range<qual_iterator>; |
5992 | |
5993 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5994 | |
5995 | qual_iterator qual_begin() const { |
5996 | return getObjectType()->qual_begin(); |
5997 | } |
5998 | |
5999 | qual_iterator qual_end() const { |
6000 | return getObjectType()->qual_end(); |
6001 | } |
6002 | |
6003 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
6004 | |
6005 | /// Return the number of qualifying protocols on the object type. |
6006 | unsigned getNumProtocols() const { |
6007 | return getObjectType()->getNumProtocols(); |
6008 | } |
6009 | |
6010 | /// Retrieve a qualifying protocol by index on the object type. |
6011 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
6012 | return getObjectType()->getProtocol(I); |
6013 | } |
6014 | |
6015 | bool isSugared() const { return false; } |
6016 | QualType desugar() const { return QualType(this, 0); } |
6017 | |
6018 | /// Retrieve the type of the superclass of this object pointer type. |
6019 | /// |
6020 | /// This operation substitutes any type arguments into the |
6021 | /// superclass of the current class type, potentially producing a |
6022 | /// pointer to a specialization of the superclass type. Produces a |
6023 | /// null type if there is no superclass. |
6024 | QualType getSuperClassType() const; |
6025 | |
6026 | /// Strip off the Objective-C "kindof" type and (with it) any |
6027 | /// protocol qualifiers. |
6028 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
6029 | const ASTContext &ctx) const; |
6030 | |
6031 | void Profile(llvm::FoldingSetNodeID &ID) { |
6032 | Profile(ID, getPointeeType()); |
6033 | } |
6034 | |
6035 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6036 | ID.AddPointer(T.getAsOpaquePtr()); |
6037 | } |
6038 | |
6039 | static bool classof(const Type *T) { |
6040 | return T->getTypeClass() == ObjCObjectPointer; |
6041 | } |
6042 | }; |
6043 | |
6044 | class AtomicType : public Type, public llvm::FoldingSetNode { |
6045 | friend class ASTContext; // ASTContext creates these. |
6046 | |
6047 | QualType ValueType; |
6048 | |
6049 | AtomicType(QualType ValTy, QualType Canonical) |
6050 | : Type(Atomic, Canonical, ValTy->isDependentType(), |
6051 | ValTy->isInstantiationDependentType(), |
6052 | ValTy->isVariablyModifiedType(), |
6053 | ValTy->containsUnexpandedParameterPack()), |
6054 | ValueType(ValTy) {} |
6055 | |
6056 | public: |
6057 | /// Gets the type contained by this atomic type, i.e. |
6058 | /// the type returned by performing an atomic load of this atomic type. |
6059 | QualType getValueType() const { return ValueType; } |
6060 | |
6061 | bool isSugared() const { return false; } |
6062 | QualType desugar() const { return QualType(this, 0); } |
6063 | |
6064 | void Profile(llvm::FoldingSetNodeID &ID) { |
6065 | Profile(ID, getValueType()); |
6066 | } |
6067 | |
6068 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6069 | ID.AddPointer(T.getAsOpaquePtr()); |
6070 | } |
6071 | |
6072 | static bool classof(const Type *T) { |
6073 | return T->getTypeClass() == Atomic; |
6074 | } |
6075 | }; |
6076 | |
6077 | /// PipeType - OpenCL20. |
6078 | class PipeType : public Type, public llvm::FoldingSetNode { |
6079 | friend class ASTContext; // ASTContext creates these. |
6080 | |
6081 | QualType ElementType; |
6082 | bool isRead; |
6083 | |
6084 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
6085 | : Type(Pipe, CanonicalPtr, elemType->isDependentType(), |
6086 | elemType->isInstantiationDependentType(), |
6087 | elemType->isVariablyModifiedType(), |
6088 | elemType->containsUnexpandedParameterPack()), |
6089 | ElementType(elemType), isRead(isRead) {} |
6090 | |
6091 | public: |
6092 | QualType getElementType() const { return ElementType; } |
6093 | |
6094 | bool isSugared() const { return false; } |
6095 | |
6096 | QualType desugar() const { return QualType(this, 0); } |
6097 | |
6098 | void Profile(llvm::FoldingSetNodeID &ID) { |
6099 | Profile(ID, getElementType(), isReadOnly()); |
6100 | } |
6101 | |
6102 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
6103 | ID.AddPointer(T.getAsOpaquePtr()); |
6104 | ID.AddBoolean(isRead); |
6105 | } |
6106 | |
6107 | static bool classof(const Type *T) { |
6108 | return T->getTypeClass() == Pipe; |
6109 | } |
6110 | |
6111 | bool isReadOnly() const { return isRead; } |
6112 | }; |
6113 | |
6114 | /// A qualifier set is used to build a set of qualifiers. |
6115 | class QualifierCollector : public Qualifiers { |
6116 | public: |
6117 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
6118 | |
6119 | /// Collect any qualifiers on the given type and return an |
6120 | /// unqualified type. The qualifiers are assumed to be consistent |
6121 | /// with those already in the type. |
6122 | const Type *strip(QualType type) { |
6123 | addFastQualifiers(type.getLocalFastQualifiers()); |
6124 | if (!type.hasLocalNonFastQualifiers()) |
6125 | return type.getTypePtrUnsafe(); |
6126 | |
6127 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
6128 | addConsistentQualifiers(extQuals->getQualifiers()); |
6129 | return extQuals->getBaseType(); |
6130 | } |
6131 | |
6132 | /// Apply the collected qualifiers to the given type. |
6133 | QualType apply(const ASTContext &Context, QualType QT) const; |
6134 | |
6135 | /// Apply the collected qualifiers to the given type. |
6136 | QualType apply(const ASTContext &Context, const Type* T) const; |
6137 | }; |
6138 | |
6139 | // Inline function definitions. |
6140 | |
6141 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
6142 | SplitQualType desugar = |
6143 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
6144 | desugar.Quals.addConsistentQualifiers(Quals); |
6145 | return desugar; |
6146 | } |
6147 | |
6148 | inline const Type *QualType::getTypePtr() const { |
6149 | return getCommonPtr()->BaseType; |
6150 | } |
6151 | |
6152 | inline const Type *QualType::getTypePtrOrNull() const { |
6153 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
6154 | } |
6155 | |
6156 | inline SplitQualType QualType::split() const { |
6157 | if (!hasLocalNonFastQualifiers()) |
6158 | return SplitQualType(getTypePtrUnsafe(), |
6159 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
6160 | |
6161 | const ExtQuals *eq = getExtQualsUnsafe(); |
6162 | Qualifiers qs = eq->getQualifiers(); |
6163 | qs.addFastQualifiers(getLocalFastQualifiers()); |
6164 | return SplitQualType(eq->getBaseType(), qs); |
6165 | } |
6166 | |
6167 | inline Qualifiers QualType::getLocalQualifiers() const { |
6168 | Qualifiers Quals; |
6169 | if (hasLocalNonFastQualifiers()) |
6170 | Quals = getExtQualsUnsafe()->getQualifiers(); |
6171 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
6172 | return Quals; |
6173 | } |
6174 | |
6175 | inline Qualifiers QualType::getQualifiers() const { |
6176 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
6177 | quals.addFastQualifiers(getLocalFastQualifiers()); |
6178 | return quals; |
6179 | } |
6180 | |
6181 | inline unsigned QualType::getCVRQualifiers() const { |
6182 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
6183 | cvr |= getLocalCVRQualifiers(); |
6184 | return cvr; |
6185 | } |
6186 | |
6187 | inline QualType QualType::getCanonicalType() const { |
6188 | QualType canon = getCommonPtr()->CanonicalType; |
6189 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
6190 | } |
6191 | |
6192 | inline bool QualType::isCanonical() const { |
6193 | return getTypePtr()->isCanonicalUnqualified(); |
6194 | } |
6195 | |
6196 | inline bool QualType::isCanonicalAsParam() const { |
6197 | if (!isCanonical()) return false; |
6198 | if (hasLocalQualifiers()) return false; |
6199 | |
6200 | const Type *T = getTypePtr(); |
6201 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
6202 | return false; |
6203 | |
6204 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
6205 | } |
6206 | |
6207 | inline bool QualType::isConstQualified() const { |
6208 | return isLocalConstQualified() || |
6209 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
6210 | } |
6211 | |
6212 | inline bool QualType::isRestrictQualified() const { |
6213 | return isLocalRestrictQualified() || |
6214 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
6215 | } |
6216 | |
6217 | |
6218 | inline bool QualType::isVolatileQualified() const { |
6219 | return isLocalVolatileQualified() || |
6220 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
6221 | } |
6222 | |
6223 | inline bool QualType::hasQualifiers() const { |
6224 | return hasLocalQualifiers() || |
6225 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
6226 | } |
6227 | |
6228 | inline QualType QualType::getUnqualifiedType() const { |
6229 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6230 | return QualType(getTypePtr(), 0); |
6231 | |
6232 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
6233 | } |
6234 | |
6235 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
6236 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6237 | return split(); |
6238 | |
6239 | return getSplitUnqualifiedTypeImpl(*this); |
6240 | } |
6241 | |
6242 | inline void QualType::removeLocalConst() { |
6243 | removeLocalFastQualifiers(Qualifiers::Const); |
6244 | } |
6245 | |
6246 | inline void QualType::removeLocalRestrict() { |
6247 | removeLocalFastQualifiers(Qualifiers::Restrict); |
6248 | } |
6249 | |
6250 | inline void QualType::removeLocalVolatile() { |
6251 | removeLocalFastQualifiers(Qualifiers::Volatile); |
6252 | } |
6253 | |
6254 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
6255 | assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6255, __PRETTY_FUNCTION__)); |
6256 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
6257 | "Fast bits differ from CVR bits!"); |
6258 | |
6259 | // Fast path: we don't need to touch the slow qualifiers. |
6260 | removeLocalFastQualifiers(Mask); |
6261 | } |
6262 | |
6263 | /// Return the address space of this type. |
6264 | inline LangAS QualType::getAddressSpace() const { |
6265 | return getQualifiers().getAddressSpace(); |
6266 | } |
6267 | |
6268 | /// Return the gc attribute of this type. |
6269 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
6270 | return getQualifiers().getObjCGCAttr(); |
6271 | } |
6272 | |
6273 | inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
6274 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6275 | return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); |
6276 | return false; |
6277 | } |
6278 | |
6279 | inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { |
6280 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6281 | return hasNonTrivialToPrimitiveDestructCUnion(RD); |
6282 | return false; |
6283 | } |
6284 | |
6285 | inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { |
6286 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6287 | return hasNonTrivialToPrimitiveCopyCUnion(RD); |
6288 | return false; |
6289 | } |
6290 | |
6291 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
6292 | if (const auto *PT = t.getAs<PointerType>()) { |
6293 | if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) |
6294 | return FT->getExtInfo(); |
6295 | } else if (const auto *FT = t.getAs<FunctionType>()) |
6296 | return FT->getExtInfo(); |
6297 | |
6298 | return FunctionType::ExtInfo(); |
6299 | } |
6300 | |
6301 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
6302 | return getFunctionExtInfo(*t); |
6303 | } |
6304 | |
6305 | /// Determine whether this type is more |
6306 | /// qualified than the Other type. For example, "const volatile int" |
6307 | /// is more qualified than "const int", "volatile int", and |
6308 | /// "int". However, it is not more qualified than "const volatile |
6309 | /// int". |
6310 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
6311 | Qualifiers MyQuals = getQualifiers(); |
6312 | Qualifiers OtherQuals = other.getQualifiers(); |
6313 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
6314 | } |
6315 | |
6316 | /// Determine whether this type is at last |
6317 | /// as qualified as the Other type. For example, "const volatile |
6318 | /// int" is at least as qualified as "const int", "volatile int", |
6319 | /// "int", and "const volatile int". |
6320 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
6321 | Qualifiers OtherQuals = other.getQualifiers(); |
6322 | |
6323 | // Ignore __unaligned qualifier if this type is a void. |
6324 | if (getUnqualifiedType()->isVoidType()) |
6325 | OtherQuals.removeUnaligned(); |
6326 | |
6327 | return getQualifiers().compatiblyIncludes(OtherQuals); |
6328 | } |
6329 | |
6330 | /// If Type is a reference type (e.g., const |
6331 | /// int&), returns the type that the reference refers to ("const |
6332 | /// int"). Otherwise, returns the type itself. This routine is used |
6333 | /// throughout Sema to implement C++ 5p6: |
6334 | /// |
6335 | /// If an expression initially has the type "reference to T" (8.3.2, |
6336 | /// 8.5.3), the type is adjusted to "T" prior to any further |
6337 | /// analysis, the expression designates the object or function |
6338 | /// denoted by the reference, and the expression is an lvalue. |
6339 | inline QualType QualType::getNonReferenceType() const { |
6340 | if (const auto *RefType = (*this)->getAs<ReferenceType>()) |
6341 | return RefType->getPointeeType(); |
6342 | else |
6343 | return *this; |
6344 | } |
6345 | |
6346 | inline bool QualType::isCForbiddenLValueType() const { |
6347 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
6348 | getTypePtr()->isFunctionType()); |
6349 | } |
6350 | |
6351 | /// Tests whether the type is categorized as a fundamental type. |
6352 | /// |
6353 | /// \returns True for types specified in C++0x [basic.fundamental]. |
6354 | inline bool Type::isFundamentalType() const { |
6355 | return isVoidType() || |
6356 | isNullPtrType() || |
6357 | // FIXME: It's really annoying that we don't have an |
6358 | // 'isArithmeticType()' which agrees with the standard definition. |
6359 | (isArithmeticType() && !isEnumeralType()); |
6360 | } |
6361 | |
6362 | /// Tests whether the type is categorized as a compound type. |
6363 | /// |
6364 | /// \returns True for types specified in C++0x [basic.compound]. |
6365 | inline bool Type::isCompoundType() const { |
6366 | // C++0x [basic.compound]p1: |
6367 | // Compound types can be constructed in the following ways: |
6368 | // -- arrays of objects of a given type [...]; |
6369 | return isArrayType() || |
6370 | // -- functions, which have parameters of given types [...]; |
6371 | isFunctionType() || |
6372 | // -- pointers to void or objects or functions [...]; |
6373 | isPointerType() || |
6374 | // -- references to objects or functions of a given type. [...] |
6375 | isReferenceType() || |
6376 | // -- classes containing a sequence of objects of various types, [...]; |
6377 | isRecordType() || |
6378 | // -- unions, which are classes capable of containing objects of different |
6379 | // types at different times; |
6380 | isUnionType() || |
6381 | // -- enumerations, which comprise a set of named constant values. [...]; |
6382 | isEnumeralType() || |
6383 | // -- pointers to non-static class members, [...]. |
6384 | isMemberPointerType(); |
6385 | } |
6386 | |
6387 | inline bool Type::isFunctionType() const { |
6388 | return isa<FunctionType>(CanonicalType); |
6389 | } |
6390 | |
6391 | inline bool Type::isPointerType() const { |
6392 | return isa<PointerType>(CanonicalType); |
6393 | } |
6394 | |
6395 | inline bool Type::isAnyPointerType() const { |
6396 | return isPointerType() || isObjCObjectPointerType(); |
6397 | } |
6398 | |
6399 | inline bool Type::isBlockPointerType() const { |
6400 | return isa<BlockPointerType>(CanonicalType); |
6401 | } |
6402 | |
6403 | inline bool Type::isReferenceType() const { |
6404 | return isa<ReferenceType>(CanonicalType); |
6405 | } |
6406 | |
6407 | inline bool Type::isLValueReferenceType() const { |
6408 | return isa<LValueReferenceType>(CanonicalType); |
6409 | } |
6410 | |
6411 | inline bool Type::isRValueReferenceType() const { |
6412 | return isa<RValueReferenceType>(CanonicalType); |
6413 | } |
6414 | |
6415 | inline bool Type::isFunctionPointerType() const { |
6416 | if (const auto *T = getAs<PointerType>()) |
6417 | return T->getPointeeType()->isFunctionType(); |
6418 | else |
6419 | return false; |
6420 | } |
6421 | |
6422 | inline bool Type::isFunctionReferenceType() const { |
6423 | if (const auto *T = getAs<ReferenceType>()) |
6424 | return T->getPointeeType()->isFunctionType(); |
6425 | else |
6426 | return false; |
6427 | } |
6428 | |
6429 | inline bool Type::isMemberPointerType() const { |
6430 | return isa<MemberPointerType>(CanonicalType); |
6431 | } |
6432 | |
6433 | inline bool Type::isMemberFunctionPointerType() const { |
6434 | if (const auto *T = getAs<MemberPointerType>()) |
6435 | return T->isMemberFunctionPointer(); |
6436 | else |
6437 | return false; |
6438 | } |
6439 | |
6440 | inline bool Type::isMemberDataPointerType() const { |
6441 | if (const auto *T = getAs<MemberPointerType>()) |
6442 | return T->isMemberDataPointer(); |
6443 | else |
6444 | return false; |
6445 | } |
6446 | |
6447 | inline bool Type::isArrayType() const { |
6448 | return isa<ArrayType>(CanonicalType); |
6449 | } |
6450 | |
6451 | inline bool Type::isConstantArrayType() const { |
6452 | return isa<ConstantArrayType>(CanonicalType); |
6453 | } |
6454 | |
6455 | inline bool Type::isIncompleteArrayType() const { |
6456 | return isa<IncompleteArrayType>(CanonicalType); |
6457 | } |
6458 | |
6459 | inline bool Type::isVariableArrayType() const { |
6460 | return isa<VariableArrayType>(CanonicalType); |
6461 | } |
6462 | |
6463 | inline bool Type::isDependentSizedArrayType() const { |
6464 | return isa<DependentSizedArrayType>(CanonicalType); |
6465 | } |
6466 | |
6467 | inline bool Type::isBuiltinType() const { |
6468 | return isa<BuiltinType>(CanonicalType); |
6469 | } |
6470 | |
6471 | inline bool Type::isRecordType() const { |
6472 | return isa<RecordType>(CanonicalType); |
6473 | } |
6474 | |
6475 | inline bool Type::isEnumeralType() const { |
6476 | return isa<EnumType>(CanonicalType); |
6477 | } |
6478 | |
6479 | inline bool Type::isAnyComplexType() const { |
6480 | return isa<ComplexType>(CanonicalType); |
6481 | } |
6482 | |
6483 | inline bool Type::isVectorType() const { |
6484 | return isa<VectorType>(CanonicalType); |
6485 | } |
6486 | |
6487 | inline bool Type::isExtVectorType() const { |
6488 | return isa<ExtVectorType>(CanonicalType); |
6489 | } |
6490 | |
6491 | inline bool Type::isDependentAddressSpaceType() const { |
6492 | return isa<DependentAddressSpaceType>(CanonicalType); |
6493 | } |
6494 | |
6495 | inline bool Type::isObjCObjectPointerType() const { |
6496 | return isa<ObjCObjectPointerType>(CanonicalType); |
6497 | } |
6498 | |
6499 | inline bool Type::isObjCObjectType() const { |
6500 | return isa<ObjCObjectType>(CanonicalType); |
6501 | } |
6502 | |
6503 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6504 | return isa<ObjCInterfaceType>(CanonicalType) || |
6505 | isa<ObjCObjectType>(CanonicalType); |
6506 | } |
6507 | |
6508 | inline bool Type::isAtomicType() const { |
6509 | return isa<AtomicType>(CanonicalType); |
6510 | } |
6511 | |
6512 | inline bool Type::isObjCQualifiedIdType() const { |
6513 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6514 | return OPT->isObjCQualifiedIdType(); |
6515 | return false; |
6516 | } |
6517 | |
6518 | inline bool Type::isObjCQualifiedClassType() const { |
6519 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6520 | return OPT->isObjCQualifiedClassType(); |
6521 | return false; |
6522 | } |
6523 | |
6524 | inline bool Type::isObjCIdType() const { |
6525 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6526 | return OPT->isObjCIdType(); |
6527 | return false; |
6528 | } |
6529 | |
6530 | inline bool Type::isObjCClassType() const { |
6531 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6532 | return OPT->isObjCClassType(); |
6533 | return false; |
6534 | } |
6535 | |
6536 | inline bool Type::isObjCSelType() const { |
6537 | if (const auto *OPT = getAs<PointerType>()) |
6538 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6539 | return false; |
6540 | } |
6541 | |
6542 | inline bool Type::isObjCBuiltinType() const { |
6543 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6544 | } |
6545 | |
6546 | inline bool Type::isDecltypeType() const { |
6547 | return isa<DecltypeType>(this); |
6548 | } |
6549 | |
6550 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6551 | inline bool Type::is##Id##Type() const { \ |
6552 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6553 | } |
6554 | #include "clang/Basic/OpenCLImageTypes.def" |
6555 | |
6556 | inline bool Type::isSamplerT() const { |
6557 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6558 | } |
6559 | |
6560 | inline bool Type::isEventT() const { |
6561 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6562 | } |
6563 | |
6564 | inline bool Type::isClkEventT() const { |
6565 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6566 | } |
6567 | |
6568 | inline bool Type::isQueueT() const { |
6569 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6570 | } |
6571 | |
6572 | inline bool Type::isReserveIDT() const { |
6573 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6574 | } |
6575 | |
6576 | inline bool Type::isImageType() const { |
6577 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6578 | return |
6579 | #include "clang/Basic/OpenCLImageTypes.def" |
6580 | false; // end boolean or operation |
6581 | } |
6582 | |
6583 | inline bool Type::isPipeType() const { |
6584 | return isa<PipeType>(CanonicalType); |
6585 | } |
6586 | |
6587 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6588 | inline bool Type::is##Id##Type() const { \ |
6589 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6590 | } |
6591 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6592 | |
6593 | inline bool Type::isOCLIntelSubgroupAVCType() const { |
6594 | #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ |
6595 | isOCLIntelSubgroupAVC##Id##Type() || |
6596 | return |
6597 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6598 | false; // end of boolean or operation |
6599 | } |
6600 | |
6601 | inline bool Type::isOCLExtOpaqueType() const { |
6602 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || |
6603 | return |
6604 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6605 | false; // end of boolean or operation |
6606 | } |
6607 | |
6608 | inline bool Type::isOpenCLSpecificType() const { |
6609 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6610 | isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); |
6611 | } |
6612 | |
6613 | inline bool Type::isTemplateTypeParmType() const { |
6614 | return isa<TemplateTypeParmType>(CanonicalType); |
6615 | } |
6616 | |
6617 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6618 | if (const BuiltinType *BT = getAs<BuiltinType>()) |
6619 | if (BT->getKind() == (BuiltinType::Kind) K) |
6620 | return true; |
6621 | return false; |
6622 | } |
6623 | |
6624 | inline bool Type::isPlaceholderType() const { |
6625 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6626 | return BT->isPlaceholderType(); |
6627 | return false; |
6628 | } |
6629 | |
6630 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6631 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6632 | if (BT->isPlaceholderType()) |
6633 | return BT; |
6634 | return nullptr; |
6635 | } |
6636 | |
6637 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6638 | assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ? static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6638, __PRETTY_FUNCTION__)); |
6639 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6640 | return (BT->getKind() == (BuiltinType::Kind) K); |
6641 | return false; |
6642 | } |
6643 | |
6644 | inline bool Type::isNonOverloadPlaceholderType() const { |
6645 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6646 | return BT->isNonOverloadPlaceholderType(); |
6647 | return false; |
6648 | } |
6649 | |
6650 | inline bool Type::isVoidType() const { |
6651 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6652 | return BT->getKind() == BuiltinType::Void; |
6653 | return false; |
6654 | } |
6655 | |
6656 | inline bool Type::isHalfType() const { |
6657 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6658 | return BT->getKind() == BuiltinType::Half; |
6659 | // FIXME: Should we allow complex __fp16? Probably not. |
6660 | return false; |
6661 | } |
6662 | |
6663 | inline bool Type::isFloat16Type() const { |
6664 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6665 | return BT->getKind() == BuiltinType::Float16; |
6666 | return false; |
6667 | } |
6668 | |
6669 | inline bool Type::isFloat128Type() const { |
6670 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6671 | return BT->getKind() == BuiltinType::Float128; |
6672 | return false; |
6673 | } |
6674 | |
6675 | inline bool Type::isNullPtrType() const { |
6676 | if (const auto *BT = getAs<BuiltinType>()) |
6677 | return BT->getKind() == BuiltinType::NullPtr; |
6678 | return false; |
6679 | } |
6680 | |
6681 | bool IsEnumDeclComplete(EnumDecl *); |
6682 | bool IsEnumDeclScoped(EnumDecl *); |
6683 | |
6684 | inline bool Type::isIntegerType() const { |
6685 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6686 | return BT->getKind() >= BuiltinType::Bool && |
6687 | BT->getKind() <= BuiltinType::Int128; |
6688 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6689 | // Incomplete enum types are not treated as integer types. |
6690 | // FIXME: In C++, enum types are never integer types. |
6691 | return IsEnumDeclComplete(ET->getDecl()) && |
6692 | !IsEnumDeclScoped(ET->getDecl()); |
6693 | } |
6694 | return false; |
6695 | } |
6696 | |
6697 | inline bool Type::isFixedPointType() const { |
6698 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6699 | return BT->getKind() >= BuiltinType::ShortAccum && |
6700 | BT->getKind() <= BuiltinType::SatULongFract; |
6701 | } |
6702 | return false; |
6703 | } |
6704 | |
6705 | inline bool Type::isFixedPointOrIntegerType() const { |
6706 | return isFixedPointType() || isIntegerType(); |
6707 | } |
6708 | |
6709 | inline bool Type::isSaturatedFixedPointType() const { |
6710 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6711 | return BT->getKind() >= BuiltinType::SatShortAccum && |
6712 | BT->getKind() <= BuiltinType::SatULongFract; |
6713 | } |
6714 | return false; |
6715 | } |
6716 | |
6717 | inline bool Type::isUnsaturatedFixedPointType() const { |
6718 | return isFixedPointType() && !isSaturatedFixedPointType(); |
6719 | } |
6720 | |
6721 | inline bool Type::isSignedFixedPointType() const { |
6722 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6723 | return ((BT->getKind() >= BuiltinType::ShortAccum && |
6724 | BT->getKind() <= BuiltinType::LongAccum) || |
6725 | (BT->getKind() >= BuiltinType::ShortFract && |
6726 | BT->getKind() <= BuiltinType::LongFract) || |
6727 | (BT->getKind() >= BuiltinType::SatShortAccum && |
6728 | BT->getKind() <= BuiltinType::SatLongAccum) || |
6729 | (BT->getKind() >= BuiltinType::SatShortFract && |
6730 | BT->getKind() <= BuiltinType::SatLongFract)); |
6731 | } |
6732 | return false; |
6733 | } |
6734 | |
6735 | inline bool Type::isUnsignedFixedPointType() const { |
6736 | return isFixedPointType() && !isSignedFixedPointType(); |
6737 | } |
6738 | |
6739 | inline bool Type::isScalarType() const { |
6740 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6741 | return BT->getKind() > BuiltinType::Void && |
6742 | BT->getKind() <= BuiltinType::NullPtr; |
6743 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
6744 | // Enums are scalar types, but only if they are defined. Incomplete enums |
6745 | // are not treated as scalar types. |
6746 | return IsEnumDeclComplete(ET->getDecl()); |
6747 | return isa<PointerType>(CanonicalType) || |
6748 | isa<BlockPointerType>(CanonicalType) || |
6749 | isa<MemberPointerType>(CanonicalType) || |
6750 | isa<ComplexType>(CanonicalType) || |
6751 | isa<ObjCObjectPointerType>(CanonicalType); |
6752 | } |
6753 | |
6754 | inline bool Type::isIntegralOrEnumerationType() const { |
6755 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6756 | return BT->getKind() >= BuiltinType::Bool && |
6757 | BT->getKind() <= BuiltinType::Int128; |
6758 | |
6759 | // Check for a complete enum type; incomplete enum types are not properly an |
6760 | // enumeration type in the sense required here. |
6761 | if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) |
6762 | return IsEnumDeclComplete(ET->getDecl()); |
6763 | |
6764 | return false; |
6765 | } |
6766 | |
6767 | inline bool Type::isBooleanType() const { |
6768 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6769 | return BT->getKind() == BuiltinType::Bool; |
6770 | return false; |
6771 | } |
6772 | |
6773 | inline bool Type::isUndeducedType() const { |
6774 | auto *DT = getContainedDeducedType(); |
6775 | return DT && !DT->isDeduced(); |
6776 | } |
6777 | |
6778 | /// Determines whether this is a type for which one can define |
6779 | /// an overloaded operator. |
6780 | inline bool Type::isOverloadableType() const { |
6781 | return isDependentType() || isRecordType() || isEnumeralType(); |
6782 | } |
6783 | |
6784 | /// Determines whether this type can decay to a pointer type. |
6785 | inline bool Type::canDecayToPointerType() const { |
6786 | return isFunctionType() || isArrayType(); |
6787 | } |
6788 | |
6789 | inline bool Type::hasPointerRepresentation() const { |
6790 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
6791 | isObjCObjectPointerType() || isNullPtrType()); |
6792 | } |
6793 | |
6794 | inline bool Type::hasObjCPointerRepresentation() const { |
6795 | return isObjCObjectPointerType(); |
6796 | } |
6797 | |
6798 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
6799 | const Type *type = this; |
6800 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
6801 | type = arrayType->getElementType().getTypePtr(); |
6802 | return type; |
6803 | } |
6804 | |
6805 | inline const Type *Type::getPointeeOrArrayElementType() const { |
6806 | const Type *type = this; |
6807 | if (type->isAnyPointerType()) |
6808 | return type->getPointeeType().getTypePtr(); |
6809 | else if (type->isArrayType()) |
6810 | return type->getBaseElementTypeUnsafe(); |
6811 | return type; |
6812 | } |
6813 | |
6814 | /// Insertion operator for diagnostics. This allows sending Qualifiers into a |
6815 | /// diagnostic with <<. |
6816 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6817 | Qualifiers Q) { |
6818 | DB.AddTaggedVal(Q.getAsOpaqueValue(), |
6819 | DiagnosticsEngine::ArgumentKind::ak_qual); |
6820 | return DB; |
6821 | } |
6822 | |
6823 | /// Insertion operator for partial diagnostics. This allows sending Qualifiers |
6824 | /// into a diagnostic with <<. |
6825 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6826 | Qualifiers Q) { |
6827 | PD.AddTaggedVal(Q.getAsOpaqueValue(), |
6828 | DiagnosticsEngine::ArgumentKind::ak_qual); |
6829 | return PD; |
6830 | } |
6831 | |
6832 | /// Insertion operator for diagnostics. This allows sending QualType's into a |
6833 | /// diagnostic with <<. |
6834 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6835 | QualType T) { |
6836 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6837 | DiagnosticsEngine::ak_qualtype); |
6838 | return DB; |
6839 | } |
6840 | |
6841 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
6842 | /// into a diagnostic with <<. |
6843 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6844 | QualType T) { |
6845 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6846 | DiagnosticsEngine::ak_qualtype); |
6847 | return PD; |
6848 | } |
6849 | |
6850 | // Helper class template that is used by Type::getAs to ensure that one does |
6851 | // not try to look through a qualified type to get to an array type. |
6852 | template <typename T> |
6853 | using TypeIsArrayType = |
6854 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
6855 | std::is_base_of<ArrayType, T>::value>; |
6856 | |
6857 | // Member-template getAs<specific type>'. |
6858 | template <typename T> const T *Type::getAs() const { |
6859 | static_assert(!TypeIsArrayType<T>::value, |
6860 | "ArrayType cannot be used with getAs!"); |
6861 | |
6862 | // If this is directly a T type, return it. |
6863 | if (const auto *Ty = dyn_cast<T>(this)) |
6864 | return Ty; |
6865 | |
6866 | // If the canonical form of this type isn't the right kind, reject it. |
6867 | if (!isa<T>(CanonicalType)) |
6868 | return nullptr; |
6869 | |
6870 | // If this is a typedef for the type, strip the typedef off without |
6871 | // losing all typedef information. |
6872 | return cast<T>(getUnqualifiedDesugaredType()); |
6873 | } |
6874 | |
6875 | template <typename T> const T *Type::getAsAdjusted() const { |
6876 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
6877 | |
6878 | // If this is directly a T type, return it. |
6879 | if (const auto *Ty = dyn_cast<T>(this)) |
6880 | return Ty; |
6881 | |
6882 | // If the canonical form of this type isn't the right kind, reject it. |
6883 | if (!isa<T>(CanonicalType)) |
6884 | return nullptr; |
6885 | |
6886 | // Strip off type adjustments that do not modify the underlying nature of the |
6887 | // type. |
6888 | const Type *Ty = this; |
6889 | while (Ty) { |
6890 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
6891 | Ty = A->getModifiedType().getTypePtr(); |
6892 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
6893 | Ty = E->desugar().getTypePtr(); |
6894 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
6895 | Ty = P->desugar().getTypePtr(); |
6896 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
6897 | Ty = A->desugar().getTypePtr(); |
6898 | else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) |
6899 | Ty = M->desugar().getTypePtr(); |
6900 | else |
6901 | break; |
6902 | } |
6903 | |
6904 | // Just because the canonical type is correct does not mean we can use cast<>, |
6905 | // since we may not have stripped off all the sugar down to the base type. |
6906 | return dyn_cast<T>(Ty); |
6907 | } |
6908 | |
6909 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
6910 | // If this is directly an array type, return it. |
6911 | if (const auto *arr = dyn_cast<ArrayType>(this)) |
6912 | return arr; |
6913 | |
6914 | // If the canonical form of this type isn't the right kind, reject it. |
6915 | if (!isa<ArrayType>(CanonicalType)) |
6916 | return nullptr; |
6917 | |
6918 | // If this is a typedef for the type, strip the typedef off without |
6919 | // losing all typedef information. |
6920 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
6921 | } |
6922 | |
6923 | template <typename T> const T *Type::castAs() const { |
6924 | static_assert(!TypeIsArrayType<T>::value, |
6925 | "ArrayType cannot be used with castAs!"); |
6926 | |
6927 | if (const auto *ty = dyn_cast<T>(this)) return ty; |
6928 | assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6928, __PRETTY_FUNCTION__)); |
6929 | return cast<T>(getUnqualifiedDesugaredType()); |
6930 | } |
6931 | |
6932 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
6933 | assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6933, __PRETTY_FUNCTION__)); |
6934 | if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; |
6935 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
6936 | } |
6937 | |
6938 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
6939 | QualType CanonicalPtr) |
6940 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
6941 | #ifndef NDEBUG |
6942 | QualType Adjusted = getAdjustedType(); |
6943 | (void)AttributedType::stripOuterNullability(Adjusted); |
6944 | assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6944, __PRETTY_FUNCTION__)); |
6945 | #endif |
6946 | } |
6947 | |
6948 | QualType DecayedType::getPointeeType() const { |
6949 | QualType Decayed = getDecayedType(); |
6950 | (void)AttributedType::stripOuterNullability(Decayed); |
6951 | return cast<PointerType>(Decayed)->getPointeeType(); |
6952 | } |
6953 | |
6954 | // Get the decimal string representation of a fixed point type, represented |
6955 | // as a scaled integer. |
6956 | // TODO: At some point, we should change the arguments to instead just accept an |
6957 | // APFixedPoint instead of APSInt and scale. |
6958 | void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, |
6959 | unsigned Scale); |
6960 | |
6961 | } // namespace clang |
6962 | |
6963 | #endif // LLVM_CLANG_AST_TYPE_H |