Bug Summary

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

Annotated Source Code

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
51using namespace clang;
52using llvm::APSInt;
53using llvm::APFloat;
54
55static bool IsGlobalLValue(APValue::LValueBase B);
56
57namespace {
58 struct LValue;
59 struct CallStackFrame;
60 struct EvalInfo;
61
62 static QualType getType(APValue::LValueBase B) {
63 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
81 return Inner->getType();
82 }
83
84 return Base->getType();
85 }
86
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// field or base class.
89 static
90 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
93 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109 return getAsBaseOrMember(E).getInt();
110 }
111
112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 const FunctionDecl *Callee = CE->getDirectCallee();
115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. Ignore it.
129 if (const auto *Cast = dyn_cast<CastExpr>(E))
130 E = Cast->getSubExpr()->IgnoreParens();
131
132 if (const auto *CE = dyn_cast<CallExpr>(E))
133 return getAllocSizeAttr(CE) ? CE : nullptr;
134 return nullptr;
135 }
136
137 /// Determines whether or not the given Base contains a call to a function
138 /// with the alloc_size attribute.
139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140 const auto *E = Base.dyn_cast<const Expr *>();
141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
142 }
143
144 /// Determines if an LValue with the given LValueBase will have an unsized
145 /// array in its designator.
146 /// Find the path length and type of the most-derived subobject in the given
147 /// path, and find the size of the containing array, if any.
148 static unsigned
149 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
150 ArrayRef<APValue::LValuePathEntry> Path,
151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152 // This only accepts LValueBases from APValues, and APValues don't support
153 // arrays that lack size info.
154 assert(!isBaseAnAllocSizeCall(Base) &&((!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here"
) ? static_cast<void> (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 155, __PRETTY_FUNCTION__))
155 "Unsized arrays shouldn't appear here")((!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here"
) ? static_cast<void> (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 155, __PRETTY_FUNCTION__))
;
156 unsigned MostDerivedLength = 0;
157 Type = getType(Base);
158
159 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
160 if (Type->isArrayType()) {
161 const ConstantArrayType *CAT =
162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
165 MostDerivedLength = I + 1;
166 IsArray = true;
167 } else if (Type->isAnyComplexType()) {
168 const ComplexType *CT = Type->castAs<ComplexType>();
169 Type = CT->getElementType();
170 ArraySize = 2;
171 MostDerivedLength = I + 1;
172 IsArray = true;
173 } else if (const FieldDecl *FD = getAsField(Path[I])) {
174 Type = FD->getType();
175 ArraySize = 0;
176 MostDerivedLength = I + 1;
177 IsArray = false;
178 } else {
179 // Path[I] describes a base class.
180 ArraySize = 0;
181 IsArray = false;
182 }
183 }
184 return MostDerivedLength;
185 }
186
187 // The order of this enum is important for diagnostics.
188 enum CheckSubobjectKind {
189 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
190 CSK_This, CSK_Real, CSK_Imag
191 };
192
193 /// A path from a glvalue to a subobject of that glvalue.
194 struct SubobjectDesignator {
195 /// True if the subobject was named in a manner not supported by C++11. Such
196 /// lvalues can still be folded, but they are not core constant expressions
197 /// and we cannot perform lvalue-to-rvalue conversions on them.
198 unsigned Invalid : 1;
199
200 /// Is this a pointer one past the end of an object?
201 unsigned IsOnePastTheEnd : 1;
202
203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
205
206 /// Indicator of whether the most-derived object is an array element.
207 unsigned MostDerivedIsArrayElement : 1;
208
209 /// The length of the path to the most-derived object of which this is a
210 /// subobject.
211 unsigned MostDerivedPathLength : 28;
212
213 /// The size of the array of which the most-derived object is an element.
214 /// This will always be 0 if the most-derived object is not an array
215 /// element. 0 is not an indicator of whether or not the most-derived object
216 /// is an array, however, because 0-length arrays are allowed.
217 ///
218 /// If the current array is an unsized array, the value of this is
219 /// undefined.
220 uint64_t MostDerivedArraySize;
221
222 /// The type of the most derived object referred to by this address.
223 QualType MostDerivedType;
224
225 typedef APValue::LValuePathEntry PathEntry;
226
227 /// The entries on the path from the glvalue to the designated subobject.
228 SmallVector<PathEntry, 8> Entries;
229
230 SubobjectDesignator() : Invalid(true) {}
231
232 explicit SubobjectDesignator(QualType T)
233 : Invalid(false), IsOnePastTheEnd(false),
234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235 MostDerivedPathLength(0), MostDerivedArraySize(0),
236 MostDerivedType(T) {}
237
238 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
239 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241 MostDerivedPathLength(0), MostDerivedArraySize(0) {
242 assert(V.isLValue() && "Non-LValue used to make an LValue designator?")((V.isLValue() && "Non-LValue used to make an LValue designator?"
) ? static_cast<void> (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 242, __PRETTY_FUNCTION__))
;
243 if (!Invalid) {
244 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
245 ArrayRef<PathEntry> VEntries = V.getLValuePath();
246 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
247 if (V.getLValueBase()) {
248 bool IsArray = false;
249 MostDerivedPathLength = findMostDerivedSubobject(
250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251 MostDerivedType, IsArray);
252 MostDerivedIsArrayElement = IsArray;
253 }
254 }
255 }
256
257 void setInvalid() {
258 Invalid = true;
259 Entries.clear();
260 }
261
262 /// Determine whether the most derived subobject is an array without a
263 /// known bound.
264 bool isMostDerivedAnUnsizedArray() const {
265 assert(!Invalid && "Calling this makes no sense on invalid designators")((!Invalid && "Calling this makes no sense on invalid designators"
) ? static_cast<void> (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 265, __PRETTY_FUNCTION__))
;
266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
267 }
268
269 /// Determine what the most derived array's size is. Results in an assertion
270 /// failure if the most derived array lacks a size.
271 uint64_t getMostDerivedArraySize() const {
272 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")((!isMostDerivedAnUnsizedArray() && "Unsized array has no size"
) ? static_cast<void> (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 272, __PRETTY_FUNCTION__))
;
273 return MostDerivedArraySize;
274 }
275
276 /// Determine whether this is a one-past-the-end pointer.
277 bool isOnePastTheEnd() const {
278 assert(!Invalid)((!Invalid) ? static_cast<void> (0) : __assert_fail ("!Invalid"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 278, __PRETTY_FUNCTION__))
;
279 if (IsOnePastTheEnd)
280 return true;
281 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
282 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
283 return true;
284 return false;
285 }
286
287 /// Check that this refers to a valid subobject.
288 bool isValidSubobject() const {
289 if (Invalid)
290 return false;
291 return !isOnePastTheEnd();
292 }
293 /// Check that this refers to a valid subobject, and if not, produce a
294 /// relevant diagnostic and set the designator as invalid.
295 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
296
297 /// Update this designator to refer to the first element within this array.
298 void addArrayUnchecked(const ConstantArrayType *CAT) {
299 PathEntry Entry;
300 Entry.ArrayIndex = 0;
301 Entries.push_back(Entry);
302
303 // This is a most-derived object.
304 MostDerivedType = CAT->getElementType();
305 MostDerivedIsArrayElement = true;
306 MostDerivedArraySize = CAT->getSize().getZExtValue();
307 MostDerivedPathLength = Entries.size();
308 }
309 /// Update this designator to refer to the first element within the array of
310 /// elements of type T. This is an array of unknown size.
311 void addUnsizedArrayUnchecked(QualType ElemTy) {
312 PathEntry Entry;
313 Entry.ArrayIndex = 0;
314 Entries.push_back(Entry);
315
316 MostDerivedType = ElemTy;
317 MostDerivedIsArrayElement = true;
318 // The value in MostDerivedArraySize is undefined in this case. So, set it
319 // to an arbitrary value that's likely to loudly break things if it's
320 // used.
321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322 MostDerivedPathLength = Entries.size();
323 }
324 /// Update this designator to refer to the given base or member of this
325 /// object.
326 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
327 PathEntry Entry;
328 APValue::BaseOrMemberType Value(D, Virtual);
329 Entry.BaseOrMember = Value.getOpaqueValue();
330 Entries.push_back(Entry);
331
332 // If this isn't a base class, it's a new most-derived object.
333 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334 MostDerivedType = FD->getType();
335 MostDerivedIsArrayElement = false;
336 MostDerivedArraySize = 0;
337 MostDerivedPathLength = Entries.size();
338 }
339 }
340 /// Update this designator to refer to the given complex component.
341 void addComplexUnchecked(QualType EltTy, bool Imag) {
342 PathEntry Entry;
343 Entry.ArrayIndex = Imag;
344 Entries.push_back(Entry);
345
346 // This is technically a most-derived object, though in practice this
347 // is unlikely to matter.
348 MostDerivedType = EltTy;
349 MostDerivedIsArrayElement = true;
350 MostDerivedArraySize = 2;
351 MostDerivedPathLength = Entries.size();
352 }
353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, APSInt N);
354 /// Add N to the address of this subobject.
355 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
356 if (Invalid || !N) return;
357 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
358 if (isMostDerivedAnUnsizedArray()) {
359 // Can't verify -- trust that the user is doing the right thing (or if
360 // not, trust that the caller will catch the bad behavior).
361 // FIXME: Should we reject if this overflows, at least?
362 Entries.back().ArrayIndex += TruncatedN;
363 return;
364 }
365
366 // [expr.add]p4: For the purposes of these operators, a pointer to a
367 // nonarray object behaves the same as a pointer to the first element of
368 // an array of length one with the type of the object as its element type.
369 bool IsArray = MostDerivedPathLength == Entries.size() &&
370 MostDerivedIsArrayElement;
371 uint64_t ArrayIndex =
372 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
373 uint64_t ArraySize =
374 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
375
376 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
377 // Calculate the actual index in a wide enough type, so we can include
378 // it in the note.
379 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
380 (llvm::APInt&)N += ArrayIndex;
381 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")((N.ugt(ArraySize) && "bounds check failed for in-bounds index"
) ? static_cast<void> (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 381, __PRETTY_FUNCTION__))
;
382 diagnosePointerArithmetic(Info, E, N);
383 setInvalid();
384 return;
385 }
386
387 ArrayIndex += TruncatedN;
388 assert(ArrayIndex <= ArraySize &&((ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index"
) ? static_cast<void> (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 389, __PRETTY_FUNCTION__))
389 "bounds check succeeded for out-of-bounds index")((ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index"
) ? static_cast<void> (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 389, __PRETTY_FUNCTION__))
;
390
391 if (IsArray)
392 Entries.back().ArrayIndex = ArrayIndex;
393 else
394 IsOnePastTheEnd = (ArrayIndex != 0);
395 }
396 };
397
398 /// A stack frame in the constexpr call stack.
399 struct CallStackFrame {
400 EvalInfo &Info;
401
402 /// Parent - The caller of this stack frame.
403 CallStackFrame *Caller;
404
405 /// Callee - The function which was called.
406 const FunctionDecl *Callee;
407
408 /// This - The binding for the this pointer in this call, if any.
409 const LValue *This;
410
411 /// Arguments - Parameter bindings for this function call, indexed by
412 /// parameters' function scope indices.
413 APValue *Arguments;
414
415 // Note that we intentionally use std::map here so that references to
416 // values are stable.
417 typedef std::map<const void*, APValue> MapTy;
418 typedef MapTy::const_iterator temp_iterator;
419 /// Temporaries - Temporary lvalues materialized within this stack frame.
420 MapTy Temporaries;
421
422 /// CallLoc - The location of the call expression for this call.
423 SourceLocation CallLoc;
424
425 /// Index - The call index of this call.
426 unsigned Index;
427
428 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
429 // on the overall stack usage of deeply-recursing constexpr evaluataions.
430 // (We should cache this map rather than recomputing it repeatedly.)
431 // But let's try this and see how it goes; we can look into caching the map
432 // as a later change.
433
434 /// LambdaCaptureFields - Mapping from captured variables/this to
435 /// corresponding data members in the closure class.
436 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
437 FieldDecl *LambdaThisCaptureField;
438
439 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
440 const FunctionDecl *Callee, const LValue *This,
441 APValue *Arguments);
442 ~CallStackFrame();
443
444 APValue *getTemporary(const void *Key) {
445 MapTy::iterator I = Temporaries.find(Key);
446 return I == Temporaries.end() ? nullptr : &I->second;
447 }
448 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
449 };
450
451 /// Temporarily override 'this'.
452 class ThisOverrideRAII {
453 public:
454 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
455 : Frame(Frame), OldThis(Frame.This) {
456 if (Enable)
457 Frame.This = NewThis;
458 }
459 ~ThisOverrideRAII() {
460 Frame.This = OldThis;
461 }
462 private:
463 CallStackFrame &Frame;
464 const LValue *OldThis;
465 };
466
467 /// A partial diagnostic which we might know in advance that we are not going
468 /// to emit.
469 class OptionalDiagnostic {
470 PartialDiagnostic *Diag;
471
472 public:
473 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
474 : Diag(Diag) {}
475
476 template<typename T>
477 OptionalDiagnostic &operator<<(const T &v) {
478 if (Diag)
479 *Diag << v;
480 return *this;
481 }
482
483 OptionalDiagnostic &operator<<(const APSInt &I) {
484 if (Diag) {
485 SmallVector<char, 32> Buffer;
486 I.toString(Buffer);
487 *Diag << StringRef(Buffer.data(), Buffer.size());
488 }
489 return *this;
490 }
491
492 OptionalDiagnostic &operator<<(const APFloat &F) {
493 if (Diag) {
494 // FIXME: Force the precision of the source value down so we don't
495 // print digits which are usually useless (we don't really care here if
496 // we truncate a digit by accident in edge cases). Ideally,
497 // APFloat::toString would automatically print the shortest
498 // representation which rounds to the correct value, but it's a bit
499 // tricky to implement.
500 unsigned precision =
501 llvm::APFloat::semanticsPrecision(F.getSemantics());
502 precision = (precision * 59 + 195) / 196;
503 SmallVector<char, 32> Buffer;
504 F.toString(Buffer, precision);
505 *Diag << StringRef(Buffer.data(), Buffer.size());
506 }
507 return *this;
508 }
509 };
510
511 /// A cleanup, and a flag indicating whether it is lifetime-extended.
512 class Cleanup {
513 llvm::PointerIntPair<APValue*, 1, bool> Value;
514
515 public:
516 Cleanup(APValue *Val, bool IsLifetimeExtended)
517 : Value(Val, IsLifetimeExtended) {}
518
519 bool isLifetimeExtended() const { return Value.getInt(); }
520 void endLifetime() {
521 *Value.getPointer() = APValue();
522 }
523 };
524
525 /// EvalInfo - This is a private struct used by the evaluator to capture
526 /// information about a subexpression as it is folded. It retains information
527 /// about the AST context, but also maintains information about the folded
528 /// expression.
529 ///
530 /// If an expression could be evaluated, it is still possible it is not a C
531 /// "integer constant expression" or constant expression. If not, this struct
532 /// captures information about how and why not.
533 ///
534 /// One bit of information passed *into* the request for constant folding
535 /// indicates whether the subexpression is "evaluated" or not according to C
536 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
537 /// evaluate the expression regardless of what the RHS is, but C only allows
538 /// certain things in certain situations.
539 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8)alignas(8) EvalInfo {
540 ASTContext &Ctx;
541
542 /// EvalStatus - Contains information about the evaluation.
543 Expr::EvalStatus &EvalStatus;
544
545 /// CurrentCall - The top of the constexpr call stack.
546 CallStackFrame *CurrentCall;
547
548 /// CallStackDepth - The number of calls in the call stack right now.
549 unsigned CallStackDepth;
550
551 /// NextCallIndex - The next call index to assign.
552 unsigned NextCallIndex;
553
554 /// StepsLeft - The remaining number of evaluation steps we're permitted
555 /// to perform. This is essentially a limit for the number of statements
556 /// we will evaluate.
557 unsigned StepsLeft;
558
559 /// BottomFrame - The frame in which evaluation started. This must be
560 /// initialized after CurrentCall and CallStackDepth.
561 CallStackFrame BottomFrame;
562
563 /// A stack of values whose lifetimes end at the end of some surrounding
564 /// evaluation frame.
565 llvm::SmallVector<Cleanup, 16> CleanupStack;
566
567 /// EvaluatingDecl - This is the declaration whose initializer is being
568 /// evaluated, if any.
569 APValue::LValueBase EvaluatingDecl;
570
571 /// EvaluatingDeclValue - This is the value being constructed for the
572 /// declaration whose initializer is being evaluated, if any.
573 APValue *EvaluatingDeclValue;
574
575 /// The current array initialization index, if we're performing array
576 /// initialization.
577 uint64_t ArrayInitIndex = -1;
578
579 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
580 /// notes attached to it will also be stored, otherwise they will not be.
581 bool HasActiveDiagnostic;
582
583 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
584 /// fold (not just why it's not strictly a constant expression)?
585 bool HasFoldFailureDiagnostic;
586
587 /// \brief Whether or not we're currently speculatively evaluating.
588 bool IsSpeculativelyEvaluating;
589
590 enum EvaluationMode {
591 /// Evaluate as a constant expression. Stop if we find that the expression
592 /// is not a constant expression.
593 EM_ConstantExpression,
594
595 /// Evaluate as a potential constant expression. Keep going if we hit a
596 /// construct that we can't evaluate yet (because we don't yet know the
597 /// value of something) but stop if we hit something that could never be
598 /// a constant expression.
599 EM_PotentialConstantExpression,
600
601 /// Fold the expression to a constant. Stop if we hit a side-effect that
602 /// we can't model.
603 EM_ConstantFold,
604
605 /// Evaluate the expression looking for integer overflow and similar
606 /// issues. Don't worry about side-effects, and try to visit all
607 /// subexpressions.
608 EM_EvaluateForOverflow,
609
610 /// Evaluate in any way we know how. Don't worry about side-effects that
611 /// can't be modeled.
612 EM_IgnoreSideEffects,
613
614 /// Evaluate as a constant expression. Stop if we find that the expression
615 /// is not a constant expression. Some expressions can be retried in the
616 /// optimizer if we don't constant fold them here, but in an unevaluated
617 /// context we try to fold them immediately since the optimizer never
618 /// gets a chance to look at it.
619 EM_ConstantExpressionUnevaluated,
620
621 /// Evaluate as a potential constant expression. Keep going if we hit a
622 /// construct that we can't evaluate yet (because we don't yet know the
623 /// value of something) but stop if we hit something that could never be
624 /// a constant expression. Some expressions can be retried in the
625 /// optimizer if we don't constant fold them here, but in an unevaluated
626 /// context we try to fold them immediately since the optimizer never
627 /// gets a chance to look at it.
628 EM_PotentialConstantExpressionUnevaluated,
629
630 /// Evaluate as a constant expression. In certain scenarios, if:
631 /// - we find a MemberExpr with a base that can't be evaluated, or
632 /// - we find a variable initialized with a call to a function that has
633 /// the alloc_size attribute on it
634 /// then we may consider evaluation to have succeeded.
635 ///
636 /// In either case, the LValue returned shall have an invalid base; in the
637 /// former, the base will be the invalid MemberExpr, in the latter, the
638 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
639 /// said CallExpr.
640 EM_OffsetFold,
641 } EvalMode;
642
643 /// Are we checking whether the expression is a potential constant
644 /// expression?
645 bool checkingPotentialConstantExpression() const {
646 return EvalMode == EM_PotentialConstantExpression ||
647 EvalMode == EM_PotentialConstantExpressionUnevaluated;
648 }
649
650 /// Are we checking an expression for overflow?
651 // FIXME: We should check for any kind of undefined or suspicious behavior
652 // in such constructs, not just overflow.
653 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
654
655 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
656 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
657 CallStackDepth(0), NextCallIndex(1),
658 StepsLeft(getLangOpts().ConstexprStepLimit),
659 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
660 EvaluatingDecl((const ValueDecl *)nullptr),
661 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
662 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
663 EvalMode(Mode) {}
664
665 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
666 EvaluatingDecl = Base;
667 EvaluatingDeclValue = &Value;
668 }
669
670 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
671
672 bool CheckCallLimit(SourceLocation Loc) {
673 // Don't perform any constexpr calls (other than the call we're checking)
674 // when checking a potential constant expression.
675 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
676 return false;
677 if (NextCallIndex == 0) {
678 // NextCallIndex has wrapped around.
679 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
680 return false;
681 }
682 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
683 return true;
684 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
685 << getLangOpts().ConstexprCallDepth;
686 return false;
687 }
688
689 CallStackFrame *getCallFrame(unsigned CallIndex) {
690 assert(CallIndex && "no call index in getCallFrame")((CallIndex && "no call index in getCallFrame") ? static_cast
<void> (0) : __assert_fail ("CallIndex && \"no call index in getCallFrame\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 690, __PRETTY_FUNCTION__))
;
691 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
692 // be null in this loop.
693 CallStackFrame *Frame = CurrentCall;
694 while (Frame->Index > CallIndex)
695 Frame = Frame->Caller;
696 return (Frame->Index == CallIndex) ? Frame : nullptr;
697 }
698
699 bool nextStep(const Stmt *S) {
700 if (!StepsLeft) {
701 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
702 return false;
703 }
704 --StepsLeft;
705 return true;
706 }
707
708 private:
709 /// Add a diagnostic to the diagnostics list.
710 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
711 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
712 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
713 return EvalStatus.Diag->back().second;
714 }
715
716 /// Add notes containing a call stack to the current point of evaluation.
717 void addCallStack(unsigned Limit);
718
719 private:
720 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
721 unsigned ExtraNotes, bool IsCCEDiag) {
722
723 if (EvalStatus.Diag) {
724 // If we have a prior diagnostic, it will be noting that the expression
725 // isn't a constant expression. This diagnostic is more important,
726 // unless we require this evaluation to produce a constant expression.
727 //
728 // FIXME: We might want to show both diagnostics to the user in
729 // EM_ConstantFold mode.
730 if (!EvalStatus.Diag->empty()) {
731 switch (EvalMode) {
732 case EM_ConstantFold:
733 case EM_IgnoreSideEffects:
734 case EM_EvaluateForOverflow:
735 if (!HasFoldFailureDiagnostic)
736 break;
737 // We've already failed to fold something. Keep that diagnostic.
738 case EM_ConstantExpression:
739 case EM_PotentialConstantExpression:
740 case EM_ConstantExpressionUnevaluated:
741 case EM_PotentialConstantExpressionUnevaluated:
742 case EM_OffsetFold:
743 HasActiveDiagnostic = false;
744 return OptionalDiagnostic();
745 }
746 }
747
748 unsigned CallStackNotes = CallStackDepth - 1;
749 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
750 if (Limit)
751 CallStackNotes = std::min(CallStackNotes, Limit + 1);
752 if (checkingPotentialConstantExpression())
753 CallStackNotes = 0;
754
755 HasActiveDiagnostic = true;
756 HasFoldFailureDiagnostic = !IsCCEDiag;
757 EvalStatus.Diag->clear();
758 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
759 addDiag(Loc, DiagId);
760 if (!checkingPotentialConstantExpression())
761 addCallStack(Limit);
762 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
763 }
764 HasActiveDiagnostic = false;
765 return OptionalDiagnostic();
766 }
767 public:
768 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
769 OptionalDiagnostic
770 FFDiag(SourceLocation Loc,
771 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
772 unsigned ExtraNotes = 0) {
773 return Diag(Loc, DiagId, ExtraNotes, false);
774 }
775
776 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
777 = diag::note_invalid_subexpr_in_const_expr,
778 unsigned ExtraNotes = 0) {
779 if (EvalStatus.Diag)
780 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
781 HasActiveDiagnostic = false;
782 return OptionalDiagnostic();
783 }
784
785 /// Diagnose that the evaluation does not produce a C++11 core constant
786 /// expression.
787 ///
788 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
789 /// EM_PotentialConstantExpression mode and we produce one of these.
790 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
791 = diag::note_invalid_subexpr_in_const_expr,
792 unsigned ExtraNotes = 0) {
793 // Don't override a previous diagnostic. Don't bother collecting
794 // diagnostics if we're evaluating for overflow.
795 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
796 HasActiveDiagnostic = false;
797 return OptionalDiagnostic();
798 }
799 return Diag(Loc, DiagId, ExtraNotes, true);
800 }
801 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
802 = diag::note_invalid_subexpr_in_const_expr,
803 unsigned ExtraNotes = 0) {
804 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
805 }
806 /// Add a note to a prior diagnostic.
807 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
808 if (!HasActiveDiagnostic)
809 return OptionalDiagnostic();
810 return OptionalDiagnostic(&addDiag(Loc, DiagId));
811 }
812
813 /// Add a stack of notes to a prior diagnostic.
814 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
815 if (HasActiveDiagnostic) {
816 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
817 Diags.begin(), Diags.end());
818 }
819 }
820
821 /// Should we continue evaluation after encountering a side-effect that we
822 /// couldn't model?
823 bool keepEvaluatingAfterSideEffect() {
824 switch (EvalMode) {
825 case EM_PotentialConstantExpression:
826 case EM_PotentialConstantExpressionUnevaluated:
827 case EM_EvaluateForOverflow:
828 case EM_IgnoreSideEffects:
829 return true;
830
831 case EM_ConstantExpression:
832 case EM_ConstantExpressionUnevaluated:
833 case EM_ConstantFold:
834 case EM_OffsetFold:
835 return false;
836 }
837 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 837)
;
838 }
839
840 /// Note that we have had a side-effect, and determine whether we should
841 /// keep evaluating.
842 bool noteSideEffect() {
843 EvalStatus.HasSideEffects = true;
844 return keepEvaluatingAfterSideEffect();
845 }
846
847 /// Should we continue evaluation after encountering undefined behavior?
848 bool keepEvaluatingAfterUndefinedBehavior() {
849 switch (EvalMode) {
850 case EM_EvaluateForOverflow:
851 case EM_IgnoreSideEffects:
852 case EM_ConstantFold:
853 case EM_OffsetFold:
854 return true;
855
856 case EM_PotentialConstantExpression:
857 case EM_PotentialConstantExpressionUnevaluated:
858 case EM_ConstantExpression:
859 case EM_ConstantExpressionUnevaluated:
860 return false;
861 }
862 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 862)
;
863 }
864
865 /// Note that we hit something that was technically undefined behavior, but
866 /// that we can evaluate past it (such as signed overflow or floating-point
867 /// division by zero.)
868 bool noteUndefinedBehavior() {
869 EvalStatus.HasUndefinedBehavior = true;
870 return keepEvaluatingAfterUndefinedBehavior();
871 }
872
873 /// Should we continue evaluation as much as possible after encountering a
874 /// construct which can't be reduced to a value?
875 bool keepEvaluatingAfterFailure() {
876 if (!StepsLeft)
877 return false;
878
879 switch (EvalMode) {
880 case EM_PotentialConstantExpression:
881 case EM_PotentialConstantExpressionUnevaluated:
882 case EM_EvaluateForOverflow:
883 return true;
884
885 case EM_ConstantExpression:
886 case EM_ConstantExpressionUnevaluated:
887 case EM_ConstantFold:
888 case EM_IgnoreSideEffects:
889 case EM_OffsetFold:
890 return false;
891 }
892 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 892)
;
893 }
894
895 /// Notes that we failed to evaluate an expression that other expressions
896 /// directly depend on, and determine if we should keep evaluating. This
897 /// should only be called if we actually intend to keep evaluating.
898 ///
899 /// Call noteSideEffect() instead if we may be able to ignore the value that
900 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
901 ///
902 /// (Foo(), 1) // use noteSideEffect
903 /// (Foo() || true) // use noteSideEffect
904 /// Foo() + 1 // use noteFailure
905 LLVM_NODISCARD[[clang::warn_unused_result]] bool noteFailure() {
906 // Failure when evaluating some expression often means there is some
907 // subexpression whose evaluation was skipped. Therefore, (because we
908 // don't track whether we skipped an expression when unwinding after an
909 // evaluation failure) every evaluation failure that bubbles up from a
910 // subexpression implies that a side-effect has potentially happened. We
911 // skip setting the HasSideEffects flag to true until we decide to
912 // continue evaluating after that point, which happens here.
913 bool KeepGoing = keepEvaluatingAfterFailure();
914 EvalStatus.HasSideEffects |= KeepGoing;
915 return KeepGoing;
916 }
917
918 class ArrayInitLoopIndex {
919 EvalInfo &Info;
920 uint64_t OuterIndex;
921
922 public:
923 ArrayInitLoopIndex(EvalInfo &Info)
924 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
925 Info.ArrayInitIndex = 0;
926 }
927 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
928
929 operator uint64_t&() { return Info.ArrayInitIndex; }
930 };
931 };
932
933 /// Object used to treat all foldable expressions as constant expressions.
934 struct FoldConstant {
935 EvalInfo &Info;
936 bool Enabled;
937 bool HadNoPriorDiags;
938 EvalInfo::EvaluationMode OldMode;
939
940 explicit FoldConstant(EvalInfo &Info, bool Enabled)
941 : Info(Info),
942 Enabled(Enabled),
943 HadNoPriorDiags(Info.EvalStatus.Diag &&
944 Info.EvalStatus.Diag->empty() &&
945 !Info.EvalStatus.HasSideEffects),
946 OldMode(Info.EvalMode) {
947 if (Enabled &&
948 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
949 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
950 Info.EvalMode = EvalInfo::EM_ConstantFold;
951 }
952 void keepDiagnostics() { Enabled = false; }
953 ~FoldConstant() {
954 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
955 !Info.EvalStatus.HasSideEffects)
956 Info.EvalStatus.Diag->clear();
957 Info.EvalMode = OldMode;
958 }
959 };
960
961 /// RAII object used to treat the current evaluation as the correct pointer
962 /// offset fold for the current EvalMode
963 struct FoldOffsetRAII {
964 EvalInfo &Info;
965 EvalInfo::EvaluationMode OldMode;
966 explicit FoldOffsetRAII(EvalInfo &Info)
967 : Info(Info), OldMode(Info.EvalMode) {
968 if (!Info.checkingPotentialConstantExpression())
969 Info.EvalMode = EvalInfo::EM_OffsetFold;
970 }
971
972 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
973 };
974
975 /// RAII object used to optionally suppress diagnostics and side-effects from
976 /// a speculative evaluation.
977 class SpeculativeEvaluationRAII {
978 /// Pair of EvalInfo, and a bit that stores whether or not we were
979 /// speculatively evaluating when we created this RAII.
980 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
981 Expr::EvalStatus Old;
982
983 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
984 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
985 Old = Other.Old;
986 Other.InfoAndOldSpecEval.setPointer(nullptr);
987 }
988
989 void maybeRestoreState() {
990 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
991 if (!Info)
992 return;
993
994 Info->EvalStatus = Old;
995 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
996 }
997
998 public:
999 SpeculativeEvaluationRAII() = default;
1000
1001 SpeculativeEvaluationRAII(
1002 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1003 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
1004 Old(Info.EvalStatus) {
1005 Info.EvalStatus.Diag = NewDiag;
1006 Info.IsSpeculativelyEvaluating = true;
1007 }
1008
1009 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1010 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1011 moveFromAndCancel(std::move(Other));
1012 }
1013
1014 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1015 maybeRestoreState();
1016 moveFromAndCancel(std::move(Other));
1017 return *this;
1018 }
1019
1020 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1021 };
1022
1023 /// RAII object wrapping a full-expression or block scope, and handling
1024 /// the ending of the lifetime of temporaries created within it.
1025 template<bool IsFullExpression>
1026 class ScopeRAII {
1027 EvalInfo &Info;
1028 unsigned OldStackSize;
1029 public:
1030 ScopeRAII(EvalInfo &Info)
1031 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1032 ~ScopeRAII() {
1033 // Body moved to a static method to encourage the compiler to inline away
1034 // instances of this class.
1035 cleanup(Info, OldStackSize);
1036 }
1037 private:
1038 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1039 unsigned NewEnd = OldStackSize;
1040 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1041 I != N; ++I) {
1042 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1043 // Full-expression cleanup of a lifetime-extended temporary: nothing
1044 // to do, just move this cleanup to the right place in the stack.
1045 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1046 ++NewEnd;
1047 } else {
1048 // End the lifetime of the object.
1049 Info.CleanupStack[I].endLifetime();
1050 }
1051 }
1052 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1053 Info.CleanupStack.end());
1054 }
1055 };
1056 typedef ScopeRAII<false> BlockScopeRAII;
1057 typedef ScopeRAII<true> FullExpressionRAII;
1058}
1059
1060bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1061 CheckSubobjectKind CSK) {
1062 if (Invalid)
1063 return false;
1064 if (isOnePastTheEnd()) {
1065 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1066 << CSK;
1067 setInvalid();
1068 return false;
1069 }
1070 return true;
1071}
1072
1073void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1074 const Expr *E, APSInt N) {
1075 // If we're complaining, we must be able to statically determine the size of
1076 // the most derived array.
1077 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1078 Info.CCEDiag(E, diag::note_constexpr_array_index)
1079 << N << /*array*/ 0
1080 << static_cast<unsigned>(getMostDerivedArraySize());
1081 else
1082 Info.CCEDiag(E, diag::note_constexpr_array_index)
1083 << N << /*non-array*/ 1;
1084 setInvalid();
1085}
1086
1087CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1088 const FunctionDecl *Callee, const LValue *This,
1089 APValue *Arguments)
1090 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1091 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1092 Info.CurrentCall = this;
1093 ++Info.CallStackDepth;
1094}
1095
1096CallStackFrame::~CallStackFrame() {
1097 assert(Info.CurrentCall == this && "calls retired out of order")((Info.CurrentCall == this && "calls retired out of order"
) ? static_cast<void> (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1097, __PRETTY_FUNCTION__))
;
1098 --Info.CallStackDepth;
1099 Info.CurrentCall = Caller;
1100}
1101
1102APValue &CallStackFrame::createTemporary(const void *Key,
1103 bool IsLifetimeExtended) {
1104 APValue &Result = Temporaries[Key];
1105 assert(Result.isUninit() && "temporary created multiple times")((Result.isUninit() && "temporary created multiple times"
) ? static_cast<void> (0) : __assert_fail ("Result.isUninit() && \"temporary created multiple times\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1105, __PRETTY_FUNCTION__))
;
1106 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1107 return Result;
1108}
1109
1110static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1111
1112void EvalInfo::addCallStack(unsigned Limit) {
1113 // Determine which calls to skip, if any.
1114 unsigned ActiveCalls = CallStackDepth - 1;
1115 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1116 if (Limit && Limit < ActiveCalls) {
1117 SkipStart = Limit / 2 + Limit % 2;
1118 SkipEnd = ActiveCalls - Limit / 2;
1119 }
1120
1121 // Walk the call stack and add the diagnostics.
1122 unsigned CallIdx = 0;
1123 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1124 Frame = Frame->Caller, ++CallIdx) {
1125 // Skip this call?
1126 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1127 if (CallIdx == SkipStart) {
1128 // Note that we're skipping calls.
1129 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1130 << unsigned(ActiveCalls - Limit);
1131 }
1132 continue;
1133 }
1134
1135 // Use a different note for an inheriting constructor, because from the
1136 // user's perspective it's not really a function at all.
1137 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1138 if (CD->isInheritingConstructor()) {
1139 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1140 << CD->getParent();
1141 continue;
1142 }
1143 }
1144
1145 SmallVector<char, 128> Buffer;
1146 llvm::raw_svector_ostream Out(Buffer);
1147 describeCall(Frame, Out);
1148 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1149 }
1150}
1151
1152namespace {
1153 struct ComplexValue {
1154 private:
1155 bool IsInt;
1156
1157 public:
1158 APSInt IntReal, IntImag;
1159 APFloat FloatReal, FloatImag;
1160
1161 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1162
1163 void makeComplexFloat() { IsInt = false; }
1164 bool isComplexFloat() const { return !IsInt; }
1165 APFloat &getComplexFloatReal() { return FloatReal; }
1166 APFloat &getComplexFloatImag() { return FloatImag; }
1167
1168 void makeComplexInt() { IsInt = true; }
1169 bool isComplexInt() const { return IsInt; }
1170 APSInt &getComplexIntReal() { return IntReal; }
1171 APSInt &getComplexIntImag() { return IntImag; }
1172
1173 void moveInto(APValue &v) const {
1174 if (isComplexFloat())
1175 v = APValue(FloatReal, FloatImag);
1176 else
1177 v = APValue(IntReal, IntImag);
1178 }
1179 void setFrom(const APValue &v) {
1180 assert(v.isComplexFloat() || v.isComplexInt())((v.isComplexFloat() || v.isComplexInt()) ? static_cast<void
> (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1180, __PRETTY_FUNCTION__))
;
1181 if (v.isComplexFloat()) {
1182 makeComplexFloat();
1183 FloatReal = v.getComplexFloatReal();
1184 FloatImag = v.getComplexFloatImag();
1185 } else {
1186 makeComplexInt();
1187 IntReal = v.getComplexIntReal();
1188 IntImag = v.getComplexIntImag();
1189 }
1190 }
1191 };
1192
1193 struct LValue {
1194 APValue::LValueBase Base;
1195 CharUnits Offset;
1196 unsigned InvalidBase : 1;
1197 unsigned CallIndex : 31;
1198 SubobjectDesignator Designator;
1199 bool IsNullPtr;
1200
1201 const APValue::LValueBase getLValueBase() const { return Base; }
1202 CharUnits &getLValueOffset() { return Offset; }
1203 const CharUnits &getLValueOffset() const { return Offset; }
1204 unsigned getLValueCallIndex() const { return CallIndex; }
1205 SubobjectDesignator &getLValueDesignator() { return Designator; }
1206 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1207 bool isNullPointer() const { return IsNullPtr;}
1208
1209 void moveInto(APValue &V) const {
1210 if (Designator.Invalid)
1211 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1212 IsNullPtr);
1213 else {
1214 assert(!InvalidBase && "APValues can't handle invalid LValue bases")((!InvalidBase && "APValues can't handle invalid LValue bases"
) ? static_cast<void> (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1214, __PRETTY_FUNCTION__))
;
1215 assert(!Designator.FirstEntryIsAnUnsizedArray &&((!Designator.FirstEntryIsAnUnsizedArray && "Unsized array with a valid base?"
) ? static_cast<void> (0) : __assert_fail ("!Designator.FirstEntryIsAnUnsizedArray && \"Unsized array with a valid base?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1216, __PRETTY_FUNCTION__))
1216 "Unsized array with a valid base?")((!Designator.FirstEntryIsAnUnsizedArray && "Unsized array with a valid base?"
) ? static_cast<void> (0) : __assert_fail ("!Designator.FirstEntryIsAnUnsizedArray && \"Unsized array with a valid base?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1216, __PRETTY_FUNCTION__))
;
1217 V = APValue(Base, Offset, Designator.Entries,
1218 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1219 }
1220 }
1221 void setFrom(ASTContext &Ctx, const APValue &V) {
1222 assert(V.isLValue() && "Setting LValue from a non-LValue?")((V.isLValue() && "Setting LValue from a non-LValue?"
) ? static_cast<void> (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1222, __PRETTY_FUNCTION__))
;
1223 Base = V.getLValueBase();
1224 Offset = V.getLValueOffset();
1225 InvalidBase = false;
1226 CallIndex = V.getLValueCallIndex();
1227 Designator = SubobjectDesignator(Ctx, V);
1228 IsNullPtr = V.isNullPointer();
1229 }
1230
1231 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1232 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
1233#ifndef NDEBUG
1234 // We only allow a few types of invalid bases. Enforce that here.
1235 if (BInvalid) {
1236 const auto *E = B.get<const Expr *>();
1237 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
"Unexpected type of invalid base") ? static_cast<void>
(0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1238, __PRETTY_FUNCTION__))
1238 "Unexpected type of invalid base")(((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
"Unexpected type of invalid base") ? static_cast<void>
(0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1238, __PRETTY_FUNCTION__))
;
1239 }
1240#endif
1241
1242 Base = B;
1243 Offset = CharUnits::fromQuantity(Offset_);
1244 InvalidBase = BInvalid;
1245 CallIndex = I;
1246 Designator = SubobjectDesignator(getType(B));
1247 IsNullPtr = IsNullPtr_;
1248 }
1249
1250 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1251 set(B, I, true);
1252 }
1253
1254 // Check that this LValue is not based on a null pointer. If it is, produce
1255 // a diagnostic and mark the designator as invalid.
1256 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1257 CheckSubobjectKind CSK) {
1258 if (Designator.Invalid)
1259 return false;
1260 if (IsNullPtr) {
1261 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1262 << CSK;
1263 Designator.setInvalid();
1264 return false;
1265 }
1266 return true;
1267 }
1268
1269 // Check this LValue refers to an object. If not, set the designator to be
1270 // invalid and emit a diagnostic.
1271 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1272 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1273 Designator.checkSubobject(Info, E, CSK);
1274 }
1275
1276 void addDecl(EvalInfo &Info, const Expr *E,
1277 const Decl *D, bool Virtual = false) {
1278 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1279 Designator.addDeclUnchecked(D, Virtual);
1280 }
1281 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1282 assert(Designator.Entries.empty() && getType(Base)->isPointerType())((Designator.Entries.empty() && getType(Base)->isPointerType
()) ? static_cast<void> (0) : __assert_fail ("Designator.Entries.empty() && getType(Base)->isPointerType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1282, __PRETTY_FUNCTION__))
;
1283 assert(isBaseAnAllocSizeCall(Base) &&((isBaseAnAllocSizeCall(Base) && "Only alloc_size bases can have unsized arrays"
) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(Base) && \"Only alloc_size bases can have unsized arrays\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1284, __PRETTY_FUNCTION__))
1284 "Only alloc_size bases can have unsized arrays")((isBaseAnAllocSizeCall(Base) && "Only alloc_size bases can have unsized arrays"
) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(Base) && \"Only alloc_size bases can have unsized arrays\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1284, __PRETTY_FUNCTION__))
;
1285 Designator.FirstEntryIsAnUnsizedArray = true;
1286 Designator.addUnsizedArrayUnchecked(ElemTy);
1287 }
1288 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1289 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1290 Designator.addArrayUnchecked(CAT);
1291 }
1292 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1293 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1294 Designator.addComplexUnchecked(EltTy, Imag);
1295 }
1296 void clearIsNullPointer() {
1297 IsNullPtr = false;
1298 }
1299 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, APSInt Index,
1300 CharUnits ElementSize) {
1301 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1302 // but we're not required to diagnose it and it's valid in C++.)
1303 if (!Index)
1304 return;
1305
1306 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1307 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1308 // offsets.
1309 uint64_t Offset64 = Offset.getQuantity();
1310 uint64_t ElemSize64 = ElementSize.getQuantity();
1311 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1312 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1313
1314 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1315 Designator.adjustIndex(Info, E, Index);
1316 clearIsNullPointer();
1317 }
1318 void adjustOffset(CharUnits N) {
1319 Offset += N;
1320 if (N.getQuantity())
1321 clearIsNullPointer();
1322 }
1323 };
1324
1325 struct MemberPtr {
1326 MemberPtr() {}
1327 explicit MemberPtr(const ValueDecl *Decl) :
1328 DeclAndIsDerivedMember(Decl, false), Path() {}
1329
1330 /// The member or (direct or indirect) field referred to by this member
1331 /// pointer, or 0 if this is a null member pointer.
1332 const ValueDecl *getDecl() const {
1333 return DeclAndIsDerivedMember.getPointer();
1334 }
1335 /// Is this actually a member of some type derived from the relevant class?
1336 bool isDerivedMember() const {
1337 return DeclAndIsDerivedMember.getInt();
1338 }
1339 /// Get the class which the declaration actually lives in.
1340 const CXXRecordDecl *getContainingRecord() const {
1341 return cast<CXXRecordDecl>(
1342 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1343 }
1344
1345 void moveInto(APValue &V) const {
1346 V = APValue(getDecl(), isDerivedMember(), Path);
1347 }
1348 void setFrom(const APValue &V) {
1349 assert(V.isMemberPointer())((V.isMemberPointer()) ? static_cast<void> (0) : __assert_fail
("V.isMemberPointer()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1349, __PRETTY_FUNCTION__))
;
1350 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1351 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1352 Path.clear();
1353 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1354 Path.insert(Path.end(), P.begin(), P.end());
1355 }
1356
1357 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1358 /// whether the member is a member of some class derived from the class type
1359 /// of the member pointer.
1360 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1361 /// Path - The path of base/derived classes from the member declaration's
1362 /// class (exclusive) to the class type of the member pointer (inclusive).
1363 SmallVector<const CXXRecordDecl*, 4> Path;
1364
1365 /// Perform a cast towards the class of the Decl (either up or down the
1366 /// hierarchy).
1367 bool castBack(const CXXRecordDecl *Class) {
1368 assert(!Path.empty())((!Path.empty()) ? static_cast<void> (0) : __assert_fail
("!Path.empty()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1368, __PRETTY_FUNCTION__))
;
1369 const CXXRecordDecl *Expected;
1370 if (Path.size() >= 2)
1371 Expected = Path[Path.size() - 2];
1372 else
1373 Expected = getContainingRecord();
1374 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1375 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1376 // if B does not contain the original member and is not a base or
1377 // derived class of the class containing the original member, the result
1378 // of the cast is undefined.
1379 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1380 // (D::*). We consider that to be a language defect.
1381 return false;
1382 }
1383 Path.pop_back();
1384 return true;
1385 }
1386 /// Perform a base-to-derived member pointer cast.
1387 bool castToDerived(const CXXRecordDecl *Derived) {
1388 if (!getDecl())
1389 return true;
1390 if (!isDerivedMember()) {
1391 Path.push_back(Derived);
1392 return true;
1393 }
1394 if (!castBack(Derived))
1395 return false;
1396 if (Path.empty())
1397 DeclAndIsDerivedMember.setInt(false);
1398 return true;
1399 }
1400 /// Perform a derived-to-base member pointer cast.
1401 bool castToBase(const CXXRecordDecl *Base) {
1402 if (!getDecl())
1403 return true;
1404 if (Path.empty())
1405 DeclAndIsDerivedMember.setInt(true);
1406 if (isDerivedMember()) {
1407 Path.push_back(Base);
1408 return true;
1409 }
1410 return castBack(Base);
1411 }
1412 };
1413
1414 /// Compare two member pointers, which are assumed to be of the same type.
1415 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1416 if (!LHS.getDecl() || !RHS.getDecl())
1417 return !LHS.getDecl() && !RHS.getDecl();
1418 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1419 return false;
1420 return LHS.Path == RHS.Path;
1421 }
1422}
1423
1424static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1425static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1426 const LValue &This, const Expr *E,
1427 bool AllowNonLiteralTypes = false);
1428static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1429 bool InvalidBaseOK = false);
1430static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1431 bool InvalidBaseOK = false);
1432static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1433 EvalInfo &Info);
1434static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1435static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1436static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1437 EvalInfo &Info);
1438static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1439static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1440static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1441 EvalInfo &Info);
1442static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1443
1444//===----------------------------------------------------------------------===//
1445// Misc utilities
1446//===----------------------------------------------------------------------===//
1447
1448/// Negate an APSInt in place, converting it to a signed form if necessary, and
1449/// preserving its value (by extending by up to one bit as needed).
1450static void negateAsSigned(APSInt &Int) {
1451 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1452 Int = Int.extend(Int.getBitWidth() + 1);
1453 Int.setIsSigned(true);
1454 }
1455 Int = -Int;
1456}
1457
1458/// Produce a string describing the given constexpr call.
1459static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1460 unsigned ArgIndex = 0;
1461 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1462 !isa<CXXConstructorDecl>(Frame->Callee) &&
1463 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1464
1465 if (!IsMemberCall)
1466 Out << *Frame->Callee << '(';
1467
1468 if (Frame->This && IsMemberCall) {
1469 APValue Val;
1470 Frame->This->moveInto(Val);
1471 Val.printPretty(Out, Frame->Info.Ctx,
1472 Frame->This->Designator.MostDerivedType);
1473 // FIXME: Add parens around Val if needed.
1474 Out << "->" << *Frame->Callee << '(';
1475 IsMemberCall = false;
1476 }
1477
1478 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1479 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1480 if (ArgIndex > (unsigned)IsMemberCall)
1481 Out << ", ";
1482
1483 const ParmVarDecl *Param = *I;
1484 const APValue &Arg = Frame->Arguments[ArgIndex];
1485 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1486
1487 if (ArgIndex == 0 && IsMemberCall)
1488 Out << "->" << *Frame->Callee << '(';
1489 }
1490
1491 Out << ')';
1492}
1493
1494/// Evaluate an expression to see if it had side-effects, and discard its
1495/// result.
1496/// \return \c true if the caller should keep evaluating.
1497static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1498 APValue Scratch;
1499 if (!Evaluate(Scratch, Info, E))
1500 // We don't need the value, but we might have skipped a side effect here.
1501 return Info.noteSideEffect();
1502 return true;
1503}
1504
1505/// Should this call expression be treated as a string literal?
1506static bool IsStringLiteralCall(const CallExpr *E) {
1507 unsigned Builtin = E->getBuiltinCallee();
1508 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1509 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1510}
1511
1512static bool IsGlobalLValue(APValue::LValueBase B) {
1513 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1514 // constant expression of pointer type that evaluates to...
1515
1516 // ... a null pointer value, or a prvalue core constant expression of type
1517 // std::nullptr_t.
1518 if (!B) return true;
1519
1520 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1521 // ... the address of an object with static storage duration,
1522 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1523 return VD->hasGlobalStorage();
1524 // ... the address of a function,
1525 return isa<FunctionDecl>(D);
1526 }
1527
1528 const Expr *E = B.get<const Expr*>();
1529 switch (E->getStmtClass()) {
1530 default:
1531 return false;
1532 case Expr::CompoundLiteralExprClass: {
1533 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1534 return CLE->isFileScope() && CLE->isLValue();
1535 }
1536 case Expr::MaterializeTemporaryExprClass:
1537 // A materialized temporary might have been lifetime-extended to static
1538 // storage duration.
1539 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1540 // A string literal has static storage duration.
1541 case Expr::StringLiteralClass:
1542 case Expr::PredefinedExprClass:
1543 case Expr::ObjCStringLiteralClass:
1544 case Expr::ObjCEncodeExprClass:
1545 case Expr::CXXTypeidExprClass:
1546 case Expr::CXXUuidofExprClass:
1547 return true;
1548 case Expr::CallExprClass:
1549 return IsStringLiteralCall(cast<CallExpr>(E));
1550 // For GCC compatibility, &&label has static storage duration.
1551 case Expr::AddrLabelExprClass:
1552 return true;
1553 // A Block literal expression may be used as the initialization value for
1554 // Block variables at global or local static scope.
1555 case Expr::BlockExprClass:
1556 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1557 case Expr::ImplicitValueInitExprClass:
1558 // FIXME:
1559 // We can never form an lvalue with an implicit value initialization as its
1560 // base through expression evaluation, so these only appear in one case: the
1561 // implicit variable declaration we invent when checking whether a constexpr
1562 // constructor can produce a constant expression. We must assume that such
1563 // an expression might be a global lvalue.
1564 return true;
1565 }
1566}
1567
1568static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1569 assert(Base && "no location for a null lvalue")((Base && "no location for a null lvalue") ? static_cast
<void> (0) : __assert_fail ("Base && \"no location for a null lvalue\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1569, __PRETTY_FUNCTION__))
;
1570 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1571 if (VD)
1572 Info.Note(VD->getLocation(), diag::note_declared_at);
1573 else
1574 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1575 diag::note_constexpr_temporary_here);
1576}
1577
1578/// Check that this reference or pointer core constant expression is a valid
1579/// value for an address or reference constant expression. Return true if we
1580/// can fold this expression, whether or not it's a constant expression.
1581static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1582 QualType Type, const LValue &LVal) {
1583 bool IsReferenceType = Type->isReferenceType();
1584
1585 APValue::LValueBase Base = LVal.getLValueBase();
1586 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1587
1588 // Check that the object is a global. Note that the fake 'this' object we
1589 // manufacture when checking potential constant expressions is conservatively
1590 // assumed to be global here.
1591 if (!IsGlobalLValue(Base)) {
1592 if (Info.getLangOpts().CPlusPlus11) {
1593 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1594 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1595 << IsReferenceType << !Designator.Entries.empty()
1596 << !!VD << VD;
1597 NoteLValueLocation(Info, Base);
1598 } else {
1599 Info.FFDiag(Loc);
1600 }
1601 // Don't allow references to temporaries to escape.
1602 return false;
1603 }
1604 assert((Info.checkingPotentialConstantExpression() ||(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex
() == 0) && "have call index for global lvalue") ? static_cast
<void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1606, __PRETTY_FUNCTION__))
1605 LVal.getLValueCallIndex() == 0) &&(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex
() == 0) && "have call index for global lvalue") ? static_cast
<void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1606, __PRETTY_FUNCTION__))
1606 "have call index for global lvalue")(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex
() == 0) && "have call index for global lvalue") ? static_cast
<void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1606, __PRETTY_FUNCTION__))
;
1607
1608 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1609 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1610 // Check if this is a thread-local variable.
1611 if (Var->getTLSKind())
1612 return false;
1613
1614 // A dllimport variable never acts like a constant.
1615 if (Var->hasAttr<DLLImportAttr>())
1616 return false;
1617 }
1618 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1619 // __declspec(dllimport) must be handled very carefully:
1620 // We must never initialize an expression with the thunk in C++.
1621 // Doing otherwise would allow the same id-expression to yield
1622 // different addresses for the same function in different translation
1623 // units. However, this means that we must dynamically initialize the
1624 // expression with the contents of the import address table at runtime.
1625 //
1626 // The C language has no notion of ODR; furthermore, it has no notion of
1627 // dynamic initialization. This means that we are permitted to
1628 // perform initialization with the address of the thunk.
1629 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1630 return false;
1631 }
1632 }
1633
1634 // Allow address constant expressions to be past-the-end pointers. This is
1635 // an extension: the standard requires them to point to an object.
1636 if (!IsReferenceType)
1637 return true;
1638
1639 // A reference constant expression must refer to an object.
1640 if (!Base) {
1641 // FIXME: diagnostic
1642 Info.CCEDiag(Loc);
1643 return true;
1644 }
1645
1646 // Does this refer one past the end of some object?
1647 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1648 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1649 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1650 << !Designator.Entries.empty() << !!VD << VD;
1651 NoteLValueLocation(Info, Base);
1652 }
1653
1654 return true;
1655}
1656
1657/// Check that this core constant expression is of literal type, and if not,
1658/// produce an appropriate diagnostic.
1659static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1660 const LValue *This = nullptr) {
1661 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1662 return true;
1663
1664 // C++1y: A constant initializer for an object o [...] may also invoke
1665 // constexpr constructors for o and its subobjects even if those objects
1666 // are of non-literal class types.
1667 //
1668 // C++11 missed this detail for aggregates, so classes like this:
1669 // struct foo_t { union { int i; volatile int j; } u; };
1670 // are not (obviously) initializable like so:
1671 // __attribute__((__require_constant_initialization__))
1672 // static const foo_t x = {{0}};
1673 // because "i" is a subobject with non-literal initialization (due to the
1674 // volatile member of the union). See:
1675 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1676 // Therefore, we use the C++1y behavior.
1677 if (This && Info.EvaluatingDecl == This->getLValueBase())
1678 return true;
1679
1680 // Prvalue constant expressions must be of literal types.
1681 if (Info.getLangOpts().CPlusPlus11)
1682 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1683 << E->getType();
1684 else
1685 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1686 return false;
1687}
1688
1689/// Check that this core constant expression value is a valid value for a
1690/// constant expression. If not, report an appropriate diagnostic. Does not
1691/// check that the expression is of literal type.
1692static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1693 QualType Type, const APValue &Value) {
1694 if (Value.isUninit()) {
1695 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1696 << true << Type;
1697 return false;
1698 }
1699
1700 // We allow _Atomic(T) to be initialized from anything that T can be
1701 // initialized from.
1702 if (const AtomicType *AT = Type->getAs<AtomicType>())
1703 Type = AT->getValueType();
1704
1705 // Core issue 1454: For a literal constant expression of array or class type,
1706 // each subobject of its value shall have been initialized by a constant
1707 // expression.
1708 if (Value.isArray()) {
1709 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1710 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1711 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1712 Value.getArrayInitializedElt(I)))
1713 return false;
1714 }
1715 if (!Value.hasArrayFiller())
1716 return true;
1717 return CheckConstantExpression(Info, DiagLoc, EltTy,
1718 Value.getArrayFiller());
1719 }
1720 if (Value.isUnion() && Value.getUnionField()) {
1721 return CheckConstantExpression(Info, DiagLoc,
1722 Value.getUnionField()->getType(),
1723 Value.getUnionValue());
1724 }
1725 if (Value.isStruct()) {
1726 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1727 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1728 unsigned BaseIndex = 0;
1729 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1730 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1731 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1732 Value.getStructBase(BaseIndex)))
1733 return false;
1734 }
1735 }
1736 for (const auto *I : RD->fields()) {
1737 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1738 Value.getStructField(I->getFieldIndex())))
1739 return false;
1740 }
1741 }
1742
1743 if (Value.isLValue()) {
1744 LValue LVal;
1745 LVal.setFrom(Info.Ctx, Value);
1746 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1747 }
1748
1749 // Everything else is fine.
1750 return true;
1751}
1752
1753static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1754 return LVal.Base.dyn_cast<const ValueDecl*>();
1755}
1756
1757static bool IsLiteralLValue(const LValue &Value) {
1758 if (Value.CallIndex)
1759 return false;
1760 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1761 return E && !isa<MaterializeTemporaryExpr>(E);
1762}
1763
1764static bool IsWeakLValue(const LValue &Value) {
1765 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1766 return Decl && Decl->isWeak();
1767}
1768
1769static bool isZeroSized(const LValue &Value) {
1770 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1771 if (Decl && isa<VarDecl>(Decl)) {
1772 QualType Ty = Decl->getType();
1773 if (Ty->isArrayType())
1774 return Ty->isIncompleteType() ||
1775 Decl->getASTContext().getTypeSize(Ty) == 0;
1776 }
1777 return false;
1778}
1779
1780static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1781 // A null base expression indicates a null pointer. These are always
1782 // evaluatable, and they are false unless the offset is zero.
1783 if (!Value.getLValueBase()) {
1784 Result = !Value.getLValueOffset().isZero();
1785 return true;
1786 }
1787
1788 // We have a non-null base. These are generally known to be true, but if it's
1789 // a weak declaration it can be null at runtime.
1790 Result = true;
1791 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1792 return !Decl || !Decl->isWeak();
1793}
1794
1795static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1796 switch (Val.getKind()) {
1797 case APValue::Uninitialized:
1798 return false;
1799 case APValue::Int:
1800 Result = Val.getInt().getBoolValue();
1801 return true;
1802 case APValue::Float:
1803 Result = !Val.getFloat().isZero();
1804 return true;
1805 case APValue::ComplexInt:
1806 Result = Val.getComplexIntReal().getBoolValue() ||
1807 Val.getComplexIntImag().getBoolValue();
1808 return true;
1809 case APValue::ComplexFloat:
1810 Result = !Val.getComplexFloatReal().isZero() ||
1811 !Val.getComplexFloatImag().isZero();
1812 return true;
1813 case APValue::LValue:
1814 return EvalPointerValueAsBool(Val, Result);
1815 case APValue::MemberPointer:
1816 Result = Val.getMemberPointerDecl();
1817 return true;
1818 case APValue::Vector:
1819 case APValue::Array:
1820 case APValue::Struct:
1821 case APValue::Union:
1822 case APValue::AddrLabelDiff:
1823 return false;
1824 }
1825
1826 llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1826)
;
1827}
1828
1829static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1830 EvalInfo &Info) {
1831 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition")((E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"
) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && \"missing lvalue-to-rvalue conv in bool condition\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1831, __PRETTY_FUNCTION__))
;
1832 APValue Val;
1833 if (!Evaluate(Val, Info, E))
1834 return false;
1835 return HandleConversionToBool(Val, Result);
1836}
1837
1838template<typename T>
1839static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1840 const T &SrcValue, QualType DestType) {
1841 Info.CCEDiag(E, diag::note_constexpr_overflow)
1842 << SrcValue << DestType;
1843 return Info.noteUndefinedBehavior();
1844}
1845
1846static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1847 QualType SrcType, const APFloat &Value,
1848 QualType DestType, APSInt &Result) {
1849 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1850 // Determine whether we are converting to unsigned or signed.
1851 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1852
1853 Result = APSInt(DestWidth, !DestSigned);
1854 bool ignored;
1855 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1856 & APFloat::opInvalidOp)
1857 return HandleOverflow(Info, E, Value, DestType);
1858 return true;
1859}
1860
1861static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1862 QualType SrcType, QualType DestType,
1863 APFloat &Result) {
1864 APFloat Value = Result;
1865 bool ignored;
1866 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1867 APFloat::rmNearestTiesToEven, &ignored)
1868 & APFloat::opOverflow)
1869 return HandleOverflow(Info, E, Value, DestType);
1870 return true;
1871}
1872
1873static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1874 QualType DestType, QualType SrcType,
1875 const APSInt &Value) {
1876 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1877 APSInt Result = Value;
1878 // Figure out if this is a truncate, extend or noop cast.
1879 // If the input is signed, do a sign extend, noop, or truncate.
1880 Result = Result.extOrTrunc(DestWidth);
1881 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1882 return Result;
1883}
1884
1885static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1886 QualType SrcType, const APSInt &Value,
1887 QualType DestType, APFloat &Result) {
1888 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1889 if (Result.convertFromAPInt(Value, Value.isSigned(),
1890 APFloat::rmNearestTiesToEven)
1891 & APFloat::opOverflow)
1892 return HandleOverflow(Info, E, Value, DestType);
1893 return true;
1894}
1895
1896static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1897 APValue &Value, const FieldDecl *FD) {
1898 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")((FD->isBitField() && "truncateBitfieldValue on non-bitfield"
) ? static_cast<void> (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1898, __PRETTY_FUNCTION__))
;
1899
1900 if (!Value.isInt()) {
1901 // Trying to store a pointer-cast-to-integer into a bitfield.
1902 // FIXME: In this case, we should provide the diagnostic for casting
1903 // a pointer to an integer.
1904 assert(Value.isLValue() && "integral value neither int nor lvalue?")((Value.isLValue() && "integral value neither int nor lvalue?"
) ? static_cast<void> (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 1904, __PRETTY_FUNCTION__))
;
1905 Info.FFDiag(E);
1906 return false;
1907 }
1908
1909 APSInt &Int = Value.getInt();
1910 unsigned OldBitWidth = Int.getBitWidth();
1911 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1912 if (NewBitWidth < OldBitWidth)
1913 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1914 return true;
1915}
1916
1917static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1918 llvm::APInt &Res) {
1919 APValue SVal;
1920 if (!Evaluate(SVal, Info, E))
1921 return false;
1922 if (SVal.isInt()) {
1923 Res = SVal.getInt();
1924 return true;
1925 }
1926 if (SVal.isFloat()) {
1927 Res = SVal.getFloat().bitcastToAPInt();
1928 return true;
1929 }
1930 if (SVal.isVector()) {
1931 QualType VecTy = E->getType();
1932 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1933 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1934 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1935 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1936 Res = llvm::APInt::getNullValue(VecSize);
1937 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1938 APValue &Elt = SVal.getVectorElt(i);
1939 llvm::APInt EltAsInt;
1940 if (Elt.isInt()) {
1941 EltAsInt = Elt.getInt();
1942 } else if (Elt.isFloat()) {
1943 EltAsInt = Elt.getFloat().bitcastToAPInt();
1944 } else {
1945 // Don't try to handle vectors of anything other than int or float
1946 // (not sure if it's possible to hit this case).
1947 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1948 return false;
1949 }
1950 unsigned BaseEltSize = EltAsInt.getBitWidth();
1951 if (BigEndian)
1952 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1953 else
1954 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1955 }
1956 return true;
1957 }
1958 // Give up if the input isn't an int, float, or vector. For example, we
1959 // reject "(v4i16)(intptr_t)&a".
1960 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1961 return false;
1962}
1963
1964/// Perform the given integer operation, which is known to need at most BitWidth
1965/// bits, and check for overflow in the original type (if that type was not an
1966/// unsigned type).
1967template<typename Operation>
1968static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1969 const APSInt &LHS, const APSInt &RHS,
1970 unsigned BitWidth, Operation Op,
1971 APSInt &Result) {
1972 if (LHS.isUnsigned()) {
1973 Result = Op(LHS, RHS);
1974 return true;
1975 }
1976
1977 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1978 Result = Value.trunc(LHS.getBitWidth());
1979 if (Result.extend(BitWidth) != Value) {
1980 if (Info.checkingForOverflow())
1981 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1982 diag::warn_integer_constant_overflow)
1983 << Result.toString(10) << E->getType();
1984 else
1985 return HandleOverflow(Info, E, Value, E->getType());
1986 }
1987 return true;
1988}
1989
1990/// Perform the given binary integer operation.
1991static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1992 BinaryOperatorKind Opcode, APSInt RHS,
1993 APSInt &Result) {
1994 switch (Opcode) {
1995 default:
1996 Info.FFDiag(E);
1997 return false;
1998 case BO_Mul:
1999 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2000 std::multiplies<APSInt>(), Result);
2001 case BO_Add:
2002 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2003 std::plus<APSInt>(), Result);
2004 case BO_Sub:
2005 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2006 std::minus<APSInt>(), Result);
2007 case BO_And: Result = LHS & RHS; return true;
2008 case BO_Xor: Result = LHS ^ RHS; return true;
2009 case BO_Or: Result = LHS | RHS; return true;
2010 case BO_Div:
2011 case BO_Rem:
2012 if (RHS == 0) {
2013 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2014 return false;
2015 }
2016 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2017 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2018 // this operation and gives the two's complement result.
2019 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2020 LHS.isSigned() && LHS.isMinSignedValue())
2021 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2022 E->getType());
2023 return true;
2024 case BO_Shl: {
2025 if (Info.getLangOpts().OpenCL)
2026 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2027 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2028 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2029 RHS.isUnsigned());
2030 else if (RHS.isSigned() && RHS.isNegative()) {
2031 // During constant-folding, a negative shift is an opposite shift. Such
2032 // a shift is not a constant expression.
2033 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2034 RHS = -RHS;
2035 goto shift_right;
2036 }
2037 shift_left:
2038 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2039 // the shifted type.
2040 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2041 if (SA != RHS) {
2042 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2043 << RHS << E->getType() << LHS.getBitWidth();
2044 } else if (LHS.isSigned()) {
2045 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2046 // operand, and must not overflow the corresponding unsigned type.
2047 if (LHS.isNegative())
2048 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2049 else if (LHS.countLeadingZeros() < SA)
2050 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2051 }
2052 Result = LHS << SA;
2053 return true;
2054 }
2055 case BO_Shr: {
2056 if (Info.getLangOpts().OpenCL)
2057 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2058 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2059 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2060 RHS.isUnsigned());
2061 else if (RHS.isSigned() && RHS.isNegative()) {
2062 // During constant-folding, a negative shift is an opposite shift. Such a
2063 // shift is not a constant expression.
2064 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2065 RHS = -RHS;
2066 goto shift_left;
2067 }
2068 shift_right:
2069 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2070 // shifted type.
2071 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2072 if (SA != RHS)
2073 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2074 << RHS << E->getType() << LHS.getBitWidth();
2075 Result = LHS >> SA;
2076 return true;
2077 }
2078
2079 case BO_LT: Result = LHS < RHS; return true;
2080 case BO_GT: Result = LHS > RHS; return true;
2081 case BO_LE: Result = LHS <= RHS; return true;
2082 case BO_GE: Result = LHS >= RHS; return true;
2083 case BO_EQ: Result = LHS == RHS; return true;
2084 case BO_NE: Result = LHS != RHS; return true;
2085 }
2086}
2087
2088/// Perform the given binary floating-point operation, in-place, on LHS.
2089static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2090 APFloat &LHS, BinaryOperatorKind Opcode,
2091 const APFloat &RHS) {
2092 switch (Opcode) {
2093 default:
2094 Info.FFDiag(E);
2095 return false;
2096 case BO_Mul:
2097 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2098 break;
2099 case BO_Add:
2100 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2101 break;
2102 case BO_Sub:
2103 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2104 break;
2105 case BO_Div:
2106 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2107 break;
2108 }
2109
2110 if (LHS.isInfinity() || LHS.isNaN()) {
2111 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2112 return Info.noteUndefinedBehavior();
2113 }
2114 return true;
2115}
2116
2117/// Cast an lvalue referring to a base subobject to a derived class, by
2118/// truncating the lvalue's path to the given length.
2119static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2120 const RecordDecl *TruncatedType,
2121 unsigned TruncatedElements) {
2122 SubobjectDesignator &D = Result.Designator;
2123
2124 // Check we actually point to a derived class object.
2125 if (TruncatedElements == D.Entries.size())
2126 return true;
2127 assert(TruncatedElements >= D.MostDerivedPathLength &&((TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class"
) ? static_cast<void> (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2128, __PRETTY_FUNCTION__))
2128 "not casting to a derived class")((TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class"
) ? static_cast<void> (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2128, __PRETTY_FUNCTION__))
;
2129 if (!Result.checkSubobject(Info, E, CSK_Derived))
2130 return false;
2131
2132 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2133 const RecordDecl *RD = TruncatedType;
2134 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2135 if (RD->isInvalidDecl()) return false;
2136 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2137 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2138 if (isVirtualBaseClass(D.Entries[I]))
2139 Result.Offset -= Layout.getVBaseClassOffset(Base);
2140 else
2141 Result.Offset -= Layout.getBaseClassOffset(Base);
2142 RD = Base;
2143 }
2144 D.Entries.resize(TruncatedElements);
2145 return true;
2146}
2147
2148static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2149 const CXXRecordDecl *Derived,
2150 const CXXRecordDecl *Base,
2151 const ASTRecordLayout *RL = nullptr) {
2152 if (!RL) {
2153 if (Derived->isInvalidDecl()) return false;
2154 RL = &Info.Ctx.getASTRecordLayout(Derived);
2155 }
2156
2157 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2158 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2159 return true;
2160}
2161
2162static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2163 const CXXRecordDecl *DerivedDecl,
2164 const CXXBaseSpecifier *Base) {
2165 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2166
2167 if (!Base->isVirtual())
2168 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2169
2170 SubobjectDesignator &D = Obj.Designator;
2171 if (D.Invalid)
2172 return false;
2173
2174 // Extract most-derived object and corresponding type.
2175 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2176 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2177 return false;
2178
2179 // Find the virtual base class.
2180 if (DerivedDecl->isInvalidDecl()) return false;
2181 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2182 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2183 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2184 return true;
2185}
2186
2187static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2188 QualType Type, LValue &Result) {
2189 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2190 PathE = E->path_end();
2191 PathI != PathE; ++PathI) {
2192 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2193 *PathI))
2194 return false;
2195 Type = (*PathI)->getType();
2196 }
2197 return true;
2198}
2199
2200/// Update LVal to refer to the given field, which must be a member of the type
2201/// currently described by LVal.
2202static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2203 const FieldDecl *FD,
2204 const ASTRecordLayout *RL = nullptr) {
2205 if (!RL) {
2206 if (FD->getParent()->isInvalidDecl()) return false;
2207 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2208 }
2209
2210 unsigned I = FD->getFieldIndex();
2211 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2212 LVal.addDecl(Info, E, FD);
2213 return true;
2214}
2215
2216/// Update LVal to refer to the given indirect field.
2217static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2218 LValue &LVal,
2219 const IndirectFieldDecl *IFD) {
2220 for (const auto *C : IFD->chain())
2221 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2222 return false;
2223 return true;
2224}
2225
2226/// Get the size of the given type in char units.
2227static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2228 QualType Type, CharUnits &Size) {
2229 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2230 // extension.
2231 if (Type->isVoidType() || Type->isFunctionType()) {
2232 Size = CharUnits::One();
2233 return true;
2234 }
2235
2236 if (Type->isDependentType()) {
2237 Info.FFDiag(Loc);
2238 return false;
2239 }
2240
2241 if (!Type->isConstantSizeType()) {
2242 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2243 // FIXME: Better diagnostic.
2244 Info.FFDiag(Loc);
2245 return false;
2246 }
2247
2248 Size = Info.Ctx.getTypeSizeInChars(Type);
2249 return true;
2250}
2251
2252/// Update a pointer value to model pointer arithmetic.
2253/// \param Info - Information about the ongoing evaluation.
2254/// \param E - The expression being evaluated, for diagnostic purposes.
2255/// \param LVal - The pointer value to be updated.
2256/// \param EltTy - The pointee type represented by LVal.
2257/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2258static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2259 LValue &LVal, QualType EltTy,
2260 APSInt Adjustment) {
2261 CharUnits SizeOfPointee;
2262 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
19
Called C++ object pointer is null
2263 return false;
2264
2265 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2266 return true;
2267}
2268
2269static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2270 LValue &LVal, QualType EltTy,
2271 int64_t Adjustment) {
2272 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
17
Passing null pointer value via 2nd parameter 'E'
18
Calling 'HandleLValueArrayAdjustment'
2273 APSInt::get(Adjustment));
2274}
2275
2276/// Update an lvalue to refer to a component of a complex number.
2277/// \param Info - Information about the ongoing evaluation.
2278/// \param LVal - The lvalue to be updated.
2279/// \param EltTy - The complex number's component type.
2280/// \param Imag - False for the real component, true for the imaginary.
2281static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2282 LValue &LVal, QualType EltTy,
2283 bool Imag) {
2284 if (Imag) {
2285 CharUnits SizeOfComponent;
2286 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2287 return false;
2288 LVal.Offset += SizeOfComponent;
2289 }
2290 LVal.addComplex(Info, E, EltTy, Imag);
2291 return true;
2292}
2293
2294static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2295 QualType Type, const LValue &LVal,
2296 APValue &RVal);
2297
2298/// Try to evaluate the initializer for a variable declaration.
2299///
2300/// \param Info Information about the ongoing evaluation.
2301/// \param E An expression to be used when printing diagnostics.
2302/// \param VD The variable whose initializer should be obtained.
2303/// \param Frame The frame in which the variable was created. Must be null
2304/// if this variable is not local to the evaluation.
2305/// \param Result Filled in with a pointer to the value of the variable.
2306static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2307 const VarDecl *VD, CallStackFrame *Frame,
2308 APValue *&Result) {
2309
2310 // If this is a parameter to an active constexpr function call, perform
2311 // argument substitution.
2312 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2313 // Assume arguments of a potential constant expression are unknown
2314 // constant expressions.
2315 if (Info.checkingPotentialConstantExpression())
2316 return false;
2317 if (!Frame || !Frame->Arguments) {
2318 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2319 return false;
2320 }
2321 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2322 return true;
2323 }
2324
2325 // If this is a local variable, dig out its value.
2326 if (Frame) {
2327 Result = Frame->getTemporary(VD);
2328 if (!Result) {
2329 // Assume variables referenced within a lambda's call operator that were
2330 // not declared within the call operator are captures and during checking
2331 // of a potential constant expression, assume they are unknown constant
2332 // expressions.
2333 assert(isLambdaCallOperator(Frame->Callee) &&((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext
() != Frame->Callee || VD->isInitCapture()) && "missing value for local variable"
) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2335, __PRETTY_FUNCTION__))
2334 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext
() != Frame->Callee || VD->isInitCapture()) && "missing value for local variable"
) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2335, __PRETTY_FUNCTION__))
2335 "missing value for local variable")((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext
() != Frame->Callee || VD->isInitCapture()) && "missing value for local variable"
) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2335, __PRETTY_FUNCTION__))
;
2336 if (Info.checkingPotentialConstantExpression())
2337 return false;
2338 // FIXME: implement capture evaluation during constant expr evaluation.
2339 Info.FFDiag(E->getLocStart(),
2340 diag::note_unimplemented_constexpr_lambda_feature_ast)
2341 << "captures not currently allowed";
2342 return false;
2343 }
2344 return true;
2345 }
2346
2347 // Dig out the initializer, and use the declaration which it's attached to.
2348 const Expr *Init = VD->getAnyInitializer(VD);
2349 if (!Init || Init->isValueDependent()) {
2350 // If we're checking a potential constant expression, the variable could be
2351 // initialized later.
2352 if (!Info.checkingPotentialConstantExpression())
2353 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2354 return false;
2355 }
2356
2357 // If we're currently evaluating the initializer of this declaration, use that
2358 // in-flight value.
2359 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2360 Result = Info.EvaluatingDeclValue;
2361 return true;
2362 }
2363
2364 // Never evaluate the initializer of a weak variable. We can't be sure that
2365 // this is the definition which will be used.
2366 if (VD->isWeak()) {
2367 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2368 return false;
2369 }
2370
2371 // Check that we can fold the initializer. In C++, we will have already done
2372 // this in the cases where it matters for conformance.
2373 SmallVector<PartialDiagnosticAt, 8> Notes;
2374 if (!VD->evaluateValue(Notes)) {
2375 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2376 Notes.size() + 1) << VD;
2377 Info.Note(VD->getLocation(), diag::note_declared_at);
2378 Info.addNotes(Notes);
2379 return false;
2380 } else if (!VD->checkInitIsICE()) {
2381 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2382 Notes.size() + 1) << VD;
2383 Info.Note(VD->getLocation(), diag::note_declared_at);
2384 Info.addNotes(Notes);
2385 }
2386
2387 Result = VD->getEvaluatedValue();
2388 return true;
2389}
2390
2391static bool IsConstNonVolatile(QualType T) {
2392 Qualifiers Quals = T.getQualifiers();
2393 return Quals.hasConst() && !Quals.hasVolatile();
2394}
2395
2396/// Get the base index of the given base class within an APValue representing
2397/// the given derived class.
2398static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2399 const CXXRecordDecl *Base) {
2400 Base = Base->getCanonicalDecl();
2401 unsigned Index = 0;
2402 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2403 E = Derived->bases_end(); I != E; ++I, ++Index) {
2404 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2405 return Index;
2406 }
2407
2408 llvm_unreachable("base class missing from derived class's bases list")::llvm::llvm_unreachable_internal("base class missing from derived class's bases list"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2408)
;
2409}
2410
2411/// Extract the value of a character from a string literal.
2412static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2413 uint64_t Index) {
2414 // FIXME: Support MakeStringConstant
2415 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2416 std::string Str;
2417 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2418 assert(Index <= Str.size() && "Index too large")((Index <= Str.size() && "Index too large") ? static_cast
<void> (0) : __assert_fail ("Index <= Str.size() && \"Index too large\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2418, __PRETTY_FUNCTION__))
;
2419 return APSInt::getUnsigned(Str.c_str()[Index]);
2420 }
2421
2422 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2423 Lit = PE->getFunctionName();
2424 const StringLiteral *S = cast<StringLiteral>(Lit);
2425 const ConstantArrayType *CAT =
2426 Info.Ctx.getAsConstantArrayType(S->getType());
2427 assert(CAT && "string literal isn't an array")((CAT && "string literal isn't an array") ? static_cast
<void> (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2427, __PRETTY_FUNCTION__))
;
2428 QualType CharType = CAT->getElementType();
2429 assert(CharType->isIntegerType() && "unexpected character type")((CharType->isIntegerType() && "unexpected character type"
) ? static_cast<void> (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2429, __PRETTY_FUNCTION__))
;
2430
2431 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2432 CharType->isUnsignedIntegerType());
2433 if (Index < S->getLength())
2434 Value = S->getCodeUnit(Index);
2435 return Value;
2436}
2437
2438// Expand a string literal into an array of characters.
2439static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2440 APValue &Result) {
2441 const StringLiteral *S = cast<StringLiteral>(Lit);
2442 const ConstantArrayType *CAT =
2443 Info.Ctx.getAsConstantArrayType(S->getType());
2444 assert(CAT && "string literal isn't an array")((CAT && "string literal isn't an array") ? static_cast
<void> (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2444, __PRETTY_FUNCTION__))
;
2445 QualType CharType = CAT->getElementType();
2446 assert(CharType->isIntegerType() && "unexpected character type")((CharType->isIntegerType() && "unexpected character type"
) ? static_cast<void> (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2446, __PRETTY_FUNCTION__))
;
2447
2448 unsigned Elts = CAT->getSize().getZExtValue();
2449 Result = APValue(APValue::UninitArray(),
2450 std::min(S->getLength(), Elts), Elts);
2451 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2452 CharType->isUnsignedIntegerType());
2453 if (Result.hasArrayFiller())
2454 Result.getArrayFiller() = APValue(Value);
2455 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2456 Value = S->getCodeUnit(I);
2457 Result.getArrayInitializedElt(I) = APValue(Value);
2458 }
2459}
2460
2461// Expand an array so that it has more than Index filled elements.
2462static void expandArray(APValue &Array, unsigned Index) {
2463 unsigned Size = Array.getArraySize();
2464 assert(Index < Size)((Index < Size) ? static_cast<void> (0) : __assert_fail
("Index < Size", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2464, __PRETTY_FUNCTION__))
;
2465
2466 // Always at least double the number of elements for which we store a value.
2467 unsigned OldElts = Array.getArrayInitializedElts();
2468 unsigned NewElts = std::max(Index+1, OldElts * 2);
2469 NewElts = std::min(Size, std::max(NewElts, 8u));
2470
2471 // Copy the data across.
2472 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2473 for (unsigned I = 0; I != OldElts; ++I)
2474 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2475 for (unsigned I = OldElts; I != NewElts; ++I)
2476 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2477 if (NewValue.hasArrayFiller())
2478 NewValue.getArrayFiller() = Array.getArrayFiller();
2479 Array.swap(NewValue);
2480}
2481
2482/// Determine whether a type would actually be read by an lvalue-to-rvalue
2483/// conversion. If it's of class type, we may assume that the copy operation
2484/// is trivial. Note that this is never true for a union type with fields
2485/// (because the copy always "reads" the active member) and always true for
2486/// a non-class type.
2487static bool isReadByLvalueToRvalueConversion(QualType T) {
2488 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2489 if (!RD || (RD->isUnion() && !RD->field_empty()))
2490 return true;
2491 if (RD->isEmpty())
2492 return false;
2493
2494 for (auto *Field : RD->fields())
2495 if (isReadByLvalueToRvalueConversion(Field->getType()))
2496 return true;
2497
2498 for (auto &BaseSpec : RD->bases())
2499 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2500 return true;
2501
2502 return false;
2503}
2504
2505/// Diagnose an attempt to read from any unreadable field within the specified
2506/// type, which might be a class type.
2507static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2508 QualType T) {
2509 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2510 if (!RD)
2511 return false;
2512
2513 if (!RD->hasMutableFields())
2514 return false;
2515
2516 for (auto *Field : RD->fields()) {
2517 // If we're actually going to read this field in some way, then it can't
2518 // be mutable. If we're in a union, then assigning to a mutable field
2519 // (even an empty one) can change the active member, so that's not OK.
2520 // FIXME: Add core issue number for the union case.
2521 if (Field->isMutable() &&
2522 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2523 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2524 Info.Note(Field->getLocation(), diag::note_declared_at);
2525 return true;
2526 }
2527
2528 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2529 return true;
2530 }
2531
2532 for (auto &BaseSpec : RD->bases())
2533 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2534 return true;
2535
2536 // All mutable fields were empty, and thus not actually read.
2537 return false;
2538}
2539
2540/// Kinds of access we can perform on an object, for diagnostics.
2541enum AccessKinds {
2542 AK_Read,
2543 AK_Assign,
2544 AK_Increment,
2545 AK_Decrement
2546};
2547
2548namespace {
2549/// A handle to a complete object (an object that is not a subobject of
2550/// another object).
2551struct CompleteObject {
2552 /// The value of the complete object.
2553 APValue *Value;
2554 /// The type of the complete object.
2555 QualType Type;
2556
2557 CompleteObject() : Value(nullptr) {}
2558 CompleteObject(APValue *Value, QualType Type)
2559 : Value(Value), Type(Type) {
2560 assert(Value && "missing value for complete object")((Value && "missing value for complete object") ? static_cast
<void> (0) : __assert_fail ("Value && \"missing value for complete object\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2560, __PRETTY_FUNCTION__))
;
2561 }
2562
2563 explicit operator bool() const { return Value; }
2564};
2565} // end anonymous namespace
2566
2567/// Find the designated sub-object of an rvalue.
2568template<typename SubobjectHandler>
2569typename SubobjectHandler::result_type
2570findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2571 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2572 if (Sub.Invalid)
2573 // A diagnostic will have already been produced.
2574 return handler.failed();
2575 if (Sub.isOnePastTheEnd()) {
2576 if (Info.getLangOpts().CPlusPlus11)
2577 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2578 << handler.AccessKind;
2579 else
2580 Info.FFDiag(E);
2581 return handler.failed();
2582 }
2583
2584 APValue *O = Obj.Value;
2585 QualType ObjType = Obj.Type;
2586 const FieldDecl *LastField = nullptr;
2587
2588 // Walk the designator's path to find the subobject.
2589 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2590 if (O->isUninit()) {
2591 if (!Info.checkingPotentialConstantExpression())
2592 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2593 return handler.failed();
2594 }
2595
2596 if (I == N) {
2597 // If we are reading an object of class type, there may still be more
2598 // things we need to check: if there are any mutable subobjects, we
2599 // cannot perform this read. (This only happens when performing a trivial
2600 // copy or assignment.)
2601 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2602 diagnoseUnreadableFields(Info, E, ObjType))
2603 return handler.failed();
2604
2605 if (!handler.found(*O, ObjType))
2606 return false;
2607
2608 // If we modified a bit-field, truncate it to the right width.
2609 if (handler.AccessKind != AK_Read &&
2610 LastField && LastField->isBitField() &&
2611 !truncateBitfieldValue(Info, E, *O, LastField))
2612 return false;
2613
2614 return true;
2615 }
2616
2617 LastField = nullptr;
2618 if (ObjType->isArrayType()) {
2619 // Next subobject is an array element.
2620 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2621 assert(CAT && "vla in literal type?")((CAT && "vla in literal type?") ? static_cast<void
> (0) : __assert_fail ("CAT && \"vla in literal type?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2621, __PRETTY_FUNCTION__))
;
2622 uint64_t Index = Sub.Entries[I].ArrayIndex;
2623 if (CAT->getSize().ule(Index)) {
2624 // Note, it should not be possible to form a pointer with a valid
2625 // designator which points more than one past the end of the array.
2626 if (Info.getLangOpts().CPlusPlus11)
2627 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2628 << handler.AccessKind;
2629 else
2630 Info.FFDiag(E);
2631 return handler.failed();
2632 }
2633
2634 ObjType = CAT->getElementType();
2635
2636 // An array object is represented as either an Array APValue or as an
2637 // LValue which refers to a string literal.
2638 if (O->isLValue()) {
2639 assert(I == N - 1 && "extracting subobject of character?")((I == N - 1 && "extracting subobject of character?")
? static_cast<void> (0) : __assert_fail ("I == N - 1 && \"extracting subobject of character?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2639, __PRETTY_FUNCTION__))
;
2640 assert(!O->hasLValuePath() || O->getLValuePath().empty())((!O->hasLValuePath() || O->getLValuePath().empty()) ? static_cast
<void> (0) : __assert_fail ("!O->hasLValuePath() || O->getLValuePath().empty()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2640, __PRETTY_FUNCTION__))
;
2641 if (handler.AccessKind != AK_Read)
2642 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2643 *O);
2644 else
2645 return handler.foundString(*O, ObjType, Index);
2646 }
2647
2648 if (O->getArrayInitializedElts() > Index)
2649 O = &O->getArrayInitializedElt(Index);
2650 else if (handler.AccessKind != AK_Read) {
2651 expandArray(*O, Index);
2652 O = &O->getArrayInitializedElt(Index);
2653 } else
2654 O = &O->getArrayFiller();
2655 } else if (ObjType->isAnyComplexType()) {
2656 // Next subobject is a complex number.
2657 uint64_t Index = Sub.Entries[I].ArrayIndex;
2658 if (Index > 1) {
2659 if (Info.getLangOpts().CPlusPlus11)
2660 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2661 << handler.AccessKind;
2662 else
2663 Info.FFDiag(E);
2664 return handler.failed();
2665 }
2666
2667 bool WasConstQualified = ObjType.isConstQualified();
2668 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2669 if (WasConstQualified)
2670 ObjType.addConst();
2671
2672 assert(I == N - 1 && "extracting subobject of scalar?")((I == N - 1 && "extracting subobject of scalar?") ? static_cast
<void> (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2672, __PRETTY_FUNCTION__))
;
2673 if (O->isComplexInt()) {
2674 return handler.found(Index ? O->getComplexIntImag()
2675 : O->getComplexIntReal(), ObjType);
2676 } else {
2677 assert(O->isComplexFloat())((O->isComplexFloat()) ? static_cast<void> (0) : __assert_fail
("O->isComplexFloat()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2677, __PRETTY_FUNCTION__))
;
2678 return handler.found(Index ? O->getComplexFloatImag()
2679 : O->getComplexFloatReal(), ObjType);
2680 }
2681 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2682 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2683 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2684 << Field;
2685 Info.Note(Field->getLocation(), diag::note_declared_at);
2686 return handler.failed();
2687 }
2688
2689 // Next subobject is a class, struct or union field.
2690 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2691 if (RD->isUnion()) {
2692 const FieldDecl *UnionField = O->getUnionField();
2693 if (!UnionField ||
2694 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2695 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2696 << handler.AccessKind << Field << !UnionField << UnionField;
2697 return handler.failed();
2698 }
2699 O = &O->getUnionValue();
2700 } else
2701 O = &O->getStructField(Field->getFieldIndex());
2702
2703 bool WasConstQualified = ObjType.isConstQualified();
2704 ObjType = Field->getType();
2705 if (WasConstQualified && !Field->isMutable())
2706 ObjType.addConst();
2707
2708 if (ObjType.isVolatileQualified()) {
2709 if (Info.getLangOpts().CPlusPlus) {
2710 // FIXME: Include a description of the path to the volatile subobject.
2711 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2712 << handler.AccessKind << 2 << Field;
2713 Info.Note(Field->getLocation(), diag::note_declared_at);
2714 } else {
2715 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2716 }
2717 return handler.failed();
2718 }
2719
2720 LastField = Field;
2721 } else {
2722 // Next subobject is a base class.
2723 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2724 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2725 O = &O->getStructBase(getBaseIndex(Derived, Base));
2726
2727 bool WasConstQualified = ObjType.isConstQualified();
2728 ObjType = Info.Ctx.getRecordType(Base);
2729 if (WasConstQualified)
2730 ObjType.addConst();
2731 }
2732 }
2733}
2734
2735namespace {
2736struct ExtractSubobjectHandler {
2737 EvalInfo &Info;
2738 APValue &Result;
2739
2740 static const AccessKinds AccessKind = AK_Read;
2741
2742 typedef bool result_type;
2743 bool failed() { return false; }
2744 bool found(APValue &Subobj, QualType SubobjType) {
2745 Result = Subobj;
2746 return true;
2747 }
2748 bool found(APSInt &Value, QualType SubobjType) {
2749 Result = APValue(Value);
2750 return true;
2751 }
2752 bool found(APFloat &Value, QualType SubobjType) {
2753 Result = APValue(Value);
2754 return true;
2755 }
2756 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2757 Result = APValue(extractStringLiteralCharacter(
2758 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2759 return true;
2760 }
2761};
2762} // end anonymous namespace
2763
2764const AccessKinds ExtractSubobjectHandler::AccessKind;
2765
2766/// Extract the designated sub-object of an rvalue.
2767static bool extractSubobject(EvalInfo &Info, const Expr *E,
2768 const CompleteObject &Obj,
2769 const SubobjectDesignator &Sub,
2770 APValue &Result) {
2771 ExtractSubobjectHandler Handler = { Info, Result };
2772 return findSubobject(Info, E, Obj, Sub, Handler);
2773}
2774
2775namespace {
2776struct ModifySubobjectHandler {
2777 EvalInfo &Info;
2778 APValue &NewVal;
2779 const Expr *E;
2780
2781 typedef bool result_type;
2782 static const AccessKinds AccessKind = AK_Assign;
2783
2784 bool checkConst(QualType QT) {
2785 // Assigning to a const object has undefined behavior.
2786 if (QT.isConstQualified()) {
2787 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2788 return false;
2789 }
2790 return true;
2791 }
2792
2793 bool failed() { return false; }
2794 bool found(APValue &Subobj, QualType SubobjType) {
2795 if (!checkConst(SubobjType))
2796 return false;
2797 // We've been given ownership of NewVal, so just swap it in.
2798 Subobj.swap(NewVal);
2799 return true;
2800 }
2801 bool found(APSInt &Value, QualType SubobjType) {
2802 if (!checkConst(SubobjType))
2803 return false;
2804 if (!NewVal.isInt()) {
2805 // Maybe trying to write a cast pointer value into a complex?
2806 Info.FFDiag(E);
2807 return false;
2808 }
2809 Value = NewVal.getInt();
2810 return true;
2811 }
2812 bool found(APFloat &Value, QualType SubobjType) {
2813 if (!checkConst(SubobjType))
2814 return false;
2815 Value = NewVal.getFloat();
2816 return true;
2817 }
2818 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2819 llvm_unreachable("shouldn't encounter string elements with ExpandArrays")::llvm::llvm_unreachable_internal("shouldn't encounter string elements with ExpandArrays"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 2819)
;
2820 }
2821};
2822} // end anonymous namespace
2823
2824const AccessKinds ModifySubobjectHandler::AccessKind;
2825
2826/// Update the designated sub-object of an rvalue to the given value.
2827static bool modifySubobject(EvalInfo &Info, const Expr *E,
2828 const CompleteObject &Obj,
2829 const SubobjectDesignator &Sub,
2830 APValue &NewVal) {
2831 ModifySubobjectHandler Handler = { Info, NewVal, E };
2832 return findSubobject(Info, E, Obj, Sub, Handler);
2833}
2834
2835/// Find the position where two subobject designators diverge, or equivalently
2836/// the length of the common initial subsequence.
2837static unsigned FindDesignatorMismatch(QualType ObjType,
2838 const SubobjectDesignator &A,
2839 const SubobjectDesignator &B,
2840 bool &WasArrayIndex) {
2841 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2842 for (/**/; I != N; ++I) {
2843 if (!ObjType.isNull() &&
2844 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2845 // Next subobject is an array element.
2846 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2847 WasArrayIndex = true;
2848 return I;
2849 }
2850 if (ObjType->isAnyComplexType())
2851 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2852 else
2853 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2854 } else {
2855 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2856 WasArrayIndex = false;
2857 return I;
2858 }
2859 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2860 // Next subobject is a field.
2861 ObjType = FD->getType();
2862 else
2863 // Next subobject is a base class.
2864 ObjType = QualType();
2865 }
2866 }
2867 WasArrayIndex = false;
2868 return I;
2869}
2870
2871/// Determine whether the given subobject designators refer to elements of the
2872/// same array object.
2873static bool AreElementsOfSameArray(QualType ObjType,
2874 const SubobjectDesignator &A,
2875 const SubobjectDesignator &B) {
2876 if (A.Entries.size() != B.Entries.size())
2877 return false;
2878
2879 bool IsArray = A.MostDerivedIsArrayElement;
2880 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2881 // A is a subobject of the array element.
2882 return false;
2883
2884 // If A (and B) designates an array element, the last entry will be the array
2885 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2886 // of length 1' case, and the entire path must match.
2887 bool WasArrayIndex;
2888 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2889 return CommonLength >= A.Entries.size() - IsArray;
2890}
2891
2892/// Find the complete object to which an LValue refers.
2893static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2894 AccessKinds AK, const LValue &LVal,
2895 QualType LValType) {
2896 if (!LVal.Base) {
2897 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2898 return CompleteObject();
2899 }
2900
2901 CallStackFrame *Frame = nullptr;
2902 if (LVal.CallIndex) {
2903 Frame = Info.getCallFrame(LVal.CallIndex);
2904 if (!Frame) {
2905 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2906 << AK << LVal.Base.is<const ValueDecl*>();
2907 NoteLValueLocation(Info, LVal.Base);
2908 return CompleteObject();
2909 }
2910 }
2911
2912 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2913 // is not a constant expression (even if the object is non-volatile). We also
2914 // apply this rule to C++98, in order to conform to the expected 'volatile'
2915 // semantics.
2916 if (LValType.isVolatileQualified()) {
2917 if (Info.getLangOpts().CPlusPlus)
2918 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2919 << AK << LValType;
2920 else
2921 Info.FFDiag(E);
2922 return CompleteObject();
2923 }
2924
2925 // Compute value storage location and type of base object.
2926 APValue *BaseVal = nullptr;
2927 QualType BaseType = getType(LVal.Base);
2928
2929 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2930 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2931 // In C++11, constexpr, non-volatile variables initialized with constant
2932 // expressions are constant expressions too. Inside constexpr functions,
2933 // parameters are constant expressions even if they're non-const.
2934 // In C++1y, objects local to a constant expression (those with a Frame) are
2935 // both readable and writable inside constant expressions.
2936 // In C, such things can also be folded, although they are not ICEs.
2937 const VarDecl *VD = dyn_cast<VarDecl>(D);
2938 if (VD) {
2939 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2940 VD = VDef;
2941 }
2942 if (!VD || VD->isInvalidDecl()) {
2943 Info.FFDiag(E);
2944 return CompleteObject();
2945 }
2946
2947 // Accesses of volatile-qualified objects are not allowed.
2948 if (BaseType.isVolatileQualified()) {
2949 if (Info.getLangOpts().CPlusPlus) {
2950 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2951 << AK << 1 << VD;
2952 Info.Note(VD->getLocation(), diag::note_declared_at);
2953 } else {
2954 Info.FFDiag(E);
2955 }
2956 return CompleteObject();
2957 }
2958
2959 // Unless we're looking at a local variable or argument in a constexpr call,
2960 // the variable we're reading must be const.
2961 if (!Frame) {
2962 if (Info.getLangOpts().CPlusPlus14 &&
2963 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2964 // OK, we can read and modify an object if we're in the process of
2965 // evaluating its initializer, because its lifetime began in this
2966 // evaluation.
2967 } else if (AK != AK_Read) {
2968 // All the remaining cases only permit reading.
2969 Info.FFDiag(E, diag::note_constexpr_modify_global);
2970 return CompleteObject();
2971 } else if (VD->isConstexpr()) {
2972 // OK, we can read this variable.
2973 } else if (BaseType->isIntegralOrEnumerationType()) {
2974 // In OpenCL if a variable is in constant address space it is a const value.
2975 if (!(BaseType.isConstQualified() ||
2976 (Info.getLangOpts().OpenCL &&
2977 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
2978 if (Info.getLangOpts().CPlusPlus) {
2979 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2980 Info.Note(VD->getLocation(), diag::note_declared_at);
2981 } else {
2982 Info.FFDiag(E);
2983 }
2984 return CompleteObject();
2985 }
2986 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2987 // We support folding of const floating-point types, in order to make
2988 // static const data members of such types (supported as an extension)
2989 // more useful.
2990 if (Info.getLangOpts().CPlusPlus11) {
2991 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2992 Info.Note(VD->getLocation(), diag::note_declared_at);
2993 } else {
2994 Info.CCEDiag(E);
2995 }
2996 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2997 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2998 // Keep evaluating to see what we can do.
2999 } else {
3000 // FIXME: Allow folding of values of any literal type in all languages.
3001 if (Info.checkingPotentialConstantExpression() &&
3002 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3003 // The definition of this variable could be constexpr. We can't
3004 // access it right now, but may be able to in future.
3005 } else if (Info.getLangOpts().CPlusPlus11) {
3006 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3007 Info.Note(VD->getLocation(), diag::note_declared_at);
3008 } else {
3009 Info.FFDiag(E);
3010 }
3011 return CompleteObject();
3012 }
3013 }
3014
3015 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3016 return CompleteObject();
3017 } else {
3018 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3019
3020 if (!Frame) {
3021 if (const MaterializeTemporaryExpr *MTE =
3022 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3023 assert(MTE->getStorageDuration() == SD_Static &&((MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary"
) ? static_cast<void> (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3024, __PRETTY_FUNCTION__))
3024 "should have a frame for a non-global materialized temporary")((MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary"
) ? static_cast<void> (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3024, __PRETTY_FUNCTION__))
;
3025
3026 // Per C++1y [expr.const]p2:
3027 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3028 // - a [...] glvalue of integral or enumeration type that refers to
3029 // a non-volatile const object [...]
3030 // [...]
3031 // - a [...] glvalue of literal type that refers to a non-volatile
3032 // object whose lifetime began within the evaluation of e.
3033 //
3034 // C++11 misses the 'began within the evaluation of e' check and
3035 // instead allows all temporaries, including things like:
3036 // int &&r = 1;
3037 // int x = ++r;
3038 // constexpr int k = r;
3039 // Therefore we use the C++1y rules in C++11 too.
3040 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3041 const ValueDecl *ED = MTE->getExtendingDecl();
3042 if (!(BaseType.isConstQualified() &&
3043 BaseType->isIntegralOrEnumerationType()) &&
3044 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3045 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3046 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3047 return CompleteObject();
3048 }
3049
3050 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3051 assert(BaseVal && "got reference to unevaluated temporary")((BaseVal && "got reference to unevaluated temporary"
) ? static_cast<void> (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3051, __PRETTY_FUNCTION__))
;
3052 } else {
3053 Info.FFDiag(E);
3054 return CompleteObject();
3055 }
3056 } else {
3057 BaseVal = Frame->getTemporary(Base);
3058 assert(BaseVal && "missing value for temporary")((BaseVal && "missing value for temporary") ? static_cast
<void> (0) : __assert_fail ("BaseVal && \"missing value for temporary\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3058, __PRETTY_FUNCTION__))
;
3059 }
3060
3061 // Volatile temporary objects cannot be accessed in constant expressions.
3062 if (BaseType.isVolatileQualified()) {
3063 if (Info.getLangOpts().CPlusPlus) {
3064 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3065 << AK << 0;
3066 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3067 } else {
3068 Info.FFDiag(E);
3069 }
3070 return CompleteObject();
3071 }
3072 }
3073
3074 // During the construction of an object, it is not yet 'const'.
3075 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3076 // and this doesn't do quite the right thing for const subobjects of the
3077 // object under construction.
3078 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3079 BaseType = Info.Ctx.getCanonicalType(BaseType);
3080 BaseType.removeLocalConst();
3081 }
3082
3083 // In C++1y, we can't safely access any mutable state when we might be
3084 // evaluating after an unmodeled side effect.
3085 //
3086 // FIXME: Not all local state is mutable. Allow local constant subobjects
3087 // to be read here (but take care with 'mutable' fields).
3088 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3089 Info.EvalStatus.HasSideEffects) ||
3090 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3091 return CompleteObject();
3092
3093 return CompleteObject(BaseVal, BaseType);
3094}
3095
3096/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3097/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3098/// glvalue referred to by an entity of reference type.
3099///
3100/// \param Info - Information about the ongoing evaluation.
3101/// \param Conv - The expression for which we are performing the conversion.
3102/// Used for diagnostics.
3103/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3104/// case of a non-class type).
3105/// \param LVal - The glvalue on which we are attempting to perform this action.
3106/// \param RVal - The produced value will be placed here.
3107static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3108 QualType Type,
3109 const LValue &LVal, APValue &RVal) {
3110 if (LVal.Designator.Invalid)
3111 return false;
3112
3113 // Check for special cases where there is no existing APValue to look at.
3114 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3115 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3116 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3117 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3118 // initializer until now for such expressions. Such an expression can't be
3119 // an ICE in C, so this only matters for fold.
3120 if (Type.isVolatileQualified()) {
3121 Info.FFDiag(Conv);
3122 return false;
3123 }
3124 APValue Lit;
3125 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3126 return false;
3127 CompleteObject LitObj(&Lit, Base->getType());
3128 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3129 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3130 // We represent a string literal array as an lvalue pointing at the
3131 // corresponding expression, rather than building an array of chars.
3132 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3133 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3134 CompleteObject StrObj(&Str, Base->getType());
3135 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3136 }
3137 }
3138
3139 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3140 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3141}
3142
3143/// Perform an assignment of Val to LVal. Takes ownership of Val.
3144static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3145 QualType LValType, APValue &Val) {
3146 if (LVal.Designator.Invalid)
3147 return false;
3148
3149 if (!Info.getLangOpts().CPlusPlus14) {
3150 Info.FFDiag(E);
3151 return false;
3152 }
3153
3154 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3155 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3156}
3157
3158static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3159 return T->isSignedIntegerType() &&
3160 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3161}
3162
3163namespace {
3164struct CompoundAssignSubobjectHandler {
3165 EvalInfo &Info;
3166 const Expr *E;
3167 QualType PromotedLHSType;
3168 BinaryOperatorKind Opcode;
3169 const APValue &RHS;
3170
3171 static const AccessKinds AccessKind = AK_Assign;
3172
3173 typedef bool result_type;
3174
3175 bool checkConst(QualType QT) {
3176 // Assigning to a const object has undefined behavior.
3177 if (QT.isConstQualified()) {
3178 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3179 return false;
3180 }
3181 return true;
3182 }
3183
3184 bool failed() { return false; }
3185 bool found(APValue &Subobj, QualType SubobjType) {
3186 switch (Subobj.getKind()) {
3187 case APValue::Int:
3188 return found(Subobj.getInt(), SubobjType);
3189 case APValue::Float:
3190 return found(Subobj.getFloat(), SubobjType);
3191 case APValue::ComplexInt:
3192 case APValue::ComplexFloat:
3193 // FIXME: Implement complex compound assignment.
3194 Info.FFDiag(E);
3195 return false;
3196 case APValue::LValue:
3197 return foundPointer(Subobj, SubobjType);
3198 default:
3199 // FIXME: can this happen?
3200 Info.FFDiag(E);
3201 return false;
3202 }
3203 }
3204 bool found(APSInt &Value, QualType SubobjType) {
3205 if (!checkConst(SubobjType))
3206 return false;
3207
3208 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3209 // We don't support compound assignment on integer-cast-to-pointer
3210 // values.
3211 Info.FFDiag(E);
3212 return false;
3213 }
3214
3215 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3216 SubobjType, Value);
3217 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3218 return false;
3219 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3220 return true;
3221 }
3222 bool found(APFloat &Value, QualType SubobjType) {
3223 return checkConst(SubobjType) &&
3224 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3225 Value) &&
3226 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3227 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3228 }
3229 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3230 if (!checkConst(SubobjType))
3231 return false;
3232
3233 QualType PointeeType;
3234 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3235 PointeeType = PT->getPointeeType();
3236
3237 if (PointeeType.isNull() || !RHS.isInt() ||
3238 (Opcode != BO_Add && Opcode != BO_Sub)) {
3239 Info.FFDiag(E);
3240 return false;
3241 }
3242
3243 APSInt Offset = RHS.getInt();
3244 if (Opcode == BO_Sub)
3245 negateAsSigned(Offset);
3246
3247 LValue LVal;
3248 LVal.setFrom(Info.Ctx, Subobj);
3249 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3250 return false;
3251 LVal.moveInto(Subobj);
3252 return true;
3253 }
3254 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3255 llvm_unreachable("shouldn't encounter string elements here")::llvm::llvm_unreachable_internal("shouldn't encounter string elements here"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3255)
;
3256 }
3257};
3258} // end anonymous namespace
3259
3260const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3261
3262/// Perform a compound assignment of LVal <op>= RVal.
3263static bool handleCompoundAssignment(
3264 EvalInfo &Info, const Expr *E,
3265 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3266 BinaryOperatorKind Opcode, const APValue &RVal) {
3267 if (LVal.Designator.Invalid)
3268 return false;
3269
3270 if (!Info.getLangOpts().CPlusPlus14) {
3271 Info.FFDiag(E);
3272 return false;
3273 }
3274
3275 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3276 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3277 RVal };
3278 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3279}
3280
3281namespace {
3282struct IncDecSubobjectHandler {
3283 EvalInfo &Info;
3284 const Expr *E;
3285 AccessKinds AccessKind;
3286 APValue *Old;
3287
3288 typedef bool result_type;
3289
3290 bool checkConst(QualType QT) {
3291 // Assigning to a const object has undefined behavior.
3292 if (QT.isConstQualified()) {
3293 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3294 return false;
3295 }
3296 return true;
3297 }
3298
3299 bool failed() { return false; }
3300 bool found(APValue &Subobj, QualType SubobjType) {
3301 // Stash the old value. Also clear Old, so we don't clobber it later
3302 // if we're post-incrementing a complex.
3303 if (Old) {
3304 *Old = Subobj;
3305 Old = nullptr;
3306 }
3307
3308 switch (Subobj.getKind()) {
3309 case APValue::Int:
3310 return found(Subobj.getInt(), SubobjType);
3311 case APValue::Float:
3312 return found(Subobj.getFloat(), SubobjType);
3313 case APValue::ComplexInt:
3314 return found(Subobj.getComplexIntReal(),
3315 SubobjType->castAs<ComplexType>()->getElementType()
3316 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3317 case APValue::ComplexFloat:
3318 return found(Subobj.getComplexFloatReal(),
3319 SubobjType->castAs<ComplexType>()->getElementType()
3320 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3321 case APValue::LValue:
3322 return foundPointer(Subobj, SubobjType);
3323 default:
3324 // FIXME: can this happen?
3325 Info.FFDiag(E);
3326 return false;
3327 }
3328 }
3329 bool found(APSInt &Value, QualType SubobjType) {
3330 if (!checkConst(SubobjType))
3331 return false;
3332
3333 if (!SubobjType->isIntegerType()) {
3334 // We don't support increment / decrement on integer-cast-to-pointer
3335 // values.
3336 Info.FFDiag(E);
3337 return false;
3338 }
3339
3340 if (Old) *Old = APValue(Value);
3341
3342 // bool arithmetic promotes to int, and the conversion back to bool
3343 // doesn't reduce mod 2^n, so special-case it.
3344 if (SubobjType->isBooleanType()) {
3345 if (AccessKind == AK_Increment)
3346 Value = 1;
3347 else
3348 Value = !Value;
3349 return true;
3350 }
3351
3352 bool WasNegative = Value.isNegative();
3353 if (AccessKind == AK_Increment) {
3354 ++Value;
3355
3356 if (!WasNegative && Value.isNegative() &&
3357 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3358 APSInt ActualValue(Value, /*IsUnsigned*/true);
3359 return HandleOverflow(Info, E, ActualValue, SubobjType);
3360 }
3361 } else {
3362 --Value;
3363
3364 if (WasNegative && !Value.isNegative() &&
3365 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3366 unsigned BitWidth = Value.getBitWidth();
3367 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3368 ActualValue.setBit(BitWidth);
3369 return HandleOverflow(Info, E, ActualValue, SubobjType);
3370 }
3371 }
3372 return true;
3373 }
3374 bool found(APFloat &Value, QualType SubobjType) {
3375 if (!checkConst(SubobjType))
3376 return false;
3377
3378 if (Old) *Old = APValue(Value);
3379
3380 APFloat One(Value.getSemantics(), 1);
3381 if (AccessKind == AK_Increment)
3382 Value.add(One, APFloat::rmNearestTiesToEven);
3383 else
3384 Value.subtract(One, APFloat::rmNearestTiesToEven);
3385 return true;
3386 }
3387 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3388 if (!checkConst(SubobjType))
3389 return false;
3390
3391 QualType PointeeType;
3392 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3393 PointeeType = PT->getPointeeType();
3394 else {
3395 Info.FFDiag(E);
3396 return false;
3397 }
3398
3399 LValue LVal;
3400 LVal.setFrom(Info.Ctx, Subobj);
3401 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3402 AccessKind == AK_Increment ? 1 : -1))
3403 return false;
3404 LVal.moveInto(Subobj);
3405 return true;
3406 }
3407 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3408 llvm_unreachable("shouldn't encounter string elements here")::llvm::llvm_unreachable_internal("shouldn't encounter string elements here"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3408)
;
3409 }
3410};
3411} // end anonymous namespace
3412
3413/// Perform an increment or decrement on LVal.
3414static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3415 QualType LValType, bool IsIncrement, APValue *Old) {
3416 if (LVal.Designator.Invalid)
3417 return false;
3418
3419 if (!Info.getLangOpts().CPlusPlus14) {
3420 Info.FFDiag(E);
3421 return false;
3422 }
3423
3424 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3425 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3426 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3427 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3428}
3429
3430/// Build an lvalue for the object argument of a member function call.
3431static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3432 LValue &This) {
3433 if (Object->getType()->isPointerType())
3434 return EvaluatePointer(Object, This, Info);
3435
3436 if (Object->isGLValue())
3437 return EvaluateLValue(Object, This, Info);
3438
3439 if (Object->getType()->isLiteralType(Info.Ctx))
3440 return EvaluateTemporary(Object, This, Info);
3441
3442 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3443 return false;
3444}
3445
3446/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3447/// lvalue referring to the result.
3448///
3449/// \param Info - Information about the ongoing evaluation.
3450/// \param LV - An lvalue referring to the base of the member pointer.
3451/// \param RHS - The member pointer expression.
3452/// \param IncludeMember - Specifies whether the member itself is included in
3453/// the resulting LValue subobject designator. This is not possible when
3454/// creating a bound member function.
3455/// \return The field or method declaration to which the member pointer refers,
3456/// or 0 if evaluation fails.
3457static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3458 QualType LVType,
3459 LValue &LV,
3460 const Expr *RHS,
3461 bool IncludeMember = true) {
3462 MemberPtr MemPtr;
3463 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3464 return nullptr;
3465
3466 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3467 // member value, the behavior is undefined.
3468 if (!MemPtr.getDecl()) {
3469 // FIXME: Specific diagnostic.
3470 Info.FFDiag(RHS);
3471 return nullptr;
3472 }
3473
3474 if (MemPtr.isDerivedMember()) {
3475 // This is a member of some derived class. Truncate LV appropriately.
3476 // The end of the derived-to-base path for the base object must match the
3477 // derived-to-base path for the member pointer.
3478 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3479 LV.Designator.Entries.size()) {
3480 Info.FFDiag(RHS);
3481 return nullptr;
3482 }
3483 unsigned PathLengthToMember =
3484 LV.Designator.Entries.size() - MemPtr.Path.size();
3485 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3486 const CXXRecordDecl *LVDecl = getAsBaseClass(
3487 LV.Designator.Entries[PathLengthToMember + I]);
3488 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3489 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3490 Info.FFDiag(RHS);
3491 return nullptr;
3492 }
3493 }
3494
3495 // Truncate the lvalue to the appropriate derived class.
3496 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3497 PathLengthToMember))
3498 return nullptr;
3499 } else if (!MemPtr.Path.empty()) {
3500 // Extend the LValue path with the member pointer's path.
3501 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3502 MemPtr.Path.size() + IncludeMember);
3503
3504 // Walk down to the appropriate base class.
3505 if (const PointerType *PT = LVType->getAs<PointerType>())
3506 LVType = PT->getPointeeType();
3507 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3508 assert(RD && "member pointer access on non-class-type expression")((RD && "member pointer access on non-class-type expression"
) ? static_cast<void> (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3508, __PRETTY_FUNCTION__))
;
3509 // The first class in the path is that of the lvalue.
3510 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3511 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3512 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3513 return nullptr;
3514 RD = Base;
3515 }
3516 // Finally cast to the class containing the member.
3517 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3518 MemPtr.getContainingRecord()))
3519 return nullptr;
3520 }
3521
3522 // Add the member. Note that we cannot build bound member functions here.
3523 if (IncludeMember) {
3524 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3525 if (!HandleLValueMember(Info, RHS, LV, FD))
3526 return nullptr;
3527 } else if (const IndirectFieldDecl *IFD =
3528 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3529 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3530 return nullptr;
3531 } else {
3532 llvm_unreachable("can't construct reference to bound member function")::llvm::llvm_unreachable_internal("can't construct reference to bound member function"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3532)
;
3533 }
3534 }
3535
3536 return MemPtr.getDecl();
3537}
3538
3539static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3540 const BinaryOperator *BO,
3541 LValue &LV,
3542 bool IncludeMember = true) {
3543 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)((BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3543, __PRETTY_FUNCTION__))
;
3544
3545 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3546 if (Info.noteFailure()) {
3547 MemberPtr MemPtr;
3548 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3549 }
3550 return nullptr;
3551 }
3552
3553 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3554 BO->getRHS(), IncludeMember);
3555}
3556
3557/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3558/// the provided lvalue, which currently refers to the base object.
3559static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3560 LValue &Result) {
3561 SubobjectDesignator &D = Result.Designator;
3562 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3563 return false;
3564
3565 QualType TargetQT = E->getType();
3566 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3567 TargetQT = PT->getPointeeType();
3568
3569 // Check this cast lands within the final derived-to-base subobject path.
3570 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3571 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3572 << D.MostDerivedType << TargetQT;
3573 return false;
3574 }
3575
3576 // Check the type of the final cast. We don't need to check the path,
3577 // since a cast can only be formed if the path is unique.
3578 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3579 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3580 const CXXRecordDecl *FinalType;
3581 if (NewEntriesSize == D.MostDerivedPathLength)
3582 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3583 else
3584 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3585 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3586 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3587 << D.MostDerivedType << TargetQT;
3588 return false;
3589 }
3590
3591 // Truncate the lvalue to the appropriate derived class.
3592 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3593}
3594
3595namespace {
3596enum EvalStmtResult {
3597 /// Evaluation failed.
3598 ESR_Failed,
3599 /// Hit a 'return' statement.
3600 ESR_Returned,
3601 /// Evaluation succeeded.
3602 ESR_Succeeded,
3603 /// Hit a 'continue' statement.
3604 ESR_Continue,
3605 /// Hit a 'break' statement.
3606 ESR_Break,
3607 /// Still scanning for 'case' or 'default' statement.
3608 ESR_CaseNotFound
3609};
3610}
3611
3612static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3613 // We don't need to evaluate the initializer for a static local.
3614 if (!VD->hasLocalStorage())
3615 return true;
3616
3617 LValue Result;
3618 Result.set(VD, Info.CurrentCall->Index);
3619 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3620
3621 const Expr *InitE = VD->getInit();
3622 if (!InitE) {
3623 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3624 << false << VD->getType();
3625 Val = APValue();
3626 return false;
3627 }
3628
3629 if (InitE->isValueDependent())
3630 return false;
3631
3632 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3633 // Wipe out any partially-computed value, to allow tracking that this
3634 // evaluation failed.
3635 Val = APValue();
3636 return false;
3637 }
3638
3639 return true;
3640}
3641
3642static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3643 bool OK = true;
3644
3645 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3646 OK &= EvaluateVarDecl(Info, VD);
3647
3648 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3649 for (auto *BD : DD->bindings())
3650 if (auto *VD = BD->getHoldingVar())
3651 OK &= EvaluateDecl(Info, VD);
3652
3653 return OK;
3654}
3655
3656
3657/// Evaluate a condition (either a variable declaration or an expression).
3658static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3659 const Expr *Cond, bool &Result) {
3660 FullExpressionRAII Scope(Info);
3661 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3662 return false;
3663 return EvaluateAsBooleanCondition(Cond, Result, Info);
3664}
3665
3666namespace {
3667/// \brief A location where the result (returned value) of evaluating a
3668/// statement should be stored.
3669struct StmtResult {
3670 /// The APValue that should be filled in with the returned value.
3671 APValue &Value;
3672 /// The location containing the result, if any (used to support RVO).
3673 const LValue *Slot;
3674};
3675}
3676
3677static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3678 const Stmt *S,
3679 const SwitchCase *SC = nullptr);
3680
3681/// Evaluate the body of a loop, and translate the result as appropriate.
3682static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3683 const Stmt *Body,
3684 const SwitchCase *Case = nullptr) {
3685 BlockScopeRAII Scope(Info);
3686 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3687 case ESR_Break:
3688 return ESR_Succeeded;
3689 case ESR_Succeeded:
3690 case ESR_Continue:
3691 return ESR_Continue;
3692 case ESR_Failed:
3693 case ESR_Returned:
3694 case ESR_CaseNotFound:
3695 return ESR;
3696 }
3697 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3697)
;
3698}
3699
3700/// Evaluate a switch statement.
3701static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3702 const SwitchStmt *SS) {
3703 BlockScopeRAII Scope(Info);
3704
3705 // Evaluate the switch condition.
3706 APSInt Value;
3707 {
3708 FullExpressionRAII Scope(Info);
3709 if (const Stmt *Init = SS->getInit()) {
3710 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3711 if (ESR != ESR_Succeeded)
3712 return ESR;
3713 }
3714 if (SS->getConditionVariable() &&
3715 !EvaluateDecl(Info, SS->getConditionVariable()))
3716 return ESR_Failed;
3717 if (!EvaluateInteger(SS->getCond(), Value, Info))
3718 return ESR_Failed;
3719 }
3720
3721 // Find the switch case corresponding to the value of the condition.
3722 // FIXME: Cache this lookup.
3723 const SwitchCase *Found = nullptr;
3724 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3725 SC = SC->getNextSwitchCase()) {
3726 if (isa<DefaultStmt>(SC)) {
3727 Found = SC;
3728 continue;
3729 }
3730
3731 const CaseStmt *CS = cast<CaseStmt>(SC);
3732 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3733 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3734 : LHS;
3735 if (LHS <= Value && Value <= RHS) {
3736 Found = SC;
3737 break;
3738 }
3739 }
3740
3741 if (!Found)
3742 return ESR_Succeeded;
3743
3744 // Search the switch body for the switch case and evaluate it from there.
3745 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3746 case ESR_Break:
3747 return ESR_Succeeded;
3748 case ESR_Succeeded:
3749 case ESR_Continue:
3750 case ESR_Failed:
3751 case ESR_Returned:
3752 return ESR;
3753 case ESR_CaseNotFound:
3754 // This can only happen if the switch case is nested within a statement
3755 // expression. We have no intention of supporting that.
3756 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3757 return ESR_Failed;
3758 }
3759 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 3759)
;
3760}
3761
3762// Evaluate a statement.
3763static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3764 const Stmt *S, const SwitchCase *Case) {
3765 if (!Info.nextStep(S))
3766 return ESR_Failed;
3767
3768 // If we're hunting down a 'case' or 'default' label, recurse through
3769 // substatements until we hit the label.
3770 if (Case) {
3771 // FIXME: We don't start the lifetime of objects whose initialization we
3772 // jump over. However, such objects must be of class type with a trivial
3773 // default constructor that initialize all subobjects, so must be empty,
3774 // so this almost never matters.
3775 switch (S->getStmtClass()) {
3776 case Stmt::CompoundStmtClass:
3777 // FIXME: Precompute which substatement of a compound statement we
3778 // would jump to, and go straight there rather than performing a
3779 // linear scan each time.
3780 case Stmt::LabelStmtClass:
3781 case Stmt::AttributedStmtClass:
3782 case Stmt::DoStmtClass:
3783 break;
3784
3785 case Stmt::CaseStmtClass:
3786 case Stmt::DefaultStmtClass:
3787 if (Case == S)
3788 Case = nullptr;
3789 break;
3790
3791 case Stmt::IfStmtClass: {
3792 // FIXME: Precompute which side of an 'if' we would jump to, and go
3793 // straight there rather than scanning both sides.
3794 const IfStmt *IS = cast<IfStmt>(S);
3795
3796 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3797 // preceded by our switch label.
3798 BlockScopeRAII Scope(Info);
3799
3800 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3801 if (ESR != ESR_CaseNotFound || !IS->getElse())
3802 return ESR;
3803 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3804 }
3805
3806 case Stmt::WhileStmtClass: {
3807 EvalStmtResult ESR =
3808 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3809 if (ESR != ESR_Continue)
3810 return ESR;
3811 break;
3812 }
3813
3814 case Stmt::ForStmtClass: {
3815 const ForStmt *FS = cast<ForStmt>(S);
3816 EvalStmtResult ESR =
3817 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3818 if (ESR != ESR_Continue)
3819 return ESR;
3820 if (FS->getInc()) {
3821 FullExpressionRAII IncScope(Info);
3822 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3823 return ESR_Failed;
3824 }
3825 break;
3826 }
3827
3828 case Stmt::DeclStmtClass:
3829 // FIXME: If the variable has initialization that can't be jumped over,
3830 // bail out of any immediately-surrounding compound-statement too.
3831 default:
3832 return ESR_CaseNotFound;
3833 }
3834 }
3835
3836 switch (S->getStmtClass()) {
3837 default:
3838 if (const Expr *E = dyn_cast<Expr>(S)) {
3839 // Don't bother evaluating beyond an expression-statement which couldn't
3840 // be evaluated.
3841 FullExpressionRAII Scope(Info);
3842 if (!EvaluateIgnoredValue(Info, E))
3843 return ESR_Failed;
3844 return ESR_Succeeded;
3845 }
3846
3847 Info.FFDiag(S->getLocStart());
3848 return ESR_Failed;
3849
3850 case Stmt::NullStmtClass:
3851 return ESR_Succeeded;
3852
3853 case Stmt::DeclStmtClass: {
3854 const DeclStmt *DS = cast<DeclStmt>(S);
3855 for (const auto *DclIt : DS->decls()) {
3856 // Each declaration initialization is its own full-expression.
3857 // FIXME: This isn't quite right; if we're performing aggregate
3858 // initialization, each braced subexpression is its own full-expression.
3859 FullExpressionRAII Scope(Info);
3860 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3861 return ESR_Failed;
3862 }
3863 return ESR_Succeeded;
3864 }
3865
3866 case Stmt::ReturnStmtClass: {
3867 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3868 FullExpressionRAII Scope(Info);
3869 if (RetExpr &&
3870 !(Result.Slot
3871 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3872 : Evaluate(Result.Value, Info, RetExpr)))
3873 return ESR_Failed;
3874 return ESR_Returned;
3875 }
3876
3877 case Stmt::CompoundStmtClass: {
3878 BlockScopeRAII Scope(Info);
3879
3880 const CompoundStmt *CS = cast<CompoundStmt>(S);
3881 for (const auto *BI : CS->body()) {
3882 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3883 if (ESR == ESR_Succeeded)
3884 Case = nullptr;
3885 else if (ESR != ESR_CaseNotFound)
3886 return ESR;
3887 }
3888 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3889 }
3890
3891 case Stmt::IfStmtClass: {
3892 const IfStmt *IS = cast<IfStmt>(S);
3893
3894 // Evaluate the condition, as either a var decl or as an expression.
3895 BlockScopeRAII Scope(Info);
3896 if (const Stmt *Init = IS->getInit()) {
3897 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3898 if (ESR != ESR_Succeeded)
3899 return ESR;
3900 }
3901 bool Cond;
3902 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3903 return ESR_Failed;
3904
3905 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3906 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3907 if (ESR != ESR_Succeeded)
3908 return ESR;
3909 }
3910 return ESR_Succeeded;
3911 }
3912
3913 case Stmt::WhileStmtClass: {
3914 const WhileStmt *WS = cast<WhileStmt>(S);
3915 while (true) {
3916 BlockScopeRAII Scope(Info);
3917 bool Continue;
3918 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3919 Continue))
3920 return ESR_Failed;
3921 if (!Continue)
3922 break;
3923
3924 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3925 if (ESR != ESR_Continue)
3926 return ESR;
3927 }
3928 return ESR_Succeeded;
3929 }
3930
3931 case Stmt::DoStmtClass: {
3932 const DoStmt *DS = cast<DoStmt>(S);
3933 bool Continue;
3934 do {
3935 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3936 if (ESR != ESR_Continue)
3937 return ESR;
3938 Case = nullptr;
3939
3940 FullExpressionRAII CondScope(Info);
3941 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3942 return ESR_Failed;
3943 } while (Continue);
3944 return ESR_Succeeded;
3945 }
3946
3947 case Stmt::ForStmtClass: {
3948 const ForStmt *FS = cast<ForStmt>(S);
3949 BlockScopeRAII Scope(Info);
3950 if (FS->getInit()) {
3951 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3952 if (ESR != ESR_Succeeded)
3953 return ESR;
3954 }
3955 while (true) {
3956 BlockScopeRAII Scope(Info);
3957 bool Continue = true;
3958 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3959 FS->getCond(), Continue))
3960 return ESR_Failed;
3961 if (!Continue)
3962 break;
3963
3964 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3965 if (ESR != ESR_Continue)
3966 return ESR;
3967
3968 if (FS->getInc()) {
3969 FullExpressionRAII IncScope(Info);
3970 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3971 return ESR_Failed;
3972 }
3973 }
3974 return ESR_Succeeded;
3975 }
3976
3977 case Stmt::CXXForRangeStmtClass: {
3978 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3979 BlockScopeRAII Scope(Info);
3980
3981 // Initialize the __range variable.
3982 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3983 if (ESR != ESR_Succeeded)
3984 return ESR;
3985
3986 // Create the __begin and __end iterators.
3987 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3988 if (ESR != ESR_Succeeded)
3989 return ESR;
3990 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
3991 if (ESR != ESR_Succeeded)
3992 return ESR;
3993
3994 while (true) {
3995 // Condition: __begin != __end.
3996 {
3997 bool Continue = true;
3998 FullExpressionRAII CondExpr(Info);
3999 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4000 return ESR_Failed;
4001 if (!Continue)
4002 break;
4003 }
4004
4005 // User's variable declaration, initialized by *__begin.
4006 BlockScopeRAII InnerScope(Info);
4007 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4008 if (ESR != ESR_Succeeded)
4009 return ESR;
4010
4011 // Loop body.
4012 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4013 if (ESR != ESR_Continue)
4014 return ESR;
4015
4016 // Increment: ++__begin
4017 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4018 return ESR_Failed;
4019 }
4020
4021 return ESR_Succeeded;
4022 }
4023
4024 case Stmt::SwitchStmtClass:
4025 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4026
4027 case Stmt::ContinueStmtClass:
4028 return ESR_Continue;
4029
4030 case Stmt::BreakStmtClass:
4031 return ESR_Break;
4032
4033 case Stmt::LabelStmtClass:
4034 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4035
4036 case Stmt::AttributedStmtClass:
4037 // As a general principle, C++11 attributes can be ignored without
4038 // any semantic impact.
4039 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4040 Case);
4041
4042 case Stmt::CaseStmtClass:
4043 case Stmt::DefaultStmtClass:
4044 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4045 }
4046}
4047
4048/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4049/// default constructor. If so, we'll fold it whether or not it's marked as
4050/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4051/// so we need special handling.
4052static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4053 const CXXConstructorDecl *CD,
4054 bool IsValueInitialization) {
4055 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4056 return false;
4057
4058 // Value-initialization does not call a trivial default constructor, so such a
4059 // call is a core constant expression whether or not the constructor is
4060 // constexpr.
4061 if (!CD->isConstexpr() && !IsValueInitialization) {
4062 if (Info.getLangOpts().CPlusPlus11) {
4063 // FIXME: If DiagDecl is an implicitly-declared special member function,
4064 // we should be much more explicit about why it's not constexpr.
4065 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4066 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4067 Info.Note(CD->getLocation(), diag::note_declared_at);
4068 } else {
4069 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4070 }
4071 }
4072 return true;
4073}
4074
4075/// CheckConstexprFunction - Check that a function can be called in a constant
4076/// expression.
4077static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4078 const FunctionDecl *Declaration,
4079 const FunctionDecl *Definition,
4080 const Stmt *Body) {
4081 // Potential constant expressions can contain calls to declared, but not yet
4082 // defined, constexpr functions.
4083 if (Info.checkingPotentialConstantExpression() && !Definition &&
4084 Declaration->isConstexpr())
4085 return false;
4086
4087 // Bail out with no diagnostic if the function declaration itself is invalid.
4088 // We will have produced a relevant diagnostic while parsing it.
4089 if (Declaration->isInvalidDecl())
4090 return false;
4091
4092 // Can we evaluate this function call?
4093 if (Definition && Definition->isConstexpr() &&
4094 !Definition->isInvalidDecl() && Body)
4095 return true;
4096
4097 if (Info.getLangOpts().CPlusPlus11) {
4098 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4099
4100 // If this function is not constexpr because it is an inherited
4101 // non-constexpr constructor, diagnose that directly.
4102 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4103 if (CD && CD->isInheritingConstructor()) {
4104 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4105 if (!Inherited->isConstexpr())
4106 DiagDecl = CD = Inherited;
4107 }
4108
4109 // FIXME: If DiagDecl is an implicitly-declared special member function
4110 // or an inheriting constructor, we should be much more explicit about why
4111 // it's not constexpr.
4112 if (CD && CD->isInheritingConstructor())
4113 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4114 << CD->getInheritedConstructor().getConstructor()->getParent();
4115 else
4116 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4117 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4118 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4119 } else {
4120 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4121 }
4122 return false;
4123}
4124
4125/// Determine if a class has any fields that might need to be copied by a
4126/// trivial copy or move operation.
4127static bool hasFields(const CXXRecordDecl *RD) {
4128 if (!RD || RD->isEmpty())
4129 return false;
4130 for (auto *FD : RD->fields()) {
4131 if (FD->isUnnamedBitfield())
4132 continue;
4133 return true;
4134 }
4135 for (auto &Base : RD->bases())
4136 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4137 return true;
4138 return false;
4139}
4140
4141namespace {
4142typedef SmallVector<APValue, 8> ArgVector;
4143}
4144
4145/// EvaluateArgs - Evaluate the arguments to a function call.
4146static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4147 EvalInfo &Info) {
4148 bool Success = true;
4149 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4150 I != E; ++I) {
4151 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4152 // If we're checking for a potential constant expression, evaluate all
4153 // initializers even if some of them fail.
4154 if (!Info.noteFailure())
4155 return false;
4156 Success = false;
4157 }
4158 }
4159 return Success;
4160}
4161
4162/// Evaluate a function call.
4163static bool HandleFunctionCall(SourceLocation CallLoc,
4164 const FunctionDecl *Callee, const LValue *This,
4165 ArrayRef<const Expr*> Args, const Stmt *Body,
4166 EvalInfo &Info, APValue &Result,
4167 const LValue *ResultSlot) {
4168 ArgVector ArgValues(Args.size());
4169 if (!EvaluateArgs(Args, ArgValues, Info))
4170 return false;
4171
4172 if (!Info.CheckCallLimit(CallLoc))
4173 return false;
4174
4175 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4176
4177 // For a trivial copy or move assignment, perform an APValue copy. This is
4178 // essential for unions, where the operations performed by the assignment
4179 // operator cannot be represented as statements.
4180 //
4181 // Skip this for non-union classes with no fields; in that case, the defaulted
4182 // copy/move does not actually read the object.
4183 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4184 if (MD && MD->isDefaulted() &&
4185 (MD->getParent()->isUnion() ||
4186 (MD->isTrivial() && hasFields(MD->getParent())))) {
4187 assert(This &&((This && (MD->isCopyAssignmentOperator() || MD->
isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4188, __PRETTY_FUNCTION__))
4188 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))((This && (MD->isCopyAssignmentOperator() || MD->
isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4188, __PRETTY_FUNCTION__))
;
4189 LValue RHS;
4190 RHS.setFrom(Info.Ctx, ArgValues[0]);
4191 APValue RHSValue;
4192 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4193 RHS, RHSValue))
4194 return false;
4195 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4196 RHSValue))
4197 return false;
4198 This->moveInto(Result);
4199 return true;
4200 } else if (MD && isLambdaCallOperator(MD)) {
4201 // We're in a lambda; determine the lambda capture field maps.
4202 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4203 Frame.LambdaThisCaptureField);
4204 }
4205
4206 StmtResult Ret = {Result, ResultSlot};
4207 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4208 if (ESR == ESR_Succeeded) {
4209 if (Callee->getReturnType()->isVoidType())
4210 return true;
4211 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4212 }
4213 return ESR == ESR_Returned;
4214}
4215
4216/// Evaluate a constructor call.
4217static bool HandleConstructorCall(const Expr *E, const LValue &This,
4218 APValue *ArgValues,
4219 const CXXConstructorDecl *Definition,
4220 EvalInfo &Info, APValue &Result) {
4221 SourceLocation CallLoc = E->getExprLoc();
4222 if (!Info.CheckCallLimit(CallLoc))
4223 return false;
4224
4225 const CXXRecordDecl *RD = Definition->getParent();
4226 if (RD->getNumVBases()) {
4227 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4228 return false;
4229 }
4230
4231 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4232
4233 // FIXME: Creating an APValue just to hold a nonexistent return value is
4234 // wasteful.
4235 APValue RetVal;
4236 StmtResult Ret = {RetVal, nullptr};
4237
4238 // If it's a delegating constructor, delegate.
4239 if (Definition->isDelegatingConstructor()) {
4240 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4241 {
4242 FullExpressionRAII InitScope(Info);
4243 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4244 return false;
4245 }
4246 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4247 }
4248
4249 // For a trivial copy or move constructor, perform an APValue copy. This is
4250 // essential for unions (or classes with anonymous union members), where the
4251 // operations performed by the constructor cannot be represented by
4252 // ctor-initializers.
4253 //
4254 // Skip this for empty non-union classes; we should not perform an
4255 // lvalue-to-rvalue conversion on them because their copy constructor does not
4256 // actually read them.
4257 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4258 (Definition->getParent()->isUnion() ||
4259 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4260 LValue RHS;
4261 RHS.setFrom(Info.Ctx, ArgValues[0]);
4262 return handleLValueToRValueConversion(
4263 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4264 RHS, Result);
4265 }
4266
4267 // Reserve space for the struct members.
4268 if (!RD->isUnion() && Result.isUninit())
4269 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4270 std::distance(RD->field_begin(), RD->field_end()));
4271
4272 if (RD->isInvalidDecl()) return false;
4273 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4274
4275 // A scope for temporaries lifetime-extended by reference members.
4276 BlockScopeRAII LifetimeExtendedScope(Info);
4277
4278 bool Success = true;
4279 unsigned BasesSeen = 0;
4280#ifndef NDEBUG
4281 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4282#endif
4283 for (const auto *I : Definition->inits()) {
4284 LValue Subobject = This;
4285 APValue *Value = &Result;
4286
4287 // Determine the subobject to initialize.
4288 FieldDecl *FD = nullptr;
4289 if (I->isBaseInitializer()) {
4290 QualType BaseType(I->getBaseClass(), 0);
4291#ifndef NDEBUG
4292 // Non-virtual base classes are initialized in the order in the class
4293 // definition. We have already checked for virtual base classes.
4294 assert(!BaseIt->isVirtual() && "virtual base for literal type")((!BaseIt->isVirtual() && "virtual base for literal type"
) ? static_cast<void> (0) : __assert_fail ("!BaseIt->isVirtual() && \"virtual base for literal type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4294, __PRETTY_FUNCTION__))
;
4295 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&((Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
"base class initializers not in expected order") ? static_cast
<void> (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4296, __PRETTY_FUNCTION__))
4296 "base class initializers not in expected order")((Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
"base class initializers not in expected order") ? static_cast
<void> (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4296, __PRETTY_FUNCTION__))
;
4297 ++BaseIt;
4298#endif
4299 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4300 BaseType->getAsCXXRecordDecl(), &Layout))
4301 return false;
4302 Value = &Result.getStructBase(BasesSeen++);
4303 } else if ((FD = I->getMember())) {
4304 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4305 return false;
4306 if (RD->isUnion()) {
4307 Result = APValue(FD);
4308 Value = &Result.getUnionValue();
4309 } else {
4310 Value = &Result.getStructField(FD->getFieldIndex());
4311 }
4312 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4313 // Walk the indirect field decl's chain to find the object to initialize,
4314 // and make sure we've initialized every step along it.
4315 for (auto *C : IFD->chain()) {
4316 FD = cast<FieldDecl>(C);
4317 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4318 // Switch the union field if it differs. This happens if we had
4319 // preceding zero-initialization, and we're now initializing a union
4320 // subobject other than the first.
4321 // FIXME: In this case, the values of the other subobjects are
4322 // specified, since zero-initialization sets all padding bits to zero.
4323 if (Value->isUninit() ||
4324 (Value->isUnion() && Value->getUnionField() != FD)) {
4325 if (CD->isUnion())
4326 *Value = APValue(FD);
4327 else
4328 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4329 std::distance(CD->field_begin(), CD->field_end()));
4330 }
4331 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4332 return false;
4333 if (CD->isUnion())
4334 Value = &Value->getUnionValue();
4335 else
4336 Value = &Value->getStructField(FD->getFieldIndex());
4337 }
4338 } else {
4339 llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4339)
;
4340 }
4341
4342 FullExpressionRAII InitScope(Info);
4343 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4344 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4345 *Value, FD))) {
4346 // If we're checking for a potential constant expression, evaluate all
4347 // initializers even if some of them fail.
4348 if (!Info.noteFailure())
4349 return false;
4350 Success = false;
4351 }
4352 }
4353
4354 return Success &&
4355 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4356}
4357
4358static bool HandleConstructorCall(const Expr *E, const LValue &This,
4359 ArrayRef<const Expr*> Args,
4360 const CXXConstructorDecl *Definition,
4361 EvalInfo &Info, APValue &Result) {
4362 ArgVector ArgValues(Args.size());
4363 if (!EvaluateArgs(Args, ArgValues, Info))
4364 return false;
4365
4366 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4367 Info, Result);
4368}
4369
4370//===----------------------------------------------------------------------===//
4371// Generic Evaluation
4372//===----------------------------------------------------------------------===//
4373namespace {
4374
4375template <class Derived>
4376class ExprEvaluatorBase
4377 : public ConstStmtVisitor<Derived, bool> {
4378private:
4379 Derived &getDerived() { return static_cast<Derived&>(*this); }
4380 bool DerivedSuccess(const APValue &V, const Expr *E) {
4381 return getDerived().Success(V, E);
4382 }
4383 bool DerivedZeroInitialization(const Expr *E) {
4384 return getDerived().ZeroInitialization(E);
4385 }
4386
4387 // Check whether a conditional operator with a non-constant condition is a
4388 // potential constant expression. If neither arm is a potential constant
4389 // expression, then the conditional operator is not either.
4390 template<typename ConditionalOperator>
4391 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4392 assert(Info.checkingPotentialConstantExpression())((Info.checkingPotentialConstantExpression()) ? static_cast<
void> (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4392, __PRETTY_FUNCTION__))
;
4393
4394 // Speculatively evaluate both arms.
4395 SmallVector<PartialDiagnosticAt, 8> Diag;
4396 {
4397 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4398 StmtVisitorTy::Visit(E->getFalseExpr());
4399 if (Diag.empty())
4400 return;
4401 }
4402
4403 {
4404 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4405 Diag.clear();
4406 StmtVisitorTy::Visit(E->getTrueExpr());
4407 if (Diag.empty())
4408 return;
4409 }
4410
4411 Error(E, diag::note_constexpr_conditional_never_const);
4412 }
4413
4414
4415 template<typename ConditionalOperator>
4416 bool HandleConditionalOperator(const ConditionalOperator *E) {
4417 bool BoolResult;
4418 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4419 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
4420 CheckPotentialConstantConditional(E);
4421 return false;
4422 }
4423
4424 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4425 return StmtVisitorTy::Visit(EvalExpr);
4426 }
4427
4428protected:
4429 EvalInfo &Info;
4430 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4431 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4432
4433 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4434 return Info.CCEDiag(E, D);
4435 }
4436
4437 bool ZeroInitialization(const Expr *E) { return Error(E); }
4438
4439public:
4440 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4441
4442 EvalInfo &getEvalInfo() { return Info; }
4443
4444 /// Report an evaluation error. This should only be called when an error is
4445 /// first discovered. When propagating an error, just return false.
4446 bool Error(const Expr *E, diag::kind D) {
4447 Info.FFDiag(E, D);
4448 return false;
4449 }
4450 bool Error(const Expr *E) {
4451 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4452 }
4453
4454 bool VisitStmt(const Stmt *) {
4455 llvm_unreachable("Expression evaluator should not be called on stmts")::llvm::llvm_unreachable_internal("Expression evaluator should not be called on stmts"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4455)
;
4456 }
4457 bool VisitExpr(const Expr *E) {
4458 return Error(E);
4459 }
4460
4461 bool VisitParenExpr(const ParenExpr *E)
4462 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4463 bool VisitUnaryExtension(const UnaryOperator *E)
4464 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4465 bool VisitUnaryPlus(const UnaryOperator *E)
4466 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4467 bool VisitChooseExpr(const ChooseExpr *E)
4468 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4469 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4470 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4471 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4472 { return StmtVisitorTy::Visit(E->getReplacement()); }
4473 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4474 { return StmtVisitorTy::Visit(E->getExpr()); }
4475 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4476 // The initializer may not have been parsed yet, or might be erroneous.
4477 if (!E->getExpr())
4478 return Error(E);
4479 return StmtVisitorTy::Visit(E->getExpr());
4480 }
4481 // We cannot create any objects for which cleanups are required, so there is
4482 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4483 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4484 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4485
4486 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4487 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4488 return static_cast<Derived*>(this)->VisitCastExpr(E);
4489 }
4490 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4491 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4492 return static_cast<Derived*>(this)->VisitCastExpr(E);
4493 }
4494
4495 bool VisitBinaryOperator(const BinaryOperator *E) {
4496 switch (E->getOpcode()) {
4497 default:
4498 return Error(E);
4499
4500 case BO_Comma:
4501 VisitIgnoredValue(E->getLHS());
4502 return StmtVisitorTy::Visit(E->getRHS());
4503
4504 case BO_PtrMemD:
4505 case BO_PtrMemI: {
4506 LValue Obj;
4507 if (!HandleMemberPointerAccess(Info, E, Obj))
4508 return false;
4509 APValue Result;
4510 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4511 return false;
4512 return DerivedSuccess(Result, E);
4513 }
4514 }
4515 }
4516
4517 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4518 // Evaluate and cache the common expression. We treat it as a temporary,
4519 // even though it's not quite the same thing.
4520 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4521 Info, E->getCommon()))
4522 return false;
4523
4524 return HandleConditionalOperator(E);
4525 }
4526
4527 bool VisitConditionalOperator(const ConditionalOperator *E) {
4528 bool IsBcpCall = false;
4529 // If the condition (ignoring parens) is a __builtin_constant_p call,
4530 // the result is a constant expression if it can be folded without
4531 // side-effects. This is an important GNU extension. See GCC PR38377
4532 // for discussion.
4533 if (const CallExpr *CallCE =
4534 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4535 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4536 IsBcpCall = true;
4537
4538 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4539 // constant expression; we can't check whether it's potentially foldable.
4540 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4541 return false;
4542
4543 FoldConstant Fold(Info, IsBcpCall);
4544 if (!HandleConditionalOperator(E)) {
4545 Fold.keepDiagnostics();
4546 return false;
4547 }
4548
4549 return true;
4550 }
4551
4552 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4553 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4554 return DerivedSuccess(*Value, E);
4555
4556 const Expr *Source = E->getSourceExpr();
4557 if (!Source)
4558 return Error(E);
4559 if (Source == E) { // sanity checking.
4560 assert(0 && "OpaqueValueExpr recursively refers to itself")((0 && "OpaqueValueExpr recursively refers to itself"
) ? static_cast<void> (0) : __assert_fail ("0 && \"OpaqueValueExpr recursively refers to itself\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4560, __PRETTY_FUNCTION__))
;
4561 return Error(E);
4562 }
4563 return StmtVisitorTy::Visit(Source);
4564 }
4565
4566 bool VisitCallExpr(const CallExpr *E) {
4567 APValue Result;
4568 if (!handleCallExpr(E, Result, nullptr))
4569 return false;
4570 return DerivedSuccess(Result, E);
4571 }
4572
4573 bool handleCallExpr(const CallExpr *E, APValue &Result,
4574 const LValue *ResultSlot) {
4575 const Expr *Callee = E->getCallee()->IgnoreParens();
4576 QualType CalleeType = Callee->getType();
4577
4578 const FunctionDecl *FD = nullptr;
4579 LValue *This = nullptr, ThisVal;
4580 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4581 bool HasQualifier = false;
4582
4583 // Extract function decl and 'this' pointer from the callee.
4584 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4585 const ValueDecl *Member = nullptr;
4586 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4587 // Explicit bound member calls, such as x.f() or p->g();
4588 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4589 return false;
4590 Member = ME->getMemberDecl();
4591 This = &ThisVal;
4592 HasQualifier = ME->hasQualifier();
4593 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4594 // Indirect bound member calls ('.*' or '->*').
4595 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4596 if (!Member) return false;
4597 This = &ThisVal;
4598 } else
4599 return Error(Callee);
4600
4601 FD = dyn_cast<FunctionDecl>(Member);
4602 if (!FD)
4603 return Error(Callee);
4604 } else if (CalleeType->isFunctionPointerType()) {
4605 LValue Call;
4606 if (!EvaluatePointer(Callee, Call, Info))
4607 return false;
4608
4609 if (!Call.getLValueOffset().isZero())
4610 return Error(Callee);
4611 FD = dyn_cast_or_null<FunctionDecl>(
4612 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4613 if (!FD)
4614 return Error(Callee);
4615 // Don't call function pointers which have been cast to some other type.
4616 // Per DR (no number yet), the caller and callee can differ in noexcept.
4617 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4618 CalleeType->getPointeeType(), FD->getType())) {
4619 return Error(E);
4620 }
4621
4622 // Overloaded operator calls to member functions are represented as normal
4623 // calls with '*this' as the first argument.
4624 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4625 if (MD && !MD->isStatic()) {
4626 // FIXME: When selecting an implicit conversion for an overloaded
4627 // operator delete, we sometimes try to evaluate calls to conversion
4628 // operators without a 'this' parameter!
4629 if (Args.empty())
4630 return Error(E);
4631
4632 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4633 return false;
4634 This = &ThisVal;
4635 Args = Args.slice(1);
4636 } else if (MD && MD->isLambdaStaticInvoker()) {
4637 // Map the static invoker for the lambda back to the call operator.
4638 // Conveniently, we don't have to slice out the 'this' argument (as is
4639 // being done for the non-static case), since a static member function
4640 // doesn't have an implicit argument passed in.
4641 const CXXRecordDecl *ClosureClass = MD->getParent();
4642 assert(((ClosureClass->captures_begin() == ClosureClass->captures_end
() && "Number of captures must be zero for conversion to function-ptr"
) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4644, __PRETTY_FUNCTION__))
4643 ClosureClass->captures_begin() == ClosureClass->captures_end() &&((ClosureClass->captures_begin() == ClosureClass->captures_end
() && "Number of captures must be zero for conversion to function-ptr"
) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4644, __PRETTY_FUNCTION__))
4644 "Number of captures must be zero for conversion to function-ptr")((ClosureClass->captures_begin() == ClosureClass->captures_end
() && "Number of captures must be zero for conversion to function-ptr"
) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4644, __PRETTY_FUNCTION__))
;
4645
4646 const CXXMethodDecl *LambdaCallOp =
4647 ClosureClass->getLambdaCallOperator();
4648
4649 // Set 'FD', the function that will be called below, to the call
4650 // operator. If the closure object represents a generic lambda, find
4651 // the corresponding specialization of the call operator.
4652
4653 if (ClosureClass->isGenericLambda()) {
4654 assert(MD->isFunctionTemplateSpecialization() &&((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a "
"template specialization") ? static_cast<void> (0) : __assert_fail
("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4656, __PRETTY_FUNCTION__))
4655 "A generic lambda's static-invoker function must be a "((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a "
"template specialization") ? static_cast<void> (0) : __assert_fail
("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4656, __PRETTY_FUNCTION__))
4656 "template specialization")((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a "
"template specialization") ? static_cast<void> (0) : __assert_fail
("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4656, __PRETTY_FUNCTION__))
;
4657 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4658 FunctionTemplateDecl *CallOpTemplate =
4659 LambdaCallOp->getDescribedFunctionTemplate();
4660 void *InsertPos = nullptr;
4661 FunctionDecl *CorrespondingCallOpSpecialization =
4662 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4663 assert(CorrespondingCallOpSpecialization &&((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? static_cast
<void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4665, __PRETTY_FUNCTION__))
4664 "We must always have a function call operator specialization "((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? static_cast
<void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4665, __PRETTY_FUNCTION__))
4665 "that corresponds to our static invoker specialization")((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization "
"that corresponds to our static invoker specialization") ? static_cast
<void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4665, __PRETTY_FUNCTION__))
;
4666 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4667 } else
4668 FD = LambdaCallOp;
4669 }
4670
4671
4672 } else
4673 return Error(E);
4674
4675 if (This && !This->checkSubobject(Info, E, CSK_This))
4676 return false;
4677
4678 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4679 // calls to such functions in constant expressions.
4680 if (This && !HasQualifier &&
4681 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4682 return Error(E, diag::note_constexpr_virtual_call);
4683
4684 const FunctionDecl *Definition = nullptr;
4685 Stmt *Body = FD->getBody(Definition);
4686
4687 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4688 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4689 Result, ResultSlot))
4690 return false;
4691
4692 return true;
4693 }
4694
4695 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4696 return StmtVisitorTy::Visit(E->getInitializer());
4697 }
4698 bool VisitInitListExpr(const InitListExpr *E) {
4699 if (E->getNumInits() == 0)
4700 return DerivedZeroInitialization(E);
4701 if (E->getNumInits() == 1)
4702 return StmtVisitorTy::Visit(E->getInit(0));
4703 return Error(E);
4704 }
4705 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4706 return DerivedZeroInitialization(E);
4707 }
4708 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4709 return DerivedZeroInitialization(E);
4710 }
4711 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4712 return DerivedZeroInitialization(E);
4713 }
4714
4715 /// A member expression where the object is a prvalue is itself a prvalue.
4716 bool VisitMemberExpr(const MemberExpr *E) {
4717 assert(!E->isArrow() && "missing call to bound member function?")((!E->isArrow() && "missing call to bound member function?"
) ? static_cast<void> (0) : __assert_fail ("!E->isArrow() && \"missing call to bound member function?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4717, __PRETTY_FUNCTION__))
;
4718
4719 APValue Val;
4720 if (!Evaluate(Val, Info, E->getBase()))
4721 return false;
4722
4723 QualType BaseTy = E->getBase()->getType();
4724
4725 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4726 if (!FD) return Error(E);
4727 assert(!FD->getType()->isReferenceType() && "prvalue reference?")((!FD->getType()->isReferenceType() && "prvalue reference?"
) ? static_cast<void> (0) : __assert_fail ("!FD->getType()->isReferenceType() && \"prvalue reference?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4727, __PRETTY_FUNCTION__))
;
4728 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==((BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl
() == FD->getParent()->getCanonicalDecl() && "record / field mismatch"
) ? static_cast<void> (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4729, __PRETTY_FUNCTION__))
4729 FD->getParent()->getCanonicalDecl() && "record / field mismatch")((BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl
() == FD->getParent()->getCanonicalDecl() && "record / field mismatch"
) ? static_cast<void> (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4729, __PRETTY_FUNCTION__))
;
4730
4731 CompleteObject Obj(&Val, BaseTy);
4732 SubobjectDesignator Designator(BaseTy);
4733 Designator.addDeclUnchecked(FD);
4734
4735 APValue Result;
4736 return extractSubobject(Info, E, Obj, Designator, Result) &&
4737 DerivedSuccess(Result, E);
4738 }
4739
4740 bool VisitCastExpr(const CastExpr *E) {
4741 switch (E->getCastKind()) {
4742 default:
4743 break;
4744
4745 case CK_AtomicToNonAtomic: {
4746 APValue AtomicVal;
4747 // This does not need to be done in place even for class/array types:
4748 // atomic-to-non-atomic conversion implies copying the object
4749 // representation.
4750 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4751 return false;
4752 return DerivedSuccess(AtomicVal, E);
4753 }
4754
4755 case CK_NoOp:
4756 case CK_UserDefinedConversion:
4757 return StmtVisitorTy::Visit(E->getSubExpr());
4758
4759 case CK_LValueToRValue: {
4760 LValue LVal;
4761 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4762 return false;
4763 APValue RVal;
4764 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4765 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4766 LVal, RVal))
4767 return false;
4768 return DerivedSuccess(RVal, E);
4769 }
4770 }
4771
4772 return Error(E);
4773 }
4774
4775 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4776 return VisitUnaryPostIncDec(UO);
4777 }
4778 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4779 return VisitUnaryPostIncDec(UO);
4780 }
4781 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4782 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4783 return Error(UO);
4784
4785 LValue LVal;
4786 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4787 return false;
4788 APValue RVal;
4789 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4790 UO->isIncrementOp(), &RVal))
4791 return false;
4792 return DerivedSuccess(RVal, UO);
4793 }
4794
4795 bool VisitStmtExpr(const StmtExpr *E) {
4796 // We will have checked the full-expressions inside the statement expression
4797 // when they were completed, and don't need to check them again now.
4798 if (Info.checkingForOverflow())
4799 return Error(E);
4800
4801 BlockScopeRAII Scope(Info);
4802 const CompoundStmt *CS = E->getSubStmt();
4803 if (CS->body_empty())
4804 return true;
4805
4806 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4807 BE = CS->body_end();
4808 /**/; ++BI) {
4809 if (BI + 1 == BE) {
4810 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4811 if (!FinalExpr) {
4812 Info.FFDiag((*BI)->getLocStart(),
4813 diag::note_constexpr_stmt_expr_unsupported);
4814 return false;
4815 }
4816 return this->Visit(FinalExpr);
4817 }
4818
4819 APValue ReturnValue;
4820 StmtResult Result = { ReturnValue, nullptr };
4821 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4822 if (ESR != ESR_Succeeded) {
4823 // FIXME: If the statement-expression terminated due to 'return',
4824 // 'break', or 'continue', it would be nice to propagate that to
4825 // the outer statement evaluation rather than bailing out.
4826 if (ESR != ESR_Failed)
4827 Info.FFDiag((*BI)->getLocStart(),
4828 diag::note_constexpr_stmt_expr_unsupported);
4829 return false;
4830 }
4831 }
4832
4833 llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above."
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4833)
;
4834 }
4835
4836 /// Visit a value which is evaluated, but whose value is ignored.
4837 void VisitIgnoredValue(const Expr *E) {
4838 EvaluateIgnoredValue(Info, E);
4839 }
4840
4841 /// Potentially visit a MemberExpr's base expression.
4842 void VisitIgnoredBaseExpression(const Expr *E) {
4843 // While MSVC doesn't evaluate the base expression, it does diagnose the
4844 // presence of side-effecting behavior.
4845 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4846 return;
4847 VisitIgnoredValue(E);
4848 }
4849};
4850
4851}
4852
4853//===----------------------------------------------------------------------===//
4854// Common base class for lvalue and temporary evaluation.
4855//===----------------------------------------------------------------------===//
4856namespace {
4857template<class Derived>
4858class LValueExprEvaluatorBase
4859 : public ExprEvaluatorBase<Derived> {
4860protected:
4861 LValue &Result;
4862 bool InvalidBaseOK;
4863 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4864 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4865
4866 bool Success(APValue::LValueBase B) {
4867 Result.set(B);
4868 return true;
4869 }
4870
4871 bool evaluatePointer(const Expr *E, LValue &Result) {
4872 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4873 }
4874
4875public:
4876 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4877 : ExprEvaluatorBaseTy(Info), Result(Result),
4878 InvalidBaseOK(InvalidBaseOK) {}
4879
4880 bool Success(const APValue &V, const Expr *E) {
4881 Result.setFrom(this->Info.Ctx, V);
4882 return true;
4883 }
4884
4885 bool VisitMemberExpr(const MemberExpr *E) {
4886 // Handle non-static data members.
4887 QualType BaseTy;
4888 bool EvalOK;
4889 if (E->isArrow()) {
4890 EvalOK = evaluatePointer(E->getBase(), Result);
4891 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4892 } else if (E->getBase()->isRValue()) {
4893 assert(E->getBase()->getType()->isRecordType())((E->getBase()->getType()->isRecordType()) ? static_cast
<void> (0) : __assert_fail ("E->getBase()->getType()->isRecordType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4893, __PRETTY_FUNCTION__))
;
4894 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4895 BaseTy = E->getBase()->getType();
4896 } else {
4897 EvalOK = this->Visit(E->getBase());
4898 BaseTy = E->getBase()->getType();
4899 }
4900 if (!EvalOK) {
4901 if (!InvalidBaseOK)
4902 return false;
4903 Result.setInvalid(E);
4904 return true;
4905 }
4906
4907 const ValueDecl *MD = E->getMemberDecl();
4908 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4909 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==((BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl
() == FD->getParent()->getCanonicalDecl() && "record / field mismatch"
) ? static_cast<void> (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4910, __PRETTY_FUNCTION__))
4910 FD->getParent()->getCanonicalDecl() && "record / field mismatch")((BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl
() == FD->getParent()->getCanonicalDecl() && "record / field mismatch"
) ? static_cast<void> (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 4910, __PRETTY_FUNCTION__))
;
4911 (void)BaseTy;
4912 if (!HandleLValueMember(this->Info, E, Result, FD))
4913 return false;
4914 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4915 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4916 return false;
4917 } else
4918 return this->Error(E);
4919
4920 if (MD->getType()->isReferenceType()) {
4921 APValue RefValue;
4922 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4923 RefValue))
4924 return false;
4925 return Success(RefValue, E);
4926 }
4927 return true;
4928 }
4929
4930 bool VisitBinaryOperator(const BinaryOperator *E) {
4931 switch (E->getOpcode()) {
4932 default:
4933 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4934
4935 case BO_PtrMemD:
4936 case BO_PtrMemI:
4937 return HandleMemberPointerAccess(this->Info, E, Result);
4938 }
4939 }
4940
4941 bool VisitCastExpr(const CastExpr *E) {
4942 switch (E->getCastKind()) {
4943 default:
4944 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4945
4946 case CK_DerivedToBase:
4947 case CK_UncheckedDerivedToBase:
4948 if (!this->Visit(E->getSubExpr()))
4949 return false;
4950
4951 // Now figure out the necessary offset to add to the base LV to get from
4952 // the derived class to the base class.
4953 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4954 Result);
4955 }
4956 }
4957};
4958}
4959
4960//===----------------------------------------------------------------------===//
4961// LValue Evaluation
4962//
4963// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4964// function designators (in C), decl references to void objects (in C), and
4965// temporaries (if building with -Wno-address-of-temporary).
4966//
4967// LValue evaluation produces values comprising a base expression of one of the
4968// following types:
4969// - Declarations
4970// * VarDecl
4971// * FunctionDecl
4972// - Literals
4973// * CompoundLiteralExpr in C (and in global scope in C++)
4974// * StringLiteral
4975// * CXXTypeidExpr
4976// * PredefinedExpr
4977// * ObjCStringLiteralExpr
4978// * ObjCEncodeExpr
4979// * AddrLabelExpr
4980// * BlockExpr
4981// * CallExpr for a MakeStringConstant builtin
4982// - Locals and temporaries
4983// * MaterializeTemporaryExpr
4984// * Any Expr, with a CallIndex indicating the function in which the temporary
4985// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4986// from the AST (FIXME).
4987// * A MaterializeTemporaryExpr that has static storage duration, with no
4988// CallIndex, for a lifetime-extended temporary.
4989// plus an offset in bytes.
4990//===----------------------------------------------------------------------===//
4991namespace {
4992class LValueExprEvaluator
4993 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4994public:
4995 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
4996 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
4997
4998 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4999 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5000
5001 bool VisitDeclRefExpr(const DeclRefExpr *E);
5002 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5003 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5004 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5005 bool VisitMemberExpr(const MemberExpr *E);
5006 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5007 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5008 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5009 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5010 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5011 bool VisitUnaryDeref(const UnaryOperator *E);
5012 bool VisitUnaryReal(const UnaryOperator *E);
5013 bool VisitUnaryImag(const UnaryOperator *E);
5014 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5015 return VisitUnaryPreIncDec(UO);
5016 }
5017 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5018 return VisitUnaryPreIncDec(UO);
5019 }
5020 bool VisitBinAssign(const BinaryOperator *BO);
5021 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5022
5023 bool VisitCastExpr(const CastExpr *E) {
5024 switch (E->getCastKind()) {
5025 default:
5026 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5027
5028 case CK_LValueBitCast:
5029 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5030 if (!Visit(E->getSubExpr()))
5031 return false;
5032 Result.Designator.setInvalid();
5033 return true;
5034
5035 case CK_BaseToDerived:
5036 if (!Visit(E->getSubExpr()))
5037 return false;
5038 return HandleBaseToDerivedCast(Info, E, Result);
5039 }
5040 }
5041};
5042} // end anonymous namespace
5043
5044/// Evaluate an expression as an lvalue. This can be legitimately called on
5045/// expressions which are not glvalues, in three cases:
5046/// * function designators in C, and
5047/// * "extern void" objects
5048/// * @selector() expressions in Objective-C
5049static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5050 bool InvalidBaseOK) {
5051 assert(E->isGLValue() || E->getType()->isFunctionType() ||((E->isGLValue() || E->getType()->isFunctionType() ||
E->getType()->isVoidType() || isa<ObjCSelectorExpr>
(E)) ? static_cast<void> (0) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5052, __PRETTY_FUNCTION__))
5052 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E))((E->isGLValue() || E->getType()->isFunctionType() ||
E->getType()->isVoidType() || isa<ObjCSelectorExpr>
(E)) ? static_cast<void> (0) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5052, __PRETTY_FUNCTION__))
;
5053 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5054}
5055
5056bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5057 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5058 return Success(FD);
5059 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5060 return VisitVarDecl(E, VD);
5061 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5062 return Visit(BD->getBinding());
5063 return Error(E);
5064}
5065
5066
5067bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5068
5069 // If we are within a lambda's call operator, check whether the 'VD' referred
5070 // to within 'E' actually represents a lambda-capture that maps to a
5071 // data-member/field within the closure object, and if so, evaluate to the
5072 // field or what the field refers to.
5073 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5074 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5075 if (Info.checkingPotentialConstantExpression())
5076 return false;
5077 // Start with 'Result' referring to the complete closure object...
5078 Result = *Info.CurrentCall->This;
5079 // ... then update it to refer to the field of the closure object
5080 // that represents the capture.
5081 if (!HandleLValueMember(Info, E, Result, FD))
5082 return false;
5083 // And if the field is of reference type, update 'Result' to refer to what
5084 // the field refers to.
5085 if (FD->getType()->isReferenceType()) {
5086 APValue RVal;
5087 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5088 RVal))
5089 return false;
5090 Result.setFrom(Info.Ctx, RVal);
5091 }
5092 return true;
5093 }
5094 }
5095 CallStackFrame *Frame = nullptr;
5096 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5097 // Only if a local variable was declared in the function currently being
5098 // evaluated, do we expect to be able to find its value in the current
5099 // frame. (Otherwise it was likely declared in an enclosing context and
5100 // could either have a valid evaluatable value (for e.g. a constexpr
5101 // variable) or be ill-formed (and trigger an appropriate evaluation
5102 // diagnostic)).
5103 if (Info.CurrentCall->Callee &&
5104 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5105 Frame = Info.CurrentCall;
5106 }
5107 }
5108
5109 if (!VD->getType()->isReferenceType()) {
5110 if (Frame) {
5111 Result.set(VD, Frame->Index);
5112 return true;
5113 }
5114 return Success(VD);
5115 }
5116
5117 APValue *V;
5118 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5119 return false;
5120 if (V->isUninit()) {
5121 if (!Info.checkingPotentialConstantExpression())
5122 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5123 return false;
5124 }
5125 return Success(*V, E);
5126}
5127
5128bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5129 const MaterializeTemporaryExpr *E) {
5130 // Walk through the expression to find the materialized temporary itself.
5131 SmallVector<const Expr *, 2> CommaLHSs;
5132 SmallVector<SubobjectAdjustment, 2> Adjustments;
5133 const Expr *Inner = E->GetTemporaryExpr()->
5134 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5135
5136 // If we passed any comma operators, evaluate their LHSs.
5137 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5138 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5139 return false;
5140
5141 // A materialized temporary with static storage duration can appear within the
5142 // result of a constant expression evaluation, so we need to preserve its
5143 // value for use outside this evaluation.
5144 APValue *Value;
5145 if (E->getStorageDuration() == SD_Static) {
5146 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5147 *Value = APValue();
5148 Result.set(E);
5149 } else {
5150 Value = &Info.CurrentCall->
5151 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5152 Result.set(E, Info.CurrentCall->Index);
5153 }
5154
5155 QualType Type = Inner->getType();
5156
5157 // Materialize the temporary itself.
5158 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5159 (E->getStorageDuration() == SD_Static &&
5160 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5161 *Value = APValue();
5162 return false;
5163 }
5164
5165 // Adjust our lvalue to refer to the desired subobject.
5166 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5167 --I;
5168 switch (Adjustments[I].Kind) {
5169 case SubobjectAdjustment::DerivedToBaseAdjustment:
5170 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5171 Type, Result))
5172 return false;
5173 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5174 break;
5175
5176 case SubobjectAdjustment::FieldAdjustment:
5177 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5178 return false;
5179 Type = Adjustments[I].Field->getType();
5180 break;
5181
5182 case SubobjectAdjustment::MemberPointerAdjustment:
5183 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5184 Adjustments[I].Ptr.RHS))
5185 return false;
5186 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5187 break;
5188 }
5189 }
5190
5191 return true;
5192}
5193
5194bool
5195LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5196 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&(((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
"lvalue compound literal in c++?") ? static_cast<void>
(0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5197, __PRETTY_FUNCTION__))
5197 "lvalue compound literal in c++?")(((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
"lvalue compound literal in c++?") ? static_cast<void>
(0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5197, __PRETTY_FUNCTION__))
;
5198 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5199 // only see this when folding in C, so there's no standard to follow here.
5200 return Success(E);
5201}
5202
5203bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5204 if (!E->isPotentiallyEvaluated())
5205 return Success(E);
5206
5207 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5208 << E->getExprOperand()->getType()
5209 << E->getExprOperand()->getSourceRange();
5210 return false;
5211}
5212
5213bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5214 return Success(E);
5215}
5216
5217bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5218 // Handle static data members.
5219 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5220 VisitIgnoredBaseExpression(E->getBase());
5221 return VisitVarDecl(E, VD);
5222 }
5223
5224 // Handle static member functions.
5225 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5226 if (MD->isStatic()) {
5227 VisitIgnoredBaseExpression(E->getBase());
5228 return Success(MD);
5229 }
5230 }
5231
5232 // Handle non-static data members.
5233 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5234}
5235
5236bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5237 // FIXME: Deal with vectors as array subscript bases.
5238 if (E->getBase()->getType()->isVectorType())
5239 return Error(E);
5240
5241 if (!evaluatePointer(E->getBase(), Result))
5242 return false;
5243
5244 APSInt Index;
5245 if (!EvaluateInteger(E->getIdx(), Index, Info))
5246 return false;
5247
5248 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5249}
5250
5251bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5252 return evaluatePointer(E->getSubExpr(), Result);
5253}
5254
5255bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5256 if (!Visit(E->getSubExpr()))
5257 return false;
5258 // __real is a no-op on scalar lvalues.
5259 if (E->getSubExpr()->getType()->isAnyComplexType())
5260 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5261 return true;
5262}
5263
5264bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5265 assert(E->getSubExpr()->getType()->isAnyComplexType() &&((E->getSubExpr()->getType()->isAnyComplexType() &&
"lvalue __imag__ on scalar?") ? static_cast<void> (0) :
__assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5266, __PRETTY_FUNCTION__))
5266 "lvalue __imag__ on scalar?")((E->getSubExpr()->getType()->isAnyComplexType() &&
"lvalue __imag__ on scalar?") ? static_cast<void> (0) :
__assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5266, __PRETTY_FUNCTION__))
;
5267 if (!Visit(E->getSubExpr()))
5268 return false;
5269 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5270 return true;
5271}
5272
5273bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5274 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5275 return Error(UO);
5276
5277 if (!this->Visit(UO->getSubExpr()))
5278 return false;
5279
5280 return handleIncDec(
5281 this->Info, UO, Result, UO->getSubExpr()->getType(),
5282 UO->isIncrementOp(), nullptr);
5283}
5284
5285bool LValueExprEvaluator::VisitCompoundAssignOperator(
5286 const CompoundAssignOperator *CAO) {
5287 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5288 return Error(CAO);
5289
5290 APValue RHS;
5291
5292 // The overall lvalue result is the result of evaluating the LHS.
5293 if (!this->Visit(CAO->getLHS())) {
5294 if (Info.noteFailure())
5295 Evaluate(RHS, this->Info, CAO->getRHS());
5296 return false;
5297 }
5298
5299 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5300 return false;
5301
5302 return handleCompoundAssignment(
5303 this->Info, CAO,
5304 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5305 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5306}
5307
5308bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5309 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5310 return Error(E);
5311
5312 APValue NewVal;
5313
5314 if (!this->Visit(E->getLHS())) {
5315 if (Info.noteFailure())
5316 Evaluate(NewVal, this->Info, E->getRHS());
5317 return false;
5318 }
5319
5320 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5321 return false;
5322
5323 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5324 NewVal);
5325}
5326
5327//===----------------------------------------------------------------------===//
5328// Pointer Evaluation
5329//===----------------------------------------------------------------------===//
5330
5331/// \brief Attempts to compute the number of bytes available at the pointer
5332/// returned by a function with the alloc_size attribute. Returns true if we
5333/// were successful. Places an unsigned number into `Result`.
5334///
5335/// This expects the given CallExpr to be a call to a function with an
5336/// alloc_size attribute.
5337static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5338 const CallExpr *Call,
5339 llvm::APInt &Result) {
5340 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5341
5342 // alloc_size args are 1-indexed, 0 means not present.
5343 assert(AllocSize && AllocSize->getElemSizeParam() != 0)((AllocSize && AllocSize->getElemSizeParam() != 0)
? static_cast<void> (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam() != 0"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5343, __PRETTY_FUNCTION__))
;
5344 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5345 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5346 if (Call->getNumArgs() <= SizeArgNo)
5347 return false;
5348
5349 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5350 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5351 return false;
5352 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5353 return false;
5354 Into = Into.zextOrSelf(BitsInSizeT);
5355 return true;
5356 };
5357
5358 APSInt SizeOfElem;
5359 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5360 return false;
5361
5362 if (!AllocSize->getNumElemsParam()) {
5363 Result = std::move(SizeOfElem);
5364 return true;
5365 }
5366
5367 APSInt NumberOfElems;
5368 // Argument numbers start at 1
5369 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5370 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5371 return false;
5372
5373 bool Overflow;
5374 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5375 if (Overflow)
5376 return false;
5377
5378 Result = std::move(BytesAvailable);
5379 return true;
5380}
5381
5382/// \brief Convenience function. LVal's base must be a call to an alloc_size
5383/// function.
5384static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5385 const LValue &LVal,
5386 llvm::APInt &Result) {
5387 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&((isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function"
) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5388, __PRETTY_FUNCTION__))
5388 "Can't get the size of a non alloc_size function")((isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function"
) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5388, __PRETTY_FUNCTION__))
;
5389 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5390 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5391 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5392}
5393
5394/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5395/// a function with the alloc_size attribute. If it was possible to do so, this
5396/// function will return true, make Result's Base point to said function call,
5397/// and mark Result's Base as invalid.
5398static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5399 LValue &Result) {
5400 if (Base.isNull())
5401 return false;
5402
5403 // Because we do no form of static analysis, we only support const variables.
5404 //
5405 // Additionally, we can't support parameters, nor can we support static
5406 // variables (in the latter case, use-before-assign isn't UB; in the former,
5407 // we have no clue what they'll be assigned to).
5408 const auto *VD =
5409 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5410 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5411 return false;
5412
5413 const Expr *Init = VD->getAnyInitializer();
5414 if (!Init)
5415 return false;
5416
5417 const Expr *E = Init->IgnoreParens();
5418 if (!tryUnwrapAllocSizeCall(E))
5419 return false;
5420
5421 // Store E instead of E unwrapped so that the type of the LValue's base is
5422 // what the user wanted.
5423 Result.setInvalid(E);
5424
5425 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5426 Result.addUnsizedArray(Info, Pointee);
5427 return true;
5428}
5429
5430namespace {
5431class PointerExprEvaluator
5432 : public ExprEvaluatorBase<PointerExprEvaluator> {
5433 LValue &Result;
5434 bool InvalidBaseOK;
5435
5436 bool Success(const Expr *E) {
5437 Result.set(E);
5438 return true;
5439 }
5440
5441 bool evaluateLValue(const Expr *E, LValue &Result) {
5442 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5443 }
5444
5445 bool evaluatePointer(const Expr *E, LValue &Result) {
5446 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5447 }
5448
5449 bool visitNonBuiltinCallExpr(const CallExpr *E);
5450public:
5451
5452 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5453 : ExprEvaluatorBaseTy(info), Result(Result),
5454 InvalidBaseOK(InvalidBaseOK) {}
5455
5456 bool Success(const APValue &V, const Expr *E) {
5457 Result.setFrom(Info.Ctx, V);
5458 return true;
5459 }
5460 bool ZeroInitialization(const Expr *E) {
5461 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5462 Result.set((Expr*)nullptr, 0, false, true, Offset);
5463 return true;
5464 }
5465
5466 bool VisitBinaryOperator(const BinaryOperator *E);
5467 bool VisitCastExpr(const CastExpr* E);
5468 bool VisitUnaryAddrOf(const UnaryOperator *E);
5469 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5470 { return Success(E); }
5471 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
5472 { return Success(E); }
5473 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5474 { return Success(E); }
5475 bool VisitCallExpr(const CallExpr *E);
5476 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5477 bool VisitBlockExpr(const BlockExpr *E) {
5478 if (!E->getBlockDecl()->hasCaptures())
5479 return Success(E);
5480 return Error(E);
5481 }
5482 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5483 // Can't look at 'this' when checking a potential constant expression.
5484 if (Info.checkingPotentialConstantExpression())
5485 return false;
5486 if (!Info.CurrentCall->This) {
5487 if (Info.getLangOpts().CPlusPlus11)
5488 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5489 else
5490 Info.FFDiag(E);
5491 return false;
5492 }
5493 Result = *Info.CurrentCall->This;
5494 // If we are inside a lambda's call operator, the 'this' expression refers
5495 // to the enclosing '*this' object (either by value or reference) which is
5496 // either copied into the closure object's field that represents the '*this'
5497 // or refers to '*this'.
5498 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5499 // Update 'Result' to refer to the data member/field of the closure object
5500 // that represents the '*this' capture.
5501 if (!HandleLValueMember(Info, E, Result,
5502 Info.CurrentCall->LambdaThisCaptureField))
5503 return false;
5504 // If we captured '*this' by reference, replace the field with its referent.
5505 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5506 ->isPointerType()) {
5507 APValue RVal;
5508 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5509 RVal))
5510 return false;
5511
5512 Result.setFrom(Info.Ctx, RVal);
5513 }
5514 }
5515 return true;
5516 }
5517
5518 // FIXME: Missing: @protocol, @selector
5519};
5520} // end anonymous namespace
5521
5522static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5523 bool InvalidBaseOK) {
5524 assert(E->isRValue() && E->getType()->hasPointerRepresentation())((E->isRValue() && E->getType()->hasPointerRepresentation
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->hasPointerRepresentation()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5524, __PRETTY_FUNCTION__))
;
5525 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5526}
5527
5528bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5529 if (E->getOpcode() != BO_Add &&
5530 E->getOpcode() != BO_Sub)
5531 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5532
5533 const Expr *PExp = E->getLHS();
5534 const Expr *IExp = E->getRHS();
5535 if (IExp->getType()->isPointerType())
5536 std::swap(PExp, IExp);
5537
5538 bool EvalPtrOK = evaluatePointer(PExp, Result);
5539 if (!EvalPtrOK && !Info.noteFailure())
5540 return false;
5541
5542 llvm::APSInt Offset;
5543 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5544 return false;
5545
5546 if (E->getOpcode() == BO_Sub)
5547 negateAsSigned(Offset);
5548
5549 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5550 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5551}
5552
5553bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5554 return evaluateLValue(E->getSubExpr(), Result);
5555}
5556
5557bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5558 const Expr* SubExpr = E->getSubExpr();
5559
5560 switch (E->getCastKind()) {
5561 default:
5562 break;
5563
5564 case CK_BitCast:
5565 case CK_CPointerToObjCPointerCast:
5566 case CK_BlockPointerToObjCPointerCast:
5567 case CK_AnyPointerToBlockPointerCast:
5568 case CK_AddressSpaceConversion:
5569 if (!Visit(SubExpr))
5570 return false;
5571 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5572 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5573 // also static_casts, but we disallow them as a resolution to DR1312.
5574 if (!E->getType()->isVoidPointerType()) {
5575 Result.Designator.setInvalid();
5576 if (SubExpr->getType()->isVoidPointerType())
5577 CCEDiag(E, diag::note_constexpr_invalid_cast)
5578 << 3 << SubExpr->getType();
5579 else
5580 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5581 }
5582 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5583 ZeroInitialization(E);
5584 return true;
5585
5586 case CK_DerivedToBase:
5587 case CK_UncheckedDerivedToBase:
5588 if (!evaluatePointer(E->getSubExpr(), Result))
5589 return false;
5590 if (!Result.Base && Result.Offset.isZero())
5591 return true;
5592
5593 // Now figure out the necessary offset to add to the base LV to get from
5594 // the derived class to the base class.
5595 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5596 castAs<PointerType>()->getPointeeType(),
5597 Result);
5598
5599 case CK_BaseToDerived:
5600 if (!Visit(E->getSubExpr()))
5601 return false;
5602 if (!Result.Base && Result.Offset.isZero())
5603 return true;
5604 return HandleBaseToDerivedCast(Info, E, Result);
5605
5606 case CK_NullToPointer:
5607 VisitIgnoredValue(E->getSubExpr());
5608 return ZeroInitialization(E);
5609
5610 case CK_IntegralToPointer: {
5611 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5612
5613 APValue Value;
5614 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5615 break;
5616
5617 if (Value.isInt()) {
5618 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5619 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5620 Result.Base = (Expr*)nullptr;
5621 Result.InvalidBase = false;
5622 Result.Offset = CharUnits::fromQuantity(N);
5623 Result.CallIndex = 0;
5624 Result.Designator.setInvalid();
5625 Result.IsNullPtr = false;
5626 return true;
5627 } else {
5628 // Cast is of an lvalue, no need to change value.
5629 Result.setFrom(Info.Ctx, Value);
5630 return true;
5631 }
5632 }
5633 case CK_ArrayToPointerDecay:
5634 if (SubExpr->isGLValue()) {
5635 if (!evaluateLValue(SubExpr, Result))
5636 return false;
5637 } else {
5638 Result.set(SubExpr, Info.CurrentCall->Index);
5639 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5640 Info, Result, SubExpr))
5641 return false;
5642 }
5643 // The result is a pointer to the first element of the array.
5644 if (const ConstantArrayType *CAT
5645 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5646 Result.addArray(Info, E, CAT);
5647 else
5648 Result.Designator.setInvalid();
5649 return true;
5650
5651 case CK_FunctionToPointerDecay:
5652 return evaluateLValue(SubExpr, Result);
5653
5654 case CK_LValueToRValue: {
5655 LValue LVal;
5656 if (!evaluateLValue(E->getSubExpr(), LVal))
5657 return false;
5658
5659 APValue RVal;
5660 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5661 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5662 LVal, RVal))
5663 return InvalidBaseOK &&
5664 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5665 return Success(RVal, E);
5666 }
5667 }
5668
5669 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5670}
5671
5672static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5673 // C++ [expr.alignof]p3:
5674 // When alignof is applied to a reference type, the result is the
5675 // alignment of the referenced type.
5676 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5677 T = Ref->getPointeeType();
5678
5679 // __alignof is defined to return the preferred alignment.
5680 if (T.getQualifiers().hasUnaligned())
5681 return CharUnits::One();
5682 return Info.Ctx.toCharUnitsFromBits(
5683 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5684}
5685
5686static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5687 E = E->IgnoreParens();
5688
5689 // The kinds of expressions that we have special-case logic here for
5690 // should be kept up to date with the special checks for those
5691 // expressions in Sema.
5692
5693 // alignof decl is always accepted, even if it doesn't make sense: we default
5694 // to 1 in those cases.
5695 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5696 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5697 /*RefAsPointee*/true);
5698
5699 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5700 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5701 /*RefAsPointee*/true);
5702
5703 return GetAlignOfType(Info, E->getType());
5704}
5705
5706// To be clear: this happily visits unsupported builtins. Better name welcomed.
5707bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5708 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5709 return true;
5710
5711 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5712 return false;
5713
5714 Result.setInvalid(E);
5715 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5716 Result.addUnsizedArray(Info, PointeeTy);
5717 return true;
5718}
5719
5720bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5721 if (IsStringLiteralCall(E))
5722 return Success(E);
5723
5724 if (unsigned BuiltinOp = E->getBuiltinCallee())
5725 return VisitBuiltinCallExpr(E, BuiltinOp);
5726
5727 return visitNonBuiltinCallExpr(E);
5728}
5729
5730bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5731 unsigned BuiltinOp) {
5732 switch (BuiltinOp) {
5733 case Builtin::BI__builtin_addressof:
5734 return evaluateLValue(E->getArg(0), Result);
5735 case Builtin::BI__builtin_assume_aligned: {
5736 // We need to be very careful here because: if the pointer does not have the
5737 // asserted alignment, then the behavior is undefined, and undefined
5738 // behavior is non-constant.
5739 if (!evaluatePointer(E->getArg(0), Result))
5740 return false;
5741
5742 LValue OffsetResult(Result);
5743 APSInt Alignment;
5744 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5745 return false;
5746 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5747
5748 if (E->getNumArgs() > 2) {
5749 APSInt Offset;
5750 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5751 return false;
5752
5753 int64_t AdditionalOffset = -Offset.getZExtValue();
5754 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5755 }
5756
5757 // If there is a base object, then it must have the correct alignment.
5758 if (OffsetResult.Base) {
5759 CharUnits BaseAlignment;
5760 if (const ValueDecl *VD =
5761 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5762 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5763 } else {
5764 BaseAlignment =
5765 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5766 }
5767
5768 if (BaseAlignment < Align) {
5769 Result.Designator.setInvalid();
5770 // FIXME: Add support to Diagnostic for long / long long.
5771 CCEDiag(E->getArg(0),
5772 diag::note_constexpr_baa_insufficient_alignment) << 0
5773 << (unsigned)BaseAlignment.getQuantity()
5774 << (unsigned)Align.getQuantity();
5775 return false;
5776 }
5777 }
5778
5779 // The offset must also have the correct alignment.
5780 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5781 Result.Designator.setInvalid();
5782
5783 (OffsetResult.Base
5784 ? CCEDiag(E->getArg(0),
5785 diag::note_constexpr_baa_insufficient_alignment) << 1
5786 : CCEDiag(E->getArg(0),
5787 diag::note_constexpr_baa_value_insufficient_alignment))
5788 << (int)OffsetResult.Offset.getQuantity()
5789 << (unsigned)Align.getQuantity();
5790 return false;
5791 }
5792
5793 return true;
5794 }
5795
5796 case Builtin::BIstrchr:
5797 case Builtin::BIwcschr:
5798 case Builtin::BImemchr:
5799 case Builtin::BIwmemchr:
5800 if (Info.getLangOpts().CPlusPlus11)
5801 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5802 << /*isConstexpr*/0 << /*isConstructor*/0
5803 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5804 else
5805 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5806 // Fall through.
5807 case Builtin::BI__builtin_strchr:
5808 case Builtin::BI__builtin_wcschr:
5809 case Builtin::BI__builtin_memchr:
5810 case Builtin::BI__builtin_char_memchr:
5811 case Builtin::BI__builtin_wmemchr: {
5812 if (!Visit(E->getArg(0)))
5813 return false;
5814 APSInt Desired;
5815 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5816 return false;
5817 uint64_t MaxLength = uint64_t(-1);
5818 if (BuiltinOp != Builtin::BIstrchr &&
5819 BuiltinOp != Builtin::BIwcschr &&
5820 BuiltinOp != Builtin::BI__builtin_strchr &&
5821 BuiltinOp != Builtin::BI__builtin_wcschr) {
5822 APSInt N;
5823 if (!EvaluateInteger(E->getArg(2), N, Info))
5824 return false;
5825 MaxLength = N.getExtValue();
5826 }
5827
5828 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5829
5830 // Figure out what value we're actually looking for (after converting to
5831 // the corresponding unsigned type if necessary).
5832 uint64_t DesiredVal;
5833 bool StopAtNull = false;
5834 switch (BuiltinOp) {
5835 case Builtin::BIstrchr:
5836 case Builtin::BI__builtin_strchr:
5837 // strchr compares directly to the passed integer, and therefore
5838 // always fails if given an int that is not a char.
5839 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5840 E->getArg(1)->getType(),
5841 Desired),
5842 Desired))
5843 return ZeroInitialization(E);
5844 StopAtNull = true;
5845 // Fall through.
5846 case Builtin::BImemchr:
5847 case Builtin::BI__builtin_memchr:
5848 case Builtin::BI__builtin_char_memchr:
5849 // memchr compares by converting both sides to unsigned char. That's also
5850 // correct for strchr if we get this far (to cope with plain char being
5851 // unsigned in the strchr case).
5852 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5853 break;
5854
5855 case Builtin::BIwcschr:
5856 case Builtin::BI__builtin_wcschr:
5857 StopAtNull = true;
5858 // Fall through.
5859 case Builtin::BIwmemchr:
5860 case Builtin::BI__builtin_wmemchr:
5861 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5862 DesiredVal = Desired.getZExtValue();
5863 break;
5864 }
5865
5866 for (; MaxLength; --MaxLength) {
5867 APValue Char;
5868 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5869 !Char.isInt())
5870 return false;
5871 if (Char.getInt().getZExtValue() == DesiredVal)
5872 return true;
5873 if (StopAtNull && !Char.getInt())
5874 break;
5875 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5876 return false;
5877 }
5878 // Not found: return nullptr.
5879 return ZeroInitialization(E);
5880 }
5881
5882 default:
5883 return visitNonBuiltinCallExpr(E);
5884 }
5885}
5886
5887//===----------------------------------------------------------------------===//
5888// Member Pointer Evaluation
5889//===----------------------------------------------------------------------===//
5890
5891namespace {
5892class MemberPointerExprEvaluator
5893 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5894 MemberPtr &Result;
5895
5896 bool Success(const ValueDecl *D) {
5897 Result = MemberPtr(D);
5898 return true;
5899 }
5900public:
5901
5902 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5903 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5904
5905 bool Success(const APValue &V, const Expr *E) {
5906 Result.setFrom(V);
5907 return true;
5908 }
5909 bool ZeroInitialization(const Expr *E) {
5910 return Success((const ValueDecl*)nullptr);
5911 }
5912
5913 bool VisitCastExpr(const CastExpr *E);
5914 bool VisitUnaryAddrOf(const UnaryOperator *E);
5915};
5916} // end anonymous namespace
5917
5918static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5919 EvalInfo &Info) {
5920 assert(E->isRValue() && E->getType()->isMemberPointerType())((E->isRValue() && E->getType()->isMemberPointerType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isMemberPointerType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5920, __PRETTY_FUNCTION__))
;
5921 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5922}
5923
5924bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5925 switch (E->getCastKind()) {
5926 default:
5927 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5928
5929 case CK_NullToMemberPointer:
5930 VisitIgnoredValue(E->getSubExpr());
5931 return ZeroInitialization(E);
5932
5933 case CK_BaseToDerivedMemberPointer: {
5934 if (!Visit(E->getSubExpr()))
5935 return false;
5936 if (E->path_empty())
5937 return true;
5938 // Base-to-derived member pointer casts store the path in derived-to-base
5939 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5940 // the wrong end of the derived->base arc, so stagger the path by one class.
5941 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5942 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5943 PathI != PathE; ++PathI) {
5944 assert(!(*PathI)->isVirtual() && "memptr cast through vbase")((!(*PathI)->isVirtual() && "memptr cast through vbase"
) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5944, __PRETTY_FUNCTION__))
;
5945 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5946 if (!Result.castToDerived(Derived))
5947 return Error(E);
5948 }
5949 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5950 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5951 return Error(E);
5952 return true;
5953 }
5954
5955 case CK_DerivedToBaseMemberPointer:
5956 if (!Visit(E->getSubExpr()))
5957 return false;
5958 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5959 PathE = E->path_end(); PathI != PathE; ++PathI) {
5960 assert(!(*PathI)->isVirtual() && "memptr cast through vbase")((!(*PathI)->isVirtual() && "memptr cast through vbase"
) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 5960, __PRETTY_FUNCTION__))
;
5961 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5962 if (!Result.castToBase(Base))
5963 return Error(E);
5964 }
5965 return true;
5966 }
5967}
5968
5969bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5970 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5971 // member can be formed.
5972 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5973}
5974
5975//===----------------------------------------------------------------------===//
5976// Record Evaluation
5977//===----------------------------------------------------------------------===//
5978
5979namespace {
5980 class RecordExprEvaluator
5981 : public ExprEvaluatorBase<RecordExprEvaluator> {
5982 const LValue &This;
5983 APValue &Result;
5984 public:
5985
5986 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5987 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5988
5989 bool Success(const APValue &V, const Expr *E) {
5990 Result = V;
5991 return true;
5992 }
5993 bool ZeroInitialization(const Expr *E) {
5994 return ZeroInitialization(E, E->getType());
5995 }
5996 bool ZeroInitialization(const Expr *E, QualType T);
5997
5998 bool VisitCallExpr(const CallExpr *E) {
5999 return handleCallExpr(E, Result, &This);
6000 }
6001 bool VisitCastExpr(const CastExpr *E);
6002 bool VisitInitListExpr(const InitListExpr *E);
6003 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6004 return VisitCXXConstructExpr(E, E->getType());
6005 }
6006 bool VisitLambdaExpr(const LambdaExpr *E);
6007 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6008 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6009 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6010 };
6011}
6012
6013/// Perform zero-initialization on an object of non-union class type.
6014/// C++11 [dcl.init]p5:
6015/// To zero-initialize an object or reference of type T means:
6016/// [...]
6017/// -- if T is a (possibly cv-qualified) non-union class type,
6018/// each non-static data member and each base-class subobject is
6019/// zero-initialized
6020static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6021 const RecordDecl *RD,
6022 const LValue &This, APValue &Result) {
6023 assert(!RD->isUnion() && "Expected non-union class type")((!RD->isUnion() && "Expected non-union class type"
) ? static_cast<void> (0) : __assert_fail ("!RD->isUnion() && \"Expected non-union class type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6023, __PRETTY_FUNCTION__))
;
6024 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6025 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6026 std::distance(RD->field_begin(), RD->field_end()));
6027
6028 if (RD->isInvalidDecl()) return false;
6029 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6030
6031 if (CD) {
6032 unsigned Index = 0;
6033 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6034 End = CD->bases_end(); I != End; ++I, ++Index) {
6035 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6036 LValue Subobject = This;
6037 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6038 return false;
6039 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6040 Result.getStructBase(Index)))
6041 return false;
6042 }
6043 }
6044
6045 for (const auto *I : RD->fields()) {
6046 // -- if T is a reference type, no initialization is performed.
6047 if (I->getType()->isReferenceType())
6048 continue;
6049
6050 LValue Subobject = This;
6051 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6052 return false;
6053
6054 ImplicitValueInitExpr VIE(I->getType());
6055 if (!EvaluateInPlace(
6056 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6057 return false;
6058 }
6059
6060 return true;
6061}
6062
6063bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6064 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6065 if (RD->isInvalidDecl()) return false;
6066 if (RD->isUnion()) {
6067 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6068 // object's first non-static named data member is zero-initialized
6069 RecordDecl::field_iterator I = RD->field_begin();
6070 if (I == RD->field_end()) {
6071 Result = APValue((const FieldDecl*)nullptr);
6072 return true;
6073 }
6074
6075 LValue Subobject = This;
6076 if (!HandleLValueMember(Info, E, Subobject, *I))
6077 return false;
6078 Result = APValue(*I);
6079 ImplicitValueInitExpr VIE(I->getType());
6080 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6081 }
6082
6083 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6084 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6085 return false;
6086 }
6087
6088 return HandleClassZeroInitialization(Info, E, RD, This, Result);
6089}
6090
6091bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6092 switch (E->getCastKind()) {
6093 default:
6094 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6095
6096 case CK_ConstructorConversion:
6097 return Visit(E->getSubExpr());
6098
6099 case CK_DerivedToBase:
6100 case CK_UncheckedDerivedToBase: {
6101 APValue DerivedObject;
6102 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6103 return false;
6104 if (!DerivedObject.isStruct())
6105 return Error(E->getSubExpr());
6106
6107 // Derived-to-base rvalue conversion: just slice off the derived part.
6108 APValue *Value = &DerivedObject;
6109 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6110 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6111 PathE = E->path_end(); PathI != PathE; ++PathI) {
6112 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base")((!(*PathI)->isVirtual() && "record rvalue with virtual base"
) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"record rvalue with virtual base\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6112, __PRETTY_FUNCTION__))
;
6113 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6114 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6115 RD = Base;
6116 }
6117 Result = *Value;
6118 return true;
6119 }
6120 }
6121}
6122
6123bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6124 if (E->isTransparent())
6125 return Visit(E->getInit(0));
6126
6127 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6128 if (RD->isInvalidDecl()) return false;
6129 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6130
6131 if (RD->isUnion()) {
6132 const FieldDecl *Field = E->getInitializedFieldInUnion();
6133 Result = APValue(Field);
6134 if (!Field)
6135 return true;
6136
6137 // If the initializer list for a union does not contain any elements, the
6138 // first element of the union is value-initialized.
6139 // FIXME: The element should be initialized from an initializer list.
6140 // Is this difference ever observable for initializer lists which
6141 // we don't build?
6142 ImplicitValueInitExpr VIE(Field->getType());
6143 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6144
6145 LValue Subobject = This;
6146 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6147 return false;
6148
6149 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6150 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6151 isa<CXXDefaultInitExpr>(InitExpr));
6152
6153 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6154 }
6155
6156 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6157 if (Result.isUninit())
6158 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6159 std::distance(RD->field_begin(), RD->field_end()));
6160 unsigned ElementNo = 0;
6161 bool Success = true;
6162
6163 // Initialize base classes.
6164 if (CXXRD) {
6165 for (const auto &Base : CXXRD->bases()) {
6166 assert(ElementNo < E->getNumInits() && "missing init for base class")((ElementNo < E->getNumInits() && "missing init for base class"
) ? static_cast<void> (0) : __assert_fail ("ElementNo < E->getNumInits() && \"missing init for base class\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6166, __PRETTY_FUNCTION__))
;
6167 const Expr *Init = E->getInit(ElementNo);
6168
6169 LValue Subobject = This;
6170 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6171 return false;
6172
6173 APValue &FieldVal = Result.getStructBase(ElementNo);
6174 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6175 if (!Info.noteFailure())
6176 return false;
6177 Success = false;
6178 }
6179 ++ElementNo;
6180 }
6181 }
6182
6183 // Initialize members.
6184 for (const auto *Field : RD->fields()) {
6185 // Anonymous bit-fields are not considered members of the class for
6186 // purposes of aggregate initialization.
6187 if (Field->isUnnamedBitfield())
6188 continue;
6189
6190 LValue Subobject = This;
6191
6192 bool HaveInit = ElementNo < E->getNumInits();
6193
6194 // FIXME: Diagnostics here should point to the end of the initializer
6195 // list, not the start.
6196 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6197 Subobject, Field, &Layout))
6198 return false;
6199
6200 // Perform an implicit value-initialization for members beyond the end of
6201 // the initializer list.
6202 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6203 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6204
6205 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6206 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6207 isa<CXXDefaultInitExpr>(Init));
6208
6209 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6210 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6211 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6212 FieldVal, Field))) {
6213 if (!Info.noteFailure())
6214 return false;
6215 Success = false;
6216 }
6217 }
6218
6219 return Success;
6220}
6221
6222bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6223 QualType T) {
6224 // Note that E's type is not necessarily the type of our class here; we might
6225 // be initializing an array element instead.
6226 const CXXConstructorDecl *FD = E->getConstructor();
6227 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6228
6229 bool ZeroInit = E->requiresZeroInitialization();
6230 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6231 // If we've already performed zero-initialization, we're already done.
6232 if (!Result.isUninit())
6233 return true;
6234
6235 // We can get here in two different ways:
6236 // 1) We're performing value-initialization, and should zero-initialize
6237 // the object, or
6238 // 2) We're performing default-initialization of an object with a trivial
6239 // constexpr default constructor, in which case we should start the
6240 // lifetimes of all the base subobjects (there can be no data member
6241 // subobjects in this case) per [basic.life]p1.
6242 // Either way, ZeroInitialization is appropriate.
6243 return ZeroInitialization(E, T);
6244 }
6245
6246 const FunctionDecl *Definition = nullptr;
6247 auto Body = FD->getBody(Definition);
6248
6249 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6250 return false;
6251
6252 // Avoid materializing a temporary for an elidable copy/move constructor.
6253 if (E->isElidable() && !ZeroInit)
6254 if (const MaterializeTemporaryExpr *ME
6255 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6256 return Visit(ME->GetTemporaryExpr());
6257
6258 if (ZeroInit && !ZeroInitialization(E, T))
6259 return false;
6260
6261 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6262 return HandleConstructorCall(E, This, Args,
6263 cast<CXXConstructorDecl>(Definition), Info,
6264 Result);
6265}
6266
6267bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6268 const CXXInheritedCtorInitExpr *E) {
6269 if (!Info.CurrentCall) {
6270 assert(Info.checkingPotentialConstantExpression())((Info.checkingPotentialConstantExpression()) ? static_cast<
void> (0) : __assert_fail ("Info.checkingPotentialConstantExpression()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6270, __PRETTY_FUNCTION__))
;
6271 return false;
6272 }
6273
6274 const CXXConstructorDecl *FD = E->getConstructor();
6275 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6276 return false;
6277
6278 const FunctionDecl *Definition = nullptr;
6279 auto Body = FD->getBody(Definition);
6280
6281 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6282 return false;
6283
6284 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6285 cast<CXXConstructorDecl>(Definition), Info,
6286 Result);
6287}
6288
6289bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6290 const CXXStdInitializerListExpr *E) {
6291 const ConstantArrayType *ArrayType =
6292 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6293
6294 LValue Array;
6295 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6296 return false;
6297
6298 // Get a pointer to the first element of the array.
6299 Array.addArray(Info, E, ArrayType);
6300
6301 // FIXME: Perform the checks on the field types in SemaInit.
6302 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6303 RecordDecl::field_iterator Field = Record->field_begin();
6304 if (Field == Record->field_end())
6305 return Error(E);
6306
6307 // Start pointer.
6308 if (!Field->getType()->isPointerType() ||
6309 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6310 ArrayType->getElementType()))
6311 return Error(E);
6312
6313 // FIXME: What if the initializer_list type has base classes, etc?
6314 Result = APValue(APValue::UninitStruct(), 0, 2);
6315 Array.moveInto(Result.getStructField(0));
6316
6317 if (++Field == Record->field_end())
6318 return Error(E);
6319
6320 if (Field->getType()->isPointerType() &&
6321 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6322 ArrayType->getElementType())) {
6323 // End pointer.
6324 if (!HandleLValueArrayAdjustment(Info, E, Array,
6325 ArrayType->getElementType(),
6326 ArrayType->getSize().getZExtValue()))
6327 return false;
6328 Array.moveInto(Result.getStructField(1));
6329 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6330 // Length.
6331 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6332 else
6333 return Error(E);
6334
6335 if (++Field != Record->field_end())
6336 return Error(E);
6337
6338 return true;
6339}
6340
6341bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6342 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6343 if (ClosureClass->isInvalidDecl()) return false;
6344
6345 if (Info.checkingPotentialConstantExpression()) return true;
6346
6347 const size_t NumFields =
6348 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6349
6350 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),((NumFields == (size_t)std::distance(E->capture_init_begin
(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? static_cast<void> (
0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6353, __PRETTY_FUNCTION__))
6351 E->capture_init_end()) &&((NumFields == (size_t)std::distance(E->capture_init_begin
(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? static_cast<void> (
0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6353, __PRETTY_FUNCTION__))
6352 "The number of lambda capture initializers should equal the number of "((NumFields == (size_t)std::distance(E->capture_init_begin
(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? static_cast<void> (
0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6353, __PRETTY_FUNCTION__))
6353 "fields within the closure type")((NumFields == (size_t)std::distance(E->capture_init_begin
(), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of "
"fields within the closure type") ? static_cast<void> (
0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6353, __PRETTY_FUNCTION__))
;
6354
6355 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6356 // Iterate through all the lambda's closure object's fields and initialize
6357 // them.
6358 auto *CaptureInitIt = E->capture_init_begin();
6359 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6360 bool Success = true;
6361 for (const auto *Field : ClosureClass->fields()) {
6362 assert(CaptureInitIt != E->capture_init_end())((CaptureInitIt != E->capture_init_end()) ? static_cast<
void> (0) : __assert_fail ("CaptureInitIt != E->capture_init_end()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6362, __PRETTY_FUNCTION__))
;
6363 // Get the initializer for this field
6364 Expr *const CurFieldInit = *CaptureInitIt++;
6365
6366 // If there is no initializer, either this is a VLA or an error has
6367 // occurred.
6368 if (!CurFieldInit)
6369 return Error(E);
6370
6371 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6372 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6373 if (!Info.keepEvaluatingAfterFailure())
6374 return false;
6375 Success = false;
6376 }
6377 ++CaptureIt;
6378 }
6379 return Success;
6380}
6381
6382static bool EvaluateRecord(const Expr *E, const LValue &This,
6383 APValue &Result, EvalInfo &Info) {
6384 assert(E->isRValue() && E->getType()->isRecordType() &&((E->isRValue() && E->getType()->isRecordType
() && "can't evaluate expression as a record rvalue")
? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6385, __PRETTY_FUNCTION__))
6385 "can't evaluate expression as a record rvalue")((E->isRValue() && E->getType()->isRecordType
() && "can't evaluate expression as a record rvalue")
? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6385, __PRETTY_FUNCTION__))
;
6386 return RecordExprEvaluator(Info, This, Result).Visit(E);
6387}
6388
6389//===----------------------------------------------------------------------===//
6390// Temporary Evaluation
6391//
6392// Temporaries are represented in the AST as rvalues, but generally behave like
6393// lvalues. The full-object of which the temporary is a subobject is implicitly
6394// materialized so that a reference can bind to it.
6395//===----------------------------------------------------------------------===//
6396namespace {
6397class TemporaryExprEvaluator
6398 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6399public:
6400 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6401 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6402
6403 /// Visit an expression which constructs the value of this temporary.
6404 bool VisitConstructExpr(const Expr *E) {
6405 Result.set(E, Info.CurrentCall->Index);
6406 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6407 Info, Result, E);
6408 }
6409
6410 bool VisitCastExpr(const CastExpr *E) {
6411 switch (E->getCastKind()) {
6412 default:
6413 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6414
6415 case CK_ConstructorConversion:
6416 return VisitConstructExpr(E->getSubExpr());
6417 }
6418 }
6419 bool VisitInitListExpr(const InitListExpr *E) {
6420 return VisitConstructExpr(E);
6421 }
6422 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6423 return VisitConstructExpr(E);
6424 }
6425 bool VisitCallExpr(const CallExpr *E) {
6426 return VisitConstructExpr(E);
6427 }
6428 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6429 return VisitConstructExpr(E);
6430 }
6431 bool VisitLambdaExpr(const LambdaExpr *E) {
6432 return VisitConstructExpr(E);
6433 }
6434};
6435} // end anonymous namespace
6436
6437/// Evaluate an expression of record type as a temporary.
6438static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6439 assert(E->isRValue() && E->getType()->isRecordType())((E->isRValue() && E->getType()->isRecordType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6439, __PRETTY_FUNCTION__))
;
6440 return TemporaryExprEvaluator(Info, Result).Visit(E);
6441}
6442
6443//===----------------------------------------------------------------------===//
6444// Vector Evaluation
6445//===----------------------------------------------------------------------===//
6446
6447namespace {
6448 class VectorExprEvaluator
6449 : public ExprEvaluatorBase<VectorExprEvaluator> {
6450 APValue &Result;
6451 public:
6452
6453 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6454 : ExprEvaluatorBaseTy(info), Result(Result) {}
6455
6456 bool Success(ArrayRef<APValue> V, const Expr *E) {
6457 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements())((V.size() == E->getType()->castAs<VectorType>()->
getNumElements()) ? static_cast<void> (0) : __assert_fail
("V.size() == E->getType()->castAs<VectorType>()->getNumElements()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6457, __PRETTY_FUNCTION__))
;
6458 // FIXME: remove this APValue copy.
6459 Result = APValue(V.data(), V.size());
6460 return true;
6461 }
6462 bool Success(const APValue &V, const Expr *E) {
6463 assert(V.isVector())((V.isVector()) ? static_cast<void> (0) : __assert_fail
("V.isVector()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6463, __PRETTY_FUNCTION__))
;
6464 Result = V;
6465 return true;
6466 }
6467 bool ZeroInitialization(const Expr *E);
6468
6469 bool VisitUnaryReal(const UnaryOperator *E)
6470 { return Visit(E->getSubExpr()); }
6471 bool VisitCastExpr(const CastExpr* E);
6472 bool VisitInitListExpr(const InitListExpr *E);
6473 bool VisitUnaryImag(const UnaryOperator *E);
6474 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6475 // binary comparisons, binary and/or/xor,
6476 // shufflevector, ExtVectorElementExpr
6477 };
6478} // end anonymous namespace
6479
6480static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6481 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue")((E->isRValue() && E->getType()->isVectorType
() &&"not a vector rvalue") ? static_cast<void>
(0) : __assert_fail ("E->isRValue() && E->getType()->isVectorType() &&\"not a vector rvalue\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6481, __PRETTY_FUNCTION__))
;
6482 return VectorExprEvaluator(Info, Result).Visit(E);
6483}
6484
6485bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6486 const VectorType *VTy = E->getType()->castAs<VectorType>();
6487 unsigned NElts = VTy->getNumElements();
6488
6489 const Expr *SE = E->getSubExpr();
6490 QualType SETy = SE->getType();
6491
6492 switch (E->getCastKind()) {
6493 case CK_VectorSplat: {
6494 APValue Val = APValue();
6495 if (SETy->isIntegerType()) {
6496 APSInt IntResult;
6497 if (!EvaluateInteger(SE, IntResult, Info))
6498 return false;
6499 Val = APValue(std::move(IntResult));
6500 } else if (SETy->isRealFloatingType()) {
6501 APFloat FloatResult(0.0);
6502 if (!EvaluateFloat(SE, FloatResult, Info))
6503 return false;
6504 Val = APValue(std::move(FloatResult));
6505 } else {
6506 return Error(E);
6507 }
6508
6509 // Splat and create vector APValue.
6510 SmallVector<APValue, 4> Elts(NElts, Val);
6511 return Success(Elts, E);
6512 }
6513 case CK_BitCast: {
6514 // Evaluate the operand into an APInt we can extract from.
6515 llvm::APInt SValInt;
6516 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6517 return false;
6518 // Extract the elements
6519 QualType EltTy = VTy->getElementType();
6520 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6521 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6522 SmallVector<APValue, 4> Elts;
6523 if (EltTy->isRealFloatingType()) {
6524 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6525 unsigned FloatEltSize = EltSize;
6526 if (&Sem == &APFloat::x87DoubleExtended())
6527 FloatEltSize = 80;
6528 for (unsigned i = 0; i < NElts; i++) {
6529 llvm::APInt Elt;
6530 if (BigEndian)
6531 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6532 else
6533 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6534 Elts.push_back(APValue(APFloat(Sem, Elt)));
6535 }
6536 } else if (EltTy->isIntegerType()) {
6537 for (unsigned i = 0; i < NElts; i++) {
6538 llvm::APInt Elt;
6539 if (BigEndian)
6540 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6541 else
6542 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6543 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6544 }
6545 } else {
6546 return Error(E);
6547 }
6548 return Success(Elts, E);
6549 }
6550 default:
6551 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6552 }
6553}
6554
6555bool
6556VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6557 const VectorType *VT = E->getType()->castAs<VectorType>();
6558 unsigned NumInits = E->getNumInits();
6559 unsigned NumElements = VT->getNumElements();
6560
6561 QualType EltTy = VT->getElementType();
6562 SmallVector<APValue, 4> Elements;
6563
6564 // The number of initializers can be less than the number of
6565 // vector elements. For OpenCL, this can be due to nested vector
6566 // initialization. For GCC compatibility, missing trailing elements
6567 // should be initialized with zeroes.
6568 unsigned CountInits = 0, CountElts = 0;
6569 while (CountElts < NumElements) {
6570 // Handle nested vector initialization.
6571 if (CountInits < NumInits
6572 && E->getInit(CountInits)->getType()->isVectorType()) {
6573 APValue v;
6574 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6575 return Error(E);
6576 unsigned vlen = v.getVectorLength();
6577 for (unsigned j = 0; j < vlen; j++)
6578 Elements.push_back(v.getVectorElt(j));
6579 CountElts += vlen;
6580 } else if (EltTy->isIntegerType()) {
6581 llvm::APSInt sInt(32);
6582 if (CountInits < NumInits) {
6583 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6584 return false;
6585 } else // trailing integer zero.
6586 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6587 Elements.push_back(APValue(sInt));
6588 CountElts++;
6589 } else {
6590 llvm::APFloat f(0.0);
6591 if (CountInits < NumInits) {
6592 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6593 return false;
6594 } else // trailing float zero.
6595 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6596 Elements.push_back(APValue(f));
6597 CountElts++;
6598 }
6599 CountInits++;
6600 }
6601 return Success(Elements, E);
6602}
6603
6604bool
6605VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6606 const VectorType *VT = E->getType()->getAs<VectorType>();
6607 QualType EltTy = VT->getElementType();
6608 APValue ZeroElement;
6609 if (EltTy->isIntegerType())
6610 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6611 else
6612 ZeroElement =
6613 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6614
6615 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6616 return Success(Elements, E);
6617}
6618
6619bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6620 VisitIgnoredValue(E->getSubExpr());
6621 return ZeroInitialization(E);
6622}
6623
6624//===----------------------------------------------------------------------===//
6625// Array Evaluation
6626//===----------------------------------------------------------------------===//
6627
6628namespace {
6629 class ArrayExprEvaluator
6630 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6631 const LValue &This;
6632 APValue &Result;
6633 public:
6634
6635 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6636 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6637
6638 bool Success(const APValue &V, const Expr *E) {
6639 assert((V.isArray() || V.isLValue()) &&(((V.isArray() || V.isLValue()) && "expected array or string literal"
) ? static_cast<void> (0) : __assert_fail ("(V.isArray() || V.isLValue()) && \"expected array or string literal\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6640, __PRETTY_FUNCTION__))
6640 "expected array or string literal")(((V.isArray() || V.isLValue()) && "expected array or string literal"
) ? static_cast<void> (0) : __assert_fail ("(V.isArray() || V.isLValue()) && \"expected array or string literal\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6640, __PRETTY_FUNCTION__))
;
6641 Result = V;
6642 return true;
6643 }
6644
6645 bool ZeroInitialization(const Expr *E) {
6646 const ConstantArrayType *CAT =
6647 Info.Ctx.getAsConstantArrayType(E->getType());
6648 if (!CAT)
6649 return Error(E);
6650
6651 Result = APValue(APValue::UninitArray(), 0,
6652 CAT->getSize().getZExtValue());
6653 if (!Result.hasArrayFiller()) return true;
6654
6655 // Zero-initialize all elements.
6656 LValue Subobject = This;
6657 Subobject.addArray(Info, E, CAT);
6658 ImplicitValueInitExpr VIE(CAT->getElementType());
6659 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6660 }
6661
6662 bool VisitCallExpr(const CallExpr *E) {
6663 return handleCallExpr(E, Result, &This);
6664 }
6665 bool VisitInitListExpr(const InitListExpr *E);
6666 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6667 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6668 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6669 const LValue &Subobject,
6670 APValue *Value, QualType Type);
6671 };
6672} // end anonymous namespace
6673
6674static bool EvaluateArray(const Expr *E, const LValue &This,
6675 APValue &Result, EvalInfo &Info) {
6676 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue")((E->isRValue() && E->getType()->isArrayType
() && "not an array rvalue") ? static_cast<void>
(0) : __assert_fail ("E->isRValue() && E->getType()->isArrayType() && \"not an array rvalue\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6676, __PRETTY_FUNCTION__))
;
6677 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6678}
6679
6680bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6681 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6682 if (!CAT)
1
Assuming 'CAT' is non-null
2
Taking false branch
6683 return Error(E);
6684
6685 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6686 // an appropriately-typed string literal enclosed in braces.
6687 if (E->isStringLiteralInit()) {
3
Assuming the condition is false
4
Taking false branch
6688 LValue LV;
6689 if (!EvaluateLValue(E->getInit(0), LV, Info))
6690 return false;
6691 APValue Val;
6692 LV.moveInto(Val);
6693 return Success(Val, E);
6694 }
6695
6696 bool Success = true;
6697
6698 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&(((!Result.isArray() || Result.getArrayInitializedElts() == 0
) && "zero-initialized array shouldn't have any initialized elts"
) ? static_cast<void> (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6699, __PRETTY_FUNCTION__))
6699 "zero-initialized array shouldn't have any initialized elts")(((!Result.isArray() || Result.getArrayInitializedElts() == 0
) && "zero-initialized array shouldn't have any initialized elts"
) ? static_cast<void> (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6699, __PRETTY_FUNCTION__))
;
6700 APValue Filler;
6701 if (Result.isArray() && Result.hasArrayFiller())
6702 Filler = Result.getArrayFiller();
6703
6704 unsigned NumEltsToInit = E->getNumInits();
6705 unsigned NumElts = CAT->getSize().getZExtValue();
6706 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5
Assuming the condition is false
6
'?' condition is false
7
'FillerExpr' initialized to a null pointer value
6707
6708 // If the initializer might depend on the array index, run it for each
6709 // array element. For now, just whitelist non-class value-initialization.
6710 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6711 NumEltsToInit = NumElts;
6712
6713 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6714
6715 // If the array was previously zero-initialized, preserve the
6716 // zero-initialized values.
6717 if (!Filler.isUninit()) {
8
Taking false branch
6718 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6719 Result.getArrayInitializedElt(I) = Filler;
6720 if (Result.hasArrayFiller())
6721 Result.getArrayFiller() = Filler;
6722 }
6723
6724 LValue Subobject = This;
6725 Subobject.addArray(Info, E, CAT);
6726 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9
Assuming 'Index' is not equal to 'NumEltsToInit'
10
Loop condition is true. Entering loop body
6727 const Expr *Init =
13
'Init' initialized to a null pointer value
6728 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
11
Assuming the condition is false
12
'?' condition is false
6729 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
14
Assuming the condition is false
6730 Info, Subobject, Init) ||
6731 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15
Passing null pointer value via 2nd parameter 'E'
16
Calling 'HandleLValueArrayAdjustment'
6732 CAT->getElementType(), 1)) {
6733 if (!Info.noteFailure())
6734 return false;
6735 Success = false;
6736 }
6737 }
6738
6739 if (!Result.hasArrayFiller())
6740 return Success;
6741
6742 // If we get here, we have a trivial filler, which we can just evaluate
6743 // once and splat over the rest of the array elements.
6744 assert(FillerExpr && "no array filler for incomplete init list")((FillerExpr && "no array filler for incomplete init list"
) ? static_cast<void> (0) : __assert_fail ("FillerExpr && \"no array filler for incomplete init list\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6744, __PRETTY_FUNCTION__))
;
6745 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6746 FillerExpr) && Success;
6747}
6748
6749bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6750 if (E->getCommonExpr() &&
6751 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6752 Info, E->getCommonExpr()->getSourceExpr()))
6753 return false;
6754
6755 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6756
6757 uint64_t Elements = CAT->getSize().getZExtValue();
6758 Result = APValue(APValue::UninitArray(), Elements, Elements);
6759
6760 LValue Subobject = This;
6761 Subobject.addArray(Info, E, CAT);
6762
6763 bool Success = true;
6764 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6765 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6766 Info, Subobject, E->getSubExpr()) ||
6767 !HandleLValueArrayAdjustment(Info, E, Subobject,
6768 CAT->getElementType(), 1)) {
6769 if (!Info.noteFailure())
6770 return false;
6771 Success = false;
6772 }
6773 }
6774
6775 return Success;
6776}
6777
6778bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6779 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6780}
6781
6782bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6783 const LValue &Subobject,
6784 APValue *Value,
6785 QualType Type) {
6786 bool HadZeroInit = !Value->isUninit();
6787
6788 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6789 unsigned N = CAT->getSize().getZExtValue();
6790
6791 // Preserve the array filler if we had prior zero-initialization.
6792 APValue Filler =
6793 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6794 : APValue();
6795
6796 *Value = APValue(APValue::UninitArray(), N, N);
6797
6798 if (HadZeroInit)
6799 for (unsigned I = 0; I != N; ++I)
6800 Value->getArrayInitializedElt(I) = Filler;
6801
6802 // Initialize the elements.
6803 LValue ArrayElt = Subobject;
6804 ArrayElt.addArray(Info, E, CAT);
6805 for (unsigned I = 0; I != N; ++I)
6806 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6807 CAT->getElementType()) ||
6808 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6809 CAT->getElementType(), 1))
6810 return false;
6811
6812 return true;
6813 }
6814
6815 if (!Type->isRecordType())
6816 return Error(E);
6817
6818 return RecordExprEvaluator(Info, Subobject, *Value)
6819 .VisitCXXConstructExpr(E, Type);
6820}
6821
6822//===----------------------------------------------------------------------===//
6823// Integer Evaluation
6824//
6825// As a GNU extension, we support casting pointers to sufficiently-wide integer
6826// types and back in constant folding. Integer values are thus represented
6827// either as an integer-valued APValue, or as an lvalue-valued APValue.
6828//===----------------------------------------------------------------------===//
6829
6830namespace {
6831class IntExprEvaluator
6832 : public ExprEvaluatorBase<IntExprEvaluator> {
6833 APValue &Result;
6834public:
6835 IntExprEvaluator(EvalInfo &info, APValue &result)
6836 : ExprEvaluatorBaseTy(info), Result(result) {}
6837
6838 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6839 assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6840, __PRETTY_FUNCTION__))
6840 "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6840, __PRETTY_FUNCTION__))
;
6841 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&((SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType
() && "Invalid evaluation result.") ? static_cast<
void> (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6842, __PRETTY_FUNCTION__))
6842 "Invalid evaluation result.")((SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType
() && "Invalid evaluation result.") ? static_cast<
void> (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6842, __PRETTY_FUNCTION__))
;
6843 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&((SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6844, __PRETTY_FUNCTION__))
6844 "Invalid evaluation result.")((SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6844, __PRETTY_FUNCTION__))
;
6845 Result = APValue(SI);
6846 return true;
6847 }
6848 bool Success(const llvm::APSInt &SI, const Expr *E) {
6849 return Success(SI, E, Result);
6850 }
6851
6852 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6853 assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6854, __PRETTY_FUNCTION__))
6854 "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6854, __PRETTY_FUNCTION__))
;
6855 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&((I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6856, __PRETTY_FUNCTION__))
6856 "Invalid evaluation result.")((I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6856, __PRETTY_FUNCTION__))
;
6857 Result = APValue(APSInt(I));
6858 Result.getInt().setIsUnsigned(
6859 E->getType()->isUnsignedIntegerOrEnumerationType());
6860 return true;
6861 }
6862 bool Success(const llvm::APInt &I, const Expr *E) {
6863 return Success(I, E, Result);
6864 }
6865
6866 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6867 assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6868, __PRETTY_FUNCTION__))
6868 "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() &&
"Invalid evaluation result.") ? static_cast<void> (0) :
__assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6868, __PRETTY_FUNCTION__))
;
6869 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6870 return true;
6871 }
6872 bool Success(uint64_t Value, const Expr *E) {
6873 return Success(Value, E, Result);
6874 }
6875
6876 bool Success(CharUnits Size, const Expr *E) {
6877 return Success(Size.getQuantity(), E);
6878 }
6879
6880 bool Success(const APValue &V, const Expr *E) {
6881 if (V.isLValue() || V.isAddrLabelDiff()) {
6882 Result = V;
6883 return true;
6884 }
6885 return Success(V.getInt(), E);
6886 }
6887
6888 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6889
6890 //===--------------------------------------------------------------------===//
6891 // Visitor Methods
6892 //===--------------------------------------------------------------------===//
6893
6894 bool VisitIntegerLiteral(const IntegerLiteral *E) {
6895 return Success(E->getValue(), E);
6896 }
6897 bool VisitCharacterLiteral(const CharacterLiteral *E) {
6898 return Success(E->getValue(), E);
6899 }
6900
6901 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6902 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6903 if (CheckReferencedDecl(E, E->getDecl()))
6904 return true;
6905
6906 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6907 }
6908 bool VisitMemberExpr(const MemberExpr *E) {
6909 if (CheckReferencedDecl(E, E->getMemberDecl())) {
6910 VisitIgnoredBaseExpression(E->getBase());
6911 return true;
6912 }
6913
6914 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6915 }
6916
6917 bool VisitCallExpr(const CallExpr *E);
6918 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6919 bool VisitBinaryOperator(const BinaryOperator *E);
6920 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6921 bool VisitUnaryOperator(const UnaryOperator *E);
6922
6923 bool VisitCastExpr(const CastExpr* E);
6924 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6925
6926 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6927 return Success(E->getValue(), E);
6928 }
6929
6930 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6931 return Success(E->getValue(), E);
6932 }
6933
6934 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6935 if (Info.ArrayInitIndex == uint64_t(-1)) {
6936 // We were asked to evaluate this subexpression independent of the
6937 // enclosing ArrayInitLoopExpr. We can't do that.
6938 Info.FFDiag(E);
6939 return false;
6940 }
6941 return Success(Info.ArrayInitIndex, E);
6942 }
6943
6944 // Note, GNU defines __null as an integer, not a pointer.
6945 bool VisitGNUNullExpr(const GNUNullExpr *E) {
6946 return ZeroInitialization(E);
6947 }
6948
6949 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6950 return Success(E->getValue(), E);
6951 }
6952
6953 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6954 return Success(E->getValue(), E);
6955 }
6956
6957 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6958 return Success(E->getValue(), E);
6959 }
6960
6961 bool VisitUnaryReal(const UnaryOperator *E);
6962 bool VisitUnaryImag(const UnaryOperator *E);
6963
6964 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6965 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6966
6967 // FIXME: Missing: array subscript of vector, member of vector
6968};
6969} // end anonymous namespace
6970
6971/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6972/// produce either the integer value or a pointer.
6973///
6974/// GCC has a heinous extension which folds casts between pointer types and
6975/// pointer-sized integral types. We support this by allowing the evaluation of
6976/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6977/// Some simple arithmetic on such values is supported (they are treated much
6978/// like char*).
6979static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6980 EvalInfo &Info) {
6981 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType())((E->isRValue() && E->getType()->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isIntegralOrEnumerationType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 6981, __PRETTY_FUNCTION__))
;
6982 return IntExprEvaluator(Info, Result).Visit(E);
6983}
6984
6985static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6986 APValue Val;
6987 if (!EvaluateIntegerOrLValue(E, Val, Info))
6988 return false;
6989 if (!Val.isInt()) {
6990 // FIXME: It would be better to produce the diagnostic for casting
6991 // a pointer to an integer.
6992 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
6993 return false;
6994 }
6995 Result = Val.getInt();
6996 return true;
6997}
6998
6999/// Check whether the given declaration can be directly converted to an integral
7000/// rvalue. If not, no diagnostic is produced; there are other things we can
7001/// try.
7002bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7003 // Enums are integer constant exprs.
7004 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7005 // Check for signedness/width mismatches between E type and ECD value.
7006 bool SameSign = (ECD->getInitVal().isSigned()
7007 == E->getType()->isSignedIntegerOrEnumerationType());
7008 bool SameWidth = (ECD->getInitVal().getBitWidth()
7009 == Info.Ctx.getIntWidth(E->getType()));
7010 if (SameSign && SameWidth)
7011 return Success(ECD->getInitVal(), E);
7012 else {
7013 // Get rid of mismatch (otherwise Success assertions will fail)
7014 // by computing a new value matching the type of E.
7015 llvm::APSInt Val = ECD->getInitVal();
7016 if (!SameSign)
7017 Val.setIsSigned(!ECD->getInitVal().isSigned());
7018 if (!SameWidth)
7019 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7020 return Success(Val, E);
7021 }
7022 }
7023 return false;
7024}
7025
7026/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7027/// as GCC.
7028static int EvaluateBuiltinClassifyType(const CallExpr *E,
7029 const LangOptions &LangOpts) {
7030 // The following enum mimics the values returned by GCC.
7031 // FIXME: Does GCC differ between lvalue and rvalue references here?
7032 enum gcc_type_class {
7033 no_type_class = -1,
7034 void_type_class, integer_type_class, char_type_class,
7035 enumeral_type_class, boolean_type_class,
7036 pointer_type_class, reference_type_class, offset_type_class,
7037 real_type_class, complex_type_class,
7038 function_type_class, method_type_class,
7039 record_type_class, union_type_class,
7040 array_type_class, string_type_class,
7041 lang_type_class
7042 };
7043
7044 // If no argument was supplied, default to "no_type_class". This isn't
7045 // ideal, however it is what gcc does.
7046 if (E->getNumArgs() == 0)
7047 return no_type_class;
7048
7049 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7050 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7051
7052 switch (CanTy->getTypeClass()) {
7053#define TYPE(ID, BASE)
7054#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7055#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7056#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7057#include "clang/AST/TypeNodes.def"
7058 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7058)
;
7059
7060 case Type::Builtin:
7061 switch (BT->getKind()) {
7062#define BUILTIN_TYPE(ID, SINGLETON_ID)
7063#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7064#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7065#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7066#include "clang/AST/BuiltinTypes.def"
7067 case BuiltinType::Void:
7068 return void_type_class;
7069
7070 case BuiltinType::Bool:
7071 return boolean_type_class;
7072
7073 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7074 case BuiltinType::UChar:
7075 case BuiltinType::UShort:
7076 case BuiltinType::UInt:
7077 case BuiltinType::ULong:
7078 case BuiltinType::ULongLong:
7079 case BuiltinType::UInt128:
7080 return integer_type_class;
7081
7082 case BuiltinType::NullPtr:
7083 return pointer_type_class;
7084
7085 case BuiltinType::WChar_U:
7086 case BuiltinType::Char16:
7087 case BuiltinType::Char32:
7088 case BuiltinType::ObjCId:
7089 case BuiltinType::ObjCClass:
7090 case BuiltinType::ObjCSel:
7091#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7092 case BuiltinType::Id:
7093#include "clang/Basic/OpenCLImageTypes.def"
7094 case BuiltinType::OCLSampler:
7095 case BuiltinType::OCLEvent:
7096 case BuiltinType::OCLClkEvent:
7097 case BuiltinType::OCLQueue:
7098 case BuiltinType::OCLReserveID:
7099 case BuiltinType::Dependent:
7100 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7100)
;
7101 };
7102
7103 case Type::Enum:
7104 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7105 break;
7106
7107 case Type::Pointer:
7108 return pointer_type_class;
7109 break;
7110
7111 case Type::MemberPointer:
7112 if (CanTy->isMemberDataPointerType())
7113 return offset_type_class;
7114 else {
7115 // We expect member pointers to be either data or function pointers,
7116 // nothing else.
7117 assert(CanTy->isMemberFunctionPointerType())((CanTy->isMemberFunctionPointerType()) ? static_cast<void
> (0) : __assert_fail ("CanTy->isMemberFunctionPointerType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7117, __PRETTY_FUNCTION__))
;
7118 return method_type_class;
7119 }
7120
7121 case Type::Complex:
7122 return complex_type_class;
7123
7124 case Type::FunctionNoProto:
7125 case Type::FunctionProto:
7126 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7127
7128 case Type::Record:
7129 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7130 switch (RT->getDecl()->getTagKind()) {
7131 case TagTypeKind::TTK_Struct:
7132 case TagTypeKind::TTK_Class:
7133 case TagTypeKind::TTK_Interface:
7134 return record_type_class;
7135
7136 case TagTypeKind::TTK_Enum:
7137 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7138
7139 case TagTypeKind::TTK_Union:
7140 return union_type_class;
7141 }
7142 }
7143 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7143)
;
7144
7145 case Type::ConstantArray:
7146 case Type::VariableArray:
7147 case Type::IncompleteArray:
7148 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7149
7150 case Type::BlockPointer:
7151 case Type::LValueReference:
7152 case Type::RValueReference:
7153 case Type::Vector:
7154 case Type::ExtVector:
7155 case Type::Auto:
7156 case Type::DeducedTemplateSpecialization:
7157 case Type::ObjCObject:
7158 case Type::ObjCInterface:
7159 case Type::ObjCObjectPointer:
7160 case Type::Pipe:
7161 case Type::Atomic:
7162 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7162)
;
7163 }
7164
7165 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type")::llvm::llvm_unreachable_internal("CallExpr::isBuiltinClassifyType(): unimplemented type"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7165)
;
7166}
7167
7168/// EvaluateBuiltinConstantPForLValue - Determine the result of
7169/// __builtin_constant_p when applied to the given lvalue.
7170///
7171/// An lvalue is only "constant" if it is a pointer or reference to the first
7172/// character of a string literal.
7173template<typename LValue>
7174static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7175 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7176 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7177}
7178
7179/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7180/// GCC as we can manage.
7181static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7182 QualType ArgType = Arg->getType();
7183
7184 // __builtin_constant_p always has one operand. The rules which gcc follows
7185 // are not precisely documented, but are as follows:
7186 //
7187 // - If the operand is of integral, floating, complex or enumeration type,
7188 // and can be folded to a known value of that type, it returns 1.
7189 // - If the operand and can be folded to a pointer to the first character
7190 // of a string literal (or such a pointer cast to an integral type), it
7191 // returns 1.
7192 //
7193 // Otherwise, it returns 0.
7194 //
7195 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7196 // its support for this does not currently work.
7197 if (ArgType->isIntegralOrEnumerationType()) {
7198 Expr::EvalResult Result;
7199 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7200 return false;
7201
7202 APValue &V = Result.Val;
7203 if (V.getKind() == APValue::Int)
7204 return true;
7205 if (V.getKind() == APValue::LValue)
7206 return EvaluateBuiltinConstantPForLValue(V);
7207 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7208 return Arg->isEvaluatable(Ctx);
7209 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7210 LValue LV;
7211 Expr::EvalStatus Status;
7212 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7213 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7214 : EvaluatePointer(Arg, LV, Info)) &&
7215 !Status.HasSideEffects)
7216 return EvaluateBuiltinConstantPForLValue(LV);
7217 }
7218
7219 // Anything else isn't considered to be sufficiently constant.
7220 return false;
7221}
7222
7223/// Retrieves the "underlying object type" of the given expression,
7224/// as used by __builtin_object_size.
7225static QualType getObjectType(APValue::LValueBase B) {
7226 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7227 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7228 return VD->getType();
7229 } else if (const Expr *E = B.get<const Expr*>()) {
7230 if (isa<CompoundLiteralExpr>(E))
7231 return E->getType();
7232 }
7233
7234 return QualType();
7235}
7236
7237/// A more selective version of E->IgnoreParenCasts for
7238/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7239/// to change the type of E.
7240/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7241///
7242/// Always returns an RValue with a pointer representation.
7243static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7244 assert(E->isRValue() && E->getType()->hasPointerRepresentation())((E->isRValue() && E->getType()->hasPointerRepresentation
()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->hasPointerRepresentation()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7244, __PRETTY_FUNCTION__))
;
7245
7246 auto *NoParens = E->IgnoreParens();
7247 auto *Cast = dyn_cast<CastExpr>(NoParens);
7248 if (Cast == nullptr)
7249 return NoParens;
7250
7251 // We only conservatively allow a few kinds of casts, because this code is
7252 // inherently a simple solution that seeks to support the common case.
7253 auto CastKind = Cast->getCastKind();
7254 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7255 CastKind != CK_AddressSpaceConversion)
7256 return NoParens;
7257
7258 auto *SubExpr = Cast->getSubExpr();
7259 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7260 return NoParens;
7261 return ignorePointerCastsAndParens(SubExpr);
7262}
7263
7264/// Checks to see if the given LValue's Designator is at the end of the LValue's
7265/// record layout. e.g.
7266/// struct { struct { int a, b; } fst, snd; } obj;
7267/// obj.fst // no
7268/// obj.snd // yes
7269/// obj.fst.a // no
7270/// obj.fst.b // no
7271/// obj.snd.a // no
7272/// obj.snd.b // yes
7273///
7274/// Please note: this function is specialized for how __builtin_object_size
7275/// views "objects".
7276///
7277/// If this encounters an invalid RecordDecl, it will always return true.
7278static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7279 assert(!LVal.Designator.Invalid)((!LVal.Designator.Invalid) ? static_cast<void> (0) : __assert_fail
("!LVal.Designator.Invalid", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7279, __PRETTY_FUNCTION__))
;
7280
7281 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7282 const RecordDecl *Parent = FD->getParent();
7283 Invalid = Parent->isInvalidDecl();
7284 if (Invalid || Parent->isUnion())
7285 return true;
7286 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7287 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7288 };
7289
7290 auto &Base = LVal.getLValueBase();
7291 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7292 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7293 bool Invalid;
7294 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7295 return Invalid;
7296 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7297 for (auto *FD : IFD->chain()) {
7298 bool Invalid;
7299 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7300 return Invalid;
7301 }
7302 }
7303 }
7304
7305 unsigned I = 0;
7306 QualType BaseType = getType(Base);
7307 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7308 assert(isBaseAnAllocSizeCall(Base) &&((isBaseAnAllocSizeCall(Base) && "Unsized array in non-alloc_size call?"
) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(Base) && \"Unsized array in non-alloc_size call?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7309, __PRETTY_FUNCTION__))
7309 "Unsized array in non-alloc_size call?")((isBaseAnAllocSizeCall(Base) && "Unsized array in non-alloc_size call?"
) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(Base) && \"Unsized array in non-alloc_size call?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7309, __PRETTY_FUNCTION__))
;
7310 // If this is an alloc_size base, we should ignore the initial array index
7311 ++I;
7312 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7313 }
7314
7315 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7316 const auto &Entry = LVal.Designator.Entries[I];
7317 if (BaseType->isArrayType()) {
7318 // Because __builtin_object_size treats arrays as objects, we can ignore
7319 // the index iff this is the last array in the Designator.
7320 if (I + 1 == E)
7321 return true;
7322 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7323 uint64_t Index = Entry.ArrayIndex;
7324 if (Index + 1 != CAT->getSize())
7325 return false;
7326 BaseType = CAT->getElementType();
7327 } else if (BaseType->isAnyComplexType()) {
7328 const auto *CT = BaseType->castAs<ComplexType>();
7329 uint64_t Index = Entry.ArrayIndex;
7330 if (Index != 1)
7331 return false;
7332 BaseType = CT->getElementType();
7333 } else if (auto *FD = getAsField(Entry)) {
7334 bool Invalid;
7335 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7336 return Invalid;
7337 BaseType = FD->getType();
7338 } else {
7339 assert(getAsBaseClass(Entry) && "Expecting cast to a base class")((getAsBaseClass(Entry) && "Expecting cast to a base class"
) ? static_cast<void> (0) : __assert_fail ("getAsBaseClass(Entry) && \"Expecting cast to a base class\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7339, __PRETTY_FUNCTION__))
;
7340 return false;
7341 }
7342 }
7343 return true;
7344}
7345
7346/// Tests to see if the LValue has a user-specified designator (that isn't
7347/// necessarily valid). Note that this always returns 'true' if the LValue has
7348/// an unsized array as its first designator entry, because there's currently no
7349/// way to tell if the user typed *foo or foo[0].
7350static bool refersToCompleteObject(const LValue &LVal) {
7351 if (LVal.Designator.Invalid)
7352 return false;
7353
7354 if (!LVal.Designator.Entries.empty())
7355 return LVal.Designator.isMostDerivedAnUnsizedArray();
7356
7357 if (!LVal.InvalidBase)
7358 return true;
7359
7360 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7361 // the LValueBase.
7362 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7363 return !E || !isa<MemberExpr>(E);
7364}
7365
7366/// Attempts to detect a user writing into a piece of memory that's impossible
7367/// to figure out the size of by just using types.
7368static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7369 const SubobjectDesignator &Designator = LVal.Designator;
7370 // Notes:
7371 // - Users can only write off of the end when we have an invalid base. Invalid
7372 // bases imply we don't know where the memory came from.
7373 // - We used to be a bit more aggressive here; we'd only be conservative if
7374 // the array at the end was flexible, or if it had 0 or 1 elements. This
7375 // broke some common standard library extensions (PR30346), but was
7376 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7377 // with some sort of whitelist. OTOH, it seems that GCC is always
7378 // conservative with the last element in structs (if it's an array), so our
7379 // current behavior is more compatible than a whitelisting approach would
7380 // be.
7381 return LVal.InvalidBase &&
7382 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7383 Designator.MostDerivedIsArrayElement &&
7384 isDesignatorAtObjectEnd(Ctx, LVal);
7385}
7386
7387/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7388/// Fails if the conversion would cause loss of precision.
7389static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7390 CharUnits &Result) {
7391 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7392 if (Int.ugt(CharUnitsMax))
7393 return false;
7394 Result = CharUnits::fromQuantity(Int.getZExtValue());
7395 return true;
7396}
7397
7398/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7399/// determine how many bytes exist from the beginning of the object to either
7400/// the end of the current subobject, or the end of the object itself, depending
7401/// on what the LValue looks like + the value of Type.
7402///
7403/// If this returns false, the value of Result is undefined.
7404static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7405 unsigned Type, const LValue &LVal,
7406 CharUnits &EndOffset) {
7407 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7408
7409 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7410 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7411 return false;
7412 return HandleSizeof(Info, ExprLoc, Ty, Result);
7413 };
7414
7415 // We want to evaluate the size of the entire object. This is a valid fallback
7416 // for when Type=1 and the designator is invalid, because we're asked for an
7417 // upper-bound.
7418 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7419 // Type=3 wants a lower bound, so we can't fall back to this.
7420 if (Type == 3 && !DetermineForCompleteObject)
7421 return false;
7422
7423 llvm::APInt APEndOffset;
7424 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7425 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7426 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7427
7428 if (LVal.InvalidBase)
7429 return false;
7430
7431 QualType BaseTy = getObjectType(LVal.getLValueBase());
7432 return CheckedHandleSizeof(BaseTy, EndOffset);
7433 }
7434
7435 // We want to evaluate the size of a subobject.
7436 const SubobjectDesignator &Designator = LVal.Designator;
7437
7438 // The following is a moderately common idiom in C:
7439 //
7440 // struct Foo { int a; char c[1]; };
7441 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7442 // strcpy(&F->c[0], Bar);
7443 //
7444 // In order to not break too much legacy code, we need to support it.
7445 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7446 // If we can resolve this to an alloc_size call, we can hand that back,
7447 // because we know for certain how many bytes there are to write to.
7448 llvm::APInt APEndOffset;
7449 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7450 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7451 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7452
7453 // If we cannot determine the size of the initial allocation, then we can't
7454 // given an accurate upper-bound. However, we are still able to give
7455 // conservative lower-bounds for Type=3.
7456 if (Type == 1)
7457 return false;
7458 }
7459
7460 CharUnits BytesPerElem;
7461 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7462 return false;
7463
7464 // According to the GCC documentation, we want the size of the subobject
7465 // denoted by the pointer. But that's not quite right -- what we actually
7466 // want is the size of the immediately-enclosing array, if there is one.
7467 int64_t ElemsRemaining;
7468 if (Designator.MostDerivedIsArrayElement &&
7469 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7470 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7471 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7472 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7473 } else {
7474 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7475 }
7476
7477 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7478 return true;
7479}
7480
7481/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7482/// returns true and stores the result in @p Size.
7483///
7484/// If @p WasError is non-null, this will report whether the failure to evaluate
7485/// is to be treated as an Error in IntExprEvaluator.
7486static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7487 EvalInfo &Info, uint64_t &Size) {
7488 // Determine the denoted object.
7489 LValue LVal;
7490 {
7491 // The operand of __builtin_object_size is never evaluated for side-effects.
7492 // If there are any, but we can determine the pointed-to object anyway, then
7493 // ignore the side-effects.
7494 SpeculativeEvaluationRAII SpeculativeEval(Info);
7495 FoldOffsetRAII Fold(Info);
7496
7497 if (E->isGLValue()) {
7498 // It's possible for us to be given GLValues if we're called via
7499 // Expr::tryEvaluateObjectSize.
7500 APValue RVal;
7501 if (!EvaluateAsRValue(Info, E, RVal))
7502 return false;
7503 LVal.setFrom(Info.Ctx, RVal);
7504 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7505 /*InvalidBaseOK=*/true))
7506 return false;
7507 }
7508
7509 // If we point to before the start of the object, there are no accessible
7510 // bytes.
7511 if (LVal.getLValueOffset().isNegative()) {
7512 Size = 0;
7513 return true;
7514 }
7515
7516 CharUnits EndOffset;
7517 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7518 return false;
7519
7520 // If we've fallen outside of the end offset, just pretend there's nothing to
7521 // write to/read from.
7522 if (EndOffset <= LVal.getLValueOffset())
7523 Size = 0;
7524 else
7525 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7526 return true;
7527}
7528
7529bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7530 if (unsigned BuiltinOp = E->getBuiltinCallee())
7531 return VisitBuiltinCallExpr(E, BuiltinOp);
7532
7533 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7534}
7535
7536bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7537 unsigned BuiltinOp) {
7538 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7539 default:
7540 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7541
7542 case Builtin::BI__builtin_object_size: {
7543 // The type was checked when we built the expression.
7544 unsigned Type =
7545 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7546 assert(Type <= 3 && "unexpected type")((Type <= 3 && "unexpected type") ? static_cast<
void> (0) : __assert_fail ("Type <= 3 && \"unexpected type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7546, __PRETTY_FUNCTION__))
;
7547
7548 uint64_t Size;
7549 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7550 return Success(Size, E);
7551
7552 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7553 return Success((Type & 2) ? 0 : -1, E);
7554
7555 // Expression had no side effects, but we couldn't statically determine the
7556 // size of the referenced object.
7557 switch (Info.EvalMode) {
7558 case EvalInfo::EM_ConstantExpression:
7559 case EvalInfo::EM_PotentialConstantExpression:
7560 case EvalInfo::EM_ConstantFold:
7561 case EvalInfo::EM_EvaluateForOverflow:
7562 case EvalInfo::EM_IgnoreSideEffects:
7563 case EvalInfo::EM_OffsetFold:
7564 // Leave it to IR generation.
7565 return Error(E);
7566 case EvalInfo::EM_ConstantExpressionUnevaluated:
7567 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7568 // Reduce it to a constant now.
7569 return Success((Type & 2) ? 0 : -1, E);
7570 }
7571
7572 llvm_unreachable("unexpected EvalMode")::llvm::llvm_unreachable_internal("unexpected EvalMode", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/lib/AST/ExprConstant.cpp"
, 7572)
;
7573 }
7574
7575 case Builtin::BI__builtin_bswap16:
7576 case Builtin::BI__builtin_bswap32:
7577 case Builtin::BI__builtin_bswap64: {
7578 APSInt Val;
7579 if (!EvaluateInteger(E->getArg(0), Val, Info))
7580 return false;
7581
7582 return Success(Val.byteSwap(), E);
7583 }
7584
7585 case Builtin::BI__builtin_classify_type:
7586 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7587
7588 // FIXME: BI__builtin_clrsb
7589 // FIXME: BI__builtin_clrsbl
7590 // FIXME: BI__builtin_clrsbll
7591
7592 case Builtin::BI__builtin_clz:
7593 case Builtin::BI__builtin_clzl:
7594 case Builtin::BI__builtin_clzll:
7595 case Builtin::BI__builtin_clzs: {
7596 APSInt Val;
7597 if (!EvaluateInteger(E->getArg(0), Val, Info))
7598 return false;
7599 if (!Val)
7600 return Error(E);
7601
7602 return Success(Val.countLeadingZeros(), E);
7603 }
7604
7605 case Builtin::BI__builtin_constant_p:
7606 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7607
7608 case Builtin::BI__builtin_ctz:
7609 case Builtin::BI__builtin_ctzl:
7610 case Builtin::BI__builtin_ctzll:
7611 case Builtin::BI__builtin_ctzs: {
7612 APSInt Val;
7613 if (!EvaluateInteger(E->getArg(0), Val, Info))
7614 return false;
7615 if (!Val)
7616 return Error(E);
7617
7618 return Success(Val.countTrailingZeros(), E);
7619 }
7620
7621 case Builtin::BI__builtin_eh_return_data_regno: {
7622 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7623 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7624 return Success(Operand, E);
7625 }
7626
7627 case Builtin::BI__builtin_expect:
7628 return Visit(E->getArg(0));
7629
7630 case Builtin::BI__builtin_ffs:
7631 case Builtin::BI__builtin_ffsl: