Bug Summary

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