Bug Summary

File:tools/clang/lib/AST/ExprConstant.cpp
Warning:line 2422, column 27
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ExprConstant.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/AST -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
34//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
38#include "clang/AST/ASTDiagnostic.h"
39#include "clang/AST/ASTLambda.h"
40#include "clang/AST/CharUnits.h"
41#include "clang/AST/Expr.h"
42#include "clang/AST/RecordLayout.h"
43#include "clang/AST/StmtVisitor.h"
44#include "clang/AST/TypeLoc.h"
45#include "clang/Basic/Builtins.h"
46#include "clang/Basic/TargetInfo.h"
47#include "llvm/Support/raw_ostream.h"
48#include <cstring>
49#include <functional>
50
51#define DEBUG_TYPE"exprconstant" "exprconstant"
52
53using namespace clang;
54using llvm::APSInt;
55using llvm::APFloat;
56
57static bool IsGlobalLValue(APValue::LValueBase B);
58
59namespace {
60 struct LValue;
61 struct CallStackFrame;
62 struct EvalInfo;
63
64 static QualType getType(APValue::LValueBase B) {
65 if (!B) return QualType();
66 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
67 // FIXME: It's unclear where we're supposed to take the type from, and
68 // this actually matters for arrays of unknown bound. Eg:
69 //
70 // extern int arr[]; void f() { extern int arr[3]; };
71 // constexpr int *p = &arr[1]; // valid?
72 //
73 // For now, we take the array bound from the most recent declaration.
74 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
75 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
76 QualType T = Redecl->getType();
77 if (!T->isIncompleteArrayType())
78 return T;
79 }
80 return D->getType();
81 }
82
83 const Expr *Base = B.get<const Expr*>();
84
85 // For a materialized temporary, the type of the temporary we materialized
86 // may not be the type of the expression.
87 if (const MaterializeTemporaryExpr *MTE =
88 dyn_cast<MaterializeTemporaryExpr>(Base)) {
89 SmallVector<const Expr *, 2> CommaLHSs;
90 SmallVector<SubobjectAdjustment, 2> Adjustments;
91 const Expr *Temp = MTE->GetTemporaryExpr();
92 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
93 Adjustments);
94 // Keep any cv-qualifiers from the reference if we generated a temporary
95 // for it directly. Otherwise use the type after adjustment.
96 if (!Adjustments.empty())
97 return Inner->getType();
98 }
99
100 return Base->getType();
101 }
102
103 /// Get an LValue path entry, which is known to not be an array index, as a
104 /// field or base class.
105 static
106 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
107 APValue::BaseOrMemberType Value;
108 Value.setFromOpaqueValue(E.BaseOrMember);
109 return Value;
110 }
111
112 /// Get an LValue path entry, which is known to not be an array index, as a
113 /// field declaration.
114 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
115 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
116 }
117 /// Get an LValue path entry, which is known to not be an array index, as a
118 /// base class declaration.
119 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
120 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
121 }
122 /// Determine whether this LValue path entry for a base class names a virtual
123 /// base class.
124 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
125 return getAsBaseOrMember(E).getInt();
126 }
127
128 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
129 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
130 const FunctionDecl *Callee = CE->getDirectCallee();
131 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
132 }
133
134 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
135 /// This will look through a single cast.
136 ///
137 /// Returns null if we couldn't unwrap a function with alloc_size.
138 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
139 if (!E->getType()->isPointerType())
140 return nullptr;
141
142 E = E->IgnoreParens();
143 // If we're doing a variable assignment from e.g. malloc(N), there will
144 // probably be a cast of some kind. In exotic cases, we might also see a
145 // top-level ExprWithCleanups. Ignore them either way.
146 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
147 E = EC->getSubExpr()->IgnoreParens();
148
149 if (const auto *Cast = dyn_cast<CastExpr>(E))
150 E = Cast->getSubExpr()->IgnoreParens();
151
152 if (const auto *CE = dyn_cast<CallExpr>(E))
153 return getAllocSizeAttr(CE) ? CE : nullptr;
154 return nullptr;
155 }
156
157 /// Determines whether or not the given Base contains a call to a function
158 /// with the alloc_size attribute.
159 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
160 const auto *E = Base.dyn_cast<const Expr *>();
161 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
162 }
163
164 /// The bound to claim that an array of unknown bound has.
165 /// The value in MostDerivedArraySize is undefined in this case. So, set it
166 /// to an arbitrary value that's likely to loudly break things if it's used.
167 static const uint64_t AssumedSizeForUnsizedArray =
168 std::numeric_limits<uint64_t>::max() / 2;
169
170 /// Determines if an LValue with the given LValueBase will have an unsized
171 /// array in its designator.
172 /// Find the path length and type of the most-derived subobject in the given
173 /// path, and find the size of the containing array, if any.
174 static unsigned
175 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
176 ArrayRef<APValue::LValuePathEntry> Path,
177 uint64_t &ArraySize, QualType &Type, bool &IsArray,
178 bool &FirstEntryIsUnsizedArray) {
179 // This only accepts LValueBases from APValues, and APValues don't support
180 // arrays that lack size info.
181 assert(!isBaseAnAllocSizeCall(Base) &&(static_cast <bool> (!isBaseAnAllocSizeCall(Base) &&
"Unsized arrays shouldn't appear here") ? void (0) : __assert_fail
("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 182, __extension__ __PRETTY_FUNCTION__))
182 "Unsized arrays shouldn't appear here")(static_cast <bool> (!isBaseAnAllocSizeCall(Base) &&
"Unsized arrays shouldn't appear here") ? void (0) : __assert_fail
("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 182, __extension__ __PRETTY_FUNCTION__))
;
183 unsigned MostDerivedLength = 0;
184 Type = getType(Base);
185
186 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
187 if (Type->isArrayType()) {
188 const ArrayType *AT = Ctx.getAsArrayType(Type);
189 Type = AT->getElementType();
190 MostDerivedLength = I + 1;
191 IsArray = true;
192
193 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
194 ArraySize = CAT->getSize().getZExtValue();
195 } else {
196 assert(I == 0 && "unexpected unsized array designator")(static_cast <bool> (I == 0 && "unexpected unsized array designator"
) ? void (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 196, __extension__ __PRETTY_FUNCTION__))
;
197 FirstEntryIsUnsizedArray = true;
198 ArraySize = AssumedSizeForUnsizedArray;
199 }
200 } else if (Type->isAnyComplexType()) {
201 const ComplexType *CT = Type->castAs<ComplexType>();
202 Type = CT->getElementType();
203 ArraySize = 2;
204 MostDerivedLength = I + 1;
205 IsArray = true;
206 } else if (const FieldDecl *FD = getAsField(Path[I])) {
207 Type = FD->getType();
208 ArraySize = 0;
209 MostDerivedLength = I + 1;
210 IsArray = false;
211 } else {
212 // Path[I] describes a base class.
213 ArraySize = 0;
214 IsArray = false;
215 }
216 }
217 return MostDerivedLength;
218 }
219
220 // The order of this enum is important for diagnostics.
221 enum CheckSubobjectKind {
222 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
223 CSK_This, CSK_Real, CSK_Imag
224 };
225
226 /// A path from a glvalue to a subobject of that glvalue.
227 struct SubobjectDesignator {
228 /// True if the subobject was named in a manner not supported by C++11. Such
229 /// lvalues can still be folded, but they are not core constant expressions
230 /// and we cannot perform lvalue-to-rvalue conversions on them.
231 unsigned Invalid : 1;
232
233 /// Is this a pointer one past the end of an object?
234 unsigned IsOnePastTheEnd : 1;
235
236 /// Indicator of whether the first entry is an unsized array.
237 unsigned FirstEntryIsAnUnsizedArray : 1;
238
239 /// Indicator of whether the most-derived object is an array element.
240 unsigned MostDerivedIsArrayElement : 1;
241
242 /// The length of the path to the most-derived object of which this is a
243 /// subobject.
244 unsigned MostDerivedPathLength : 28;
245
246 /// The size of the array of which the most-derived object is an element.
247 /// This will always be 0 if the most-derived object is not an array
248 /// element. 0 is not an indicator of whether or not the most-derived object
249 /// is an array, however, because 0-length arrays are allowed.
250 ///
251 /// If the current array is an unsized array, the value of this is
252 /// undefined.
253 uint64_t MostDerivedArraySize;
254
255 /// The type of the most derived object referred to by this address.
256 QualType MostDerivedType;
257
258 typedef APValue::LValuePathEntry PathEntry;
259
260 /// The entries on the path from the glvalue to the designated subobject.
261 SmallVector<PathEntry, 8> Entries;
262
263 SubobjectDesignator() : Invalid(true) {}
264
265 explicit SubobjectDesignator(QualType T)
266 : Invalid(false), IsOnePastTheEnd(false),
267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
268 MostDerivedPathLength(0), MostDerivedArraySize(0),
269 MostDerivedType(T) {}
270
271 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
272 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
274 MostDerivedPathLength(0), MostDerivedArraySize(0) {
275 assert(V.isLValue() && "Non-LValue used to make an LValue designator?")(static_cast <bool> (V.isLValue() && "Non-LValue used to make an LValue designator?"
) ? void (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 275, __extension__ __PRETTY_FUNCTION__))
;
276 if (!Invalid) {
277 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
278 ArrayRef<PathEntry> VEntries = V.getLValuePath();
279 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
280 if (V.getLValueBase()) {
281 bool IsArray = false;
282 bool FirstIsUnsizedArray = false;
283 MostDerivedPathLength = findMostDerivedSubobject(
284 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
285 MostDerivedType, IsArray, FirstIsUnsizedArray);
286 MostDerivedIsArrayElement = IsArray;
287 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
288 }
289 }
290 }
291
292 void setInvalid() {
293 Invalid = true;
294 Entries.clear();
295 }
296
297 /// Determine whether the most derived subobject is an array without a
298 /// known bound.
299 bool isMostDerivedAnUnsizedArray() const {
300 assert(!Invalid && "Calling this makes no sense on invalid designators")(static_cast <bool> (!Invalid && "Calling this makes no sense on invalid designators"
) ? void (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 300, __extension__ __PRETTY_FUNCTION__))
;
301 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
302 }
303
304 /// Determine what the most derived array's size is. Results in an assertion
305 /// failure if the most derived array lacks a size.
306 uint64_t getMostDerivedArraySize() const {
307 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")(static_cast <bool> (!isMostDerivedAnUnsizedArray() &&
"Unsized array has no size") ? void (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 307, __extension__ __PRETTY_FUNCTION__))
;
308 return MostDerivedArraySize;
309 }
310
311 /// Determine whether this is a one-past-the-end pointer.
312 bool isOnePastTheEnd() const {
313 assert(!Invalid)(static_cast <bool> (!Invalid) ? void (0) : __assert_fail
("!Invalid", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 313, __extension__ __PRETTY_FUNCTION__))
;
314 if (IsOnePastTheEnd)
315 return true;
316 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
317 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
318 return true;
319 return false;
320 }
321
322 /// Check that this refers to a valid subobject.
323 bool isValidSubobject() const {
324 if (Invalid)
325 return false;
326 return !isOnePastTheEnd();
327 }
328 /// Check that this refers to a valid subobject, and if not, produce a
329 /// relevant diagnostic and set the designator as invalid.
330 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
331
332 /// Update this designator to refer to the first element within this array.
333 void addArrayUnchecked(const ConstantArrayType *CAT) {
334 PathEntry Entry;
335 Entry.ArrayIndex = 0;
336 Entries.push_back(Entry);
337
338 // This is a most-derived object.
339 MostDerivedType = CAT->getElementType();
340 MostDerivedIsArrayElement = true;
341 MostDerivedArraySize = CAT->getSize().getZExtValue();
342 MostDerivedPathLength = Entries.size();
343 }
344 /// Update this designator to refer to the first element within the array of
345 /// elements of type T. This is an array of unknown size.
346 void addUnsizedArrayUnchecked(QualType ElemTy) {
347 PathEntry Entry;
348 Entry.ArrayIndex = 0;
349 Entries.push_back(Entry);
350
351 MostDerivedType = ElemTy;
352 MostDerivedIsArrayElement = true;
353 // The value in MostDerivedArraySize is undefined in this case. So, set it
354 // to an arbitrary value that's likely to loudly break things if it's
355 // used.
356 MostDerivedArraySize = AssumedSizeForUnsizedArray;
357 MostDerivedPathLength = Entries.size();
358 }
359 /// Update this designator to refer to the given base or member of this
360 /// object.
361 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
362 PathEntry Entry;
363 APValue::BaseOrMemberType Value(D, Virtual);
364 Entry.BaseOrMember = Value.getOpaqueValue();
365 Entries.push_back(Entry);
366
367 // If this isn't a base class, it's a new most-derived object.
368 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
369 MostDerivedType = FD->getType();
370 MostDerivedIsArrayElement = false;
371 MostDerivedArraySize = 0;
372 MostDerivedPathLength = Entries.size();
373 }
374 }
375 /// Update this designator to refer to the given complex component.
376 void addComplexUnchecked(QualType EltTy, bool Imag) {
377 PathEntry Entry;
378 Entry.ArrayIndex = Imag;
379 Entries.push_back(Entry);
380
381 // This is technically a most-derived object, though in practice this
382 // is unlikely to matter.
383 MostDerivedType = EltTy;
384 MostDerivedIsArrayElement = true;
385 MostDerivedArraySize = 2;
386 MostDerivedPathLength = Entries.size();
387 }
388 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
389 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
390 const APSInt &N);
391 /// Add N to the address of this subobject.
392 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
393 if (Invalid || !N) return;
394 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
395 if (isMostDerivedAnUnsizedArray()) {
396 diagnoseUnsizedArrayPointerArithmetic(Info, E);
397 // Can't verify -- trust that the user is doing the right thing (or if
398 // not, trust that the caller will catch the bad behavior).
399 // FIXME: Should we reject if this overflows, at least?
400 Entries.back().ArrayIndex += TruncatedN;
401 return;
402 }
403
404 // [expr.add]p4: For the purposes of these operators, a pointer to a
405 // nonarray object behaves the same as a pointer to the first element of
406 // an array of length one with the type of the object as its element type.
407 bool IsArray = MostDerivedPathLength == Entries.size() &&
408 MostDerivedIsArrayElement;
409 uint64_t ArrayIndex =
410 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
411 uint64_t ArraySize =
412 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
413
414 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
415 // Calculate the actual index in a wide enough type, so we can include
416 // it in the note.
417 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
418 (llvm::APInt&)N += ArrayIndex;
419 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")(static_cast <bool> (N.ugt(ArraySize) && "bounds check failed for in-bounds index"
) ? void (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 419, __extension__ __PRETTY_FUNCTION__))
;
420 diagnosePointerArithmetic(Info, E, N);
421 setInvalid();
422 return;
423 }
424
425 ArrayIndex += TruncatedN;
426 assert(ArrayIndex <= ArraySize &&(static_cast <bool> (ArrayIndex <= ArraySize &&
"bounds check succeeded for out-of-bounds index") ? void (0)
: __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 427, __extension__ __PRETTY_FUNCTION__))
427 "bounds check succeeded for out-of-bounds index")(static_cast <bool> (ArrayIndex <= ArraySize &&
"bounds check succeeded for out-of-bounds index") ? void (0)
: __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 427, __extension__ __PRETTY_FUNCTION__))
;
428
429 if (IsArray)
430 Entries.back().ArrayIndex = ArrayIndex;
431 else
432 IsOnePastTheEnd = (ArrayIndex != 0);
433 }
434 };
435
436 /// A stack frame in the constexpr call stack.
437 struct CallStackFrame {
438 EvalInfo &Info;
439
440 /// Parent - The caller of this stack frame.
441 CallStackFrame *Caller;
442
443 /// Callee - The function which was called.
444 const FunctionDecl *Callee;
445
446 /// This - The binding for the this pointer in this call, if any.
447 const LValue *This;
448
449 /// Arguments - Parameter bindings for this function call, indexed by
450 /// parameters' function scope indices.
451 APValue *Arguments;
452
453 // Note that we intentionally use std::map here so that references to
454 // values are stable.
455 typedef std::pair<const void *, unsigned> MapKeyTy;
456 typedef std::map<MapKeyTy, APValue> MapTy;
457 /// Temporaries - Temporary lvalues materialized within this stack frame.
458 MapTy Temporaries;
459
460 /// CallLoc - The location of the call expression for this call.
461 SourceLocation CallLoc;
462
463 /// Index - The call index of this call.
464 unsigned Index;
465
466 /// The stack of integers for tracking version numbers for temporaries.
467 SmallVector<unsigned, 2> TempVersionStack = {1};
468 unsigned CurTempVersion = TempVersionStack.back();
469
470 unsigned getTempVersion() const { return TempVersionStack.back(); }
471
472 void pushTempVersion() {
473 TempVersionStack.push_back(++CurTempVersion);
474 }
475
476 void popTempVersion() {
477 TempVersionStack.pop_back();
478 }
479
480 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
481 // on the overall stack usage of deeply-recursing constexpr evaluataions.
482 // (We should cache this map rather than recomputing it repeatedly.)
483 // But let's try this and see how it goes; we can look into caching the map
484 // as a later change.
485
486 /// LambdaCaptureFields - Mapping from captured variables/this to
487 /// corresponding data members in the closure class.
488 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
489 FieldDecl *LambdaThisCaptureField;
490
491 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
492 const FunctionDecl *Callee, const LValue *This,
493 APValue *Arguments);
494 ~CallStackFrame();
495
496 // Return the temporary for Key whose version number is Version.
497 APValue *getTemporary(const void *Key, unsigned Version) {
498 MapKeyTy KV(Key, Version);
499 auto LB = Temporaries.lower_bound(KV);
500 if (LB != Temporaries.end() && LB->first == KV)
501 return &LB->second;
502 // Pair (Key,Version) wasn't found in the map. Check that no elements
503 // in the map have 'Key' as their key.
504 assert((LB == Temporaries.end() || LB->first.first != Key) &&(static_cast <bool> ((LB == Temporaries.end() || LB->
first.first != Key) && (LB == Temporaries.begin() || std
::prev(LB)->first.first != Key) && "Element with key 'Key' found in map"
) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 506, __extension__ __PRETTY_FUNCTION__))
505 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&(static_cast <bool> ((LB == Temporaries.end() || LB->
first.first != Key) && (LB == Temporaries.begin() || std
::prev(LB)->first.first != Key) && "Element with key 'Key' found in map"
) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 506, __extension__ __PRETTY_FUNCTION__))
506 "Element with key 'Key' found in map")(static_cast <bool> ((LB == Temporaries.end() || LB->
first.first != Key) && (LB == Temporaries.begin() || std
::prev(LB)->first.first != Key) && "Element with key 'Key' found in map"
) ? void (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 506, __extension__ __PRETTY_FUNCTION__))
;
507 return nullptr;
508 }
509
510 // Return the current temporary for Key in the map.
511 APValue *getCurrentTemporary(const void *Key) {
512 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
513 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
514 return &std::prev(UB)->second;
515 return nullptr;
516 }
517
518 // Return the version number of the current temporary for Key.
519 unsigned getCurrentTemporaryVersion(const void *Key) const {
520 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
521 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
522 return std::prev(UB)->first.second;
523 return 0;
524 }
525
526 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
527 };
528
529 /// Temporarily override 'this'.
530 class ThisOverrideRAII {
531 public:
532 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
533 : Frame(Frame), OldThis(Frame.This) {
534 if (Enable)
535 Frame.This = NewThis;
536 }
537 ~ThisOverrideRAII() {
538 Frame.This = OldThis;
539 }
540 private:
541 CallStackFrame &Frame;
542 const LValue *OldThis;
543 };
544
545 /// A partial diagnostic which we might know in advance that we are not going
546 /// to emit.
547 class OptionalDiagnostic {
548 PartialDiagnostic *Diag;
549
550 public:
551 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
552 : Diag(Diag) {}
553
554 template<typename T>
555 OptionalDiagnostic &operator<<(const T &v) {
556 if (Diag)
557 *Diag << v;
558 return *this;
559 }
560
561 OptionalDiagnostic &operator<<(const APSInt &I) {
562 if (Diag) {
563 SmallVector<char, 32> Buffer;
564 I.toString(Buffer);
565 *Diag << StringRef(Buffer.data(), Buffer.size());
566 }
567 return *this;
568 }
569
570 OptionalDiagnostic &operator<<(const APFloat &F) {
571 if (Diag) {
572 // FIXME: Force the precision of the source value down so we don't
573 // print digits which are usually useless (we don't really care here if
574 // we truncate a digit by accident in edge cases). Ideally,
575 // APFloat::toString would automatically print the shortest
576 // representation which rounds to the correct value, but it's a bit
577 // tricky to implement.
578 unsigned precision =
579 llvm::APFloat::semanticsPrecision(F.getSemantics());
580 precision = (precision * 59 + 195) / 196;
581 SmallVector<char, 32> Buffer;
582 F.toString(Buffer, precision);
583 *Diag << StringRef(Buffer.data(), Buffer.size());
584 }
585 return *this;
586 }
587 };
588
589 /// A cleanup, and a flag indicating whether it is lifetime-extended.
590 class Cleanup {
591 llvm::PointerIntPair<APValue*, 1, bool> Value;
592
593 public:
594 Cleanup(APValue *Val, bool IsLifetimeExtended)
595 : Value(Val, IsLifetimeExtended) {}
596
597 bool isLifetimeExtended() const { return Value.getInt(); }
598 void endLifetime() {
599 *Value.getPointer() = APValue();
600 }
601 };
602
603 /// EvalInfo - This is a private struct used by the evaluator to capture
604 /// information about a subexpression as it is folded. It retains information
605 /// about the AST context, but also maintains information about the folded
606 /// expression.
607 ///
608 /// If an expression could be evaluated, it is still possible it is not a C
609 /// "integer constant expression" or constant expression. If not, this struct
610 /// captures information about how and why not.
611 ///
612 /// One bit of information passed *into* the request for constant folding
613 /// indicates whether the subexpression is "evaluated" or not according to C
614 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
615 /// evaluate the expression regardless of what the RHS is, but C only allows
616 /// certain things in certain situations.
617 struct EvalInfo {
618 ASTContext &Ctx;
619
620 /// EvalStatus - Contains information about the evaluation.
621 Expr::EvalStatus &EvalStatus;
622
623 /// CurrentCall - The top of the constexpr call stack.
624 CallStackFrame *CurrentCall;
625
626 /// CallStackDepth - The number of calls in the call stack right now.
627 unsigned CallStackDepth;
628
629 /// NextCallIndex - The next call index to assign.
630 unsigned NextCallIndex;
631
632 /// StepsLeft - The remaining number of evaluation steps we're permitted
633 /// to perform. This is essentially a limit for the number of statements
634 /// we will evaluate.
635 unsigned StepsLeft;
636
637 /// BottomFrame - The frame in which evaluation started. This must be
638 /// initialized after CurrentCall and CallStackDepth.
639 CallStackFrame BottomFrame;
640
641 /// A stack of values whose lifetimes end at the end of some surrounding
642 /// evaluation frame.
643 llvm::SmallVector<Cleanup, 16> CleanupStack;
644
645 /// EvaluatingDecl - This is the declaration whose initializer is being
646 /// evaluated, if any.
647 APValue::LValueBase EvaluatingDecl;
648
649 /// EvaluatingDeclValue - This is the value being constructed for the
650 /// declaration whose initializer is being evaluated, if any.
651 APValue *EvaluatingDeclValue;
652
653 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
654 /// the call index that that lvalue was allocated in.
655 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
656 EvaluatingObject;
657
658 /// EvaluatingConstructors - Set of objects that are currently being
659 /// constructed.
660 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
661
662 struct EvaluatingConstructorRAII {
663 EvalInfo &EI;
664 EvaluatingObject Object;
665 bool DidInsert;
666 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
667 : EI(EI), Object(Object) {
668 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
669 }
670 ~EvaluatingConstructorRAII() {
671 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
672 }
673 };
674
675 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
676 unsigned Version) {
677 return EvaluatingConstructors.count(
678 EvaluatingObject(Decl, {CallIndex, Version}));
679 }
680
681 /// The current array initialization index, if we're performing array
682 /// initialization.
683 uint64_t ArrayInitIndex = -1;
684
685 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
686 /// notes attached to it will also be stored, otherwise they will not be.
687 bool HasActiveDiagnostic;
688
689 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
690 /// fold (not just why it's not strictly a constant expression)?
691 bool HasFoldFailureDiagnostic;
692
693 /// \brief Whether or not we're currently speculatively evaluating.
694 bool IsSpeculativelyEvaluating;
695
696 enum EvaluationMode {
697 /// Evaluate as a constant expression. Stop if we find that the expression
698 /// is not a constant expression.
699 EM_ConstantExpression,
700
701 /// Evaluate as a potential constant expression. Keep going if we hit a
702 /// construct that we can't evaluate yet (because we don't yet know the
703 /// value of something) but stop if we hit something that could never be
704 /// a constant expression.
705 EM_PotentialConstantExpression,
706
707 /// Fold the expression to a constant. Stop if we hit a side-effect that
708 /// we can't model.
709 EM_ConstantFold,
710
711 /// Evaluate the expression looking for integer overflow and similar
712 /// issues. Don't worry about side-effects, and try to visit all
713 /// subexpressions.
714 EM_EvaluateForOverflow,
715
716 /// Evaluate in any way we know how. Don't worry about side-effects that
717 /// can't be modeled.
718 EM_IgnoreSideEffects,
719
720 /// Evaluate as a constant expression. Stop if we find that the expression
721 /// is not a constant expression. Some expressions can be retried in the
722 /// optimizer if we don't constant fold them here, but in an unevaluated
723 /// context we try to fold them immediately since the optimizer never
724 /// gets a chance to look at it.
725 EM_ConstantExpressionUnevaluated,
726
727 /// Evaluate as a potential constant expression. Keep going if we hit a
728 /// construct that we can't evaluate yet (because we don't yet know the
729 /// value of something) but stop if we hit something that could never be
730 /// a constant expression. Some expressions can be retried in the
731 /// optimizer if we don't constant fold them here, but in an unevaluated
732 /// context we try to fold them immediately since the optimizer never
733 /// gets a chance to look at it.
734 EM_PotentialConstantExpressionUnevaluated,
735
736 /// Evaluate as a constant expression. In certain scenarios, if:
737 /// - we find a MemberExpr with a base that can't be evaluated, or
738 /// - we find a variable initialized with a call to a function that has
739 /// the alloc_size attribute on it
740 /// then we may consider evaluation to have succeeded.
741 ///
742 /// In either case, the LValue returned shall have an invalid base; in the
743 /// former, the base will be the invalid MemberExpr, in the latter, the
744 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
745 /// said CallExpr.
746 EM_OffsetFold,
747 } EvalMode;
748
749 /// Are we checking whether the expression is a potential constant
750 /// expression?
751 bool checkingPotentialConstantExpression() const {
752 return EvalMode == EM_PotentialConstantExpression ||
753 EvalMode == EM_PotentialConstantExpressionUnevaluated;
754 }
755
756 /// Are we checking an expression for overflow?
757 // FIXME: We should check for any kind of undefined or suspicious behavior
758 // in such constructs, not just overflow.
759 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
760
761 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
762 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
763 CallStackDepth(0), NextCallIndex(1),
764 StepsLeft(getLangOpts().ConstexprStepLimit),
765 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
766 EvaluatingDecl((const ValueDecl *)nullptr),
767 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
768 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
769 EvalMode(Mode) {}
770
771 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
772 EvaluatingDecl = Base;
773 EvaluatingDeclValue = &Value;
774 EvaluatingConstructors.insert({Base, {0, 0}});
775 }
776
777 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
778
779 bool CheckCallLimit(SourceLocation Loc) {
780 // Don't perform any constexpr calls (other than the call we're checking)
781 // when checking a potential constant expression.
782 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
783 return false;
784 if (NextCallIndex == 0) {
785 // NextCallIndex has wrapped around.
786 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
787 return false;
788 }
789 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
790 return true;
791 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
792 << getLangOpts().ConstexprCallDepth;
793 return false;
794 }
795
796 CallStackFrame *getCallFrame(unsigned CallIndex) {
797 assert(CallIndex && "no call index in getCallFrame")(static_cast <bool> (CallIndex && "no call index in getCallFrame"
) ? void (0) : __assert_fail ("CallIndex && \"no call index in getCallFrame\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 797, __extension__ __PRETTY_FUNCTION__))
;
798 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
799 // be null in this loop.
800 CallStackFrame *Frame = CurrentCall;
801 while (Frame->Index > CallIndex)
802 Frame = Frame->Caller;
803 return (Frame->Index == CallIndex) ? Frame : nullptr;
804 }
805
806 bool nextStep(const Stmt *S) {
807 if (!StepsLeft) {
808 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
809 return false;
810 }
811 --StepsLeft;
812 return true;
813 }
814
815 private:
816 /// Add a diagnostic to the diagnostics list.
817 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
818 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
819 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
820 return EvalStatus.Diag->back().second;
821 }
822
823 /// Add notes containing a call stack to the current point of evaluation.
824 void addCallStack(unsigned Limit);
825
826 private:
827 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
828 unsigned ExtraNotes, bool IsCCEDiag) {
829
830 if (EvalStatus.Diag) {
831 // If we have a prior diagnostic, it will be noting that the expression
832 // isn't a constant expression. This diagnostic is more important,
833 // unless we require this evaluation to produce a constant expression.
834 //
835 // FIXME: We might want to show both diagnostics to the user in
836 // EM_ConstantFold mode.
837 if (!EvalStatus.Diag->empty()) {
838 switch (EvalMode) {
839 case EM_ConstantFold:
840 case EM_IgnoreSideEffects:
841 case EM_EvaluateForOverflow:
842 if (!HasFoldFailureDiagnostic)
843 break;
844 // We've already failed to fold something. Keep that diagnostic.
845 LLVM_FALLTHROUGH[[clang::fallthrough]];
846 case EM_ConstantExpression:
847 case EM_PotentialConstantExpression:
848 case EM_ConstantExpressionUnevaluated:
849 case EM_PotentialConstantExpressionUnevaluated:
850 case EM_OffsetFold:
851 HasActiveDiagnostic = false;
852 return OptionalDiagnostic();
853 }
854 }
855
856 unsigned CallStackNotes = CallStackDepth - 1;
857 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
858 if (Limit)
859 CallStackNotes = std::min(CallStackNotes, Limit + 1);
860 if (checkingPotentialConstantExpression())
861 CallStackNotes = 0;
862
863 HasActiveDiagnostic = true;
864 HasFoldFailureDiagnostic = !IsCCEDiag;
865 EvalStatus.Diag->clear();
866 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
867 addDiag(Loc, DiagId);
868 if (!checkingPotentialConstantExpression())
869 addCallStack(Limit);
870 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
871 }
872 HasActiveDiagnostic = false;
873 return OptionalDiagnostic();
874 }
875 public:
876 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
877 OptionalDiagnostic
878 FFDiag(SourceLocation Loc,
879 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
880 unsigned ExtraNotes = 0) {
881 return Diag(Loc, DiagId, ExtraNotes, false);
882 }
883
884 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
885 = diag::note_invalid_subexpr_in_const_expr,
886 unsigned ExtraNotes = 0) {
887 if (EvalStatus.Diag)
888 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
889 HasActiveDiagnostic = false;
890 return OptionalDiagnostic();
891 }
892
893 /// Diagnose that the evaluation does not produce a C++11 core constant
894 /// expression.
895 ///
896 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
897 /// EM_PotentialConstantExpression mode and we produce one of these.
898 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
899 = diag::note_invalid_subexpr_in_const_expr,
900 unsigned ExtraNotes = 0) {
901 // Don't override a previous diagnostic. Don't bother collecting
902 // diagnostics if we're evaluating for overflow.
903 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
904 HasActiveDiagnostic = false;
905 return OptionalDiagnostic();
906 }
907 return Diag(Loc, DiagId, ExtraNotes, true);
908 }
909 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
910 = diag::note_invalid_subexpr_in_const_expr,
911 unsigned ExtraNotes = 0) {
912 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
913 }
914 /// Add a note to a prior diagnostic.
915 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
916 if (!HasActiveDiagnostic)
917 return OptionalDiagnostic();
918 return OptionalDiagnostic(&addDiag(Loc, DiagId));
919 }
920
921 /// Add a stack of notes to a prior diagnostic.
922 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
923 if (HasActiveDiagnostic) {
924 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
925 Diags.begin(), Diags.end());
926 }
927 }
928
929 /// Should we continue evaluation after encountering a side-effect that we
930 /// couldn't model?
931 bool keepEvaluatingAfterSideEffect() {
932 switch (EvalMode) {
933 case EM_PotentialConstantExpression:
934 case EM_PotentialConstantExpressionUnevaluated:
935 case EM_EvaluateForOverflow:
936 case EM_IgnoreSideEffects:
937 return true;
938
939 case EM_ConstantExpression:
940 case EM_ConstantExpressionUnevaluated:
941 case EM_ConstantFold:
942 case EM_OffsetFold:
943 return false;
944 }
945 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 945)
;
946 }
947
948 /// Note that we have had a side-effect, and determine whether we should
949 /// keep evaluating.
950 bool noteSideEffect() {
951 EvalStatus.HasSideEffects = true;
952 return keepEvaluatingAfterSideEffect();
953 }
954
955 /// Should we continue evaluation after encountering undefined behavior?
956 bool keepEvaluatingAfterUndefinedBehavior() {
957 switch (EvalMode) {
958 case EM_EvaluateForOverflow:
959 case EM_IgnoreSideEffects:
960 case EM_ConstantFold:
961 case EM_OffsetFold:
962 return true;
963
964 case EM_PotentialConstantExpression:
965 case EM_PotentialConstantExpressionUnevaluated:
966 case EM_ConstantExpression:
967 case EM_ConstantExpressionUnevaluated:
968 return false;
969 }
970 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 970)
;
971 }
972
973 /// Note that we hit something that was technically undefined behavior, but
974 /// that we can evaluate past it (such as signed overflow or floating-point
975 /// division by zero.)
976 bool noteUndefinedBehavior() {
977 EvalStatus.HasUndefinedBehavior = true;
978 return keepEvaluatingAfterUndefinedBehavior();
979 }
980
981 /// Should we continue evaluation as much as possible after encountering a
982 /// construct which can't be reduced to a value?
983 bool keepEvaluatingAfterFailure() {
984 if (!StepsLeft)
985 return false;
986
987 switch (EvalMode) {
988 case EM_PotentialConstantExpression:
989 case EM_PotentialConstantExpressionUnevaluated:
990 case EM_EvaluateForOverflow:
991 return true;
992
993 case EM_ConstantExpression:
994 case EM_ConstantExpressionUnevaluated:
995 case EM_ConstantFold:
996 case EM_IgnoreSideEffects:
997 case EM_OffsetFold:
998 return false;
999 }
1000 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1000)
;
1001 }
1002
1003 /// Notes that we failed to evaluate an expression that other expressions
1004 /// directly depend on, and determine if we should keep evaluating. This
1005 /// should only be called if we actually intend to keep evaluating.
1006 ///
1007 /// Call noteSideEffect() instead if we may be able to ignore the value that
1008 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1009 ///
1010 /// (Foo(), 1) // use noteSideEffect
1011 /// (Foo() || true) // use noteSideEffect
1012 /// Foo() + 1 // use noteFailure
1013 LLVM_NODISCARD[[clang::warn_unused_result]] bool noteFailure() {
1014 // Failure when evaluating some expression often means there is some
1015 // subexpression whose evaluation was skipped. Therefore, (because we
1016 // don't track whether we skipped an expression when unwinding after an
1017 // evaluation failure) every evaluation failure that bubbles up from a
1018 // subexpression implies that a side-effect has potentially happened. We
1019 // skip setting the HasSideEffects flag to true until we decide to
1020 // continue evaluating after that point, which happens here.
1021 bool KeepGoing = keepEvaluatingAfterFailure();
1022 EvalStatus.HasSideEffects |= KeepGoing;
1023 return KeepGoing;
1024 }
1025
1026 class ArrayInitLoopIndex {
1027 EvalInfo &Info;
1028 uint64_t OuterIndex;
1029
1030 public:
1031 ArrayInitLoopIndex(EvalInfo &Info)
1032 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1033 Info.ArrayInitIndex = 0;
1034 }
1035 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1036
1037 operator uint64_t&() { return Info.ArrayInitIndex; }
1038 };
1039 };
1040
1041 /// Object used to treat all foldable expressions as constant expressions.
1042 struct FoldConstant {
1043 EvalInfo &Info;
1044 bool Enabled;
1045 bool HadNoPriorDiags;
1046 EvalInfo::EvaluationMode OldMode;
1047
1048 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1049 : Info(Info),
1050 Enabled(Enabled),
1051 HadNoPriorDiags(Info.EvalStatus.Diag &&
1052 Info.EvalStatus.Diag->empty() &&
1053 !Info.EvalStatus.HasSideEffects),
1054 OldMode(Info.EvalMode) {
1055 if (Enabled &&
1056 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1057 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1058 Info.EvalMode = EvalInfo::EM_ConstantFold;
1059 }
1060 void keepDiagnostics() { Enabled = false; }
1061 ~FoldConstant() {
1062 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1063 !Info.EvalStatus.HasSideEffects)
1064 Info.EvalStatus.Diag->clear();
1065 Info.EvalMode = OldMode;
1066 }
1067 };
1068
1069 /// RAII object used to treat the current evaluation as the correct pointer
1070 /// offset fold for the current EvalMode
1071 struct FoldOffsetRAII {
1072 EvalInfo &Info;
1073 EvalInfo::EvaluationMode OldMode;
1074 explicit FoldOffsetRAII(EvalInfo &Info)
1075 : Info(Info), OldMode(Info.EvalMode) {
1076 if (!Info.checkingPotentialConstantExpression())
1077 Info.EvalMode = EvalInfo::EM_OffsetFold;
1078 }
1079
1080 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1081 };
1082
1083 /// RAII object used to optionally suppress diagnostics and side-effects from
1084 /// a speculative evaluation.
1085 class SpeculativeEvaluationRAII {
1086 EvalInfo *Info = nullptr;
1087 Expr::EvalStatus OldStatus;
1088 bool OldIsSpeculativelyEvaluating;
1089
1090 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1091 Info = Other.Info;
1092 OldStatus = Other.OldStatus;
1093 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1094 Other.Info = nullptr;
1095 }
1096
1097 void maybeRestoreState() {
1098 if (!Info)
1099 return;
1100
1101 Info->EvalStatus = OldStatus;
1102 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1103 }
1104
1105 public:
1106 SpeculativeEvaluationRAII() = default;
1107
1108 SpeculativeEvaluationRAII(
1109 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1110 : Info(&Info), OldStatus(Info.EvalStatus),
1111 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1112 Info.EvalStatus.Diag = NewDiag;
1113 Info.IsSpeculativelyEvaluating = true;
1114 }
1115
1116 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1117 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1118 moveFromAndCancel(std::move(Other));
1119 }
1120
1121 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1122 maybeRestoreState();
1123 moveFromAndCancel(std::move(Other));
1124 return *this;
1125 }
1126
1127 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1128 };
1129
1130 /// RAII object wrapping a full-expression or block scope, and handling
1131 /// the ending of the lifetime of temporaries created within it.
1132 template<bool IsFullExpression>
1133 class ScopeRAII {
1134 EvalInfo &Info;
1135 unsigned OldStackSize;
1136 public:
1137 ScopeRAII(EvalInfo &Info)
1138 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1139 // Push a new temporary version. This is needed to distinguish between
1140 // temporaries created in different iterations of a loop.
1141 Info.CurrentCall->pushTempVersion();
1142 }
1143 ~ScopeRAII() {
1144 // Body moved to a static method to encourage the compiler to inline away
1145 // instances of this class.
1146 cleanup(Info, OldStackSize);
1147 Info.CurrentCall->popTempVersion();
1148 }
1149 private:
1150 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1151 unsigned NewEnd = OldStackSize;
1152 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1153 I != N; ++I) {
1154 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1155 // Full-expression cleanup of a lifetime-extended temporary: nothing
1156 // to do, just move this cleanup to the right place in the stack.
1157 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1158 ++NewEnd;
1159 } else {
1160 // End the lifetime of the object.
1161 Info.CleanupStack[I].endLifetime();
1162 }
1163 }
1164 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1165 Info.CleanupStack.end());
1166 }
1167 };
1168 typedef ScopeRAII<false> BlockScopeRAII;
1169 typedef ScopeRAII<true> FullExpressionRAII;
1170}
1171
1172bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1173 CheckSubobjectKind CSK) {
1174 if (Invalid)
1175 return false;
1176 if (isOnePastTheEnd()) {
1177 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1178 << CSK;
1179 setInvalid();
1180 return false;
1181 }
1182 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1183 // must actually be at least one array element; even a VLA cannot have a
1184 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1185 return true;
1186}
1187
1188void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1189 const Expr *E) {
1190 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1191 // Do not set the designator as invalid: we can represent this situation,
1192 // and correct handling of __builtin_object_size requires us to do so.
1193}
1194
1195void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1196 const Expr *E,
1197 const APSInt &N) {
1198 // If we're complaining, we must be able to statically determine the size of
1199 // the most derived array.
1200 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1201 Info.CCEDiag(E, diag::note_constexpr_array_index)
1202 << N << /*array*/ 0
1203 << static_cast<unsigned>(getMostDerivedArraySize());
1204 else
1205 Info.CCEDiag(E, diag::note_constexpr_array_index)
1206 << N << /*non-array*/ 1;
1207 setInvalid();
1208}
1209
1210CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1211 const FunctionDecl *Callee, const LValue *This,
1212 APValue *Arguments)
1213 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1214 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1215 Info.CurrentCall = this;
1216 ++Info.CallStackDepth;
1217}
1218
1219CallStackFrame::~CallStackFrame() {
1220 assert(Info.CurrentCall == this && "calls retired out of order")(static_cast <bool> (Info.CurrentCall == this &&
"calls retired out of order") ? void (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1220, __extension__ __PRETTY_FUNCTION__))
;
1221 --Info.CallStackDepth;
1222 Info.CurrentCall = Caller;
1223}
1224
1225APValue &CallStackFrame::createTemporary(const void *Key,
1226 bool IsLifetimeExtended) {
1227 unsigned Version = Info.CurrentCall->getTempVersion();
1228 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1229 assert(Result.isUninit() && "temporary created multiple times")(static_cast <bool> (Result.isUninit() && "temporary created multiple times"
) ? void (0) : __assert_fail ("Result.isUninit() && \"temporary created multiple times\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1229, __extension__ __PRETTY_FUNCTION__))
;
1230 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1231 return Result;
1232}
1233
1234static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1235
1236void EvalInfo::addCallStack(unsigned Limit) {
1237 // Determine which calls to skip, if any.
1238 unsigned ActiveCalls = CallStackDepth - 1;
1239 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1240 if (Limit && Limit < ActiveCalls) {
1241 SkipStart = Limit / 2 + Limit % 2;
1242 SkipEnd = ActiveCalls - Limit / 2;
1243 }
1244
1245 // Walk the call stack and add the diagnostics.
1246 unsigned CallIdx = 0;
1247 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1248 Frame = Frame->Caller, ++CallIdx) {
1249 // Skip this call?
1250 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1251 if (CallIdx == SkipStart) {
1252 // Note that we're skipping calls.
1253 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1254 << unsigned(ActiveCalls - Limit);
1255 }
1256 continue;
1257 }
1258
1259 // Use a different note for an inheriting constructor, because from the
1260 // user's perspective it's not really a function at all.
1261 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1262 if (CD->isInheritingConstructor()) {
1263 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1264 << CD->getParent();
1265 continue;
1266 }
1267 }
1268
1269 SmallVector<char, 128> Buffer;
1270 llvm::raw_svector_ostream Out(Buffer);
1271 describeCall(Frame, Out);
1272 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1273 }
1274}
1275
1276namespace {
1277 struct ComplexValue {
1278 private:
1279 bool IsInt;
1280
1281 public:
1282 APSInt IntReal, IntImag;
1283 APFloat FloatReal, FloatImag;
1284
1285 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1286
1287 void makeComplexFloat() { IsInt = false; }
1288 bool isComplexFloat() const { return !IsInt; }
1289 APFloat &getComplexFloatReal() { return FloatReal; }
1290 APFloat &getComplexFloatImag() { return FloatImag; }
1291
1292 void makeComplexInt() { IsInt = true; }
1293 bool isComplexInt() const { return IsInt; }
1294 APSInt &getComplexIntReal() { return IntReal; }
1295 APSInt &getComplexIntImag() { return IntImag; }
1296
1297 void moveInto(APValue &v) const {
1298 if (isComplexFloat())
1299 v = APValue(FloatReal, FloatImag);
1300 else
1301 v = APValue(IntReal, IntImag);
1302 }
1303 void setFrom(const APValue &v) {
1304 assert(v.isComplexFloat() || v.isComplexInt())(static_cast <bool> (v.isComplexFloat() || v.isComplexInt
()) ? void (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1304, __extension__ __PRETTY_FUNCTION__))
;
1305 if (v.isComplexFloat()) {
1306 makeComplexFloat();
1307 FloatReal = v.getComplexFloatReal();
1308 FloatImag = v.getComplexFloatImag();
1309 } else {
1310 makeComplexInt();
1311 IntReal = v.getComplexIntReal();
1312 IntImag = v.getComplexIntImag();
1313 }
1314 }
1315 };
1316
1317 struct LValue {
1318 APValue::LValueBase Base;
1319 CharUnits Offset;
1320 SubobjectDesignator Designator;
1321 bool IsNullPtr : 1;
1322 bool InvalidBase : 1;
1323
1324 const APValue::LValueBase getLValueBase() const { return Base; }
1325 CharUnits &getLValueOffset() { return Offset; }
1326 const CharUnits &getLValueOffset() const { return Offset; }
1327 SubobjectDesignator &getLValueDesignator() { return Designator; }
1328 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1329 bool isNullPointer() const { return IsNullPtr;}
1330
1331 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1332 unsigned getLValueVersion() const { return Base.getVersion(); }
1333
1334 void moveInto(APValue &V) const {
1335 if (Designator.Invalid)
1336 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1337 else {
1338 assert(!InvalidBase && "APValues can't handle invalid LValue bases")(static_cast <bool> (!InvalidBase && "APValues can't handle invalid LValue bases"
) ? void (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1338, __extension__ __PRETTY_FUNCTION__))
;
1339 V = APValue(Base, Offset, Designator.Entries,
1340 Designator.IsOnePastTheEnd, IsNullPtr);
1341 }
1342 }
1343 void setFrom(ASTContext &Ctx, const APValue &V) {
1344 assert(V.isLValue() && "Setting LValue from a non-LValue?")(static_cast <bool> (V.isLValue() && "Setting LValue from a non-LValue?"
) ? void (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1344, __extension__ __PRETTY_FUNCTION__))
;
1345 Base = V.getLValueBase();
1346 Offset = V.getLValueOffset();
1347 InvalidBase = false;
1348 Designator = SubobjectDesignator(Ctx, V);
1349 IsNullPtr = V.isNullPointer();
1350 }
1351
1352 void set(APValue::LValueBase B, bool BInvalid = false) {
1353#ifndef NDEBUG
1354 // We only allow a few types of invalid bases. Enforce that here.
1355 if (BInvalid) {
1356 const auto *E = B.get<const Expr *>();
1357 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall
(E)) && "Unexpected type of invalid base") ? void (0)
: __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1358, __extension__ __PRETTY_FUNCTION__))
1358 "Unexpected type of invalid base")(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall
(E)) && "Unexpected type of invalid base") ? void (0)
: __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1358, __extension__ __PRETTY_FUNCTION__))
;
1359 }
1360#endif
1361
1362 Base = B;
1363 Offset = CharUnits::fromQuantity(0);
1364 InvalidBase = BInvalid;
1365 Designator = SubobjectDesignator(getType(B));
1366 IsNullPtr = false;
1367 }
1368
1369 void setNull(QualType PointerTy, uint64_t TargetVal) {
1370 Base = (Expr *)nullptr;
1371 Offset = CharUnits::fromQuantity(TargetVal);
1372 InvalidBase = false;
1373 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1374 IsNullPtr = true;
1375 }
1376
1377 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1378 set(B, true);
1379 }
1380
1381 // Check that this LValue is not based on a null pointer. If it is, produce
1382 // a diagnostic and mark the designator as invalid.
1383 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1384 CheckSubobjectKind CSK) {
1385 if (Designator.Invalid)
1386 return false;
1387 if (IsNullPtr) {
1388 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1389 << CSK;
1390 Designator.setInvalid();
1391 return false;
1392 }
1393 return true;
1394 }
1395
1396 // Check this LValue refers to an object. If not, set the designator to be
1397 // invalid and emit a diagnostic.
1398 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1399 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1400 Designator.checkSubobject(Info, E, CSK);
1401 }
1402
1403 void addDecl(EvalInfo &Info, const Expr *E,
1404 const Decl *D, bool Virtual = false) {
1405 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1406 Designator.addDeclUnchecked(D, Virtual);
1407 }
1408 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1409 if (!Designator.Entries.empty()) {
1410 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1411 Designator.setInvalid();
1412 return;
1413 }
1414 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1415 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())(static_cast <bool> (getType(Base)->isPointerType() ||
getType(Base)->isArrayType()) ? void (0) : __assert_fail (
"getType(Base)->isPointerType() || getType(Base)->isArrayType()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1415, __extension__ __PRETTY_FUNCTION__))
;
1416 Designator.FirstEntryIsAnUnsizedArray = true;
1417 Designator.addUnsizedArrayUnchecked(ElemTy);
1418 }
1419 }
1420 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1421 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1422 Designator.addArrayUnchecked(CAT);
1423 }
1424 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1425 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1426 Designator.addComplexUnchecked(EltTy, Imag);
1427 }
1428 void clearIsNullPointer() {
1429 IsNullPtr = false;
1430 }
1431 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1432 const APSInt &Index, CharUnits ElementSize) {
1433 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1434 // but we're not required to diagnose it and it's valid in C++.)
1435 if (!Index)
1436 return;
1437
1438 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1439 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1440 // offsets.
1441 uint64_t Offset64 = Offset.getQuantity();
1442 uint64_t ElemSize64 = ElementSize.getQuantity();
1443 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1444 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1445
1446 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1447 Designator.adjustIndex(Info, E, Index);
1448 clearIsNullPointer();
1449 }
1450 void adjustOffset(CharUnits N) {
1451 Offset += N;
1452 if (N.getQuantity())
1453 clearIsNullPointer();
1454 }
1455 };
1456
1457 struct MemberPtr {
1458 MemberPtr() {}
1459 explicit MemberPtr(const ValueDecl *Decl) :
1460 DeclAndIsDerivedMember(Decl, false), Path() {}
1461
1462 /// The member or (direct or indirect) field referred to by this member
1463 /// pointer, or 0 if this is a null member pointer.
1464 const ValueDecl *getDecl() const {
1465 return DeclAndIsDerivedMember.getPointer();
1466 }
1467 /// Is this actually a member of some type derived from the relevant class?
1468 bool isDerivedMember() const {
1469 return DeclAndIsDerivedMember.getInt();
1470 }
1471 /// Get the class which the declaration actually lives in.
1472 const CXXRecordDecl *getContainingRecord() const {
1473 return cast<CXXRecordDecl>(
1474 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1475 }
1476
1477 void moveInto(APValue &V) const {
1478 V = APValue(getDecl(), isDerivedMember(), Path);
1479 }
1480 void setFrom(const APValue &V) {
1481 assert(V.isMemberPointer())(static_cast <bool> (V.isMemberPointer()) ? void (0) : __assert_fail
("V.isMemberPointer()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1481, __extension__ __PRETTY_FUNCTION__))
;
1482 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1483 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1484 Path.clear();
1485 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1486 Path.insert(Path.end(), P.begin(), P.end());
1487 }
1488
1489 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1490 /// whether the member is a member of some class derived from the class type
1491 /// of the member pointer.
1492 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1493 /// Path - The path of base/derived classes from the member declaration's
1494 /// class (exclusive) to the class type of the member pointer (inclusive).
1495 SmallVector<const CXXRecordDecl*, 4> Path;
1496
1497 /// Perform a cast towards the class of the Decl (either up or down the
1498 /// hierarchy).
1499 bool castBack(const CXXRecordDecl *Class) {
1500 assert(!Path.empty())(static_cast <bool> (!Path.empty()) ? void (0) : __assert_fail
("!Path.empty()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1500, __extension__ __PRETTY_FUNCTION__))
;
1501 const CXXRecordDecl *Expected;
1502 if (Path.size() >= 2)
1503 Expected = Path[Path.size() - 2];
1504 else
1505 Expected = getContainingRecord();
1506 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1507 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1508 // if B does not contain the original member and is not a base or
1509 // derived class of the class containing the original member, the result
1510 // of the cast is undefined.
1511 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1512 // (D::*). We consider that to be a language defect.
1513 return false;
1514 }
1515 Path.pop_back();
1516 return true;
1517 }
1518 /// Perform a base-to-derived member pointer cast.
1519 bool castToDerived(const CXXRecordDecl *Derived) {
1520 if (!getDecl())
1521 return true;
1522 if (!isDerivedMember()) {
1523 Path.push_back(Derived);
1524 return true;
1525 }
1526 if (!castBack(Derived))
1527 return false;
1528 if (Path.empty())
1529 DeclAndIsDerivedMember.setInt(false);
1530 return true;
1531 }
1532 /// Perform a derived-to-base member pointer cast.
1533 bool castToBase(const CXXRecordDecl *Base) {
1534 if (!getDecl())
1535 return true;
1536 if (Path.empty())
1537 DeclAndIsDerivedMember.setInt(true);
1538 if (isDerivedMember()) {
1539 Path.push_back(Base);
1540 return true;
1541 }
1542 return castBack(Base);
1543 }
1544 };
1545
1546 /// Compare two member pointers, which are assumed to be of the same type.
1547 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1548 if (!LHS.getDecl() || !RHS.getDecl())
1549 return !LHS.getDecl() && !RHS.getDecl();
1550 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1551 return false;
1552 return LHS.Path == RHS.Path;
1553 }
1554}
1555
1556static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1557static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1558 const LValue &This, const Expr *E,
1559 bool AllowNonLiteralTypes = false);
1560static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1561 bool InvalidBaseOK = false);
1562static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1563 bool InvalidBaseOK = false);
1564static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1565 EvalInfo &Info);
1566static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1567static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1568static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1569 EvalInfo &Info);
1570static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1571static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1572static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1573 EvalInfo &Info);
1574static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1575
1576//===----------------------------------------------------------------------===//
1577// Misc utilities
1578//===----------------------------------------------------------------------===//
1579
1580/// A helper function to create a temporary and set an LValue.
1581template <class KeyTy>
1582static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1583 LValue &LV, CallStackFrame &Frame) {
1584 LV.set({Key, Frame.Info.CurrentCall->Index,
1585 Frame.Info.CurrentCall->getTempVersion()});
1586 return Frame.createTemporary(Key, IsLifetimeExtended);
1587}
1588
1589/// Negate an APSInt in place, converting it to a signed form if necessary, and
1590/// preserving its value (by extending by up to one bit as needed).
1591static void negateAsSigned(APSInt &Int) {
1592 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1593 Int = Int.extend(Int.getBitWidth() + 1);
1594 Int.setIsSigned(true);
1595 }
1596 Int = -Int;
1597}
1598
1599/// Produce a string describing the given constexpr call.
1600static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1601 unsigned ArgIndex = 0;
1602 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1603 !isa<CXXConstructorDecl>(Frame->Callee) &&
1604 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1605
1606 if (!IsMemberCall)
1607 Out << *Frame->Callee << '(';
1608
1609 if (Frame->This && IsMemberCall) {
1610 APValue Val;
1611 Frame->This->moveInto(Val);
1612 Val.printPretty(Out, Frame->Info.Ctx,
1613 Frame->This->Designator.MostDerivedType);
1614 // FIXME: Add parens around Val if needed.
1615 Out << "->" << *Frame->Callee << '(';
1616 IsMemberCall = false;
1617 }
1618
1619 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1620 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1621 if (ArgIndex > (unsigned)IsMemberCall)
1622 Out << ", ";
1623
1624 const ParmVarDecl *Param = *I;
1625 const APValue &Arg = Frame->Arguments[ArgIndex];
1626 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1627
1628 if (ArgIndex == 0 && IsMemberCall)
1629 Out << "->" << *Frame->Callee << '(';
1630 }
1631
1632 Out << ')';
1633}
1634
1635/// Evaluate an expression to see if it had side-effects, and discard its
1636/// result.
1637/// \return \c true if the caller should keep evaluating.
1638static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1639 APValue Scratch;
1640 if (!Evaluate(Scratch, Info, E))
1641 // We don't need the value, but we might have skipped a side effect here.
1642 return Info.noteSideEffect();
1643 return true;
1644}
1645
1646/// Should this call expression be treated as a string literal?
1647static bool IsStringLiteralCall(const CallExpr *E) {
1648 unsigned Builtin = E->getBuiltinCallee();
1649 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1650 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1651}
1652
1653static bool IsGlobalLValue(APValue::LValueBase B) {
1654 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1655 // constant expression of pointer type that evaluates to...
1656
1657 // ... a null pointer value, or a prvalue core constant expression of type
1658 // std::nullptr_t.
1659 if (!B) return true;
1660
1661 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1662 // ... the address of an object with static storage duration,
1663 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1664 return VD->hasGlobalStorage();
1665 // ... the address of a function,
1666 return isa<FunctionDecl>(D);
1667 }
1668
1669 const Expr *E = B.get<const Expr*>();
1670 switch (E->getStmtClass()) {
1671 default:
1672 return false;
1673 case Expr::CompoundLiteralExprClass: {
1674 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1675 return CLE->isFileScope() && CLE->isLValue();
1676 }
1677 case Expr::MaterializeTemporaryExprClass:
1678 // A materialized temporary might have been lifetime-extended to static
1679 // storage duration.
1680 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1681 // A string literal has static storage duration.
1682 case Expr::StringLiteralClass:
1683 case Expr::PredefinedExprClass:
1684 case Expr::ObjCStringLiteralClass:
1685 case Expr::ObjCEncodeExprClass:
1686 case Expr::CXXTypeidExprClass:
1687 case Expr::CXXUuidofExprClass:
1688 return true;
1689 case Expr::CallExprClass:
1690 return IsStringLiteralCall(cast<CallExpr>(E));
1691 // For GCC compatibility, &&label has static storage duration.
1692 case Expr::AddrLabelExprClass:
1693 return true;
1694 // A Block literal expression may be used as the initialization value for
1695 // Block variables at global or local static scope.
1696 case Expr::BlockExprClass:
1697 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1698 case Expr::ImplicitValueInitExprClass:
1699 // FIXME:
1700 // We can never form an lvalue with an implicit value initialization as its
1701 // base through expression evaluation, so these only appear in one case: the
1702 // implicit variable declaration we invent when checking whether a constexpr
1703 // constructor can produce a constant expression. We must assume that such
1704 // an expression might be a global lvalue.
1705 return true;
1706 }
1707}
1708
1709static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1710 assert(Base && "no location for a null lvalue")(static_cast <bool> (Base && "no location for a null lvalue"
) ? void (0) : __assert_fail ("Base && \"no location for a null lvalue\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1710, __extension__ __PRETTY_FUNCTION__))
;
1711 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1712 if (VD)
1713 Info.Note(VD->getLocation(), diag::note_declared_at);
1714 else
1715 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1716 diag::note_constexpr_temporary_here);
1717}
1718
1719/// Check that this reference or pointer core constant expression is a valid
1720/// value for an address or reference constant expression. Return true if we
1721/// can fold this expression, whether or not it's a constant expression.
1722static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1723 QualType Type, const LValue &LVal) {
1724 bool IsReferenceType = Type->isReferenceType();
1725
1726 APValue::LValueBase Base = LVal.getLValueBase();
1727 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1728
1729 // Check that the object is a global. Note that the fake 'this' object we
1730 // manufacture when checking potential constant expressions is conservatively
1731 // assumed to be global here.
1732 if (!IsGlobalLValue(Base)) {
1733 if (Info.getLangOpts().CPlusPlus11) {
1734 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1735 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1736 << IsReferenceType << !Designator.Entries.empty()
1737 << !!VD << VD;
1738 NoteLValueLocation(Info, Base);
1739 } else {
1740 Info.FFDiag(Loc);
1741 }
1742 // Don't allow references to temporaries to escape.
1743 return false;
1744 }
1745 assert((Info.checkingPotentialConstantExpression() ||(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1747, __extension__ __PRETTY_FUNCTION__))
1746 LVal.getLValueCallIndex() == 0) &&(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1747, __extension__ __PRETTY_FUNCTION__))
1747 "have call index for global lvalue")(static_cast <bool> ((Info.checkingPotentialConstantExpression
() || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue"
) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1747, __extension__ __PRETTY_FUNCTION__))
;
1748
1749 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1750 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1751 // Check if this is a thread-local variable.
1752 if (Var->getTLSKind())
1753 return false;
1754
1755 // A dllimport variable never acts like a constant.
1756 if (Var->hasAttr<DLLImportAttr>())
1757 return false;
1758 }
1759 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1760 // __declspec(dllimport) must be handled very carefully:
1761 // We must never initialize an expression with the thunk in C++.
1762 // Doing otherwise would allow the same id-expression to yield
1763 // different addresses for the same function in different translation
1764 // units. However, this means that we must dynamically initialize the
1765 // expression with the contents of the import address table at runtime.
1766 //
1767 // The C language has no notion of ODR; furthermore, it has no notion of
1768 // dynamic initialization. This means that we are permitted to
1769 // perform initialization with the address of the thunk.
1770 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1771 return false;
1772 }
1773 }
1774
1775 // Allow address constant expressions to be past-the-end pointers. This is
1776 // an extension: the standard requires them to point to an object.
1777 if (!IsReferenceType)
1778 return true;
1779
1780 // A reference constant expression must refer to an object.
1781 if (!Base) {
1782 // FIXME: diagnostic
1783 Info.CCEDiag(Loc);
1784 return true;
1785 }
1786
1787 // Does this refer one past the end of some object?
1788 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1789 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1790 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1791 << !Designator.Entries.empty() << !!VD << VD;
1792 NoteLValueLocation(Info, Base);
1793 }
1794
1795 return true;
1796}
1797
1798/// Member pointers are constant expressions unless they point to a
1799/// non-virtual dllimport member function.
1800static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1801 SourceLocation Loc,
1802 QualType Type,
1803 const APValue &Value) {
1804 const ValueDecl *Member = Value.getMemberPointerDecl();
1805 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1806 if (!FD)
1807 return true;
1808 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1809}
1810
1811/// Check that this core constant expression is of literal type, and if not,
1812/// produce an appropriate diagnostic.
1813static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1814 const LValue *This = nullptr) {
1815 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1816 return true;
1817
1818 // C++1y: A constant initializer for an object o [...] may also invoke
1819 // constexpr constructors for o and its subobjects even if those objects
1820 // are of non-literal class types.
1821 //
1822 // C++11 missed this detail for aggregates, so classes like this:
1823 // struct foo_t { union { int i; volatile int j; } u; };
1824 // are not (obviously) initializable like so:
1825 // __attribute__((__require_constant_initialization__))
1826 // static const foo_t x = {{0}};
1827 // because "i" is a subobject with non-literal initialization (due to the
1828 // volatile member of the union). See:
1829 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1830 // Therefore, we use the C++1y behavior.
1831 if (This && Info.EvaluatingDecl == This->getLValueBase())
1832 return true;
1833
1834 // Prvalue constant expressions must be of literal types.
1835 if (Info.getLangOpts().CPlusPlus11)
1836 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1837 << E->getType();
1838 else
1839 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1840 return false;
1841}
1842
1843/// Check that this core constant expression value is a valid value for a
1844/// constant expression. If not, report an appropriate diagnostic. Does not
1845/// check that the expression is of literal type.
1846static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1847 QualType Type, const APValue &Value) {
1848 if (Value.isUninit()) {
1849 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1850 << true << Type;
1851 return false;
1852 }
1853
1854 // We allow _Atomic(T) to be initialized from anything that T can be
1855 // initialized from.
1856 if (const AtomicType *AT = Type->getAs<AtomicType>())
1857 Type = AT->getValueType();
1858
1859 // Core issue 1454: For a literal constant expression of array or class type,
1860 // each subobject of its value shall have been initialized by a constant
1861 // expression.
1862 if (Value.isArray()) {
1863 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1864 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1865 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1866 Value.getArrayInitializedElt(I)))
1867 return false;
1868 }
1869 if (!Value.hasArrayFiller())
1870 return true;
1871 return CheckConstantExpression(Info, DiagLoc, EltTy,
1872 Value.getArrayFiller());
1873 }
1874 if (Value.isUnion() && Value.getUnionField()) {
1875 return CheckConstantExpression(Info, DiagLoc,
1876 Value.getUnionField()->getType(),
1877 Value.getUnionValue());
1878 }
1879 if (Value.isStruct()) {
1880 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1881 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1882 unsigned BaseIndex = 0;
1883 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1884 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1885 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1886 Value.getStructBase(BaseIndex)))
1887 return false;
1888 }
1889 }
1890 for (const auto *I : RD->fields()) {
1891 if (I->isUnnamedBitfield())
1892 continue;
1893
1894 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1895 Value.getStructField(I->getFieldIndex())))
1896 return false;
1897 }
1898 }
1899
1900 if (Value.isLValue()) {
1901 LValue LVal;
1902 LVal.setFrom(Info.Ctx, Value);
1903 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1904 }
1905
1906 if (Value.isMemberPointer())
1907 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1908
1909 // Everything else is fine.
1910 return true;
1911}
1912
1913static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1914 return LVal.Base.dyn_cast<const ValueDecl*>();
1915}
1916
1917static bool IsLiteralLValue(const LValue &Value) {
1918 if (Value.getLValueCallIndex())
1919 return false;
1920 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1921 return E && !isa<MaterializeTemporaryExpr>(E);
1922}
1923
1924static bool IsWeakLValue(const LValue &Value) {
1925 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1926 return Decl && Decl->isWeak();
1927}
1928
1929static bool isZeroSized(const LValue &Value) {
1930 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1931 if (Decl && isa<VarDecl>(Decl)) {
1932 QualType Ty = Decl->getType();
1933 if (Ty->isArrayType())
1934 return Ty->isIncompleteType() ||
1935 Decl->getASTContext().getTypeSize(Ty) == 0;
1936 }
1937 return false;
1938}
1939
1940static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1941 // A null base expression indicates a null pointer. These are always
1942 // evaluatable, and they are false unless the offset is zero.
1943 if (!Value.getLValueBase()) {
1944 Result = !Value.getLValueOffset().isZero();
1945 return true;
1946 }
1947
1948 // We have a non-null base. These are generally known to be true, but if it's
1949 // a weak declaration it can be null at runtime.
1950 Result = true;
1951 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1952 return !Decl || !Decl->isWeak();
1953}
1954
1955static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1956 switch (Val.getKind()) {
1957 case APValue::Uninitialized:
1958 return false;
1959 case APValue::Int:
1960 Result = Val.getInt().getBoolValue();
1961 return true;
1962 case APValue::Float:
1963 Result = !Val.getFloat().isZero();
1964 return true;
1965 case APValue::ComplexInt:
1966 Result = Val.getComplexIntReal().getBoolValue() ||
1967 Val.getComplexIntImag().getBoolValue();
1968 return true;
1969 case APValue::ComplexFloat:
1970 Result = !Val.getComplexFloatReal().isZero() ||
1971 !Val.getComplexFloatImag().isZero();
1972 return true;
1973 case APValue::LValue:
1974 return EvalPointerValueAsBool(Val, Result);
1975 case APValue::MemberPointer:
1976 Result = Val.getMemberPointerDecl();
1977 return true;
1978 case APValue::Vector:
1979 case APValue::Array:
1980 case APValue::Struct:
1981 case APValue::Union:
1982 case APValue::AddrLabelDiff:
1983 return false;
1984 }
1985
1986 llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1986)
;
1987}
1988
1989static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1990 EvalInfo &Info) {
1991 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition")(static_cast <bool> (E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"
) ? void (0) : __assert_fail ("E->isRValue() && \"missing lvalue-to-rvalue conv in bool condition\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 1991, __extension__ __PRETTY_FUNCTION__))
;
1992 APValue Val;
1993 if (!Evaluate(Val, Info, E))
1994 return false;
1995 return HandleConversionToBool(Val, Result);
1996}
1997
1998template<typename T>
1999static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2000 const T &SrcValue, QualType DestType) {
2001 Info.CCEDiag(E, diag::note_constexpr_overflow)
2002 << SrcValue << DestType;
2003 return Info.noteUndefinedBehavior();
2004}
2005
2006static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2007 QualType SrcType, const APFloat &Value,
2008 QualType DestType, APSInt &Result) {
2009 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2010 // Determine whether we are converting to unsigned or signed.
2011 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2012
2013 Result = APSInt(DestWidth, !DestSigned);
2014 bool ignored;
2015 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2016 & APFloat::opInvalidOp)
2017 return HandleOverflow(Info, E, Value, DestType);
2018 return true;
2019}
2020
2021static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2022 QualType SrcType, QualType DestType,
2023 APFloat &Result) {
2024 APFloat Value = Result;
2025 bool ignored;
2026 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2027 APFloat::rmNearestTiesToEven, &ignored)
2028 & APFloat::opOverflow)
2029 return HandleOverflow(Info, E, Value, DestType);
2030 return true;
2031}
2032
2033static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2034 QualType DestType, QualType SrcType,
2035 const APSInt &Value) {
2036 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2037 APSInt Result = Value;
2038 // Figure out if this is a truncate, extend or noop cast.
2039 // If the input is signed, do a sign extend, noop, or truncate.
2040 Result = Result.extOrTrunc(DestWidth);
2041 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2042 return Result;
2043}
2044
2045static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2046 QualType SrcType, const APSInt &Value,
2047 QualType DestType, APFloat &Result) {
2048 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2049 if (Result.convertFromAPInt(Value, Value.isSigned(),
2050 APFloat::rmNearestTiesToEven)
2051 & APFloat::opOverflow)
2052 return HandleOverflow(Info, E, Value, DestType);
2053 return true;
2054}
2055
2056static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2057 APValue &Value, const FieldDecl *FD) {
2058 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")(static_cast <bool> (FD->isBitField() && "truncateBitfieldValue on non-bitfield"
) ? void (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2058, __extension__ __PRETTY_FUNCTION__))
;
2059
2060 if (!Value.isInt()) {
2061 // Trying to store a pointer-cast-to-integer into a bitfield.
2062 // FIXME: In this case, we should provide the diagnostic for casting
2063 // a pointer to an integer.
2064 assert(Value.isLValue() && "integral value neither int nor lvalue?")(static_cast <bool> (Value.isLValue() && "integral value neither int nor lvalue?"
) ? void (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2064, __extension__ __PRETTY_FUNCTION__))
;
2065 Info.FFDiag(E);
2066 return false;
2067 }
2068
2069 APSInt &Int = Value.getInt();
2070 unsigned OldBitWidth = Int.getBitWidth();
2071 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2072 if (NewBitWidth < OldBitWidth)
2073 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2074 return true;
2075}
2076
2077static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2078 llvm::APInt &Res) {
2079 APValue SVal;
2080 if (!Evaluate(SVal, Info, E))
2081 return false;
2082 if (SVal.isInt()) {
2083 Res = SVal.getInt();
2084 return true;
2085 }
2086 if (SVal.isFloat()) {
2087 Res = SVal.getFloat().bitcastToAPInt();
2088 return true;
2089 }
2090 if (SVal.isVector()) {
2091 QualType VecTy = E->getType();
2092 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2093 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2094 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2095 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2096 Res = llvm::APInt::getNullValue(VecSize);
2097 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2098 APValue &Elt = SVal.getVectorElt(i);
2099 llvm::APInt EltAsInt;
2100 if (Elt.isInt()) {
2101 EltAsInt = Elt.getInt();
2102 } else if (Elt.isFloat()) {
2103 EltAsInt = Elt.getFloat().bitcastToAPInt();
2104 } else {
2105 // Don't try to handle vectors of anything other than int or float
2106 // (not sure if it's possible to hit this case).
2107 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2108 return false;
2109 }
2110 unsigned BaseEltSize = EltAsInt.getBitWidth();
2111 if (BigEndian)
2112 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2113 else
2114 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2115 }
2116 return true;
2117 }
2118 // Give up if the input isn't an int, float, or vector. For example, we
2119 // reject "(v4i16)(intptr_t)&a".
2120 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2121 return false;
2122}
2123
2124/// Perform the given integer operation, which is known to need at most BitWidth
2125/// bits, and check for overflow in the original type (if that type was not an
2126/// unsigned type).
2127template<typename Operation>
2128static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2129 const APSInt &LHS, const APSInt &RHS,
2130 unsigned BitWidth, Operation Op,
2131 APSInt &Result) {
2132 if (LHS.isUnsigned()) {
2133 Result = Op(LHS, RHS);
2134 return true;
2135 }
2136
2137 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2138 Result = Value.trunc(LHS.getBitWidth());
2139 if (Result.extend(BitWidth) != Value) {
2140 if (Info.checkingForOverflow())
2141 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2142 diag::warn_integer_constant_overflow)
2143 << Result.toString(10) << E->getType();
2144 else
2145 return HandleOverflow(Info, E, Value, E->getType());
2146 }
2147 return true;
2148}
2149
2150/// Perform the given binary integer operation.
2151static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2152 BinaryOperatorKind Opcode, APSInt RHS,
2153 APSInt &Result) {
2154 switch (Opcode) {
2155 default:
2156 Info.FFDiag(E);
2157 return false;
2158 case BO_Mul:
2159 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2160 std::multiplies<APSInt>(), Result);
2161 case BO_Add:
2162 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2163 std::plus<APSInt>(), Result);
2164 case BO_Sub:
2165 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2166 std::minus<APSInt>(), Result);
2167 case BO_And: Result = LHS & RHS; return true;
2168 case BO_Xor: Result = LHS ^ RHS; return true;
2169 case BO_Or: Result = LHS | RHS; return true;
2170 case BO_Div:
2171 case BO_Rem:
2172 if (RHS == 0) {
2173 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2174 return false;
2175 }
2176 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2177 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2178 // this operation and gives the two's complement result.
2179 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2180 LHS.isSigned() && LHS.isMinSignedValue())
2181 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2182 E->getType());
2183 return true;
2184 case BO_Shl: {
2185 if (Info.getLangOpts().OpenCL)
2186 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2187 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2188 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2189 RHS.isUnsigned());
2190 else if (RHS.isSigned() && RHS.isNegative()) {
2191 // During constant-folding, a negative shift is an opposite shift. Such
2192 // a shift is not a constant expression.
2193 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2194 RHS = -RHS;
2195 goto shift_right;
2196 }
2197 shift_left:
2198 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2199 // the shifted type.
2200 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2201 if (SA != RHS) {
2202 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2203 << RHS << E->getType() << LHS.getBitWidth();
2204 } else if (LHS.isSigned()) {
2205 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2206 // operand, and must not overflow the corresponding unsigned type.
2207 if (LHS.isNegative())
2208 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2209 else if (LHS.countLeadingZeros() < SA)
2210 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2211 }
2212 Result = LHS << SA;
2213 return true;
2214 }
2215 case BO_Shr: {
2216 if (Info.getLangOpts().OpenCL)
2217 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2218 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2219 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2220 RHS.isUnsigned());
2221 else if (RHS.isSigned() && RHS.isNegative()) {
2222 // During constant-folding, a negative shift is an opposite shift. Such a
2223 // shift is not a constant expression.
2224 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2225 RHS = -RHS;
2226 goto shift_left;
2227 }
2228 shift_right:
2229 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2230 // shifted type.
2231 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2232 if (SA != RHS)
2233 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2234 << RHS << E->getType() << LHS.getBitWidth();
2235 Result = LHS >> SA;
2236 return true;
2237 }
2238
2239 case BO_LT: Result = LHS < RHS; return true;
2240 case BO_GT: Result = LHS > RHS; return true;
2241 case BO_LE: Result = LHS <= RHS; return true;
2242 case BO_GE: Result = LHS >= RHS; return true;
2243 case BO_EQ: Result = LHS == RHS; return true;
2244 case BO_NE: Result = LHS != RHS; return true;
2245 }
2246}
2247
2248/// Perform the given binary floating-point operation, in-place, on LHS.
2249static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2250 APFloat &LHS, BinaryOperatorKind Opcode,
2251 const APFloat &RHS) {
2252 switch (Opcode) {
2253 default:
2254 Info.FFDiag(E);
2255 return false;
2256 case BO_Mul:
2257 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2258 break;
2259 case BO_Add:
2260 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2261 break;
2262 case BO_Sub:
2263 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2264 break;
2265 case BO_Div:
2266 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2267 break;
2268 }
2269
2270 if (LHS.isInfinity() || LHS.isNaN()) {
2271 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2272 return Info.noteUndefinedBehavior();
2273 }
2274 return true;
2275}
2276
2277/// Cast an lvalue referring to a base subobject to a derived class, by
2278/// truncating the lvalue's path to the given length.
2279static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2280 const RecordDecl *TruncatedType,
2281 unsigned TruncatedElements) {
2282 SubobjectDesignator &D = Result.Designator;
2283
2284 // Check we actually point to a derived class object.
2285 if (TruncatedElements == D.Entries.size())
2286 return true;
2287 assert(TruncatedElements >= D.MostDerivedPathLength &&(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength
&& "not casting to a derived class") ? void (0) : __assert_fail
("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2288, __extension__ __PRETTY_FUNCTION__))
2288 "not casting to a derived class")(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength
&& "not casting to a derived class") ? void (0) : __assert_fail
("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2288, __extension__ __PRETTY_FUNCTION__))
;
2289 if (!Result.checkSubobject(Info, E, CSK_Derived))
2290 return false;
2291
2292 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2293 const RecordDecl *RD = TruncatedType;
2294 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2295 if (RD->isInvalidDecl()) return false;
2296 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2297 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2298 if (isVirtualBaseClass(D.Entries[I]))
2299 Result.Offset -= Layout.getVBaseClassOffset(Base);
2300 else
2301 Result.Offset -= Layout.getBaseClassOffset(Base);
2302 RD = Base;
2303 }
2304 D.Entries.resize(TruncatedElements);
2305 return true;
2306}
2307
2308static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2309 const CXXRecordDecl *Derived,
2310 const CXXRecordDecl *Base,
2311 const ASTRecordLayout *RL = nullptr) {
2312 if (!RL) {
2313 if (Derived->isInvalidDecl()) return false;
2314 RL = &Info.Ctx.getASTRecordLayout(Derived);
2315 }
2316
2317 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2318 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2319 return true;
2320}
2321
2322static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2323 const CXXRecordDecl *DerivedDecl,
2324 const CXXBaseSpecifier *Base) {
2325 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2326
2327 if (!Base->isVirtual())
2328 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2329
2330 SubobjectDesignator &D = Obj.Designator;
2331 if (D.Invalid)
2332 return false;
2333
2334 // Extract most-derived object and corresponding type.
2335 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2336 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2337 return false;
2338
2339 // Find the virtual base class.
2340 if (DerivedDecl->isInvalidDecl()) return false;
2341 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2342 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2343 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2344 return true;
2345}
2346
2347static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2348 QualType Type, LValue &Result) {
2349 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2350 PathE = E->path_end();
2351 PathI != PathE; ++PathI) {
2352 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2353 *PathI))
2354 return false;
2355 Type = (*PathI)->getType();
2356 }
2357 return true;
2358}
2359
2360/// Update LVal to refer to the given field, which must be a member of the type
2361/// currently described by LVal.
2362static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2363 const FieldDecl *FD,
2364 const ASTRecordLayout *RL = nullptr) {
2365 if (!RL) {
2366 if (FD->getParent()->isInvalidDecl()) return false;
2367 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2368 }
2369
2370 unsigned I = FD->getFieldIndex();
2371 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2372 LVal.addDecl(Info, E, FD);
2373 return true;
2374}
2375
2376/// Update LVal to refer to the given indirect field.
2377static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2378 LValue &LVal,
2379 const IndirectFieldDecl *IFD) {
2380 for (const auto *C : IFD->chain())
2381 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2382 return false;
2383 return true;
2384}
2385
2386/// Get the size of the given type in char units.
2387static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2388 QualType Type, CharUnits &Size) {
2389 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2390 // extension.
2391 if (Type->isVoidType() || Type->isFunctionType()) {
2392 Size = CharUnits::One();
2393 return true;
2394 }
2395
2396 if (Type->isDependentType()) {
2397 Info.FFDiag(Loc);
2398 return false;
2399 }
2400
2401 if (!Type->isConstantSizeType()) {
2402 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2403 // FIXME: Better diagnostic.
2404 Info.FFDiag(Loc);
2405 return false;
2406 }
2407
2408 Size = Info.Ctx.getTypeSizeInChars(Type);
2409 return true;
2410}
2411
2412/// Update a pointer value to model pointer arithmetic.
2413/// \param Info - Information about the ongoing evaluation.
2414/// \param E - The expression being evaluated, for diagnostic purposes.
2415/// \param LVal - The pointer value to be updated.
2416/// \param EltTy - The pointee type represented by LVal.
2417/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2418static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2419 LValue &LVal, QualType EltTy,
2420 APSInt Adjustment) {
2421 CharUnits SizeOfPointee;
2422 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
19
Called C++ object pointer is null
2423 return false;
2424
2425 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2426 return true;
2427}
2428
2429static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2430 LValue &LVal, QualType EltTy,
2431 int64_t Adjustment) {
2432 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
17
Passing null pointer value via 2nd parameter 'E'
18
Calling 'HandleLValueArrayAdjustment'
2433 APSInt::get(Adjustment));
2434}
2435
2436/// Update an lvalue to refer to a component of a complex number.
2437/// \param Info - Information about the ongoing evaluation.
2438/// \param LVal - The lvalue to be updated.
2439/// \param EltTy - The complex number's component type.
2440/// \param Imag - False for the real component, true for the imaginary.
2441static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2442 LValue &LVal, QualType EltTy,
2443 bool Imag) {
2444 if (Imag) {
2445 CharUnits SizeOfComponent;
2446 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2447 return false;
2448 LVal.Offset += SizeOfComponent;
2449 }
2450 LVal.addComplex(Info, E, EltTy, Imag);
2451 return true;
2452}
2453
2454static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2455 QualType Type, const LValue &LVal,
2456 APValue &RVal);
2457
2458/// Try to evaluate the initializer for a variable declaration.
2459///
2460/// \param Info Information about the ongoing evaluation.
2461/// \param E An expression to be used when printing diagnostics.
2462/// \param VD The variable whose initializer should be obtained.
2463/// \param Frame The frame in which the variable was created. Must be null
2464/// if this variable is not local to the evaluation.
2465/// \param Result Filled in with a pointer to the value of the variable.
2466static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2467 const VarDecl *VD, CallStackFrame *Frame,
2468 APValue *&Result, const LValue *LVal) {
2469
2470 // If this is a parameter to an active constexpr function call, perform
2471 // argument substitution.
2472 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2473 // Assume arguments of a potential constant expression are unknown
2474 // constant expressions.
2475 if (Info.checkingPotentialConstantExpression())
2476 return false;
2477 if (!Frame || !Frame->Arguments) {
2478 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2479 return false;
2480 }
2481 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2482 return true;
2483 }
2484
2485 // If this is a local variable, dig out its value.
2486 if (Frame) {
2487 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2488 : Frame->getCurrentTemporary(VD);
2489 if (!Result) {
2490 // Assume variables referenced within a lambda's call operator that were
2491 // not declared within the call operator are captures and during checking
2492 // of a potential constant expression, assume they are unknown constant
2493 // expressions.
2494 assert(isLambdaCallOperator(Frame->Callee) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2496, __extension__ __PRETTY_FUNCTION__))
2495 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2496, __extension__ __PRETTY_FUNCTION__))
2496 "missing value for local variable")(static_cast <bool> (isLambdaCallOperator(Frame->Callee
) && (VD->getDeclContext() != Frame->Callee || VD
->isInitCapture()) && "missing value for local variable"
) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2496, __extension__ __PRETTY_FUNCTION__))
;
2497 if (Info.checkingPotentialConstantExpression())
2498 return false;
2499 // FIXME: implement capture evaluation during constant expr evaluation.
2500 Info.FFDiag(E->getLocStart(),
2501 diag::note_unimplemented_constexpr_lambda_feature_ast)
2502 << "captures not currently allowed";
2503 return false;
2504 }
2505 return true;
2506 }
2507
2508 // Dig out the initializer, and use the declaration which it's attached to.
2509 const Expr *Init = VD->getAnyInitializer(VD);
2510 if (!Init || Init->isValueDependent()) {
2511 // If we're checking a potential constant expression, the variable could be
2512 // initialized later.
2513 if (!Info.checkingPotentialConstantExpression())
2514 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2515 return false;
2516 }
2517
2518 // If we're currently evaluating the initializer of this declaration, use that
2519 // in-flight value.
2520 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2521 Result = Info.EvaluatingDeclValue;
2522 return true;
2523 }
2524
2525 // Never evaluate the initializer of a weak variable. We can't be sure that
2526 // this is the definition which will be used.
2527 if (VD->isWeak()) {
2528 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2529 return false;
2530 }
2531
2532 // Check that we can fold the initializer. In C++, we will have already done
2533 // this in the cases where it matters for conformance.
2534 SmallVector<PartialDiagnosticAt, 8> Notes;
2535 if (!VD->evaluateValue(Notes)) {
2536 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2537 Notes.size() + 1) << VD;
2538 Info.Note(VD->getLocation(), diag::note_declared_at);
2539 Info.addNotes(Notes);
2540 return false;
2541 } else if (!VD->checkInitIsICE()) {
2542 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2543 Notes.size() + 1) << VD;
2544 Info.Note(VD->getLocation(), diag::note_declared_at);
2545 Info.addNotes(Notes);
2546 }
2547
2548 Result = VD->getEvaluatedValue();
2549 return true;
2550}
2551
2552static bool IsConstNonVolatile(QualType T) {
2553 Qualifiers Quals = T.getQualifiers();
2554 return Quals.hasConst() && !Quals.hasVolatile();
2555}
2556
2557/// Get the base index of the given base class within an APValue representing
2558/// the given derived class.
2559static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2560 const CXXRecordDecl *Base) {
2561 Base = Base->getCanonicalDecl();
2562 unsigned Index = 0;
2563 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2564 E = Derived->bases_end(); I != E; ++I, ++Index) {
2565 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2566 return Index;
2567 }
2568
2569 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-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2569)
;
2570}
2571
2572/// Extract the value of a character from a string literal.
2573static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2574 uint64_t Index) {
2575 // FIXME: Support MakeStringConstant
2576 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2577 std::string Str;
2578 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2579 assert(Index <= Str.size() && "Index too large")(static_cast <bool> (Index <= Str.size() && "Index too large"
) ? void (0) : __assert_fail ("Index <= Str.size() && \"Index too large\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2579, __extension__ __PRETTY_FUNCTION__))
;
2580 return APSInt::getUnsigned(Str.c_str()[Index]);
2581 }
2582
2583 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2584 Lit = PE->getFunctionName();
2585 const StringLiteral *S = cast<StringLiteral>(Lit);
2586 const ConstantArrayType *CAT =
2587 Info.Ctx.getAsConstantArrayType(S->getType());
2588 assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array"
) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2588, __extension__ __PRETTY_FUNCTION__))
;
2589 QualType CharType = CAT->getElementType();
2590 assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() &&
"unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2590, __extension__ __PRETTY_FUNCTION__))
;
2591
2592 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2593 CharType->isUnsignedIntegerType());
2594 if (Index < S->getLength())
2595 Value = S->getCodeUnit(Index);
2596 return Value;
2597}
2598
2599// Expand a string literal into an array of characters.
2600static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2601 APValue &Result) {
2602 const StringLiteral *S = cast<StringLiteral>(Lit);
2603 const ConstantArrayType *CAT =
2604 Info.Ctx.getAsConstantArrayType(S->getType());
2605 assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array"
) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2605, __extension__ __PRETTY_FUNCTION__))
;
2606 QualType CharType = CAT->getElementType();
2607 assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() &&
"unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2607, __extension__ __PRETTY_FUNCTION__))
;
2608
2609 unsigned Elts = CAT->getSize().getZExtValue();
2610 Result = APValue(APValue::UninitArray(),
2611 std::min(S->getLength(), Elts), Elts);
2612 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2613 CharType->isUnsignedIntegerType());
2614 if (Result.hasArrayFiller())
2615 Result.getArrayFiller() = APValue(Value);
2616 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2617 Value = S->getCodeUnit(I);
2618 Result.getArrayInitializedElt(I) = APValue(Value);
2619 }
2620}
2621
2622// Expand an array so that it has more than Index filled elements.
2623static void expandArray(APValue &Array, unsigned Index) {
2624 unsigned Size = Array.getArraySize();
2625 assert(Index < Size)(static_cast <bool> (Index < Size) ? void (0) : __assert_fail
("Index < Size", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2625, __extension__ __PRETTY_FUNCTION__))
;
2626
2627 // Always at least double the number of elements for which we store a value.
2628 unsigned OldElts = Array.getArrayInitializedElts();
2629 unsigned NewElts = std::max(Index+1, OldElts * 2);
2630 NewElts = std::min(Size, std::max(NewElts, 8u));
2631
2632 // Copy the data across.
2633 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2634 for (unsigned I = 0; I != OldElts; ++I)
2635 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2636 for (unsigned I = OldElts; I != NewElts; ++I)
2637 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2638 if (NewValue.hasArrayFiller())
2639 NewValue.getArrayFiller() = Array.getArrayFiller();
2640 Array.swap(NewValue);
2641}
2642
2643/// Determine whether a type would actually be read by an lvalue-to-rvalue
2644/// conversion. If it's of class type, we may assume that the copy operation
2645/// is trivial. Note that this is never true for a union type with fields
2646/// (because the copy always "reads" the active member) and always true for
2647/// a non-class type.
2648static bool isReadByLvalueToRvalueConversion(QualType T) {
2649 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2650 if (!RD || (RD->isUnion() && !RD->field_empty()))
2651 return true;
2652 if (RD->isEmpty())
2653 return false;
2654
2655 for (auto *Field : RD->fields())
2656 if (isReadByLvalueToRvalueConversion(Field->getType()))
2657 return true;
2658
2659 for (auto &BaseSpec : RD->bases())
2660 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2661 return true;
2662
2663 return false;
2664}
2665
2666/// Diagnose an attempt to read from any unreadable field within the specified
2667/// type, which might be a class type.
2668static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2669 QualType T) {
2670 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2671 if (!RD)
2672 return false;
2673
2674 if (!RD->hasMutableFields())
2675 return false;
2676
2677 for (auto *Field : RD->fields()) {
2678 // If we're actually going to read this field in some way, then it can't
2679 // be mutable. If we're in a union, then assigning to a mutable field
2680 // (even an empty one) can change the active member, so that's not OK.
2681 // FIXME: Add core issue number for the union case.
2682 if (Field->isMutable() &&
2683 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2684 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2685 Info.Note(Field->getLocation(), diag::note_declared_at);
2686 return true;
2687 }
2688
2689 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2690 return true;
2691 }
2692
2693 for (auto &BaseSpec : RD->bases())
2694 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2695 return true;
2696
2697 // All mutable fields were empty, and thus not actually read.
2698 return false;
2699}
2700
2701/// Kinds of access we can perform on an object, for diagnostics.
2702enum AccessKinds {
2703 AK_Read,
2704 AK_Assign,
2705 AK_Increment,
2706 AK_Decrement
2707};
2708
2709namespace {
2710/// A handle to a complete object (an object that is not a subobject of
2711/// another object).
2712struct CompleteObject {
2713 /// The value of the complete object.
2714 APValue *Value;
2715 /// The type of the complete object.
2716 QualType Type;
2717 bool LifetimeStartedInEvaluation;
2718
2719 CompleteObject() : Value(nullptr) {}
2720 CompleteObject(APValue *Value, QualType Type,
2721 bool LifetimeStartedInEvaluation)
2722 : Value(Value), Type(Type),
2723 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2724 assert(Value && "missing value for complete object")(static_cast <bool> (Value && "missing value for complete object"
) ? void (0) : __assert_fail ("Value && \"missing value for complete object\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2724, __extension__ __PRETTY_FUNCTION__))
;
2725 }
2726
2727 explicit operator bool() const { return Value; }
2728};
2729} // end anonymous namespace
2730
2731/// Find the designated sub-object of an rvalue.
2732template<typename SubobjectHandler>
2733typename SubobjectHandler::result_type
2734findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2735 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2736 if (Sub.Invalid)
2737 // A diagnostic will have already been produced.
2738 return handler.failed();
2739 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2740 if (Info.getLangOpts().CPlusPlus11)
2741 Info.FFDiag(E, Sub.isOnePastTheEnd()
2742 ? diag::note_constexpr_access_past_end
2743 : diag::note_constexpr_access_unsized_array)
2744 << handler.AccessKind;
2745 else
2746 Info.FFDiag(E);
2747 return handler.failed();
2748 }
2749
2750 APValue *O = Obj.Value;
2751 QualType ObjType = Obj.Type;
2752 const FieldDecl *LastField = nullptr;
2753 const bool MayReadMutableMembers =
2754 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2755
2756 // Walk the designator's path to find the subobject.
2757 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2758 if (O->isUninit()) {
2759 if (!Info.checkingPotentialConstantExpression())
2760 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2761 return handler.failed();
2762 }
2763
2764 if (I == N) {
2765 // If we are reading an object of class type, there may still be more
2766 // things we need to check: if there are any mutable subobjects, we
2767 // cannot perform this read. (This only happens when performing a trivial
2768 // copy or assignment.)
2769 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2770 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2771 return handler.failed();
2772
2773 if (!handler.found(*O, ObjType))
2774 return false;
2775
2776 // If we modified a bit-field, truncate it to the right width.
2777 if (handler.AccessKind != AK_Read &&
2778 LastField && LastField->isBitField() &&
2779 !truncateBitfieldValue(Info, E, *O, LastField))
2780 return false;
2781
2782 return true;
2783 }
2784
2785 LastField = nullptr;
2786 if (ObjType->isArrayType()) {
2787 // Next subobject is an array element.
2788 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2789 assert(CAT && "vla in literal type?")(static_cast <bool> (CAT && "vla in literal type?"
) ? void (0) : __assert_fail ("CAT && \"vla in literal type?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2789, __extension__ __PRETTY_FUNCTION__))
;
2790 uint64_t Index = Sub.Entries[I].ArrayIndex;
2791 if (CAT->getSize().ule(Index)) {
2792 // Note, it should not be possible to form a pointer with a valid
2793 // designator which points more than one past the end of the array.
2794 if (Info.getLangOpts().CPlusPlus11)
2795 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2796 << handler.AccessKind;
2797 else
2798 Info.FFDiag(E);
2799 return handler.failed();
2800 }
2801
2802 ObjType = CAT->getElementType();
2803
2804 // An array object is represented as either an Array APValue or as an
2805 // LValue which refers to a string literal.
2806 if (O->isLValue()) {
2807 assert(I == N - 1 && "extracting subobject of character?")(static_cast <bool> (I == N - 1 && "extracting subobject of character?"
) ? void (0) : __assert_fail ("I == N - 1 && \"extracting subobject of character?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2807, __extension__ __PRETTY_FUNCTION__))
;
2808 assert(!O->hasLValuePath() || O->getLValuePath().empty())(static_cast <bool> (!O->hasLValuePath() || O->getLValuePath
().empty()) ? void (0) : __assert_fail ("!O->hasLValuePath() || O->getLValuePath().empty()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2808, __extension__ __PRETTY_FUNCTION__))
;
2809 if (handler.AccessKind != AK_Read)
2810 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2811 *O);
2812 else
2813 return handler.foundString(*O, ObjType, Index);
2814 }
2815
2816 if (O->getArrayInitializedElts() > Index)
2817 O = &O->getArrayInitializedElt(Index);
2818 else if (handler.AccessKind != AK_Read) {
2819 expandArray(*O, Index);
2820 O = &O->getArrayInitializedElt(Index);
2821 } else
2822 O = &O->getArrayFiller();
2823 } else if (ObjType->isAnyComplexType()) {
2824 // Next subobject is a complex number.
2825 uint64_t Index = Sub.Entries[I].ArrayIndex;
2826 if (Index > 1) {
2827 if (Info.getLangOpts().CPlusPlus11)
2828 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2829 << handler.AccessKind;
2830 else
2831 Info.FFDiag(E);
2832 return handler.failed();
2833 }
2834
2835 bool WasConstQualified = ObjType.isConstQualified();
2836 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2837 if (WasConstQualified)
2838 ObjType.addConst();
2839
2840 assert(I == N - 1 && "extracting subobject of scalar?")(static_cast <bool> (I == N - 1 && "extracting subobject of scalar?"
) ? void (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2840, __extension__ __PRETTY_FUNCTION__))
;
2841 if (O->isComplexInt()) {
2842 return handler.found(Index ? O->getComplexIntImag()
2843 : O->getComplexIntReal(), ObjType);
2844 } else {
2845 assert(O->isComplexFloat())(static_cast <bool> (O->isComplexFloat()) ? void (0)
: __assert_fail ("O->isComplexFloat()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2845, __extension__ __PRETTY_FUNCTION__))
;
2846 return handler.found(Index ? O->getComplexFloatImag()
2847 : O->getComplexFloatReal(), ObjType);
2848 }
2849 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2850 // In C++14 onwards, it is permitted to read a mutable member whose
2851 // lifetime began within the evaluation.
2852 // FIXME: Should we also allow this in C++11?
2853 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2854 !MayReadMutableMembers) {
2855 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2856 << Field;
2857 Info.Note(Field->getLocation(), diag::note_declared_at);
2858 return handler.failed();
2859 }
2860
2861 // Next subobject is a class, struct or union field.
2862 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2863 if (RD->isUnion()) {
2864 const FieldDecl *UnionField = O->getUnionField();
2865 if (!UnionField ||
2866 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2867 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2868 << handler.AccessKind << Field << !UnionField << UnionField;
2869 return handler.failed();
2870 }
2871 O = &O->getUnionValue();
2872 } else
2873 O = &O->getStructField(Field->getFieldIndex());
2874
2875 bool WasConstQualified = ObjType.isConstQualified();
2876 ObjType = Field->getType();
2877 if (WasConstQualified && !Field->isMutable())
2878 ObjType.addConst();
2879
2880 if (ObjType.isVolatileQualified()) {
2881 if (Info.getLangOpts().CPlusPlus) {
2882 // FIXME: Include a description of the path to the volatile subobject.
2883 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2884 << handler.AccessKind << 2 << Field;
2885 Info.Note(Field->getLocation(), diag::note_declared_at);
2886 } else {
2887 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2888 }
2889 return handler.failed();
2890 }
2891
2892 LastField = Field;
2893 } else {
2894 // Next subobject is a base class.
2895 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2896 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2897 O = &O->getStructBase(getBaseIndex(Derived, Base));
2898
2899 bool WasConstQualified = ObjType.isConstQualified();
2900 ObjType = Info.Ctx.getRecordType(Base);
2901 if (WasConstQualified)
2902 ObjType.addConst();
2903 }
2904 }
2905}
2906
2907namespace {
2908struct ExtractSubobjectHandler {
2909 EvalInfo &Info;
2910 APValue &Result;
2911
2912 static const AccessKinds AccessKind = AK_Read;
2913
2914 typedef bool result_type;
2915 bool failed() { return false; }
2916 bool found(APValue &Subobj, QualType SubobjType) {
2917 Result = Subobj;
2918 return true;
2919 }
2920 bool found(APSInt &Value, QualType SubobjType) {
2921 Result = APValue(Value);
2922 return true;
2923 }
2924 bool found(APFloat &Value, QualType SubobjType) {
2925 Result = APValue(Value);
2926 return true;
2927 }
2928 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2929 Result = APValue(extractStringLiteralCharacter(
2930 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2931 return true;
2932 }
2933};
2934} // end anonymous namespace
2935
2936const AccessKinds ExtractSubobjectHandler::AccessKind;
2937
2938/// Extract the designated sub-object of an rvalue.
2939static bool extractSubobject(EvalInfo &Info, const Expr *E,
2940 const CompleteObject &Obj,
2941 const SubobjectDesignator &Sub,
2942 APValue &Result) {
2943 ExtractSubobjectHandler Handler = { Info, Result };
2944 return findSubobject(Info, E, Obj, Sub, Handler);
2945}
2946
2947namespace {
2948struct ModifySubobjectHandler {
2949 EvalInfo &Info;
2950 APValue &NewVal;
2951 const Expr *E;
2952
2953 typedef bool result_type;
2954 static const AccessKinds AccessKind = AK_Assign;
2955
2956 bool checkConst(QualType QT) {
2957 // Assigning to a const object has undefined behavior.
2958 if (QT.isConstQualified()) {
2959 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2960 return false;
2961 }
2962 return true;
2963 }
2964
2965 bool failed() { return false; }
2966 bool found(APValue &Subobj, QualType SubobjType) {
2967 if (!checkConst(SubobjType))
2968 return false;
2969 // We've been given ownership of NewVal, so just swap it in.
2970 Subobj.swap(NewVal);
2971 return true;
2972 }
2973 bool found(APSInt &Value, QualType SubobjType) {
2974 if (!checkConst(SubobjType))
2975 return false;
2976 if (!NewVal.isInt()) {
2977 // Maybe trying to write a cast pointer value into a complex?
2978 Info.FFDiag(E);
2979 return false;
2980 }
2981 Value = NewVal.getInt();
2982 return true;
2983 }
2984 bool found(APFloat &Value, QualType SubobjType) {
2985 if (!checkConst(SubobjType))
2986 return false;
2987 Value = NewVal.getFloat();
2988 return true;
2989 }
2990 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2991 llvm_unreachable("shouldn't encounter string elements with ExpandArrays")::llvm::llvm_unreachable_internal("shouldn't encounter string elements with ExpandArrays"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 2991)
;
2992 }
2993};
2994} // end anonymous namespace
2995
2996const AccessKinds ModifySubobjectHandler::AccessKind;
2997
2998/// Update the designated sub-object of an rvalue to the given value.
2999static bool modifySubobject(EvalInfo &Info, const Expr *E,
3000 const CompleteObject &Obj,
3001 const SubobjectDesignator &Sub,
3002 APValue &NewVal) {
3003 ModifySubobjectHandler Handler = { Info, NewVal, E };
3004 return findSubobject(Info, E, Obj, Sub, Handler);
3005}
3006
3007/// Find the position where two subobject designators diverge, or equivalently
3008/// the length of the common initial subsequence.
3009static unsigned FindDesignatorMismatch(QualType ObjType,
3010 const SubobjectDesignator &A,
3011 const SubobjectDesignator &B,
3012 bool &WasArrayIndex) {
3013 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3014 for (/**/; I != N; ++I) {
3015 if (!ObjType.isNull() &&
3016 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3017 // Next subobject is an array element.
3018 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3019 WasArrayIndex = true;
3020 return I;
3021 }
3022 if (ObjType->isAnyComplexType())
3023 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3024 else
3025 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3026 } else {
3027 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3028 WasArrayIndex = false;
3029 return I;
3030 }
3031 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3032 // Next subobject is a field.
3033 ObjType = FD->getType();
3034 else
3035 // Next subobject is a base class.
3036 ObjType = QualType();
3037 }
3038 }
3039 WasArrayIndex = false;
3040 return I;
3041}
3042
3043/// Determine whether the given subobject designators refer to elements of the
3044/// same array object.
3045static bool AreElementsOfSameArray(QualType ObjType,
3046 const SubobjectDesignator &A,
3047 const SubobjectDesignator &B) {
3048 if (A.Entries.size() != B.Entries.size())
3049 return false;
3050
3051 bool IsArray = A.MostDerivedIsArrayElement;
3052 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3053 // A is a subobject of the array element.
3054 return false;
3055
3056 // If A (and B) designates an array element, the last entry will be the array
3057 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3058 // of length 1' case, and the entire path must match.
3059 bool WasArrayIndex;
3060 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3061 return CommonLength >= A.Entries.size() - IsArray;
3062}
3063
3064/// Find the complete object to which an LValue refers.
3065static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3066 AccessKinds AK, const LValue &LVal,
3067 QualType LValType) {
3068 if (!LVal.Base) {
3069 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3070 return CompleteObject();
3071 }
3072
3073 CallStackFrame *Frame = nullptr;
3074 if (LVal.getLValueCallIndex()) {
3075 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
3076 if (!Frame) {
3077 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3078 << AK << LVal.Base.is<const ValueDecl*>();
3079 NoteLValueLocation(Info, LVal.Base);
3080 return CompleteObject();
3081 }
3082 }
3083
3084 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3085 // is not a constant expression (even if the object is non-volatile). We also
3086 // apply this rule to C++98, in order to conform to the expected 'volatile'
3087 // semantics.
3088 if (LValType.isVolatileQualified()) {
3089 if (Info.getLangOpts().CPlusPlus)
3090 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3091 << AK << LValType;
3092 else
3093 Info.FFDiag(E);
3094 return CompleteObject();
3095 }
3096
3097 // Compute value storage location and type of base object.
3098 APValue *BaseVal = nullptr;
3099 QualType BaseType = getType(LVal.Base);
3100 bool LifetimeStartedInEvaluation = Frame;
3101
3102 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3103 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3104 // In C++11, constexpr, non-volatile variables initialized with constant
3105 // expressions are constant expressions too. Inside constexpr functions,
3106 // parameters are constant expressions even if they're non-const.
3107 // In C++1y, objects local to a constant expression (those with a Frame) are
3108 // both readable and writable inside constant expressions.
3109 // In C, such things can also be folded, although they are not ICEs.
3110 const VarDecl *VD = dyn_cast<VarDecl>(D);
3111 if (VD) {
3112 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3113 VD = VDef;
3114 }
3115 if (!VD || VD->isInvalidDecl()) {
3116 Info.FFDiag(E);
3117 return CompleteObject();
3118 }
3119
3120 // Accesses of volatile-qualified objects are not allowed.
3121 if (BaseType.isVolatileQualified()) {
3122 if (Info.getLangOpts().CPlusPlus) {
3123 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3124 << AK << 1 << VD;
3125 Info.Note(VD->getLocation(), diag::note_declared_at);
3126 } else {
3127 Info.FFDiag(E);
3128 }
3129 return CompleteObject();
3130 }
3131
3132 // Unless we're looking at a local variable or argument in a constexpr call,
3133 // the variable we're reading must be const.
3134 if (!Frame) {
3135 if (Info.getLangOpts().CPlusPlus14 &&
3136 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3137 // OK, we can read and modify an object if we're in the process of
3138 // evaluating its initializer, because its lifetime began in this
3139 // evaluation.
3140 } else if (AK != AK_Read) {
3141 // All the remaining cases only permit reading.
3142 Info.FFDiag(E, diag::note_constexpr_modify_global);
3143 return CompleteObject();
3144 } else if (VD->isConstexpr()) {
3145 // OK, we can read this variable.
3146 } else if (BaseType->isIntegralOrEnumerationType()) {
3147 // In OpenCL if a variable is in constant address space it is a const value.
3148 if (!(BaseType.isConstQualified() ||
3149 (Info.getLangOpts().OpenCL &&
3150 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3151 if (Info.getLangOpts().CPlusPlus) {
3152 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3153 Info.Note(VD->getLocation(), diag::note_declared_at);
3154 } else {
3155 Info.FFDiag(E);
3156 }
3157 return CompleteObject();
3158 }
3159 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3160 // We support folding of const floating-point types, in order to make
3161 // static const data members of such types (supported as an extension)
3162 // more useful.
3163 if (Info.getLangOpts().CPlusPlus11) {
3164 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3165 Info.Note(VD->getLocation(), diag::note_declared_at);
3166 } else {
3167 Info.CCEDiag(E);
3168 }
3169 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3170 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3171 // Keep evaluating to see what we can do.
3172 } else {
3173 // FIXME: Allow folding of values of any literal type in all languages.
3174 if (Info.checkingPotentialConstantExpression() &&
3175 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3176 // The definition of this variable could be constexpr. We can't
3177 // access it right now, but may be able to in future.
3178 } else if (Info.getLangOpts().CPlusPlus11) {
3179 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3180 Info.Note(VD->getLocation(), diag::note_declared_at);
3181 } else {
3182 Info.FFDiag(E);
3183 }
3184 return CompleteObject();
3185 }
3186 }
3187
3188 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3189 return CompleteObject();
3190 } else {
3191 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3192
3193 if (!Frame) {
3194 if (const MaterializeTemporaryExpr *MTE =
3195 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3196 assert(MTE->getStorageDuration() == SD_Static &&(static_cast <bool> (MTE->getStorageDuration() == SD_Static
&& "should have a frame for a non-global materialized temporary"
) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3197, __extension__ __PRETTY_FUNCTION__))
3197 "should have a frame for a non-global materialized temporary")(static_cast <bool> (MTE->getStorageDuration() == SD_Static
&& "should have a frame for a non-global materialized temporary"
) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3197, __extension__ __PRETTY_FUNCTION__))
;
3198
3199 // Per C++1y [expr.const]p2:
3200 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3201 // - a [...] glvalue of integral or enumeration type that refers to
3202 // a non-volatile const object [...]
3203 // [...]
3204 // - a [...] glvalue of literal type that refers to a non-volatile
3205 // object whose lifetime began within the evaluation of e.
3206 //
3207 // C++11 misses the 'began within the evaluation of e' check and
3208 // instead allows all temporaries, including things like:
3209 // int &&r = 1;
3210 // int x = ++r;
3211 // constexpr int k = r;
3212 // Therefore we use the C++14 rules in C++11 too.
3213 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3214 const ValueDecl *ED = MTE->getExtendingDecl();
3215 if (!(BaseType.isConstQualified() &&
3216 BaseType->isIntegralOrEnumerationType()) &&
3217 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3218 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3219 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3220 return CompleteObject();
3221 }
3222
3223 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3224 assert(BaseVal && "got reference to unevaluated temporary")(static_cast <bool> (BaseVal && "got reference to unevaluated temporary"
) ? void (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3224, __extension__ __PRETTY_FUNCTION__))
;
3225 LifetimeStartedInEvaluation = true;
3226 } else {
3227 Info.FFDiag(E);
3228 return CompleteObject();
3229 }
3230 } else {
3231 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3232 assert(BaseVal && "missing value for temporary")(static_cast <bool> (BaseVal && "missing value for temporary"
) ? void (0) : __assert_fail ("BaseVal && \"missing value for temporary\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3232, __extension__ __PRETTY_FUNCTION__))
;
3233 }
3234
3235 // Volatile temporary objects cannot be accessed in constant expressions.
3236 if (BaseType.isVolatileQualified()) {
3237 if (Info.getLangOpts().CPlusPlus) {
3238 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3239 << AK << 0;
3240 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3241 } else {
3242 Info.FFDiag(E);
3243 }
3244 return CompleteObject();
3245 }
3246 }
3247
3248 // During the construction of an object, it is not yet 'const'.
3249 // FIXME: This doesn't do quite the right thing for const subobjects of the
3250 // object under construction.
3251 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3252 LVal.getLValueCallIndex(),
3253 LVal.getLValueVersion())) {
3254 BaseType = Info.Ctx.getCanonicalType(BaseType);
3255 BaseType.removeLocalConst();
3256 LifetimeStartedInEvaluation = true;
3257 }
3258
3259 // In C++14, we can't safely access any mutable state when we might be
3260 // evaluating after an unmodeled side effect.
3261 //
3262 // FIXME: Not all local state is mutable. Allow local constant subobjects
3263 // to be read here (but take care with 'mutable' fields).
3264 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3265 Info.EvalStatus.HasSideEffects) ||
3266 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3267 return CompleteObject();
3268
3269 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3270}
3271
3272/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3273/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3274/// glvalue referred to by an entity of reference type.
3275///
3276/// \param Info - Information about the ongoing evaluation.
3277/// \param Conv - The expression for which we are performing the conversion.
3278/// Used for diagnostics.
3279/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3280/// case of a non-class type).
3281/// \param LVal - The glvalue on which we are attempting to perform this action.
3282/// \param RVal - The produced value will be placed here.
3283static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3284 QualType Type,
3285 const LValue &LVal, APValue &RVal) {
3286 if (LVal.Designator.Invalid)
3287 return false;
3288
3289 // Check for special cases where there is no existing APValue to look at.
3290 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3291 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3292 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3293 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3294 // initializer until now for such expressions. Such an expression can't be
3295 // an ICE in C, so this only matters for fold.
3296 if (Type.isVolatileQualified()) {
3297 Info.FFDiag(Conv);
3298 return false;
3299 }
3300 APValue Lit;
3301 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3302 return false;
3303 CompleteObject LitObj(&Lit, Base->getType(), false);
3304 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3305 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3306 // We represent a string literal array as an lvalue pointing at the
3307 // corresponding expression, rather than building an array of chars.
3308 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3309 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3310 CompleteObject StrObj(&Str, Base->getType(), false);
3311 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3312 }
3313 }
3314
3315 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3316 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3317}
3318
3319/// Perform an assignment of Val to LVal. Takes ownership of Val.
3320static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3321 QualType LValType, APValue &Val) {
3322 if (LVal.Designator.Invalid)
3323 return false;
3324
3325 if (!Info.getLangOpts().CPlusPlus14) {
3326 Info.FFDiag(E);
3327 return false;
3328 }
3329
3330 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3331 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3332}
3333
3334namespace {
3335struct CompoundAssignSubobjectHandler {
3336 EvalInfo &Info;
3337 const Expr *E;
3338 QualType PromotedLHSType;
3339 BinaryOperatorKind Opcode;
3340 const APValue &RHS;
3341
3342 static const AccessKinds AccessKind = AK_Assign;
3343
3344 typedef bool result_type;
3345
3346 bool checkConst(QualType QT) {
3347 // Assigning to a const object has undefined behavior.
3348 if (QT.isConstQualified()) {
3349 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3350 return false;
3351 }
3352 return true;
3353 }
3354
3355 bool failed() { return false; }
3356 bool found(APValue &Subobj, QualType SubobjType) {
3357 switch (Subobj.getKind()) {
3358 case APValue::Int:
3359 return found(Subobj.getInt(), SubobjType);
3360 case APValue::Float:
3361 return found(Subobj.getFloat(), SubobjType);
3362 case APValue::ComplexInt:
3363 case APValue::ComplexFloat:
3364 // FIXME: Implement complex compound assignment.
3365 Info.FFDiag(E);
3366 return false;
3367 case APValue::LValue:
3368 return foundPointer(Subobj, SubobjType);
3369 default:
3370 // FIXME: can this happen?
3371 Info.FFDiag(E);
3372 return false;
3373 }
3374 }
3375 bool found(APSInt &Value, QualType SubobjType) {
3376 if (!checkConst(SubobjType))
3377 return false;
3378
3379 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3380 // We don't support compound assignment on integer-cast-to-pointer
3381 // values.
3382 Info.FFDiag(E);
3383 return false;
3384 }
3385
3386 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3387 SubobjType, Value);
3388 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3389 return false;
3390 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3391 return true;
3392 }
3393 bool found(APFloat &Value, QualType SubobjType) {
3394 return checkConst(SubobjType) &&
3395 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3396 Value) &&
3397 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3398 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3399 }
3400 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3401 if (!checkConst(SubobjType))
3402 return false;
3403
3404 QualType PointeeType;
3405 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3406 PointeeType = PT->getPointeeType();
3407
3408 if (PointeeType.isNull() || !RHS.isInt() ||
3409 (Opcode != BO_Add && Opcode != BO_Sub)) {
3410 Info.FFDiag(E);
3411 return false;
3412 }
3413
3414 APSInt Offset = RHS.getInt();
3415 if (Opcode == BO_Sub)
3416 negateAsSigned(Offset);
3417
3418 LValue LVal;
3419 LVal.setFrom(Info.Ctx, Subobj);
3420 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3421 return false;
3422 LVal.moveInto(Subobj);
3423 return true;
3424 }
3425 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3426 llvm_unreachable("shouldn't encounter string elements here")::llvm::llvm_unreachable_internal("shouldn't encounter string elements here"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3426)
;
3427 }
3428};
3429} // end anonymous namespace
3430
3431const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3432
3433/// Perform a compound assignment of LVal <op>= RVal.
3434static bool handleCompoundAssignment(
3435 EvalInfo &Info, const Expr *E,
3436 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3437 BinaryOperatorKind Opcode, const APValue &RVal) {
3438 if (LVal.Designator.Invalid)
3439 return false;
3440
3441 if (!Info.getLangOpts().CPlusPlus14) {
3442 Info.FFDiag(E);
3443 return false;
3444 }
3445
3446 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3447 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3448 RVal };
3449 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3450}
3451
3452namespace {
3453struct IncDecSubobjectHandler {
3454 EvalInfo &Info;
3455 const UnaryOperator *E;
3456 AccessKinds AccessKind;
3457 APValue *Old;
3458
3459 typedef bool result_type;
3460
3461 bool checkConst(QualType QT) {
3462 // Assigning to a const object has undefined behavior.
3463 if (QT.isConstQualified()) {
3464 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3465 return false;
3466 }
3467 return true;
3468 }
3469
3470 bool failed() { return false; }
3471 bool found(APValue &Subobj, QualType SubobjType) {
3472 // Stash the old value. Also clear Old, so we don't clobber it later
3473 // if we're post-incrementing a complex.
3474 if (Old) {
3475 *Old = Subobj;
3476 Old = nullptr;
3477 }
3478
3479 switch (Subobj.getKind()) {
3480 case APValue::Int:
3481 return found(Subobj.getInt(), SubobjType);
3482 case APValue::Float:
3483 return found(Subobj.getFloat(), SubobjType);
3484 case APValue::ComplexInt:
3485 return found(Subobj.getComplexIntReal(),
3486 SubobjType->castAs<ComplexType>()->getElementType()
3487 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3488 case APValue::ComplexFloat:
3489 return found(Subobj.getComplexFloatReal(),
3490 SubobjType->castAs<ComplexType>()->getElementType()
3491 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3492 case APValue::LValue:
3493 return foundPointer(Subobj, SubobjType);
3494 default:
3495 // FIXME: can this happen?
3496 Info.FFDiag(E);
3497 return false;
3498 }
3499 }
3500 bool found(APSInt &Value, QualType SubobjType) {
3501 if (!checkConst(SubobjType))
3502 return false;
3503
3504 if (!SubobjType->isIntegerType()) {
3505 // We don't support increment / decrement on integer-cast-to-pointer
3506 // values.
3507 Info.FFDiag(E);
3508 return false;
3509 }
3510
3511 if (Old) *Old = APValue(Value);
3512
3513 // bool arithmetic promotes to int, and the conversion back to bool
3514 // doesn't reduce mod 2^n, so special-case it.
3515 if (SubobjType->isBooleanType()) {
3516 if (AccessKind == AK_Increment)
3517 Value = 1;
3518 else
3519 Value = !Value;
3520 return true;
3521 }
3522
3523 bool WasNegative = Value.isNegative();
3524 if (AccessKind == AK_Increment) {
3525 ++Value;
3526
3527 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3528 APSInt ActualValue(Value, /*IsUnsigned*/true);
3529 return HandleOverflow(Info, E, ActualValue, SubobjType);
3530 }
3531 } else {
3532 --Value;
3533
3534 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3535 unsigned BitWidth = Value.getBitWidth();
3536 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3537 ActualValue.setBit(BitWidth);
3538 return HandleOverflow(Info, E, ActualValue, SubobjType);
3539 }
3540 }
3541 return true;
3542 }
3543 bool found(APFloat &Value, QualType SubobjType) {
3544 if (!checkConst(SubobjType))
3545 return false;
3546
3547 if (Old) *Old = APValue(Value);
3548
3549 APFloat One(Value.getSemantics(), 1);
3550 if (AccessKind == AK_Increment)
3551 Value.add(One, APFloat::rmNearestTiesToEven);
3552 else
3553 Value.subtract(One, APFloat::rmNearestTiesToEven);
3554 return true;
3555 }
3556 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3557 if (!checkConst(SubobjType))
3558 return false;
3559
3560 QualType PointeeType;
3561 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3562 PointeeType = PT->getPointeeType();
3563 else {
3564 Info.FFDiag(E);
3565 return false;
3566 }
3567
3568 LValue LVal;
3569 LVal.setFrom(Info.Ctx, Subobj);
3570 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3571 AccessKind == AK_Increment ? 1 : -1))
3572 return false;
3573 LVal.moveInto(Subobj);
3574 return true;
3575 }
3576 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3577 llvm_unreachable("shouldn't encounter string elements here")::llvm::llvm_unreachable_internal("shouldn't encounter string elements here"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3577)
;
3578 }
3579};
3580} // end anonymous namespace
3581
3582/// Perform an increment or decrement on LVal.
3583static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3584 QualType LValType, bool IsIncrement, APValue *Old) {
3585 if (LVal.Designator.Invalid)
3586 return false;
3587
3588 if (!Info.getLangOpts().CPlusPlus14) {
3589 Info.FFDiag(E);
3590 return false;
3591 }
3592
3593 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3594 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3595 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3596 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3597}
3598
3599/// Build an lvalue for the object argument of a member function call.
3600static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3601 LValue &This) {
3602 if (Object->getType()->isPointerType())
3603 return EvaluatePointer(Object, This, Info);
3604
3605 if (Object->isGLValue())
3606 return EvaluateLValue(Object, This, Info);
3607
3608 if (Object->getType()->isLiteralType(Info.Ctx))
3609 return EvaluateTemporary(Object, This, Info);
3610
3611 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3612 return false;
3613}
3614
3615/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3616/// lvalue referring to the result.
3617///
3618/// \param Info - Information about the ongoing evaluation.
3619/// \param LV - An lvalue referring to the base of the member pointer.
3620/// \param RHS - The member pointer expression.
3621/// \param IncludeMember - Specifies whether the member itself is included in
3622/// the resulting LValue subobject designator. This is not possible when
3623/// creating a bound member function.
3624/// \return The field or method declaration to which the member pointer refers,
3625/// or 0 if evaluation fails.
3626static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3627 QualType LVType,
3628 LValue &LV,
3629 const Expr *RHS,
3630 bool IncludeMember = true) {
3631 MemberPtr MemPtr;
3632 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3633 return nullptr;
3634
3635 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3636 // member value, the behavior is undefined.
3637 if (!MemPtr.getDecl()) {
3638 // FIXME: Specific diagnostic.
3639 Info.FFDiag(RHS);
3640 return nullptr;
3641 }
3642
3643 if (MemPtr.isDerivedMember()) {
3644 // This is a member of some derived class. Truncate LV appropriately.
3645 // The end of the derived-to-base path for the base object must match the
3646 // derived-to-base path for the member pointer.
3647 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3648 LV.Designator.Entries.size()) {
3649 Info.FFDiag(RHS);
3650 return nullptr;
3651 }
3652 unsigned PathLengthToMember =
3653 LV.Designator.Entries.size() - MemPtr.Path.size();
3654 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3655 const CXXRecordDecl *LVDecl = getAsBaseClass(
3656 LV.Designator.Entries[PathLengthToMember + I]);
3657 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3658 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3659 Info.FFDiag(RHS);
3660 return nullptr;
3661 }
3662 }
3663
3664 // Truncate the lvalue to the appropriate derived class.
3665 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3666 PathLengthToMember))
3667 return nullptr;
3668 } else if (!MemPtr.Path.empty()) {
3669 // Extend the LValue path with the member pointer's path.
3670 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3671 MemPtr.Path.size() + IncludeMember);
3672
3673 // Walk down to the appropriate base class.
3674 if (const PointerType *PT = LVType->getAs<PointerType>())
3675 LVType = PT->getPointeeType();
3676 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3677 assert(RD && "member pointer access on non-class-type expression")(static_cast <bool> (RD && "member pointer access on non-class-type expression"
) ? void (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3677, __extension__ __PRETTY_FUNCTION__))
;
3678 // The first class in the path is that of the lvalue.
3679 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3680 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3681 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3682 return nullptr;
3683 RD = Base;
3684 }
3685 // Finally cast to the class containing the member.
3686 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3687 MemPtr.getContainingRecord()))
3688 return nullptr;
3689 }
3690
3691 // Add the member. Note that we cannot build bound member functions here.
3692 if (IncludeMember) {
3693 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3694 if (!HandleLValueMember(Info, RHS, LV, FD))
3695 return nullptr;
3696 } else if (const IndirectFieldDecl *IFD =
3697 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3698 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3699 return nullptr;
3700 } else {
3701 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-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3701)
;
3702 }
3703 }
3704
3705 return MemPtr.getDecl();
3706}
3707
3708static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3709 const BinaryOperator *BO,
3710 LValue &LV,
3711 bool IncludeMember = true) {
3712 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)(static_cast <bool> (BO->getOpcode() == BO_PtrMemD ||
BO->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail
("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3712, __extension__ __PRETTY_FUNCTION__))
;
3713
3714 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3715 if (Info.noteFailure()) {
3716 MemberPtr MemPtr;
3717 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3718 }
3719 return nullptr;
3720 }
3721
3722 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3723 BO->getRHS(), IncludeMember);
3724}
3725
3726/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3727/// the provided lvalue, which currently refers to the base object.
3728static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3729 LValue &Result) {
3730 SubobjectDesignator &D = Result.Designator;
3731 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3732 return false;
3733
3734 QualType TargetQT = E->getType();
3735 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3736 TargetQT = PT->getPointeeType();
3737
3738 // Check this cast lands within the final derived-to-base subobject path.
3739 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3740 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3741 << D.MostDerivedType << TargetQT;
3742 return false;
3743 }
3744
3745 // Check the type of the final cast. We don't need to check the path,
3746 // since a cast can only be formed if the path is unique.
3747 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3748 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3749 const CXXRecordDecl *FinalType;
3750 if (NewEntriesSize == D.MostDerivedPathLength)
3751 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3752 else
3753 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3754 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3755 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3756 << D.MostDerivedType << TargetQT;
3757 return false;
3758 }
3759
3760 // Truncate the lvalue to the appropriate derived class.
3761 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3762}
3763
3764namespace {
3765enum EvalStmtResult {
3766 /// Evaluation failed.
3767 ESR_Failed,
3768 /// Hit a 'return' statement.
3769 ESR_Returned,
3770 /// Evaluation succeeded.
3771 ESR_Succeeded,
3772 /// Hit a 'continue' statement.
3773 ESR_Continue,
3774 /// Hit a 'break' statement.
3775 ESR_Break,
3776 /// Still scanning for 'case' or 'default' statement.
3777 ESR_CaseNotFound
3778};
3779}
3780
3781static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3782 // We don't need to evaluate the initializer for a static local.
3783 if (!VD->hasLocalStorage())
3784 return true;
3785
3786 LValue Result;
3787 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3788
3789 const Expr *InitE = VD->getInit();
3790 if (!InitE) {
3791 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3792 << false << VD->getType();
3793 Val = APValue();
3794 return false;
3795 }
3796
3797 if (InitE->isValueDependent())
3798 return false;
3799
3800 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3801 // Wipe out any partially-computed value, to allow tracking that this
3802 // evaluation failed.
3803 Val = APValue();
3804 return false;
3805 }
3806
3807 return true;
3808}
3809
3810static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3811 bool OK = true;
3812
3813 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3814 OK &= EvaluateVarDecl(Info, VD);
3815
3816 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3817 for (auto *BD : DD->bindings())
3818 if (auto *VD = BD->getHoldingVar())
3819 OK &= EvaluateDecl(Info, VD);
3820
3821 return OK;
3822}
3823
3824
3825/// Evaluate a condition (either a variable declaration or an expression).
3826static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3827 const Expr *Cond, bool &Result) {
3828 FullExpressionRAII Scope(Info);
3829 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3830 return false;
3831 return EvaluateAsBooleanCondition(Cond, Result, Info);
3832}
3833
3834namespace {
3835/// \brief A location where the result (returned value) of evaluating a
3836/// statement should be stored.
3837struct StmtResult {
3838 /// The APValue that should be filled in with the returned value.
3839 APValue &Value;
3840 /// The location containing the result, if any (used to support RVO).
3841 const LValue *Slot;
3842};
3843
3844struct TempVersionRAII {
3845 CallStackFrame &Frame;
3846
3847 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3848 Frame.pushTempVersion();
3849 }
3850
3851 ~TempVersionRAII() {
3852 Frame.popTempVersion();
3853 }
3854};
3855
3856}
3857
3858static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3859 const Stmt *S,
3860 const SwitchCase *SC = nullptr);
3861
3862/// Evaluate the body of a loop, and translate the result as appropriate.
3863static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3864 const Stmt *Body,
3865 const SwitchCase *Case = nullptr) {
3866 BlockScopeRAII Scope(Info);
3867 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3868 case ESR_Break:
3869 return ESR_Succeeded;
3870 case ESR_Succeeded:
3871 case ESR_Continue:
3872 return ESR_Continue;
3873 case ESR_Failed:
3874 case ESR_Returned:
3875 case ESR_CaseNotFound:
3876 return ESR;
3877 }
3878 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3878)
;
3879}
3880
3881/// Evaluate a switch statement.
3882static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3883 const SwitchStmt *SS) {
3884 BlockScopeRAII Scope(Info);
3885
3886 // Evaluate the switch condition.
3887 APSInt Value;
3888 {
3889 FullExpressionRAII Scope(Info);
3890 if (const Stmt *Init = SS->getInit()) {
3891 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3892 if (ESR != ESR_Succeeded)
3893 return ESR;
3894 }
3895 if (SS->getConditionVariable() &&
3896 !EvaluateDecl(Info, SS->getConditionVariable()))
3897 return ESR_Failed;
3898 if (!EvaluateInteger(SS->getCond(), Value, Info))
3899 return ESR_Failed;
3900 }
3901
3902 // Find the switch case corresponding to the value of the condition.
3903 // FIXME: Cache this lookup.
3904 const SwitchCase *Found = nullptr;
3905 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3906 SC = SC->getNextSwitchCase()) {
3907 if (isa<DefaultStmt>(SC)) {
3908 Found = SC;
3909 continue;
3910 }
3911
3912 const CaseStmt *CS = cast<CaseStmt>(SC);
3913 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3914 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3915 : LHS;
3916 if (LHS <= Value && Value <= RHS) {
3917 Found = SC;
3918 break;
3919 }
3920 }
3921
3922 if (!Found)
3923 return ESR_Succeeded;
3924
3925 // Search the switch body for the switch case and evaluate it from there.
3926 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3927 case ESR_Break:
3928 return ESR_Succeeded;
3929 case ESR_Succeeded:
3930 case ESR_Continue:
3931 case ESR_Failed:
3932 case ESR_Returned:
3933 return ESR;
3934 case ESR_CaseNotFound:
3935 // This can only happen if the switch case is nested within a statement
3936 // expression. We have no intention of supporting that.
3937 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3938 return ESR_Failed;
3939 }
3940 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 3940)
;
3941}
3942
3943// Evaluate a statement.
3944static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3945 const Stmt *S, const SwitchCase *Case) {
3946 if (!Info.nextStep(S))
3947 return ESR_Failed;
3948
3949 // If we're hunting down a 'case' or 'default' label, recurse through
3950 // substatements until we hit the label.
3951 if (Case) {
3952 // FIXME: We don't start the lifetime of objects whose initialization we
3953 // jump over. However, such objects must be of class type with a trivial
3954 // default constructor that initialize all subobjects, so must be empty,
3955 // so this almost never matters.
3956 switch (S->getStmtClass()) {
3957 case Stmt::CompoundStmtClass:
3958 // FIXME: Precompute which substatement of a compound statement we
3959 // would jump to, and go straight there rather than performing a
3960 // linear scan each time.
3961 case Stmt::LabelStmtClass:
3962 case Stmt::AttributedStmtClass:
3963 case Stmt::DoStmtClass:
3964 break;
3965
3966 case Stmt::CaseStmtClass:
3967 case Stmt::DefaultStmtClass:
3968 if (Case == S)
3969 Case = nullptr;
3970 break;
3971
3972 case Stmt::IfStmtClass: {
3973 // FIXME: Precompute which side of an 'if' we would jump to, and go
3974 // straight there rather than scanning both sides.
3975 const IfStmt *IS = cast<IfStmt>(S);
3976
3977 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3978 // preceded by our switch label.
3979 BlockScopeRAII Scope(Info);
3980
3981 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3982 if (ESR != ESR_CaseNotFound || !IS->getElse())
3983 return ESR;
3984 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3985 }
3986
3987 case Stmt::WhileStmtClass: {
3988 EvalStmtResult ESR =
3989 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3990 if (ESR != ESR_Continue)
3991 return ESR;
3992 break;
3993 }
3994
3995 case Stmt::ForStmtClass: {
3996 const ForStmt *FS = cast<ForStmt>(S);
3997 EvalStmtResult ESR =
3998 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3999 if (ESR != ESR_Continue)
4000 return ESR;
4001 if (FS->getInc()) {
4002 FullExpressionRAII IncScope(Info);
4003 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4004 return ESR_Failed;
4005 }
4006 break;
4007 }
4008
4009 case Stmt::DeclStmtClass:
4010 // FIXME: If the variable has initialization that can't be jumped over,
4011 // bail out of any immediately-surrounding compound-statement too.
4012 default:
4013 return ESR_CaseNotFound;
4014 }
4015 }
4016
4017 switch (S->getStmtClass()) {
4018 default:
4019 if (const Expr *E = dyn_cast<Expr>(S)) {
4020 // Don't bother evaluating beyond an expression-statement which couldn't
4021 // be evaluated.
4022 FullExpressionRAII Scope(Info);
4023 if (!EvaluateIgnoredValue(Info, E))
4024 return ESR_Failed;
4025 return ESR_Succeeded;
4026 }
4027
4028 Info.FFDiag(S->getLocStart());
4029 return ESR_Failed;
4030
4031 case Stmt::NullStmtClass:
4032 return ESR_Succeeded;
4033
4034 case Stmt::DeclStmtClass: {
4035 const DeclStmt *DS = cast<DeclStmt>(S);
4036 for (const auto *DclIt : DS->decls()) {
4037 // Each declaration initialization is its own full-expression.
4038 // FIXME: This isn't quite right; if we're performing aggregate
4039 // initialization, each braced subexpression is its own full-expression.
4040 FullExpressionRAII Scope(Info);
4041 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4042 return ESR_Failed;
4043 }
4044 return ESR_Succeeded;
4045 }
4046
4047 case Stmt::ReturnStmtClass: {
4048 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4049 FullExpressionRAII Scope(Info);
4050 if (RetExpr &&
4051 !(Result.Slot
4052 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4053 : Evaluate(Result.Value, Info, RetExpr)))
4054 return ESR_Failed;
4055 return ESR_Returned;
4056 }
4057
4058 case Stmt::CompoundStmtClass: {
4059 BlockScopeRAII Scope(Info);
4060
4061 const CompoundStmt *CS = cast<CompoundStmt>(S);
4062 for (const auto *BI : CS->body()) {
4063 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4064 if (ESR == ESR_Succeeded)
4065 Case = nullptr;
4066 else if (ESR != ESR_CaseNotFound)
4067 return ESR;
4068 }
4069 return Case ? ESR_CaseNotFound : ESR_Succeeded;
4070 }
4071
4072 case Stmt::IfStmtClass: {
4073 const IfStmt *IS = cast<IfStmt>(S);
4074
4075 // Evaluate the condition, as either a var decl or as an expression.
4076 BlockScopeRAII Scope(Info);
4077 if (const Stmt *Init = IS->getInit()) {
4078 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4079 if (ESR != ESR_Succeeded)
4080 return ESR;
4081 }
4082 bool Cond;
4083 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4084 return ESR_Failed;
4085
4086 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4087 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4088 if (ESR != ESR_Succeeded)
4089 return ESR;
4090 }
4091 return ESR_Succeeded;
4092 }
4093
4094 case Stmt::WhileStmtClass: {
4095 const WhileStmt *WS = cast<WhileStmt>(S);
4096 while (true) {
4097 BlockScopeRAII Scope(Info);
4098 bool Continue;
4099 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4100 Continue))
4101 return ESR_Failed;
4102 if (!Continue)
4103 break;
4104
4105 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4106 if (ESR != ESR_Continue)
4107 return ESR;
4108 }
4109 return ESR_Succeeded;
4110 }
4111
4112 case Stmt::DoStmtClass: {
4113 const DoStmt *DS = cast<DoStmt>(S);
4114 bool Continue;
4115 do {
4116 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4117 if (ESR != ESR_Continue)
4118 return ESR;
4119 Case = nullptr;
4120
4121 FullExpressionRAII CondScope(Info);
4122 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4123 return ESR_Failed;
4124 } while (Continue);
4125 return ESR_Succeeded;
4126 }
4127
4128 case Stmt::ForStmtClass: {
4129 const ForStmt *FS = cast<ForStmt>(S);
4130 BlockScopeRAII Scope(Info);
4131 if (FS->getInit()) {
4132 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4133 if (ESR != ESR_Succeeded)
4134 return ESR;
4135 }
4136 while (true) {
4137 BlockScopeRAII Scope(Info);
4138 bool Continue = true;
4139 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4140 FS->getCond(), Continue))
4141 return ESR_Failed;
4142 if (!Continue)
4143 break;
4144
4145 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4146 if (ESR != ESR_Continue)
4147 return ESR;
4148
4149 if (FS->getInc()) {
4150 FullExpressionRAII IncScope(Info);
4151 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4152 return ESR_Failed;
4153 }
4154 }
4155 return ESR_Succeeded;
4156 }
4157
4158 case Stmt::CXXForRangeStmtClass: {
4159 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4160 BlockScopeRAII Scope(Info);
4161
4162 // Initialize the __range variable.
4163 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4164 if (ESR != ESR_Succeeded)
4165 return ESR;
4166
4167 // Create the __begin and __end iterators.
4168 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4169 if (ESR != ESR_Succeeded)
4170 return ESR;
4171 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4172 if (ESR != ESR_Succeeded)
4173 return ESR;
4174
4175 while (true) {
4176 // Condition: __begin != __end.
4177 {
4178 bool Continue = true;
4179 FullExpressionRAII CondExpr(Info);
4180 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4181 return ESR_Failed;
4182 if (!Continue)
4183 break;
4184 }
4185
4186 // User's variable declaration, initialized by *__begin.
4187 BlockScopeRAII InnerScope(Info);
4188 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4189 if (ESR != ESR_Succeeded)
4190 return ESR;
4191
4192 // Loop body.
4193 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4194 if (ESR != ESR_Continue)
4195 return ESR;
4196
4197 // Increment: ++__begin
4198 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4199 return ESR_Failed;
4200 }
4201
4202 return ESR_Succeeded;
4203 }
4204
4205 case Stmt::SwitchStmtClass:
4206 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4207
4208 case Stmt::ContinueStmtClass:
4209 return ESR_Continue;
4210
4211 case Stmt::BreakStmtClass:
4212 return ESR_Break;
4213
4214 case Stmt::LabelStmtClass:
4215 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4216
4217 case Stmt::AttributedStmtClass:
4218 // As a general principle, C++11 attributes can be ignored without
4219 // any semantic impact.
4220 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4221 Case);
4222
4223 case Stmt::CaseStmtClass:
4224 case Stmt::DefaultStmtClass:
4225 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4226 }
4227}
4228
4229/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4230/// default constructor. If so, we'll fold it whether or not it's marked as
4231/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4232/// so we need special handling.
4233static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4234 const CXXConstructorDecl *CD,
4235 bool IsValueInitialization) {
4236 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4237 return false;
4238
4239 // Value-initialization does not call a trivial default constructor, so such a
4240 // call is a core constant expression whether or not the constructor is
4241 // constexpr.
4242 if (!CD->isConstexpr() && !IsValueInitialization) {
4243 if (Info.getLangOpts().CPlusPlus11) {
4244 // FIXME: If DiagDecl is an implicitly-declared special member function,
4245 // we should be much more explicit about why it's not constexpr.
4246 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4247 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4248 Info.Note(CD->getLocation(), diag::note_declared_at);
4249 } else {
4250 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4251 }
4252 }
4253 return true;
4254}
4255
4256/// CheckConstexprFunction - Check that a function can be called in a constant
4257/// expression.
4258static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4259 const FunctionDecl *Declaration,
4260 const FunctionDecl *Definition,
4261 const Stmt *Body) {
4262 // Potential constant expressions can contain calls to declared, but not yet
4263 // defined, constexpr functions.
4264 if (Info.checkingPotentialConstantExpression() && !Definition &&
4265 Declaration->isConstexpr())
4266 return false;
4267
4268 // Bail out with no diagnostic if the function declaration itself is invalid.
4269 // We will have produced a relevant diagnostic while parsing it.
4270 if (Declaration->isInvalidDecl())
4271 return false;
4272
4273 // Can we evaluate this function call?
4274 if (Definition && Definition->isConstexpr() &&
4275 !Definition->isInvalidDecl() && Body)
4276 return true;
4277
4278 if (Info.getLangOpts().CPlusPlus11) {
4279 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4280
4281 // If this function is not constexpr because it is an inherited
4282 // non-constexpr constructor, diagnose that directly.
4283 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4284 if (CD && CD->isInheritingConstructor()) {
4285 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4286 if (!Inherited->isConstexpr())
4287 DiagDecl = CD = Inherited;
4288 }
4289
4290 // FIXME: If DiagDecl is an implicitly-declared special member function
4291 // or an inheriting constructor, we should be much more explicit about why
4292 // it's not constexpr.
4293 if (CD && CD->isInheritingConstructor())
4294 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4295 << CD->getInheritedConstructor().getConstructor()->getParent();
4296 else
4297 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4298 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4299 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4300 } else {
4301 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4302 }
4303 return false;
4304}
4305
4306/// Determine if a class has any fields that might need to be copied by a
4307/// trivial copy or move operation.
4308static bool hasFields(const CXXRecordDecl *RD) {
4309 if (!RD || RD->isEmpty())
4310 return false;
4311 for (auto *FD : RD->fields()) {
4312 if (FD->isUnnamedBitfield())
4313 continue;
4314 return true;
4315 }
4316 for (auto &Base : RD->bases())
4317 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4318 return true;
4319 return false;
4320}
4321
4322namespace {
4323typedef SmallVector<APValue, 8> ArgVector;
4324}
4325
4326/// EvaluateArgs - Evaluate the arguments to a function call.
4327static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4328 EvalInfo &Info) {
4329 bool Success = true;
4330 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4331 I != E; ++I) {
4332 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4333 // If we're checking for a potential constant expression, evaluate all
4334 // initializers even if some of them fail.
4335 if (!Info.noteFailure())
4336 return false;
4337 Success = false;
4338 }
4339 }
4340 return Success;
4341}
4342
4343/// Evaluate a function call.
4344static bool HandleFunctionCall(SourceLocation CallLoc,
4345 const FunctionDecl *Callee, const LValue *This,
4346 ArrayRef<const Expr*> Args, const Stmt *Body,
4347 EvalInfo &Info, APValue &Result,
4348 const LValue *ResultSlot) {
4349 ArgVector ArgValues(Args.size());
4350 if (!EvaluateArgs(Args, ArgValues, Info))
4351 return false;
4352
4353 if (!Info.CheckCallLimit(CallLoc))
4354 return false;
4355
4356 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4357
4358 // For a trivial copy or move assignment, perform an APValue copy. This is
4359 // essential for unions, where the operations performed by the assignment
4360 // operator cannot be represented as statements.
4361 //
4362 // Skip this for non-union classes with no fields; in that case, the defaulted
4363 // copy/move does not actually read the object.
4364 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4365 if (MD && MD->isDefaulted() &&
4366 (MD->getParent()->isUnion() ||
4367 (MD->isTrivial() && hasFields(MD->getParent())))) {
4368 assert(This &&(static_cast <bool> (This && (MD->isCopyAssignmentOperator
() || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4369, __extension__ __PRETTY_FUNCTION__))
4369 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))(static_cast <bool> (This && (MD->isCopyAssignmentOperator
() || MD->isMoveAssignmentOperator())) ? void (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4369, __extension__ __PRETTY_FUNCTION__))
;
4370 LValue RHS;
4371 RHS.setFrom(Info.Ctx, ArgValues[0]);
4372 APValue RHSValue;
4373 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4374 RHS, RHSValue))
4375 return false;
4376 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4377 RHSValue))
4378 return false;
4379 This->moveInto(Result);
4380 return true;
4381 } else if (MD && isLambdaCallOperator(MD)) {
4382 // We're in a lambda; determine the lambda capture field maps unless we're
4383 // just constexpr checking a lambda's call operator. constexpr checking is
4384 // done before the captures have been added to the closure object (unless
4385 // we're inferring constexpr-ness), so we don't have access to them in this
4386 // case. But since we don't need the captures to constexpr check, we can
4387 // just ignore them.
4388 if (!Info.checkingPotentialConstantExpression())
4389 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4390 Frame.LambdaThisCaptureField);
4391 }
4392
4393 StmtResult Ret = {Result, ResultSlot};
4394 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4395 if (ESR == ESR_Succeeded) {
4396 if (Callee->getReturnType()->isVoidType())
4397 return true;
4398 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4399 }
4400 return ESR == ESR_Returned;
4401}
4402
4403/// Evaluate a constructor call.
4404static bool HandleConstructorCall(const Expr *E, const LValue &This,
4405 APValue *ArgValues,
4406 const CXXConstructorDecl *Definition,
4407 EvalInfo &Info, APValue &Result) {
4408 SourceLocation CallLoc = E->getExprLoc();
4409 if (!Info.CheckCallLimit(CallLoc))
4410 return false;
4411
4412 const CXXRecordDecl *RD = Definition->getParent();
4413 if (RD->getNumVBases()) {
4414 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4415 return false;
4416 }
4417
4418 EvalInfo::EvaluatingConstructorRAII EvalObj(
4419 Info, {This.getLValueBase(),
4420 {This.getLValueCallIndex(), This.getLValueVersion()}});
4421 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4422
4423 // FIXME: Creating an APValue just to hold a nonexistent return value is
4424 // wasteful.
4425 APValue RetVal;
4426 StmtResult Ret = {RetVal, nullptr};
4427
4428 // If it's a delegating constructor, delegate.
4429 if (Definition->isDelegatingConstructor()) {
4430 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4431 {
4432 FullExpressionRAII InitScope(Info);
4433 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4434 return false;
4435 }
4436 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4437 }
4438
4439 // For a trivial copy or move constructor, perform an APValue copy. This is
4440 // essential for unions (or classes with anonymous union members), where the
4441 // operations performed by the constructor cannot be represented by
4442 // ctor-initializers.
4443 //
4444 // Skip this for empty non-union classes; we should not perform an
4445 // lvalue-to-rvalue conversion on them because their copy constructor does not
4446 // actually read them.
4447 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4448 (Definition->getParent()->isUnion() ||
4449 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4450 LValue RHS;
4451 RHS.setFrom(Info.Ctx, ArgValues[0]);
4452 return handleLValueToRValueConversion(
4453 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4454 RHS, Result);
4455 }
4456
4457 // Reserve space for the struct members.
4458 if (!RD->isUnion() && Result.isUninit())
4459 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4460 std::distance(RD->field_begin(), RD->field_end()));
4461
4462 if (RD->isInvalidDecl()) return false;
4463 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4464
4465 // A scope for temporaries lifetime-extended by reference members.
4466 BlockScopeRAII LifetimeExtendedScope(Info);
4467
4468 bool Success = true;
4469 unsigned BasesSeen = 0;
4470#ifndef NDEBUG
4471 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4472#endif
4473 for (const auto *I : Definition->inits()) {
4474 LValue Subobject = This;
4475 LValue SubobjectParent = This;
4476 APValue *Value = &Result;
4477
4478 // Determine the subobject to initialize.
4479 FieldDecl *FD = nullptr;
4480 if (I->isBaseInitializer()) {
4481 QualType BaseType(I->getBaseClass(), 0);
4482#ifndef NDEBUG
4483 // Non-virtual base classes are initialized in the order in the class
4484 // definition. We have already checked for virtual base classes.
4485 assert(!BaseIt->isVirtual() && "virtual base for literal type")(static_cast <bool> (!BaseIt->isVirtual() &&
"virtual base for literal type") ? void (0) : __assert_fail (
"!BaseIt->isVirtual() && \"virtual base for literal type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4485, __extension__ __PRETTY_FUNCTION__))
;
4486 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&(static_cast <bool> (Info.Ctx.hasSameType(BaseIt->getType
(), BaseType) && "base class initializers not in expected order"
) ? void (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4487, __extension__ __PRETTY_FUNCTION__))
4487 "base class initializers not in expected order")(static_cast <bool> (Info.Ctx.hasSameType(BaseIt->getType
(), BaseType) && "base class initializers not in expected order"
) ? void (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4487, __extension__ __PRETTY_FUNCTION__))
;
4488 ++BaseIt;
4489#endif
4490 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4491 BaseType->getAsCXXRecordDecl(), &Layout))
4492 return false;
4493 Value = &Result.getStructBase(BasesSeen++);
4494 } else if ((FD = I->getMember())) {
4495 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4496 return false;
4497 if (RD->isUnion()) {
4498 Result = APValue(FD);
4499 Value = &Result.getUnionValue();
4500 } else {
4501 Value = &Result.getStructField(FD->getFieldIndex());
4502 }
4503 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4504 // Walk the indirect field decl's chain to find the object to initialize,
4505 // and make sure we've initialized every step along it.
4506 auto IndirectFieldChain = IFD->chain();
4507 for (auto *C : IndirectFieldChain) {
4508 FD = cast<FieldDecl>(C);
4509 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4510 // Switch the union field if it differs. This happens if we had
4511 // preceding zero-initialization, and we're now initializing a union
4512 // subobject other than the first.
4513 // FIXME: In this case, the values of the other subobjects are
4514 // specified, since zero-initialization sets all padding bits to zero.
4515 if (Value->isUninit() ||
4516 (Value->isUnion() && Value->getUnionField() != FD)) {
4517 if (CD->isUnion())
4518 *Value = APValue(FD);
4519 else
4520 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4521 std::distance(CD->field_begin(), CD->field_end()));
4522 }
4523 // Store Subobject as its parent before updating it for the last element
4524 // in the chain.
4525 if (C == IndirectFieldChain.back())
4526 SubobjectParent = Subobject;
4527 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4528 return false;
4529 if (CD->isUnion())
4530 Value = &Value->getUnionValue();
4531 else
4532 Value = &Value->getStructField(FD->getFieldIndex());
4533 }
4534 } else {
4535 llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4535)
;
4536 }
4537
4538 // Need to override This for implicit field initializers as in this case
4539 // This refers to innermost anonymous struct/union containing initializer,
4540 // not to currently constructed class.
4541 const Expr *Init = I->getInit();
4542 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4543 isa<CXXDefaultInitExpr>(Init));
4544 FullExpressionRAII InitScope(Info);
4545 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4546 (FD && FD->isBitField() &&
4547 !truncateBitfieldValue(Info, Init, *Value, FD))) {
4548 // If we're checking for a potential constant expression, evaluate all
4549 // initializers even if some of them fail.
4550 if (!Info.noteFailure())
4551 return false;
4552 Success = false;
4553 }
4554 }
4555
4556 return Success &&
4557 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4558}
4559
4560static bool HandleConstructorCall(const Expr *E, const LValue &This,
4561 ArrayRef<const Expr*> Args,
4562 const CXXConstructorDecl *Definition,
4563 EvalInfo &Info, APValue &Result) {
4564 ArgVector ArgValues(Args.size());
4565 if (!EvaluateArgs(Args, ArgValues, Info))
4566 return false;
4567
4568 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4569 Info, Result);
4570}
4571
4572//===----------------------------------------------------------------------===//
4573// Generic Evaluation
4574//===----------------------------------------------------------------------===//
4575namespace {
4576
4577template <class Derived>
4578class ExprEvaluatorBase
4579 : public ConstStmtVisitor<Derived, bool> {
4580private:
4581 Derived &getDerived() { return static_cast<Derived&>(*this); }
4582 bool DerivedSuccess(const APValue &V, const Expr *E) {
4583 return getDerived().Success(V, E);
4584 }
4585 bool DerivedZeroInitialization(const Expr *E) {
4586 return getDerived().ZeroInitialization(E);
4587 }
4588
4589 // Check whether a conditional operator with a non-constant condition is a
4590 // potential constant expression. If neither arm is a potential constant
4591 // expression, then the conditional operator is not either.
4592 template<typename ConditionalOperator>
4593 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4594 assert(Info.checkingPotentialConstantExpression())(static_cast <bool> (Info.checkingPotentialConstantExpression
()) ? void (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4594, __extension__ __PRETTY_FUNCTION__))
;
4595
4596 // Speculatively evaluate both arms.
4597 SmallVector<PartialDiagnosticAt, 8> Diag;
4598 {
4599 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4600 StmtVisitorTy::Visit(E->getFalseExpr());
4601 if (Diag.empty())
4602 return;
4603 }
4604
4605 {
4606 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4607 Diag.clear();
4608 StmtVisitorTy::Visit(E->getTrueExpr());
4609 if (Diag.empty())
4610 return;
4611 }
4612
4613 Error(E, diag::note_constexpr_conditional_never_const);
4614 }
4615
4616
4617 template<typename ConditionalOperator>
4618 bool HandleConditionalOperator(const ConditionalOperator *E) {
4619 bool BoolResult;
4620 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4621 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4622 CheckPotentialConstantConditional(E);
4623 return false;
4624 }
4625 if (Info.noteFailure()) {
4626 StmtVisitorTy::Visit(E->getTrueExpr());
4627 StmtVisitorTy::Visit(E->getFalseExpr());
4628 }
4629 return false;
4630 }
4631
4632 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4633 return StmtVisitorTy::Visit(EvalExpr);
4634 }
4635
4636protected:
4637 EvalInfo &Info;
4638 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4639 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4640
4641 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4642 return Info.CCEDiag(E, D);
4643 }
4644
4645 bool ZeroInitialization(const Expr *E) { return Error(E); }
4646
4647public:
4648 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4649
4650 EvalInfo &getEvalInfo() { return Info; }
4651
4652 /// Report an evaluation error. This should only be called when an error is
4653 /// first discovered. When propagating an error, just return false.
4654 bool Error(const Expr *E, diag::kind D) {
4655 Info.FFDiag(E, D);
4656 return false;
4657 }
4658 bool Error(const Expr *E) {
4659 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4660 }
4661
4662 bool VisitStmt(const Stmt *) {
4663 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-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4663)
;
4664 }
4665 bool VisitExpr(const Expr *E) {
4666 return Error(E);
4667 }
4668
4669 bool VisitParenExpr(const ParenExpr *E)
4670 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4671 bool VisitUnaryExtension(const UnaryOperator *E)
4672 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4673 bool VisitUnaryPlus(const UnaryOperator *E)
4674 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4675 bool VisitChooseExpr(const ChooseExpr *E)
4676 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4677 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4678 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4679 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4680 { return StmtVisitorTy::Visit(E->getReplacement()); }
4681 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4682 TempVersionRAII RAII(*Info.CurrentCall);
4683 return StmtVisitorTy::Visit(E->getExpr());
4684 }
4685 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4686 TempVersionRAII RAII(*Info.CurrentCall);
4687 // The initializer may not have been parsed yet, or might be erroneous.
4688 if (!E->getExpr())
4689 return Error(E);
4690 return StmtVisitorTy::Visit(E->getExpr());
4691 }
4692 // We cannot create any objects for which cleanups are required, so there is
4693 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4694 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4695 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4696
4697 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4698 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4699 return static_cast<Derived*>(this)->VisitCastExpr(E);
4700 }
4701 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4702 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4703 return static_cast<Derived*>(this)->VisitCastExpr(E);
4704 }
4705
4706 bool VisitBinaryOperator(const BinaryOperator *E) {
4707 switch (E->getOpcode()) {
4708 default:
4709 return Error(E);
4710
4711 case BO_Comma:
4712 VisitIgnoredValue(E->getLHS());
4713 return StmtVisitorTy::Visit(E->getRHS());
4714
4715 case BO_PtrMemD:
4716 case BO_PtrMemI: {
4717 LValue Obj;
4718 if (!HandleMemberPointerAccess(Info, E, Obj))
4719 return false;
4720 APValue Result;
4721 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4722 return false;
4723 return DerivedSuccess(Result, E);
4724 }
4725 }
4726 }
4727
4728 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4729 // Evaluate and cache the common expression. We treat it as a temporary,
4730 // even though it's not quite the same thing.
4731 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4732 Info, E->getCommon()))
4733 return false;
4734
4735 return HandleConditionalOperator(E);
4736 }
4737
4738 bool VisitConditionalOperator(const ConditionalOperator *E) {
4739 bool IsBcpCall = false;
4740 // If the condition (ignoring parens) is a __builtin_constant_p call,
4741 // the result is a constant expression if it can be folded without
4742 // side-effects. This is an important GNU extension. See GCC PR38377
4743 // for discussion.
4744 if (const CallExpr *CallCE =
4745 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4746 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4747 IsBcpCall = true;
4748
4749 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4750 // constant expression; we can't check whether it's potentially foldable.
4751 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4752 return false;
4753
4754 FoldConstant Fold(Info, IsBcpCall);
4755 if (!HandleConditionalOperator(E)) {
4756 Fold.keepDiagnostics();
4757 return false;
4758 }
4759
4760 return true;
4761 }
4762
4763 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4764 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
4765 return DerivedSuccess(*Value, E);
4766
4767 const Expr *Source = E->getSourceExpr();
4768 if (!Source)
4769 return Error(E);
4770 if (Source == E) { // sanity checking.
4771 assert(0 && "OpaqueValueExpr recursively refers to itself")(static_cast <bool> (0 && "OpaqueValueExpr recursively refers to itself"
) ? void (0) : __assert_fail ("0 && \"OpaqueValueExpr recursively refers to itself\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4771, __extension__ __PRETTY_FUNCTION__))
;
4772 return Error(E);
4773 }
4774 return StmtVisitorTy::Visit(Source);
4775 }
4776
4777 bool VisitCallExpr(const CallExpr *E) {
4778 APValue Result;
4779 if (!handleCallExpr(E, Result, nullptr))
4780 return false;
4781 return DerivedSuccess(Result, E);
4782 }
4783
4784 bool handleCallExpr(const CallExpr *E, APValue &Result,
4785 const LValue *ResultSlot) {
4786 const Expr *Callee = E->getCallee()->IgnoreParens();
4787 QualType CalleeType = Callee->getType();
4788
4789 const FunctionDecl *FD = nullptr;
4790 LValue *This = nullptr, ThisVal;
4791 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4792 bool HasQualifier = false;
4793
4794 // Extract function decl and 'this' pointer from the callee.
4795 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4796 const ValueDecl *Member = nullptr;
4797 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4798 // Explicit bound member calls, such as x.f() or p->g();
4799 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4800 return false;
4801 Member = ME->getMemberDecl();
4802 This = &ThisVal;
4803 HasQualifier = ME->hasQualifier();
4804 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4805 // Indirect bound member calls ('.*' or '->*').
4806 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4807 if (!Member) return false;
4808 This = &ThisVal;
4809 } else
4810 return Error(Callee);
4811
4812 FD = dyn_cast<FunctionDecl>(Member);
4813 if (!FD)
4814 return Error(Callee);
4815 } else if (CalleeType->isFunctionPointerType()) {
4816 LValue Call;
4817 if (!EvaluatePointer(Callee, Call, Info))
4818 return false;
4819
4820 if (!Call.getLValueOffset().isZero())
4821 return Error(Callee);
4822 FD = dyn_cast_or_null<FunctionDecl>(
4823 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4824 if (!FD)
4825 return Error(Callee);
4826 // Don't call function pointers which have been cast to some other type.
4827 // Per DR (no number yet), the caller and callee can differ in noexcept.
4828 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4829 CalleeType->getPointeeType(), FD->getType())) {
4830 return Error(E);
4831 }
4832
4833 // Overloaded operator calls to member functions are represented as normal
4834 // calls with '*this' as the first argument.
4835 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4836 if (MD && !MD->isStatic()) {
4837 // FIXME: When selecting an implicit conversion for an overloaded
4838 // operator delete, we sometimes try to evaluate calls to conversion
4839 // operators without a 'this' parameter!
4840 if (Args.empty())
4841 return Error(E);
4842
4843 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4844 return false;
4845 This = &ThisVal;
4846 Args = Args.slice(1);
4847 } else if (MD && MD->isLambdaStaticInvoker()) {
4848 // Map the static invoker for the lambda back to the call operator.
4849 // Conveniently, we don't have to slice out the 'this' argument (as is
4850 // being done for the non-static case), since a static member function
4851 // doesn't have an implicit argument passed in.
4852 const CXXRecordDecl *ClosureClass = MD->getParent();
4853 assert((static_cast <bool> (ClosureClass->captures_begin() ==
ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr"
) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4855, __extension__ __PRETTY_FUNCTION__))
4854 ClosureClass->captures_begin() == ClosureClass->captures_end() &&(static_cast <bool> (ClosureClass->captures_begin() ==
ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr"
) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4855, __extension__ __PRETTY_FUNCTION__))
4855 "Number of captures must be zero for conversion to function-ptr")(static_cast <bool> (ClosureClass->captures_begin() ==
ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr"
) ? void (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4855, __extension__ __PRETTY_FUNCTION__))
;
4856
4857 const CXXMethodDecl *LambdaCallOp =
4858 ClosureClass->getLambdaCallOperator();
4859
4860 // Set 'FD', the function that will be called below, to the call
4861 // operator. If the closure object represents a generic lambda, find
4862 // the corresponding specialization of the call operator.
4863
4864 if (ClosureClass->isGenericLambda()) {
4865 assert(MD->isFunctionTemplateSpecialization() &&(static_cast <bool> (MD->isFunctionTemplateSpecialization
() && "A generic lambda's static-invoker function must be a "
"template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4867, __extension__ __PRETTY_FUNCTION__))
4866 "A generic lambda's static-invoker function must be a "(static_cast <bool> (MD->isFunctionTemplateSpecialization
() && "A generic lambda's static-invoker function must be a "
"template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4867, __extension__ __PRETTY_FUNCTION__))
4867 "template specialization")(static_cast <bool> (MD->isFunctionTemplateSpecialization
() && "A generic lambda's static-invoker function must be a "
"template specialization") ? void (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4867, __extension__ __PRETTY_FUNCTION__))
;
4868 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4869 FunctionTemplateDecl *CallOpTemplate =
4870 LambdaCallOp->getDescribedFunctionTemplate();
4871 void *InsertPos = nullptr;
4872 FunctionDecl *CorrespondingCallOpSpecialization =
4873 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4874 assert(CorrespondingCallOpSpecialization &&(static_cast <bool> (CorrespondingCallOpSpecialization &&
"We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? void
(0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4876, __extension__ __PRETTY_FUNCTION__))
4875 "We must always have a function call operator specialization "(static_cast <bool> (CorrespondingCallOpSpecialization &&
"We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? void
(0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4876, __extension__ __PRETTY_FUNCTION__))
4876 "that corresponds to our static invoker specialization")(static_cast <bool> (CorrespondingCallOpSpecialization &&
"We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? void
(0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4876, __extension__ __PRETTY_FUNCTION__))
;
4877 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4878 } else
4879 FD = LambdaCallOp;
4880 }
4881
4882
4883 } else
4884 return Error(E);
4885
4886 if (This && !This->checkSubobject(Info, E, CSK_This))
4887 return false;
4888
4889 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4890 // calls to such functions in constant expressions.
4891 if (This && !HasQualifier &&
4892 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4893 return Error(E, diag::note_constexpr_virtual_call);
4894
4895 const FunctionDecl *Definition = nullptr;
4896 Stmt *Body = FD->getBody(Definition);
4897
4898 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4899 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4900 Result, ResultSlot))
4901 return false;
4902
4903 return true;
4904 }
4905
4906 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4907 return StmtVisitorTy::Visit(E->getInitializer());
4908 }
4909 bool VisitInitListExpr(const InitListExpr *E) {
4910 if (E->getNumInits() == 0)
4911 return DerivedZeroInitialization(E);
4912 if (E->getNumInits() == 1)
4913 return StmtVisitorTy::Visit(E->getInit(0));
4914 return Error(E);
4915 }
4916 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4917 return DerivedZeroInitialization(E);
4918 }
4919 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4920 return DerivedZeroInitialization(E);
4921 }
4922 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4923 return DerivedZeroInitialization(E);
4924 }
4925
4926 /// A member expression where the object is a prvalue is itself a prvalue.
4927 bool VisitMemberExpr(const MemberExpr *E) {
4928 assert(!E->isArrow() && "missing call to bound member function?")(static_cast <bool> (!E->isArrow() && "missing call to bound member function?"
) ? void (0) : __assert_fail ("!E->isArrow() && \"missing call to bound member function?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4928, __extension__ __PRETTY_FUNCTION__))
;
4929
4930 APValue Val;
4931 if (!Evaluate(Val, Info, E->getBase()))
4932 return false;
4933
4934 QualType BaseTy = E->getBase()->getType();
4935
4936 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4937 if (!FD) return Error(E);
4938 assert(!FD->getType()->isReferenceType() && "prvalue reference?")(static_cast <bool> (!FD->getType()->isReferenceType
() && "prvalue reference?") ? void (0) : __assert_fail
("!FD->getType()->isReferenceType() && \"prvalue reference?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4938, __extension__ __PRETTY_FUNCTION__))
;
4939 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==(static_cast <bool> (BaseTy->castAs<RecordType>
()->getDecl()->getCanonicalDecl() == FD->getParent()
->getCanonicalDecl() && "record / field mismatch")
? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4940, __extension__ __PRETTY_FUNCTION__))
4940 FD->getParent()->getCanonicalDecl() && "record / field mismatch")(static_cast <bool> (BaseTy->castAs<RecordType>
()->getDecl()->getCanonicalDecl() == FD->getParent()
->getCanonicalDecl() && "record / field mismatch")
? void (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 4940, __extension__ __PRETTY_FUNCTION__))
;
4941
4942 CompleteObject Obj(&Val, BaseTy, true);
4943 SubobjectDesignator Designator(BaseTy);
4944 Designator.addDeclUnchecked(FD);
4945
4946 APValue Result;
4947 return extractSubobject(Info, E, Obj, Designator, Result) &&
4948 DerivedSuccess(Result, E);
4949 }
4950
4951 bool VisitCastExpr(const CastExpr *E) {
4952 switch (E->getCastKind()) {
4953 default:
4954 break;
4955
4956 case CK_AtomicToNonAtomic: {
4957 APValue AtomicVal;
4958 // This does not need to be done in place even for class/array types:
4959 // atomic-to-non-atomic conversion implies copying the object
4960 // representation.
4961 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4962 return false;
4963 return DerivedSuccess(AtomicVal, E);
4964 }
4965
4966 case CK_NoOp:
4967 case CK_UserDefinedConversion:
4968 return StmtVisitorTy::Visit(E->getSubExpr());
4969
4970 case CK_LValueToRValue: {
4971 LValue LVal;
4972 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4973 return false;
4974 APValue RVal;
4975 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4976 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4977 LVal, RVal))
4978 return false;
4979 return DerivedSuccess(RVal, E);
4980 }
4981 }
4982
4983 return Error(E);
4984 }
4985
4986 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4987 return VisitUnaryPostIncDec(UO);
4988 }
4989 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4990 return VisitUnaryPostIncDec(UO);
4991 }
4992 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4993 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4994 return Error(UO);
4995
4996 LValue LVal;
4997 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4998 return false;
4999 APValue RVal;
5000 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5001 UO->isIncrementOp(), &RVal))
5002 return false;
5003 return DerivedSuccess(RVal, UO);
5004 }
5005
5006 bool VisitStmtExpr(const StmtExpr *E) {
5007 // We will have checked the full-expressions inside the statement expression
5008 // when they were completed, and don't need to check them again now.
5009 if (Info.checkingForOverflow())
5010 return Error(E);
5011
5012 BlockScopeRAII Scope(Info);
5013 const CompoundStmt *CS = E->getSubStmt();
5014 if (CS->body_empty())
5015 return true;
5016
5017 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5018 BE = CS->body_end();
5019 /**/; ++BI) {
5020 if (BI + 1 == BE) {
5021 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5022 if (!FinalExpr) {
5023 Info.FFDiag((*BI)->getLocStart(),
5024 diag::note_constexpr_stmt_expr_unsupported);
5025 return false;
5026 }
5027 return this->Visit(FinalExpr);
5028 }
5029
5030 APValue ReturnValue;
5031 StmtResult Result = { ReturnValue, nullptr };
5032 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5033 if (ESR != ESR_Succeeded) {
5034 // FIXME: If the statement-expression terminated due to 'return',
5035 // 'break', or 'continue', it would be nice to propagate that to
5036 // the outer statement evaluation rather than bailing out.
5037 if (ESR != ESR_Failed)
5038 Info.FFDiag((*BI)->getLocStart(),
5039 diag::note_constexpr_stmt_expr_unsupported);
5040 return false;
5041 }
5042 }
5043
5044 llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above."
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5044)
;
5045 }
5046
5047 /// Visit a value which is evaluated, but whose value is ignored.
5048 void VisitIgnoredValue(const Expr *E) {
5049 EvaluateIgnoredValue(Info, E);
5050 }
5051
5052 /// Potentially visit a MemberExpr's base expression.
5053 void VisitIgnoredBaseExpression(const Expr *E) {
5054 // While MSVC doesn't evaluate the base expression, it does diagnose the
5055 // presence of side-effecting behavior.
5056 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5057 return;
5058 VisitIgnoredValue(E);
5059 }
5060};
5061
5062}
5063
5064//===----------------------------------------------------------------------===//
5065// Common base class for lvalue and temporary evaluation.
5066//===----------------------------------------------------------------------===//
5067namespace {
5068template<class Derived>
5069class LValueExprEvaluatorBase
5070 : public ExprEvaluatorBase<Derived> {
5071protected:
5072 LValue &Result;
5073 bool InvalidBaseOK;
5074 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5075 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5076
5077 bool Success(APValue::LValueBase B) {
5078 Result.set(B);
5079 return true;
5080 }
5081
5082 bool evaluatePointer(const Expr *E, LValue &Result) {
5083 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5084 }
5085
5086public:
5087 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5088 : ExprEvaluatorBaseTy(Info), Result(Result),
5089 InvalidBaseOK(InvalidBaseOK) {}
5090
5091 bool Success(const APValue &V, const Expr *E) {
5092 Result.setFrom(this->Info.Ctx, V);
5093 return true;
5094 }
5095
5096 bool VisitMemberExpr(const MemberExpr *E) {
5097 // Handle non-static data members.
5098 QualType BaseTy;
5099 bool EvalOK;
5100 if (E->isArrow()) {
5101 EvalOK = evaluatePointer(E->getBase(), Result);
5102 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5103 } else if (E->getBase()->isRValue()) {
5104 assert(E->getBase()->getType()->isRecordType())(static_cast <bool> (E->getBase()->getType()->
isRecordType()) ? void (0) : __assert_fail ("E->getBase()->getType()->isRecordType()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5104, __extension__ __PRETTY_FUNCTION__))
;
5105 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5106 BaseTy = E->getBase()->getType();
5107 } else {
5108 EvalOK = this->Visit(E->getBase());
5109 BaseTy = E->getBase()->getType();
5110 }
5111 if (!EvalOK) {
5112 if (!InvalidBaseOK)
5113 return false;
5114 Result.setInvalid(E);
5115 return true;
5116 }
5117
5118 const ValueDecl *MD = E->getMemberDecl();
5119 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5120 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==(static_cast <bool> (BaseTy->getAs<RecordType>
()->getDecl()->getCanonicalDecl() == FD->getParent()
->getCanonicalDecl() && "record / field mismatch")
? void (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5121, __extension__ __PRETTY_FUNCTION__))
5121 FD->getParent()->getCanonicalDecl() && "record / field mismatch")(static_cast <bool> (BaseTy->getAs<RecordType>
()->getDecl()->getCanonicalDecl() == FD->getParent()
->getCanonicalDecl() && "record / field mismatch")
? void (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5121, __extension__ __PRETTY_FUNCTION__))
;
5122 (void)BaseTy;
5123 if (!HandleLValueMember(this->Info, E, Result, FD))
5124 return false;
5125 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5126 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5127 return false;
5128 } else
5129 return this->Error(E);
5130
5131 if (MD->getType()->isReferenceType()) {
5132 APValue RefValue;
5133 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5134 RefValue))
5135 return false;
5136 return Success(RefValue, E);
5137 }
5138 return true;
5139 }
5140
5141 bool VisitBinaryOperator(const BinaryOperator *E) {
5142 switch (E->getOpcode()) {
5143 default:
5144 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5145
5146 case BO_PtrMemD:
5147 case BO_PtrMemI:
5148 return HandleMemberPointerAccess(this->Info, E, Result);
5149 }
5150 }
5151
5152 bool VisitCastExpr(const CastExpr *E) {
5153 switch (E->getCastKind()) {
5154 default:
5155 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5156
5157 case CK_DerivedToBase:
5158 case CK_UncheckedDerivedToBase:
5159 if (!this->Visit(E->getSubExpr()))
5160 return false;
5161
5162 // Now figure out the necessary offset to add to the base LV to get from
5163 // the derived class to the base class.
5164 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5165 Result);
5166 }
5167 }
5168};
5169}
5170
5171//===----------------------------------------------------------------------===//
5172// LValue Evaluation
5173//
5174// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5175// function designators (in C), decl references to void objects (in C), and
5176// temporaries (if building with -Wno-address-of-temporary).
5177//
5178// LValue evaluation produces values comprising a base expression of one of the
5179// following types:
5180// - Declarations
5181// * VarDecl
5182// * FunctionDecl
5183// - Literals
5184// * CompoundLiteralExpr in C (and in global scope in C++)
5185// * StringLiteral
5186// * CXXTypeidExpr
5187// * PredefinedExpr
5188// * ObjCStringLiteralExpr
5189// * ObjCEncodeExpr
5190// * AddrLabelExpr
5191// * BlockExpr
5192// * CallExpr for a MakeStringConstant builtin
5193// - Locals and temporaries
5194// * MaterializeTemporaryExpr
5195// * Any Expr, with a CallIndex indicating the function in which the temporary
5196// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5197// from the AST (FIXME).
5198// * A MaterializeTemporaryExpr that has static storage duration, with no
5199// CallIndex, for a lifetime-extended temporary.
5200// plus an offset in bytes.
5201//===----------------------------------------------------------------------===//
5202namespace {
5203class LValueExprEvaluator
5204 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5205public:
5206 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5207 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5208
5209 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5210 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5211
5212 bool VisitDeclRefExpr(const DeclRefExpr *E);
5213 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5214 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5215 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5216 bool VisitMemberExpr(const MemberExpr *E);
5217 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5218 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5219 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5220 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5221 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5222 bool VisitUnaryDeref(const UnaryOperator *E);
5223 bool VisitUnaryReal(const UnaryOperator *E);
5224 bool VisitUnaryImag(const UnaryOperator *E);
5225 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5226 return VisitUnaryPreIncDec(UO);
5227 }
5228 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5229 return VisitUnaryPreIncDec(UO);
5230 }
5231 bool VisitBinAssign(const BinaryOperator *BO);
5232 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5233
5234 bool VisitCastExpr(const CastExpr *E) {
5235 switch (E->getCastKind()) {
5236 default:
5237 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5238
5239 case CK_LValueBitCast:
5240 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5241 if (!Visit(E->getSubExpr()))
5242 return false;
5243 Result.Designator.setInvalid();
5244 return true;
5245
5246 case CK_BaseToDerived:
5247 if (!Visit(E->getSubExpr()))
5248 return false;
5249 return HandleBaseToDerivedCast(Info, E, Result);
5250 }
5251 }
5252};
5253} // end anonymous namespace
5254
5255/// Evaluate an expression as an lvalue. This can be legitimately called on
5256/// expressions which are not glvalues, in three cases:
5257/// * function designators in C, and
5258/// * "extern void" objects
5259/// * @selector() expressions in Objective-C
5260static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5261 bool InvalidBaseOK) {
5262 assert(E->isGLValue() || E->getType()->isFunctionType() ||(static_cast <bool> (E->isGLValue() || E->getType
()->isFunctionType() || E->getType()->isVoidType() ||
isa<ObjCSelectorExpr>(E)) ? void (0) : __assert_fail (
"E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5263, __extension__ __PRETTY_FUNCTION__))
5263 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E))(static_cast <bool> (E->isGLValue() || E->getType
()->isFunctionType() || E->getType()->isVoidType() ||
isa<ObjCSelectorExpr>(E)) ? void (0) : __assert_fail (
"E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5263, __extension__ __PRETTY_FUNCTION__))
;
5264 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5265}
5266
5267bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5268 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5269 return Success(FD);
5270 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5271 return VisitVarDecl(E, VD);
5272 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5273 return Visit(BD->getBinding());
5274 return Error(E);
5275}
5276
5277
5278bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5279
5280 // If we are within a lambda's call operator, check whether the 'VD' referred
5281 // to within 'E' actually represents a lambda-capture that maps to a
5282 // data-member/field within the closure object, and if so, evaluate to the
5283 // field or what the field refers to.
5284 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5285 isa<DeclRefExpr>(E) &&
5286 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5287 // We don't always have a complete capture-map when checking or inferring if
5288 // the function call operator meets the requirements of a constexpr function
5289 // - but we don't need to evaluate the captures to determine constexprness
5290 // (dcl.constexpr C++17).
5291 if (Info.checkingPotentialConstantExpression())
5292 return false;
5293
5294 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5295 // Start with 'Result' referring to the complete closure object...
5296 Result = *Info.CurrentCall->This;
5297 // ... then update it to refer to the field of the closure object
5298 // that represents the capture.
5299 if (!HandleLValueMember(Info, E, Result, FD))
5300 return false;
5301 // And if the field is of reference type, update 'Result' to refer to what
5302 // the field refers to.
5303 if (FD->getType()->isReferenceType()) {
5304 APValue RVal;
5305 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5306 RVal))
5307 return false;
5308 Result.setFrom(Info.Ctx, RVal);
5309 }
5310 return true;
5311 }
5312 }
5313 CallStackFrame *Frame = nullptr;
5314 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5315 // Only if a local variable was declared in the function currently being
5316 // evaluated, do we expect to be able to find its value in the current
5317 // frame. (Otherwise it was likely declared in an enclosing context and
5318 // could either have a valid evaluatable value (for e.g. a constexpr
5319 // variable) or be ill-formed (and trigger an appropriate evaluation
5320 // diagnostic)).
5321 if (Info.CurrentCall->Callee &&
5322 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5323 Frame = Info.CurrentCall;
5324 }
5325 }
5326
5327 if (!VD->getType()->isReferenceType()) {
5328 if (Frame) {
5329 Result.set({VD, Frame->Index,
5330 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5331 return true;
5332 }
5333 return Success(VD);
5334 }
5335
5336 APValue *V;
5337 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5338 return false;
5339 if (V->isUninit()) {
5340 if (!Info.checkingPotentialConstantExpression())
5341 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5342 return false;
5343 }
5344 return Success(*V, E);
5345}
5346
5347bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5348 const MaterializeTemporaryExpr *E) {
5349 // Walk through the expression to find the materialized temporary itself.
5350 SmallVector<const Expr *, 2> CommaLHSs;
5351 SmallVector<SubobjectAdjustment, 2> Adjustments;
5352 const Expr *Inner = E->GetTemporaryExpr()->
5353 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5354
5355 // If we passed any comma operators, evaluate their LHSs.
5356 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5357 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5358 return false;
5359
5360 // A materialized temporary with static storage duration can appear within the
5361 // result of a constant expression evaluation, so we need to preserve its
5362 // value for use outside this evaluation.
5363 APValue *Value;
5364 if (E->getStorageDuration() == SD_Static) {
5365 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5366 *Value = APValue();
5367 Result.set(E);
5368 } else {
5369 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5370 *Info.CurrentCall);
5371 }
5372
5373 QualType Type = Inner->getType();
5374
5375 // Materialize the temporary itself.
5376 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5377 (E->getStorageDuration() == SD_Static &&
5378 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5379 *Value = APValue();
5380 return false;
5381 }
5382
5383 // Adjust our lvalue to refer to the desired subobject.
5384 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5385 --I;
5386 switch (Adjustments[I].Kind) {
5387 case SubobjectAdjustment::DerivedToBaseAdjustment:
5388 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5389 Type, Result))
5390 return false;
5391 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5392 break;
5393
5394 case SubobjectAdjustment::FieldAdjustment:
5395 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5396 return false;
5397 Type = Adjustments[I].Field->getType();
5398 break;
5399
5400 case SubobjectAdjustment::MemberPointerAdjustment:
5401 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5402 Adjustments[I].Ptr.RHS))
5403 return false;
5404 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5405 break;
5406 }
5407 }
5408
5409 return true;
5410}
5411
5412bool
5413LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5414 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&(static_cast <bool> ((!Info.getLangOpts().CPlusPlus || E
->isFileScope()) && "lvalue compound literal in c++?"
) ? void (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5415, __extension__ __PRETTY_FUNCTION__))
5415 "lvalue compound literal in c++?")(static_cast <bool> ((!Info.getLangOpts().CPlusPlus || E
->isFileScope()) && "lvalue compound literal in c++?"
) ? void (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5415, __extension__ __PRETTY_FUNCTION__))
;
5416 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5417 // only see this when folding in C, so there's no standard to follow here.
5418 return Success(E);
5419}
5420
5421bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5422 if (!E->isPotentiallyEvaluated())
5423 return Success(E);
5424
5425 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5426 << E->getExprOperand()->getType()
5427 << E->getExprOperand()->getSourceRange();
5428 return false;
5429}
5430
5431bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5432 return Success(E);
5433}
5434
5435bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5436 // Handle static data members.
5437 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5438 VisitIgnoredBaseExpression(E->getBase());
5439 return VisitVarDecl(E, VD);
5440 }
5441
5442 // Handle static member functions.
5443 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5444 if (MD->isStatic()) {
5445 VisitIgnoredBaseExpression(E->getBase());
5446 return Success(MD);
5447 }
5448 }
5449
5450 // Handle non-static data members.
5451 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5452}
5453
5454bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5455 // FIXME: Deal with vectors as array subscript bases.
5456 if (E->getBase()->getType()->isVectorType())
5457 return Error(E);
5458
5459 bool Success = true;
5460 if (!evaluatePointer(E->getBase(), Result)) {
5461 if (!Info.noteFailure())
5462 return false;
5463 Success = false;
5464 }
5465
5466 APSInt Index;
5467 if (!EvaluateInteger(E->getIdx(), Index, Info))
5468 return false;
5469
5470 return Success &&
5471 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5472}
5473
5474bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5475 return evaluatePointer(E->getSubExpr(), Result);
5476}
5477
5478bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5479 if (!Visit(E->getSubExpr()))
5480 return false;
5481 // __real is a no-op on scalar lvalues.
5482 if (E->getSubExpr()->getType()->isAnyComplexType())
5483 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5484 return true;
5485}
5486
5487bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5488 assert(E->getSubExpr()->getType()->isAnyComplexType() &&(static_cast <bool> (E->getSubExpr()->getType()->
isAnyComplexType() && "lvalue __imag__ on scalar?") ?
void (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5489, __extension__ __PRETTY_FUNCTION__))
5489 "lvalue __imag__ on scalar?")(static_cast <bool> (E->getSubExpr()->getType()->
isAnyComplexType() && "lvalue __imag__ on scalar?") ?
void (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5489, __extension__ __PRETTY_FUNCTION__))
;
5490 if (!Visit(E->getSubExpr()))
5491 return false;
5492 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5493 return true;
5494}
5495
5496bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5497 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5498 return Error(UO);
5499
5500 if (!this->Visit(UO->getSubExpr()))
5501 return false;
5502
5503 return handleIncDec(
5504 this->Info, UO, Result, UO->getSubExpr()->getType(),
5505 UO->isIncrementOp(), nullptr);
5506}
5507
5508bool LValueExprEvaluator::VisitCompoundAssignOperator(
5509 const CompoundAssignOperator *CAO) {
5510 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5511 return Error(CAO);
5512
5513 APValue RHS;
5514
5515 // The overall lvalue result is the result of evaluating the LHS.
5516 if (!this->Visit(CAO->getLHS())) {
5517 if (Info.noteFailure())
5518 Evaluate(RHS, this->Info, CAO->getRHS());
5519 return false;
5520 }
5521
5522 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5523 return false;
5524
5525 return handleCompoundAssignment(
5526 this->Info, CAO,
5527 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5528 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5529}
5530
5531bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5532 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5533 return Error(E);
5534
5535 APValue NewVal;
5536
5537 if (!this->Visit(E->getLHS())) {
5538 if (Info.noteFailure())
5539 Evaluate(NewVal, this->Info, E->getRHS());
5540 return false;
5541 }
5542
5543 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5544 return false;
5545
5546 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5547 NewVal);
5548}
5549
5550//===----------------------------------------------------------------------===//
5551// Pointer Evaluation
5552//===----------------------------------------------------------------------===//
5553
5554/// \brief Attempts to compute the number of bytes available at the pointer
5555/// returned by a function with the alloc_size attribute. Returns true if we
5556/// were successful. Places an unsigned number into `Result`.
5557///
5558/// This expects the given CallExpr to be a call to a function with an
5559/// alloc_size attribute.
5560static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5561 const CallExpr *Call,
5562 llvm::APInt &Result) {
5563 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5564
5565 assert(AllocSize && AllocSize->getElemSizeParam().isValid())(static_cast <bool> (AllocSize && AllocSize->
getElemSizeParam().isValid()) ? void (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam().isValid()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5565, __extension__ __PRETTY_FUNCTION__))
;
5566 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
5567 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5568 if (Call->getNumArgs() <= SizeArgNo)
5569 return false;
5570
5571 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5572 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5573 return false;
5574 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5575 return false;
5576 Into = Into.zextOrSelf(BitsInSizeT);
5577 return true;
5578 };
5579
5580 APSInt SizeOfElem;
5581 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5582 return false;
5583
5584 if (!AllocSize->getNumElemsParam().isValid()) {
5585 Result = std::move(SizeOfElem);
5586 return true;
5587 }
5588
5589 APSInt NumberOfElems;
5590 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
5591 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5592 return false;
5593
5594 bool Overflow;
5595 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5596 if (Overflow)
5597 return false;
5598
5599 Result = std::move(BytesAvailable);
5600 return true;
5601}
5602
5603/// \brief Convenience function. LVal's base must be a call to an alloc_size
5604/// function.
5605static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5606 const LValue &LVal,
5607 llvm::APInt &Result) {
5608 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&(static_cast <bool> (isBaseAnAllocSizeCall(LVal.getLValueBase
()) && "Can't get the size of a non alloc_size function"
) ? void (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5609, __extension__ __PRETTY_FUNCTION__))
5609 "Can't get the size of a non alloc_size function")(static_cast <bool> (isBaseAnAllocSizeCall(LVal.getLValueBase
()) && "Can't get the size of a non alloc_size function"
) ? void (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5609, __extension__ __PRETTY_FUNCTION__))
;
5610 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5611 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5612 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5613}
5614
5615/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5616/// a function with the alloc_size attribute. If it was possible to do so, this
5617/// function will return true, make Result's Base point to said function call,
5618/// and mark Result's Base as invalid.
5619static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5620 LValue &Result) {
5621 if (Base.isNull())
5622 return false;
5623
5624 // Because we do no form of static analysis, we only support const variables.
5625 //
5626 // Additionally, we can't support parameters, nor can we support static
5627 // variables (in the latter case, use-before-assign isn't UB; in the former,
5628 // we have no clue what they'll be assigned to).
5629 const auto *VD =
5630 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5631 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5632 return false;
5633
5634 const Expr *Init = VD->getAnyInitializer();
5635 if (!Init)
5636 return false;
5637
5638 const Expr *E = Init->IgnoreParens();
5639 if (!tryUnwrapAllocSizeCall(E))
5640 return false;
5641
5642 // Store E instead of E unwrapped so that the type of the LValue's base is
5643 // what the user wanted.
5644 Result.setInvalid(E);
5645
5646 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5647 Result.addUnsizedArray(Info, E, Pointee);
5648 return true;
5649}
5650
5651namespace {
5652class PointerExprEvaluator
5653 : public ExprEvaluatorBase<PointerExprEvaluator> {
5654 LValue &Result;
5655 bool InvalidBaseOK;
5656
5657 bool Success(const Expr *E) {
5658 Result.set(E);
5659 return true;
5660 }
5661
5662 bool evaluateLValue(const Expr *E, LValue &Result) {
5663 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5664 }
5665
5666 bool evaluatePointer(const Expr *E, LValue &Result) {
5667 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5668 }
5669
5670 bool visitNonBuiltinCallExpr(const CallExpr *E);
5671public:
5672
5673 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5674 : ExprEvaluatorBaseTy(info), Result(Result),
5675 InvalidBaseOK(InvalidBaseOK) {}
5676
5677 bool Success(const APValue &V, const Expr *E) {
5678 Result.setFrom(Info.Ctx, V);
5679 return true;
5680 }
5681 bool ZeroInitialization(const Expr *E) {
5682 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5683 Result.setNull(E->getType(), TargetVal);
5684 return true;
5685 }
5686
5687 bool VisitBinaryOperator(const BinaryOperator *E);
5688 bool VisitCastExpr(const CastExpr* E);
5689 bool VisitUnaryAddrOf(const UnaryOperator *E);
5690 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5691 { return Success(E); }
5692 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5693 if (Info.noteFailure())
5694 EvaluateIgnoredValue(Info, E->getSubExpr());
5695 return Error(E);
5696 }
5697 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5698 { return Success(E); }
5699 bool VisitCallExpr(const CallExpr *E);
5700 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5701 bool VisitBlockExpr(const BlockExpr *E) {
5702 if (!E->getBlockDecl()->hasCaptures())
5703 return Success(E);
5704 return Error(E);
5705 }
5706 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5707 // Can't look at 'this' when checking a potential constant expression.
5708 if (Info.checkingPotentialConstantExpression())
5709 return false;
5710 if (!Info.CurrentCall->This) {
5711 if (Info.getLangOpts().CPlusPlus11)
5712 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5713 else
5714 Info.FFDiag(E);
5715 return false;
5716 }
5717 Result = *Info.CurrentCall->This;
5718 // If we are inside a lambda's call operator, the 'this' expression refers
5719 // to the enclosing '*this' object (either by value or reference) which is
5720 // either copied into the closure object's field that represents the '*this'
5721 // or refers to '*this'.
5722 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5723 // Update 'Result' to refer to the data member/field of the closure object
5724 // that represents the '*this' capture.
5725 if (!HandleLValueMember(Info, E, Result,
5726 Info.CurrentCall->LambdaThisCaptureField))
5727 return false;
5728 // If we captured '*this' by reference, replace the field with its referent.
5729 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5730 ->isPointerType()) {
5731 APValue RVal;
5732 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5733 RVal))
5734 return false;
5735
5736 Result.setFrom(Info.Ctx, RVal);
5737 }
5738 }
5739 return true;
5740 }
5741
5742 // FIXME: Missing: @protocol, @selector
5743};
5744} // end anonymous namespace
5745
5746static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5747 bool InvalidBaseOK) {
5748 assert(E->isRValue() && E->getType()->hasPointerRepresentation())(static_cast <bool> (E->isRValue() && E->
getType()->hasPointerRepresentation()) ? void (0) : __assert_fail
("E->isRValue() && E->getType()->hasPointerRepresentation()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/AST/ExprConstant.cpp"
, 5748, __extension__ __PRETTY_FUNCTION__))
;
5749 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5750}
5751
5752bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5753 if (E->getOpcode() != BO_Add &&
5754 E->getOpcode() != BO_Sub)
5755 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5756
5757 const Expr *PExp = E->getLHS();
5758 const Expr *IExp = E->getRHS();
5759 if (IExp->getType()->isPointerType())
5760 std::swap(PExp, IExp);
5761
5762 bool EvalPtrOK = evaluatePointer(PExp, Result);
5763 if (!EvalPtrOK && !Info.noteFailure())
5764 return false;
5765
5766 llvm::APSInt Offset;
5767 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5768 return false;
5769
5770 if (E->getOpcode() == BO_Sub)
5771 negateAsSigned(Offset);
5772
5773 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5774 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5775}
5776
5777bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5778 return evaluateLValue(E->getSubExpr(), Result);
5779}
5780
5781bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5782 const Expr* SubExpr = E->getSubExpr();
5783
5784 switch (E->getCastKind()) {
5785 default:
5786 break;
5787
5788 case CK_BitCast:
5789 case CK_CPointerToObjCPointerCast:
5790 case CK_BlockPointerToObjCPointerCast:
5791 case CK_AnyPointerToBlockPointerCast:
5792 case CK_AddressSpaceConversion:
5793 if (!Visit(SubExpr))
5794 return false;
5795 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5796 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5797 // also static_casts, but we disallow them as a resolution to DR1312.
5798 if (!E->getType()->isVoidPointerType()) {
5799 Result.Designator.setInvalid();
5800 if (SubExpr->getType()->isVoidPointerType())
5801 CCEDiag(E, diag::note_constexpr_invalid_cast)
5802 << 3 << SubExpr->getType();
5803 else
5804 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5805 }
5806 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5807 ZeroInitialization(E);
5808 return true;
5809
5810 case CK_DerivedToBase:
5811 case CK_UncheckedDerivedToBase:
5812 if (!evaluatePointer(E->getSubExpr(), Result))
5813 return false;
5814 if (!Result.Base && Result.Offset.isZero())
5815 return true;
5816
5817 // Now figure out the necessary offset to add to the base LV to get from
5818 // the derived class to the base class.
5819 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5820 castAs<PointerType>()->getPointeeType(),
5821 Result);
5822
5823 case CK_BaseToDerived:
5824 if (!Visit(E->getSubExpr()))
5825 return false;
5826 if (!Result.Base && Result.Offset.isZero())
5827 return true;
5828 return HandleBaseToDerivedCast(Info, E, Result);
5829
5830 case CK_NullToPointer:
5831 VisitIgnoredValue(E->getSubExpr());
5832 return ZeroInitialization(E);
5833
5834 case CK_IntegralToPointer: {
5835 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5836
5837 APValue Value;
5838 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5839 break;
5840
5841 if (Value.isInt()) {
5842 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5843 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5844 Result.Base = (Expr*)nullptr;
5845 Result.InvalidBase = false;
5846 Result.Offset = CharUnits::fromQuantity(N);
5847 Result.Designator.setInvalid();
5848 Result.IsNullPtr = false;
5849 return true;
5850 } else {
5851 // Cast is of an lvalue, no need to change value.
5852 Result.setFrom(Info.Ctx, Value);
5853 return true;
5854 }
5855 }
5856
5857 case CK_ArrayToPointerDecay: {
5858 if (SubExpr->isGLValue()) {
5859 if (!evaluateLValue(SubExpr, Result))
5860 return false;
5861 } else {
5862 APValue &Value = createTemporary(SubExpr, false, Result,
5863 *Info.CurrentCall);
5864 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
5865 return false;
5866 }
5867 // The result is a pointer to the first element of the array.
5868 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5869 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5870 Result.addArray(Info, E, CAT);
5871 else
5872 Result.addUnsizedArray(Info, E, AT->getElementType());
5873 return true;
5874 }
5875
5876 case CK_FunctionToPointerDecay:
5877 return evaluateLValue(SubExpr, Result);
5878
5879 case CK_LValueToRValue: {
5880 LValue LVal;
5881 if (!evaluateLValue(E->getSubExpr(), LVal))
5882 return false;
5883
5884 APValue RVal;
5885 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5886 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5887 LVal, RVal))
5888 return InvalidBaseOK &&
5889 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5890 return Success(RVal, E);
5891 }
5892 }
5893
5894 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5895}
5896
5897static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5898 // C++ [expr.alignof]p3:
5899 // When alignof is applied to a reference type, the result is the
5900 // alignment of the referenced type.
5901 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5902 T = Ref->getPointeeType();
5903
5904 // __alignof is defined to return the preferred alignment.
5905 if (T.getQualifiers().hasUnaligned())
5906 return CharUnits::One();
5907 return Info.Ctx.toCharUnitsFromBits(