Bug Summary

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

Annotated Source Code

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