clang 20.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ExprConstShared.h"
36#include "Interp/Context.h"
37#include "Interp/Frame.h"
38#include "Interp/State.h"
39#include "clang/AST/APValue.h"
42#include "clang/AST/ASTLambda.h"
43#include "clang/AST/Attr.h"
45#include "clang/AST/CharUnits.h"
47#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/TypeLoc.h"
56#include "llvm/ADT/APFixedPoint.h"
57#include "llvm/ADT/SmallBitVector.h"
58#include "llvm/ADT/StringExtras.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/SaveAndRestore.h"
61#include "llvm/Support/SipHash.h"
62#include "llvm/Support/TimeProfiler.h"
63#include "llvm/Support/raw_ostream.h"
64#include <cstring>
65#include <functional>
66#include <optional>
67
68#define DEBUG_TYPE "exprconstant"
69
70using namespace clang;
71using llvm::APFixedPoint;
72using llvm::APInt;
73using llvm::APSInt;
74using llvm::APFloat;
75using llvm::FixedPointSemantics;
76
77namespace {
78 struct LValue;
79 class CallStackFrame;
80 class EvalInfo;
81
82 using SourceLocExprScopeGuard =
84
85 static QualType getType(APValue::LValueBase B) {
86 return B.getType();
87 }
88
89 /// Get an LValue path entry, which is known to not be an array index, as a
90 /// field declaration.
91 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
92 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
93 }
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// base class declaration.
96 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Determine whether this LValue path entry for a base class names a virtual
100 /// base class.
101 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
102 return E.getAsBaseOrMember().getInt();
103 }
104
105 /// Given an expression, determine the type used to store the result of
106 /// evaluating that expression.
107 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
108 if (E->isPRValue())
109 return E->getType();
110 return Ctx.getLValueReferenceType(E->getType());
111 }
112
113 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
114 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
115 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
116 return DirectCallee->getAttr<AllocSizeAttr>();
117 if (const Decl *IndirectCallee = CE->getCalleeDecl())
118 return IndirectCallee->getAttr<AllocSizeAttr>();
119 return nullptr;
120 }
121
122 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
123 /// This will look through a single cast.
124 ///
125 /// Returns null if we couldn't unwrap a function with alloc_size.
126 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
127 if (!E->getType()->isPointerType())
128 return nullptr;
129
130 E = E->IgnoreParens();
131 // If we're doing a variable assignment from e.g. malloc(N), there will
132 // probably be a cast of some kind. In exotic cases, we might also see a
133 // top-level ExprWithCleanups. Ignore them either way.
134 if (const auto *FE = dyn_cast<FullExpr>(E))
135 E = FE->getSubExpr()->IgnoreParens();
136
137 if (const auto *Cast = dyn_cast<CastExpr>(E))
138 E = Cast->getSubExpr()->IgnoreParens();
139
140 if (const auto *CE = dyn_cast<CallExpr>(E))
141 return getAllocSizeAttr(CE) ? CE : nullptr;
142 return nullptr;
143 }
144
145 /// Determines whether or not the given Base contains a call to a function
146 /// with the alloc_size attribute.
147 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148 const auto *E = Base.dyn_cast<const Expr *>();
149 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150 }
151
152 /// Determines whether the given kind of constant expression is only ever
153 /// used for name mangling. If so, it's permitted to reference things that we
154 /// can't generate code for (in particular, dllimported functions).
155 static bool isForManglingOnly(ConstantExprKind Kind) {
156 switch (Kind) {
157 case ConstantExprKind::Normal:
158 case ConstantExprKind::ClassTemplateArgument:
159 case ConstantExprKind::ImmediateInvocation:
160 // Note that non-type template arguments of class type are emitted as
161 // template parameter objects.
162 return false;
163
164 case ConstantExprKind::NonClassTemplateArgument:
165 return true;
166 }
167 llvm_unreachable("unknown ConstantExprKind");
168 }
169
170 static bool isTemplateArgument(ConstantExprKind Kind) {
171 switch (Kind) {
172 case ConstantExprKind::Normal:
173 case ConstantExprKind::ImmediateInvocation:
174 return false;
175
176 case ConstantExprKind::ClassTemplateArgument:
177 case ConstantExprKind::NonClassTemplateArgument:
178 return true;
179 }
180 llvm_unreachable("unknown ConstantExprKind");
181 }
182
183 /// The bound to claim that an array of unknown bound has.
184 /// The value in MostDerivedArraySize is undefined in this case. So, set it
185 /// to an arbitrary value that's likely to loudly break things if it's used.
186 static const uint64_t AssumedSizeForUnsizedArray =
187 std::numeric_limits<uint64_t>::max() / 2;
188
189 /// Determines if an LValue with the given LValueBase will have an unsized
190 /// array in its designator.
191 /// Find the path length and type of the most-derived subobject in the given
192 /// path, and find the size of the containing array, if any.
193 static unsigned
194 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
196 uint64_t &ArraySize, QualType &Type, bool &IsArray,
197 bool &FirstEntryIsUnsizedArray) {
198 // This only accepts LValueBases from APValues, and APValues don't support
199 // arrays that lack size info.
200 assert(!isBaseAnAllocSizeCall(Base) &&
201 "Unsized arrays shouldn't appear here");
202 unsigned MostDerivedLength = 0;
203 Type = getType(Base);
204
205 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
206 if (Type->isArrayType()) {
207 const ArrayType *AT = Ctx.getAsArrayType(Type);
208 Type = AT->getElementType();
209 MostDerivedLength = I + 1;
210 IsArray = true;
211
212 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
213 ArraySize = CAT->getZExtSize();
214 } else {
215 assert(I == 0 && "unexpected unsized array designator");
216 FirstEntryIsUnsizedArray = true;
217 ArraySize = AssumedSizeForUnsizedArray;
218 }
219 } else if (Type->isAnyComplexType()) {
220 const ComplexType *CT = Type->castAs<ComplexType>();
221 Type = CT->getElementType();
222 ArraySize = 2;
223 MostDerivedLength = I + 1;
224 IsArray = true;
225 } else if (const FieldDecl *FD = getAsField(Path[I])) {
226 Type = FD->getType();
227 ArraySize = 0;
228 MostDerivedLength = I + 1;
229 IsArray = false;
230 } else {
231 // Path[I] describes a base class.
232 ArraySize = 0;
233 IsArray = false;
234 }
235 }
236 return MostDerivedLength;
237 }
238
239 /// A path from a glvalue to a subobject of that glvalue.
240 struct SubobjectDesignator {
241 /// True if the subobject was named in a manner not supported by C++11. Such
242 /// lvalues can still be folded, but they are not core constant expressions
243 /// and we cannot perform lvalue-to-rvalue conversions on them.
244 LLVM_PREFERRED_TYPE(bool)
245 unsigned Invalid : 1;
246
247 /// Is this a pointer one past the end of an object?
248 LLVM_PREFERRED_TYPE(bool)
249 unsigned IsOnePastTheEnd : 1;
250
251 /// Indicator of whether the first entry is an unsized array.
252 LLVM_PREFERRED_TYPE(bool)
253 unsigned FirstEntryIsAnUnsizedArray : 1;
254
255 /// Indicator of whether the most-derived object is an array element.
256 LLVM_PREFERRED_TYPE(bool)
257 unsigned MostDerivedIsArrayElement : 1;
258
259 /// The length of the path to the most-derived object of which this is a
260 /// subobject.
261 unsigned MostDerivedPathLength : 28;
262
263 /// The size of the array of which the most-derived object is an element.
264 /// This will always be 0 if the most-derived object is not an array
265 /// element. 0 is not an indicator of whether or not the most-derived object
266 /// is an array, however, because 0-length arrays are allowed.
267 ///
268 /// If the current array is an unsized array, the value of this is
269 /// undefined.
270 uint64_t MostDerivedArraySize;
271
272 /// The type of the most derived object referred to by this address.
273 QualType MostDerivedType;
274
275 typedef APValue::LValuePathEntry PathEntry;
276
277 /// The entries on the path from the glvalue to the designated subobject.
279
280 SubobjectDesignator() : Invalid(true) {}
281
282 explicit SubobjectDesignator(QualType T)
283 : Invalid(false), IsOnePastTheEnd(false),
284 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
285 MostDerivedPathLength(0), MostDerivedArraySize(0),
286 MostDerivedType(T) {}
287
288 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
289 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
290 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
291 MostDerivedPathLength(0), MostDerivedArraySize(0) {
292 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
293 if (!Invalid) {
294 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
295 ArrayRef<PathEntry> VEntries = V.getLValuePath();
296 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
297 if (V.getLValueBase()) {
298 bool IsArray = false;
299 bool FirstIsUnsizedArray = false;
300 MostDerivedPathLength = findMostDerivedSubobject(
301 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
302 MostDerivedType, IsArray, FirstIsUnsizedArray);
303 MostDerivedIsArrayElement = IsArray;
304 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
305 }
306 }
307 }
308
309 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
310 unsigned NewLength) {
311 if (Invalid)
312 return;
313
314 assert(Base && "cannot truncate path for null pointer");
315 assert(NewLength <= Entries.size() && "not a truncation");
316
317 if (NewLength == Entries.size())
318 return;
319 Entries.resize(NewLength);
320
321 bool IsArray = false;
322 bool FirstIsUnsizedArray = false;
323 MostDerivedPathLength = findMostDerivedSubobject(
324 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
325 FirstIsUnsizedArray);
326 MostDerivedIsArrayElement = IsArray;
327 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
328 }
329
330 void setInvalid() {
331 Invalid = true;
332 Entries.clear();
333 }
334
335 /// Determine whether the most derived subobject is an array without a
336 /// known bound.
337 bool isMostDerivedAnUnsizedArray() const {
338 assert(!Invalid && "Calling this makes no sense on invalid designators");
339 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
340 }
341
342 /// Determine what the most derived array's size is. Results in an assertion
343 /// failure if the most derived array lacks a size.
344 uint64_t getMostDerivedArraySize() const {
345 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
346 return MostDerivedArraySize;
347 }
348
349 /// Determine whether this is a one-past-the-end pointer.
350 bool isOnePastTheEnd() const {
351 assert(!Invalid);
352 if (IsOnePastTheEnd)
353 return true;
354 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
355 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
356 MostDerivedArraySize)
357 return true;
358 return false;
359 }
360
361 /// Get the range of valid index adjustments in the form
362 /// {maximum value that can be subtracted from this pointer,
363 /// maximum value that can be added to this pointer}
364 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
365 if (Invalid || isMostDerivedAnUnsizedArray())
366 return {0, 0};
367
368 // [expr.add]p4: For the purposes of these operators, a pointer to a
369 // nonarray object behaves the same as a pointer to the first element of
370 // an array of length one with the type of the object as its element type.
371 bool IsArray = MostDerivedPathLength == Entries.size() &&
372 MostDerivedIsArrayElement;
373 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
374 : (uint64_t)IsOnePastTheEnd;
375 uint64_t ArraySize =
376 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
377 return {ArrayIndex, ArraySize - ArrayIndex};
378 }
379
380 /// Check that this refers to a valid subobject.
381 bool isValidSubobject() const {
382 if (Invalid)
383 return false;
384 return !isOnePastTheEnd();
385 }
386 /// Check that this refers to a valid subobject, and if not, produce a
387 /// relevant diagnostic and set the designator as invalid.
388 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
389
390 /// Get the type of the designated object.
391 QualType getType(ASTContext &Ctx) const {
392 assert(!Invalid && "invalid designator has no subobject type");
393 return MostDerivedPathLength == Entries.size()
394 ? MostDerivedType
395 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
396 }
397
398 /// Update this designator to refer to the first element within this array.
399 void addArrayUnchecked(const ConstantArrayType *CAT) {
400 Entries.push_back(PathEntry::ArrayIndex(0));
401
402 // This is a most-derived object.
403 MostDerivedType = CAT->getElementType();
404 MostDerivedIsArrayElement = true;
405 MostDerivedArraySize = CAT->getZExtSize();
406 MostDerivedPathLength = Entries.size();
407 }
408 /// Update this designator to refer to the first element within the array of
409 /// elements of type T. This is an array of unknown size.
410 void addUnsizedArrayUnchecked(QualType ElemTy) {
411 Entries.push_back(PathEntry::ArrayIndex(0));
412
413 MostDerivedType = ElemTy;
414 MostDerivedIsArrayElement = true;
415 // The value in MostDerivedArraySize is undefined in this case. So, set it
416 // to an arbitrary value that's likely to loudly break things if it's
417 // used.
418 MostDerivedArraySize = AssumedSizeForUnsizedArray;
419 MostDerivedPathLength = Entries.size();
420 }
421 /// Update this designator to refer to the given base or member of this
422 /// object.
423 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
424 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
425
426 // If this isn't a base class, it's a new most-derived object.
427 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
428 MostDerivedType = FD->getType();
429 MostDerivedIsArrayElement = false;
430 MostDerivedArraySize = 0;
431 MostDerivedPathLength = Entries.size();
432 }
433 }
434 /// Update this designator to refer to the given complex component.
435 void addComplexUnchecked(QualType EltTy, bool Imag) {
436 Entries.push_back(PathEntry::ArrayIndex(Imag));
437
438 // This is technically a most-derived object, though in practice this
439 // is unlikely to matter.
440 MostDerivedType = EltTy;
441 MostDerivedIsArrayElement = true;
442 MostDerivedArraySize = 2;
443 MostDerivedPathLength = Entries.size();
444 }
445 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
446 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
447 const APSInt &N);
448 /// Add N to the address of this subobject.
449 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
450 if (Invalid || !N) return;
451 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
452 if (isMostDerivedAnUnsizedArray()) {
453 diagnoseUnsizedArrayPointerArithmetic(Info, E);
454 // Can't verify -- trust that the user is doing the right thing (or if
455 // not, trust that the caller will catch the bad behavior).
456 // FIXME: Should we reject if this overflows, at least?
457 Entries.back() = PathEntry::ArrayIndex(
458 Entries.back().getAsArrayIndex() + TruncatedN);
459 return;
460 }
461
462 // [expr.add]p4: For the purposes of these operators, a pointer to a
463 // nonarray object behaves the same as a pointer to the first element of
464 // an array of length one with the type of the object as its element type.
465 bool IsArray = MostDerivedPathLength == Entries.size() &&
466 MostDerivedIsArrayElement;
467 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
468 : (uint64_t)IsOnePastTheEnd;
469 uint64_t ArraySize =
470 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
471
472 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
473 // Calculate the actual index in a wide enough type, so we can include
474 // it in the note.
475 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
476 (llvm::APInt&)N += ArrayIndex;
477 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
478 diagnosePointerArithmetic(Info, E, N);
479 setInvalid();
480 return;
481 }
482
483 ArrayIndex += TruncatedN;
484 assert(ArrayIndex <= ArraySize &&
485 "bounds check succeeded for out-of-bounds index");
486
487 if (IsArray)
488 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
489 else
490 IsOnePastTheEnd = (ArrayIndex != 0);
491 }
492 };
493
494 /// A scope at the end of which an object can need to be destroyed.
495 enum class ScopeKind {
496 Block,
497 FullExpression,
498 Call
499 };
500
501 /// A reference to a particular call and its arguments.
502 struct CallRef {
503 CallRef() : OrigCallee(), CallIndex(0), Version() {}
504 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
505 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
506
507 explicit operator bool() const { return OrigCallee; }
508
509 /// Get the parameter that the caller initialized, corresponding to the
510 /// given parameter in the callee.
511 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
512 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
513 : PVD;
514 }
515
516 /// The callee at the point where the arguments were evaluated. This might
517 /// be different from the actual callee (a different redeclaration, or a
518 /// virtual override), but this function's parameters are the ones that
519 /// appear in the parameter map.
520 const FunctionDecl *OrigCallee;
521 /// The call index of the frame that holds the argument values.
522 unsigned CallIndex;
523 /// The version of the parameters corresponding to this call.
524 unsigned Version;
525 };
526
527 /// A stack frame in the constexpr call stack.
528 class CallStackFrame : public interp::Frame {
529 public:
530 EvalInfo &Info;
531
532 /// Parent - The caller of this stack frame.
533 CallStackFrame *Caller;
534
535 /// Callee - The function which was called.
536 const FunctionDecl *Callee;
537
538 /// This - The binding for the this pointer in this call, if any.
539 const LValue *This;
540
541 /// CallExpr - The syntactical structure of member function calls
542 const Expr *CallExpr;
543
544 /// Information on how to find the arguments to this call. Our arguments
545 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
546 /// key and this value as the version.
547 CallRef Arguments;
548
549 /// Source location information about the default argument or default
550 /// initializer expression we're evaluating, if any.
551 CurrentSourceLocExprScope CurSourceLocExprScope;
552
553 // Note that we intentionally use std::map here so that references to
554 // values are stable.
555 typedef std::pair<const void *, unsigned> MapKeyTy;
556 typedef std::map<MapKeyTy, APValue> MapTy;
557 /// Temporaries - Temporary lvalues materialized within this stack frame.
558 MapTy Temporaries;
559
560 /// CallRange - The source range of the call expression for this call.
561 SourceRange CallRange;
562
563 /// Index - The call index of this call.
564 unsigned Index;
565
566 /// The stack of integers for tracking version numbers for temporaries.
567 SmallVector<unsigned, 2> TempVersionStack = {1};
568 unsigned CurTempVersion = TempVersionStack.back();
569
570 unsigned getTempVersion() const { return TempVersionStack.back(); }
571
572 void pushTempVersion() {
573 TempVersionStack.push_back(++CurTempVersion);
574 }
575
576 void popTempVersion() {
577 TempVersionStack.pop_back();
578 }
579
580 CallRef createCall(const FunctionDecl *Callee) {
581 return {Callee, Index, ++CurTempVersion};
582 }
583
584 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
585 // on the overall stack usage of deeply-recursing constexpr evaluations.
586 // (We should cache this map rather than recomputing it repeatedly.)
587 // But let's try this and see how it goes; we can look into caching the map
588 // as a later change.
589
590 /// LambdaCaptureFields - Mapping from captured variables/this to
591 /// corresponding data members in the closure class.
592 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
593 FieldDecl *LambdaThisCaptureField = nullptr;
594
595 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
596 const FunctionDecl *Callee, const LValue *This,
597 const Expr *CallExpr, CallRef Arguments);
598 ~CallStackFrame();
599
600 // Return the temporary for Key whose version number is Version.
601 APValue *getTemporary(const void *Key, unsigned Version) {
602 MapKeyTy KV(Key, Version);
603 auto LB = Temporaries.lower_bound(KV);
604 if (LB != Temporaries.end() && LB->first == KV)
605 return &LB->second;
606 return nullptr;
607 }
608
609 // Return the current temporary for Key in the map.
610 APValue *getCurrentTemporary(const void *Key) {
611 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
612 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
613 return &std::prev(UB)->second;
614 return nullptr;
615 }
616
617 // Return the version number of the current temporary for Key.
618 unsigned getCurrentTemporaryVersion(const void *Key) const {
619 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
620 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
621 return std::prev(UB)->first.second;
622 return 0;
623 }
624
625 /// Allocate storage for an object of type T in this stack frame.
626 /// Populates LV with a handle to the created object. Key identifies
627 /// the temporary within the stack frame, and must not be reused without
628 /// bumping the temporary version number.
629 template<typename KeyT>
630 APValue &createTemporary(const KeyT *Key, QualType T,
631 ScopeKind Scope, LValue &LV);
632
633 /// Allocate storage for a parameter of a function call made in this frame.
634 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
635
636 void describe(llvm::raw_ostream &OS) const override;
637
638 Frame *getCaller() const override { return Caller; }
639 SourceRange getCallRange() const override { return CallRange; }
640 const FunctionDecl *getCallee() const override { return Callee; }
641
642 bool isStdFunction() const {
643 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
644 if (DC->isStdNamespace())
645 return true;
646 return false;
647 }
648
649 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
650 /// permitted. See MSConstexprDocs for description of permitted contexts.
651 bool CanEvalMSConstexpr = false;
652
653 private:
654 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
655 ScopeKind Scope);
656 };
657
658 /// Temporarily override 'this'.
659 class ThisOverrideRAII {
660 public:
661 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
662 : Frame(Frame), OldThis(Frame.This) {
663 if (Enable)
664 Frame.This = NewThis;
665 }
666 ~ThisOverrideRAII() {
667 Frame.This = OldThis;
668 }
669 private:
670 CallStackFrame &Frame;
671 const LValue *OldThis;
672 };
673
674 // A shorthand time trace scope struct, prints source range, for example
675 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
676 class ExprTimeTraceScope {
677 public:
678 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
679 : TimeScope(Name, [E, &Ctx] {
680 return E->getSourceRange().printToString(Ctx.getSourceManager());
681 }) {}
682
683 private:
684 llvm::TimeTraceScope TimeScope;
685 };
686
687 /// RAII object used to change the current ability of
688 /// [[msvc::constexpr]] evaulation.
689 struct MSConstexprContextRAII {
690 CallStackFrame &Frame;
691 bool OldValue;
692 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
693 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
694 Frame.CanEvalMSConstexpr = Value;
695 }
696
697 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
698 };
699}
700
701static bool HandleDestruction(EvalInfo &Info, const Expr *E,
702 const LValue &This, QualType ThisType);
703static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
705 QualType T);
706
707namespace {
708 /// A cleanup, and a flag indicating whether it is lifetime-extended.
709 class Cleanup {
710 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
712 QualType T;
713
714 public:
715 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
716 ScopeKind Scope)
717 : Value(Val, Scope), Base(Base), T(T) {}
718
719 /// Determine whether this cleanup should be performed at the end of the
720 /// given kind of scope.
721 bool isDestroyedAtEndOf(ScopeKind K) const {
722 return (int)Value.getInt() >= (int)K;
723 }
724 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
725 if (RunDestructors) {
727 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
728 Loc = VD->getLocation();
729 else if (const Expr *E = Base.dyn_cast<const Expr*>())
730 Loc = E->getExprLoc();
731 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
732 }
733 *Value.getPointer() = APValue();
734 return true;
735 }
736
737 bool hasSideEffect() {
738 return T.isDestructedType();
739 }
740 };
741
742 /// A reference to an object whose construction we are currently evaluating.
743 struct ObjectUnderConstruction {
746 friend bool operator==(const ObjectUnderConstruction &LHS,
747 const ObjectUnderConstruction &RHS) {
748 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
749 }
750 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
751 return llvm::hash_combine(Obj.Base, Obj.Path);
752 }
753 };
754 enum class ConstructionPhase {
755 None,
756 Bases,
757 AfterBases,
758 AfterFields,
759 Destroying,
760 DestroyingBases
761 };
762}
763
764namespace llvm {
765template<> struct DenseMapInfo<ObjectUnderConstruction> {
766 using Base = DenseMapInfo<APValue::LValueBase>;
767 static ObjectUnderConstruction getEmptyKey() {
768 return {Base::getEmptyKey(), {}}; }
769 static ObjectUnderConstruction getTombstoneKey() {
770 return {Base::getTombstoneKey(), {}};
771 }
772 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
773 return hash_value(Object);
774 }
775 static bool isEqual(const ObjectUnderConstruction &LHS,
776 const ObjectUnderConstruction &RHS) {
777 return LHS == RHS;
778 }
779};
780}
781
782namespace {
783 /// A dynamically-allocated heap object.
784 struct DynAlloc {
785 /// The value of this heap-allocated object.
787 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
788 /// or a CallExpr (the latter is for direct calls to operator new inside
789 /// std::allocator<T>::allocate).
790 const Expr *AllocExpr = nullptr;
791
792 enum Kind {
793 New,
794 ArrayNew,
795 StdAllocator
796 };
797
798 /// Get the kind of the allocation. This must match between allocation
799 /// and deallocation.
800 Kind getKind() const {
801 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
802 return NE->isArray() ? ArrayNew : New;
803 assert(isa<CallExpr>(AllocExpr));
804 return StdAllocator;
805 }
806 };
807
808 struct DynAllocOrder {
809 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
810 return L.getIndex() < R.getIndex();
811 }
812 };
813
814 /// EvalInfo - This is a private struct used by the evaluator to capture
815 /// information about a subexpression as it is folded. It retains information
816 /// about the AST context, but also maintains information about the folded
817 /// expression.
818 ///
819 /// If an expression could be evaluated, it is still possible it is not a C
820 /// "integer constant expression" or constant expression. If not, this struct
821 /// captures information about how and why not.
822 ///
823 /// One bit of information passed *into* the request for constant folding
824 /// indicates whether the subexpression is "evaluated" or not according to C
825 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
826 /// evaluate the expression regardless of what the RHS is, but C only allows
827 /// certain things in certain situations.
828 class EvalInfo : public interp::State {
829 public:
830 ASTContext &Ctx;
831
832 /// EvalStatus - Contains information about the evaluation.
833 Expr::EvalStatus &EvalStatus;
834
835 /// CurrentCall - The top of the constexpr call stack.
836 CallStackFrame *CurrentCall;
837
838 /// CallStackDepth - The number of calls in the call stack right now.
839 unsigned CallStackDepth;
840
841 /// NextCallIndex - The next call index to assign.
842 unsigned NextCallIndex;
843
844 /// StepsLeft - The remaining number of evaluation steps we're permitted
845 /// to perform. This is essentially a limit for the number of statements
846 /// we will evaluate.
847 unsigned StepsLeft;
848
849 /// Enable the experimental new constant interpreter. If an expression is
850 /// not supported by the interpreter, an error is triggered.
851 bool EnableNewConstInterp;
852
853 /// BottomFrame - The frame in which evaluation started. This must be
854 /// initialized after CurrentCall and CallStackDepth.
855 CallStackFrame BottomFrame;
856
857 /// A stack of values whose lifetimes end at the end of some surrounding
858 /// evaluation frame.
860
861 /// EvaluatingDecl - This is the declaration whose initializer is being
862 /// evaluated, if any.
863 APValue::LValueBase EvaluatingDecl;
864
865 enum class EvaluatingDeclKind {
866 None,
867 /// We're evaluating the construction of EvaluatingDecl.
868 Ctor,
869 /// We're evaluating the destruction of EvaluatingDecl.
870 Dtor,
871 };
872 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
873
874 /// EvaluatingDeclValue - This is the value being constructed for the
875 /// declaration whose initializer is being evaluated, if any.
876 APValue *EvaluatingDeclValue;
877
878 /// Set of objects that are currently being constructed.
879 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
880 ObjectsUnderConstruction;
881
882 /// Current heap allocations, along with the location where each was
883 /// allocated. We use std::map here because we need stable addresses
884 /// for the stored APValues.
885 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
886
887 /// The number of heap allocations performed so far in this evaluation.
888 unsigned NumHeapAllocs = 0;
889
890 struct EvaluatingConstructorRAII {
891 EvalInfo &EI;
892 ObjectUnderConstruction Object;
893 bool DidInsert;
894 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
895 bool HasBases)
896 : EI(EI), Object(Object) {
897 DidInsert =
898 EI.ObjectsUnderConstruction
899 .insert({Object, HasBases ? ConstructionPhase::Bases
900 : ConstructionPhase::AfterBases})
901 .second;
902 }
903 void finishedConstructingBases() {
904 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
905 }
906 void finishedConstructingFields() {
907 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
908 }
909 ~EvaluatingConstructorRAII() {
910 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
911 }
912 };
913
914 struct EvaluatingDestructorRAII {
915 EvalInfo &EI;
916 ObjectUnderConstruction Object;
917 bool DidInsert;
918 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
919 : EI(EI), Object(Object) {
920 DidInsert = EI.ObjectsUnderConstruction
921 .insert({Object, ConstructionPhase::Destroying})
922 .second;
923 }
924 void startedDestroyingBases() {
925 EI.ObjectsUnderConstruction[Object] =
926 ConstructionPhase::DestroyingBases;
927 }
928 ~EvaluatingDestructorRAII() {
929 if (DidInsert)
930 EI.ObjectsUnderConstruction.erase(Object);
931 }
932 };
933
934 ConstructionPhase
935 isEvaluatingCtorDtor(APValue::LValueBase Base,
937 return ObjectsUnderConstruction.lookup({Base, Path});
938 }
939
940 /// If we're currently speculatively evaluating, the outermost call stack
941 /// depth at which we can mutate state, otherwise 0.
942 unsigned SpeculativeEvaluationDepth = 0;
943
944 /// The current array initialization index, if we're performing array
945 /// initialization.
946 uint64_t ArrayInitIndex = -1;
947
948 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
949 /// notes attached to it will also be stored, otherwise they will not be.
950 bool HasActiveDiagnostic;
951
952 /// Have we emitted a diagnostic explaining why we couldn't constant
953 /// fold (not just why it's not strictly a constant expression)?
954 bool HasFoldFailureDiagnostic;
955
956 /// Whether we're checking that an expression is a potential constant
957 /// expression. If so, do not fail on constructs that could become constant
958 /// later on (such as a use of an undefined global).
959 bool CheckingPotentialConstantExpression = false;
960
961 /// Whether we're checking for an expression that has undefined behavior.
962 /// If so, we will produce warnings if we encounter an operation that is
963 /// always undefined.
964 ///
965 /// Note that we still need to evaluate the expression normally when this
966 /// is set; this is used when evaluating ICEs in C.
967 bool CheckingForUndefinedBehavior = false;
968
969 enum EvaluationMode {
970 /// Evaluate as a constant expression. Stop if we find that the expression
971 /// is not a constant expression.
972 EM_ConstantExpression,
973
974 /// Evaluate as a constant expression. Stop if we find that the expression
975 /// is not a constant expression. Some expressions can be retried in the
976 /// optimizer if we don't constant fold them here, but in an unevaluated
977 /// context we try to fold them immediately since the optimizer never
978 /// gets a chance to look at it.
979 EM_ConstantExpressionUnevaluated,
980
981 /// Fold the expression to a constant. Stop if we hit a side-effect that
982 /// we can't model.
983 EM_ConstantFold,
984
985 /// Evaluate in any way we know how. Don't worry about side-effects that
986 /// can't be modeled.
987 EM_IgnoreSideEffects,
988 } EvalMode;
989
990 /// Are we checking whether the expression is a potential constant
991 /// expression?
992 bool checkingPotentialConstantExpression() const override {
993 return CheckingPotentialConstantExpression;
994 }
995
996 /// Are we checking an expression for overflow?
997 // FIXME: We should check for any kind of undefined or suspicious behavior
998 // in such constructs, not just overflow.
999 bool checkingForUndefinedBehavior() const override {
1000 return CheckingForUndefinedBehavior;
1001 }
1002
1003 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1004 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1005 CallStackDepth(0), NextCallIndex(1),
1006 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1007 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1008 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1009 /*This=*/nullptr,
1010 /*CallExpr=*/nullptr, CallRef()),
1011 EvaluatingDecl((const ValueDecl *)nullptr),
1012 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1013 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1014
1015 ~EvalInfo() {
1016 discardCleanups();
1017 }
1018
1019 ASTContext &getCtx() const override { return Ctx; }
1020
1021 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1022 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1023 EvaluatingDecl = Base;
1024 IsEvaluatingDecl = EDK;
1025 EvaluatingDeclValue = &Value;
1026 }
1027
1028 bool CheckCallLimit(SourceLocation Loc) {
1029 // Don't perform any constexpr calls (other than the call we're checking)
1030 // when checking a potential constant expression.
1031 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1032 return false;
1033 if (NextCallIndex == 0) {
1034 // NextCallIndex has wrapped around.
1035 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1036 return false;
1037 }
1038 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1039 return true;
1040 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1041 << getLangOpts().ConstexprCallDepth;
1042 return false;
1043 }
1044
1045 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1046 uint64_t ElemCount, bool Diag) {
1047 // FIXME: GH63562
1048 // APValue stores array extents as unsigned,
1049 // so anything that is greater that unsigned would overflow when
1050 // constructing the array, we catch this here.
1051 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1052 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1053 if (Diag)
1054 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1055 return false;
1056 }
1057
1058 // FIXME: GH63562
1059 // Arrays allocate an APValue per element.
1060 // We use the number of constexpr steps as a proxy for the maximum size
1061 // of arrays to avoid exhausting the system resources, as initialization
1062 // of each element is likely to take some number of steps anyway.
1063 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1064 if (ElemCount > Limit) {
1065 if (Diag)
1066 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1067 << ElemCount << Limit;
1068 return false;
1069 }
1070 return true;
1071 }
1072
1073 std::pair<CallStackFrame *, unsigned>
1074 getCallFrameAndDepth(unsigned CallIndex) {
1075 assert(CallIndex && "no call index in getCallFrameAndDepth");
1076 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1077 // be null in this loop.
1078 unsigned Depth = CallStackDepth;
1079 CallStackFrame *Frame = CurrentCall;
1080 while (Frame->Index > CallIndex) {
1081 Frame = Frame->Caller;
1082 --Depth;
1083 }
1084 if (Frame->Index == CallIndex)
1085 return {Frame, Depth};
1086 return {nullptr, 0};
1087 }
1088
1089 bool nextStep(const Stmt *S) {
1090 if (!StepsLeft) {
1091 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1092 return false;
1093 }
1094 --StepsLeft;
1095 return true;
1096 }
1097
1098 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1099
1100 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1101 std::optional<DynAlloc *> Result;
1102 auto It = HeapAllocs.find(DA);
1103 if (It != HeapAllocs.end())
1104 Result = &It->second;
1105 return Result;
1106 }
1107
1108 /// Get the allocated storage for the given parameter of the given call.
1109 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1110 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1111 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1112 : nullptr;
1113 }
1114
1115 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1116 struct StdAllocatorCaller {
1117 unsigned FrameIndex;
1118 QualType ElemType;
1119 explicit operator bool() const { return FrameIndex != 0; };
1120 };
1121
1122 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1123 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1124 Call = Call->Caller) {
1125 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1126 if (!MD)
1127 continue;
1128 const IdentifierInfo *FnII = MD->getIdentifier();
1129 if (!FnII || !FnII->isStr(FnName))
1130 continue;
1131
1132 const auto *CTSD =
1133 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1134 if (!CTSD)
1135 continue;
1136
1137 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1138 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1139 if (CTSD->isInStdNamespace() && ClassII &&
1140 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1141 TAL[0].getKind() == TemplateArgument::Type)
1142 return {Call->Index, TAL[0].getAsType()};
1143 }
1144
1145 return {};
1146 }
1147
1148 void performLifetimeExtension() {
1149 // Disable the cleanups for lifetime-extended temporaries.
1150 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1151 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1152 });
1153 }
1154
1155 /// Throw away any remaining cleanups at the end of evaluation. If any
1156 /// cleanups would have had a side-effect, note that as an unmodeled
1157 /// side-effect and return false. Otherwise, return true.
1158 bool discardCleanups() {
1159 for (Cleanup &C : CleanupStack) {
1160 if (C.hasSideEffect() && !noteSideEffect()) {
1161 CleanupStack.clear();
1162 return false;
1163 }
1164 }
1165 CleanupStack.clear();
1166 return true;
1167 }
1168
1169 private:
1170 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1171 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1172
1173 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1174 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1175
1176 void setFoldFailureDiagnostic(bool Flag) override {
1177 HasFoldFailureDiagnostic = Flag;
1178 }
1179
1180 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1181
1182 // If we have a prior diagnostic, it will be noting that the expression
1183 // isn't a constant expression. This diagnostic is more important,
1184 // unless we require this evaluation to produce a constant expression.
1185 //
1186 // FIXME: We might want to show both diagnostics to the user in
1187 // EM_ConstantFold mode.
1188 bool hasPriorDiagnostic() override {
1189 if (!EvalStatus.Diag->empty()) {
1190 switch (EvalMode) {
1191 case EM_ConstantFold:
1192 case EM_IgnoreSideEffects:
1193 if (!HasFoldFailureDiagnostic)
1194 break;
1195 // We've already failed to fold something. Keep that diagnostic.
1196 [[fallthrough]];
1197 case EM_ConstantExpression:
1198 case EM_ConstantExpressionUnevaluated:
1199 setActiveDiagnostic(false);
1200 return true;
1201 }
1202 }
1203 return false;
1204 }
1205
1206 unsigned getCallStackDepth() override { return CallStackDepth; }
1207
1208 public:
1209 /// Should we continue evaluation after encountering a side-effect that we
1210 /// couldn't model?
1211 bool keepEvaluatingAfterSideEffect() {
1212 switch (EvalMode) {
1213 case EM_IgnoreSideEffects:
1214 return true;
1215
1216 case EM_ConstantExpression:
1217 case EM_ConstantExpressionUnevaluated:
1218 case EM_ConstantFold:
1219 // By default, assume any side effect might be valid in some other
1220 // evaluation of this expression from a different context.
1221 return checkingPotentialConstantExpression() ||
1222 checkingForUndefinedBehavior();
1223 }
1224 llvm_unreachable("Missed EvalMode case");
1225 }
1226
1227 /// Note that we have had a side-effect, and determine whether we should
1228 /// keep evaluating.
1229 bool noteSideEffect() {
1230 EvalStatus.HasSideEffects = true;
1231 return keepEvaluatingAfterSideEffect();
1232 }
1233
1234 /// Should we continue evaluation after encountering undefined behavior?
1235 bool keepEvaluatingAfterUndefinedBehavior() {
1236 switch (EvalMode) {
1237 case EM_IgnoreSideEffects:
1238 case EM_ConstantFold:
1239 return true;
1240
1241 case EM_ConstantExpression:
1242 case EM_ConstantExpressionUnevaluated:
1243 return checkingForUndefinedBehavior();
1244 }
1245 llvm_unreachable("Missed EvalMode case");
1246 }
1247
1248 /// Note that we hit something that was technically undefined behavior, but
1249 /// that we can evaluate past it (such as signed overflow or floating-point
1250 /// division by zero.)
1251 bool noteUndefinedBehavior() override {
1252 EvalStatus.HasUndefinedBehavior = true;
1253 return keepEvaluatingAfterUndefinedBehavior();
1254 }
1255
1256 /// Should we continue evaluation as much as possible after encountering a
1257 /// construct which can't be reduced to a value?
1258 bool keepEvaluatingAfterFailure() const override {
1259 if (!StepsLeft)
1260 return false;
1261
1262 switch (EvalMode) {
1263 case EM_ConstantExpression:
1264 case EM_ConstantExpressionUnevaluated:
1265 case EM_ConstantFold:
1266 case EM_IgnoreSideEffects:
1267 return checkingPotentialConstantExpression() ||
1268 checkingForUndefinedBehavior();
1269 }
1270 llvm_unreachable("Missed EvalMode case");
1271 }
1272
1273 /// Notes that we failed to evaluate an expression that other expressions
1274 /// directly depend on, and determine if we should keep evaluating. This
1275 /// should only be called if we actually intend to keep evaluating.
1276 ///
1277 /// Call noteSideEffect() instead if we may be able to ignore the value that
1278 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1279 ///
1280 /// (Foo(), 1) // use noteSideEffect
1281 /// (Foo() || true) // use noteSideEffect
1282 /// Foo() + 1 // use noteFailure
1283 [[nodiscard]] bool noteFailure() {
1284 // Failure when evaluating some expression often means there is some
1285 // subexpression whose evaluation was skipped. Therefore, (because we
1286 // don't track whether we skipped an expression when unwinding after an
1287 // evaluation failure) every evaluation failure that bubbles up from a
1288 // subexpression implies that a side-effect has potentially happened. We
1289 // skip setting the HasSideEffects flag to true until we decide to
1290 // continue evaluating after that point, which happens here.
1291 bool KeepGoing = keepEvaluatingAfterFailure();
1292 EvalStatus.HasSideEffects |= KeepGoing;
1293 return KeepGoing;
1294 }
1295
1296 class ArrayInitLoopIndex {
1297 EvalInfo &Info;
1298 uint64_t OuterIndex;
1299
1300 public:
1301 ArrayInitLoopIndex(EvalInfo &Info)
1302 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1303 Info.ArrayInitIndex = 0;
1304 }
1305 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1306
1307 operator uint64_t&() { return Info.ArrayInitIndex; }
1308 };
1309 };
1310
1311 /// Object used to treat all foldable expressions as constant expressions.
1312 struct FoldConstant {
1313 EvalInfo &Info;
1314 bool Enabled;
1315 bool HadNoPriorDiags;
1316 EvalInfo::EvaluationMode OldMode;
1317
1318 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1319 : Info(Info),
1320 Enabled(Enabled),
1321 HadNoPriorDiags(Info.EvalStatus.Diag &&
1322 Info.EvalStatus.Diag->empty() &&
1323 !Info.EvalStatus.HasSideEffects),
1324 OldMode(Info.EvalMode) {
1325 if (Enabled)
1326 Info.EvalMode = EvalInfo::EM_ConstantFold;
1327 }
1328 void keepDiagnostics() { Enabled = false; }
1329 ~FoldConstant() {
1330 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1331 !Info.EvalStatus.HasSideEffects)
1332 Info.EvalStatus.Diag->clear();
1333 Info.EvalMode = OldMode;
1334 }
1335 };
1336
1337 /// RAII object used to set the current evaluation mode to ignore
1338 /// side-effects.
1339 struct IgnoreSideEffectsRAII {
1340 EvalInfo &Info;
1341 EvalInfo::EvaluationMode OldMode;
1342 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1343 : Info(Info), OldMode(Info.EvalMode) {
1344 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1345 }
1346
1347 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1348 };
1349
1350 /// RAII object used to optionally suppress diagnostics and side-effects from
1351 /// a speculative evaluation.
1352 class SpeculativeEvaluationRAII {
1353 EvalInfo *Info = nullptr;
1354 Expr::EvalStatus OldStatus;
1355 unsigned OldSpeculativeEvaluationDepth = 0;
1356
1357 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1358 Info = Other.Info;
1359 OldStatus = Other.OldStatus;
1360 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1361 Other.Info = nullptr;
1362 }
1363
1364 void maybeRestoreState() {
1365 if (!Info)
1366 return;
1367
1368 Info->EvalStatus = OldStatus;
1369 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1370 }
1371
1372 public:
1373 SpeculativeEvaluationRAII() = default;
1374
1375 SpeculativeEvaluationRAII(
1376 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1377 : Info(&Info), OldStatus(Info.EvalStatus),
1378 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1379 Info.EvalStatus.Diag = NewDiag;
1380 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1381 }
1382
1383 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1384 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1385 moveFromAndCancel(std::move(Other));
1386 }
1387
1388 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1389 maybeRestoreState();
1390 moveFromAndCancel(std::move(Other));
1391 return *this;
1392 }
1393
1394 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1395 };
1396
1397 /// RAII object wrapping a full-expression or block scope, and handling
1398 /// the ending of the lifetime of temporaries created within it.
1399 template<ScopeKind Kind>
1400 class ScopeRAII {
1401 EvalInfo &Info;
1402 unsigned OldStackSize;
1403 public:
1404 ScopeRAII(EvalInfo &Info)
1405 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1406 // Push a new temporary version. This is needed to distinguish between
1407 // temporaries created in different iterations of a loop.
1408 Info.CurrentCall->pushTempVersion();
1409 }
1410 bool destroy(bool RunDestructors = true) {
1411 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1412 OldStackSize = -1U;
1413 return OK;
1414 }
1415 ~ScopeRAII() {
1416 if (OldStackSize != -1U)
1417 destroy(false);
1418 // Body moved to a static method to encourage the compiler to inline away
1419 // instances of this class.
1420 Info.CurrentCall->popTempVersion();
1421 }
1422 private:
1423 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1424 unsigned OldStackSize) {
1425 assert(OldStackSize <= Info.CleanupStack.size() &&
1426 "running cleanups out of order?");
1427
1428 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1429 // for a full-expression scope.
1430 bool Success = true;
1431 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1432 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1433 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1434 Success = false;
1435 break;
1436 }
1437 }
1438 }
1439
1440 // Compact any retained cleanups.
1441 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1442 if (Kind != ScopeKind::Block)
1443 NewEnd =
1444 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1445 return C.isDestroyedAtEndOf(Kind);
1446 });
1447 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1448 return Success;
1449 }
1450 };
1451 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1452 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1453 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1454}
1455
1456bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1457 CheckSubobjectKind CSK) {
1458 if (Invalid)
1459 return false;
1460 if (isOnePastTheEnd()) {
1461 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1462 << CSK;
1463 setInvalid();
1464 return false;
1465 }
1466 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1467 // must actually be at least one array element; even a VLA cannot have a
1468 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1469 return true;
1470}
1471
1472void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1473 const Expr *E) {
1474 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1475 // Do not set the designator as invalid: we can represent this situation,
1476 // and correct handling of __builtin_object_size requires us to do so.
1477}
1478
1479void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1480 const Expr *E,
1481 const APSInt &N) {
1482 // If we're complaining, we must be able to statically determine the size of
1483 // the most derived array.
1484 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1485 Info.CCEDiag(E, diag::note_constexpr_array_index)
1486 << N << /*array*/ 0
1487 << static_cast<unsigned>(getMostDerivedArraySize());
1488 else
1489 Info.CCEDiag(E, diag::note_constexpr_array_index)
1490 << N << /*non-array*/ 1;
1491 setInvalid();
1492}
1493
1494CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1495 const FunctionDecl *Callee, const LValue *This,
1496 const Expr *CallExpr, CallRef Call)
1497 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1498 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1499 Index(Info.NextCallIndex++) {
1500 Info.CurrentCall = this;
1501 ++Info.CallStackDepth;
1502}
1503
1504CallStackFrame::~CallStackFrame() {
1505 assert(Info.CurrentCall == this && "calls retired out of order");
1506 --Info.CallStackDepth;
1507 Info.CurrentCall = Caller;
1508}
1509
1510static bool isRead(AccessKinds AK) {
1511 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1512}
1513
1515 switch (AK) {
1516 case AK_Read:
1518 case AK_MemberCall:
1519 case AK_DynamicCast:
1520 case AK_TypeId:
1521 return false;
1522 case AK_Assign:
1523 case AK_Increment:
1524 case AK_Decrement:
1525 case AK_Construct:
1526 case AK_Destroy:
1527 return true;
1528 }
1529 llvm_unreachable("unknown access kind");
1530}
1531
1532static bool isAnyAccess(AccessKinds AK) {
1533 return isRead(AK) || isModification(AK);
1534}
1535
1536/// Is this an access per the C++ definition?
1538 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1539}
1540
1541/// Is this kind of axcess valid on an indeterminate object value?
1543 switch (AK) {
1544 case AK_Read:
1545 case AK_Increment:
1546 case AK_Decrement:
1547 // These need the object's value.
1548 return false;
1549
1551 case AK_Assign:
1552 case AK_Construct:
1553 case AK_Destroy:
1554 // Construction and destruction don't need the value.
1555 return true;
1556
1557 case AK_MemberCall:
1558 case AK_DynamicCast:
1559 case AK_TypeId:
1560 // These aren't really meaningful on scalars.
1561 return true;
1562 }
1563 llvm_unreachable("unknown access kind");
1564}
1565
1566namespace {
1567 struct ComplexValue {
1568 private:
1569 bool IsInt;
1570
1571 public:
1572 APSInt IntReal, IntImag;
1573 APFloat FloatReal, FloatImag;
1574
1575 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1576
1577 void makeComplexFloat() { IsInt = false; }
1578 bool isComplexFloat() const { return !IsInt; }
1579 APFloat &getComplexFloatReal() { return FloatReal; }
1580 APFloat &getComplexFloatImag() { return FloatImag; }
1581
1582 void makeComplexInt() { IsInt = true; }
1583 bool isComplexInt() const { return IsInt; }
1584 APSInt &getComplexIntReal() { return IntReal; }
1585 APSInt &getComplexIntImag() { return IntImag; }
1586
1587 void moveInto(APValue &v) const {
1588 if (isComplexFloat())
1589 v = APValue(FloatReal, FloatImag);
1590 else
1591 v = APValue(IntReal, IntImag);
1592 }
1593 void setFrom(const APValue &v) {
1594 assert(v.isComplexFloat() || v.isComplexInt());
1595 if (v.isComplexFloat()) {
1596 makeComplexFloat();
1597 FloatReal = v.getComplexFloatReal();
1598 FloatImag = v.getComplexFloatImag();
1599 } else {
1600 makeComplexInt();
1601 IntReal = v.getComplexIntReal();
1602 IntImag = v.getComplexIntImag();
1603 }
1604 }
1605 };
1606
1607 struct LValue {
1609 CharUnits Offset;
1610 SubobjectDesignator Designator;
1611 bool IsNullPtr : 1;
1612 bool InvalidBase : 1;
1613
1614 const APValue::LValueBase getLValueBase() const { return Base; }
1615 CharUnits &getLValueOffset() { return Offset; }
1616 const CharUnits &getLValueOffset() const { return Offset; }
1617 SubobjectDesignator &getLValueDesignator() { return Designator; }
1618 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1619 bool isNullPointer() const { return IsNullPtr;}
1620
1621 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1622 unsigned getLValueVersion() const { return Base.getVersion(); }
1623
1624 void moveInto(APValue &V) const {
1625 if (Designator.Invalid)
1626 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1627 else {
1628 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1629 V = APValue(Base, Offset, Designator.Entries,
1630 Designator.IsOnePastTheEnd, IsNullPtr);
1631 }
1632 }
1633 void setFrom(ASTContext &Ctx, const APValue &V) {
1634 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1635 Base = V.getLValueBase();
1636 Offset = V.getLValueOffset();
1637 InvalidBase = false;
1638 Designator = SubobjectDesignator(Ctx, V);
1639 IsNullPtr = V.isNullPointer();
1640 }
1641
1642 void set(APValue::LValueBase B, bool BInvalid = false) {
1643#ifndef NDEBUG
1644 // We only allow a few types of invalid bases. Enforce that here.
1645 if (BInvalid) {
1646 const auto *E = B.get<const Expr *>();
1647 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1648 "Unexpected type of invalid base");
1649 }
1650#endif
1651
1652 Base = B;
1653 Offset = CharUnits::fromQuantity(0);
1654 InvalidBase = BInvalid;
1655 Designator = SubobjectDesignator(getType(B));
1656 IsNullPtr = false;
1657 }
1658
1659 void setNull(ASTContext &Ctx, QualType PointerTy) {
1660 Base = (const ValueDecl *)nullptr;
1661 Offset =
1663 InvalidBase = false;
1664 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1665 IsNullPtr = true;
1666 }
1667
1668 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1669 set(B, true);
1670 }
1671
1672 std::string toString(ASTContext &Ctx, QualType T) const {
1673 APValue Printable;
1674 moveInto(Printable);
1675 return Printable.getAsString(Ctx, T);
1676 }
1677
1678 private:
1679 // Check that this LValue is not based on a null pointer. If it is, produce
1680 // a diagnostic and mark the designator as invalid.
1681 template <typename GenDiagType>
1682 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1683 if (Designator.Invalid)
1684 return false;
1685 if (IsNullPtr) {
1686 GenDiag();
1687 Designator.setInvalid();
1688 return false;
1689 }
1690 return true;
1691 }
1692
1693 public:
1694 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1695 CheckSubobjectKind CSK) {
1696 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1697 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1698 });
1699 }
1700
1701 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1702 AccessKinds AK) {
1703 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1704 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1705 });
1706 }
1707
1708 // Check this LValue refers to an object. If not, set the designator to be
1709 // invalid and emit a diagnostic.
1710 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1711 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1712 Designator.checkSubobject(Info, E, CSK);
1713 }
1714
1715 void addDecl(EvalInfo &Info, const Expr *E,
1716 const Decl *D, bool Virtual = false) {
1717 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1718 Designator.addDeclUnchecked(D, Virtual);
1719 }
1720 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1721 if (!Designator.Entries.empty()) {
1722 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1723 Designator.setInvalid();
1724 return;
1725 }
1726 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1727 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1728 Designator.FirstEntryIsAnUnsizedArray = true;
1729 Designator.addUnsizedArrayUnchecked(ElemTy);
1730 }
1731 }
1732 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1733 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1734 Designator.addArrayUnchecked(CAT);
1735 }
1736 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1737 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1738 Designator.addComplexUnchecked(EltTy, Imag);
1739 }
1740 void clearIsNullPointer() {
1741 IsNullPtr = false;
1742 }
1743 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1744 const APSInt &Index, CharUnits ElementSize) {
1745 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1746 // but we're not required to diagnose it and it's valid in C++.)
1747 if (!Index)
1748 return;
1749
1750 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1751 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1752 // offsets.
1753 uint64_t Offset64 = Offset.getQuantity();
1754 uint64_t ElemSize64 = ElementSize.getQuantity();
1755 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1756 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1757
1758 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1759 Designator.adjustIndex(Info, E, Index);
1760 clearIsNullPointer();
1761 }
1762 void adjustOffset(CharUnits N) {
1763 Offset += N;
1764 if (N.getQuantity())
1765 clearIsNullPointer();
1766 }
1767 };
1768
1769 struct MemberPtr {
1770 MemberPtr() {}
1771 explicit MemberPtr(const ValueDecl *Decl)
1772 : DeclAndIsDerivedMember(Decl, false) {}
1773
1774 /// The member or (direct or indirect) field referred to by this member
1775 /// pointer, or 0 if this is a null member pointer.
1776 const ValueDecl *getDecl() const {
1777 return DeclAndIsDerivedMember.getPointer();
1778 }
1779 /// Is this actually a member of some type derived from the relevant class?
1780 bool isDerivedMember() const {
1781 return DeclAndIsDerivedMember.getInt();
1782 }
1783 /// Get the class which the declaration actually lives in.
1784 const CXXRecordDecl *getContainingRecord() const {
1785 return cast<CXXRecordDecl>(
1786 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1787 }
1788
1789 void moveInto(APValue &V) const {
1790 V = APValue(getDecl(), isDerivedMember(), Path);
1791 }
1792 void setFrom(const APValue &V) {
1793 assert(V.isMemberPointer());
1794 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1795 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1796 Path.clear();
1797 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1798 Path.insert(Path.end(), P.begin(), P.end());
1799 }
1800
1801 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1802 /// whether the member is a member of some class derived from the class type
1803 /// of the member pointer.
1804 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1805 /// Path - The path of base/derived classes from the member declaration's
1806 /// class (exclusive) to the class type of the member pointer (inclusive).
1808
1809 /// Perform a cast towards the class of the Decl (either up or down the
1810 /// hierarchy).
1811 bool castBack(const CXXRecordDecl *Class) {
1812 assert(!Path.empty());
1813 const CXXRecordDecl *Expected;
1814 if (Path.size() >= 2)
1815 Expected = Path[Path.size() - 2];
1816 else
1817 Expected = getContainingRecord();
1818 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1819 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1820 // if B does not contain the original member and is not a base or
1821 // derived class of the class containing the original member, the result
1822 // of the cast is undefined.
1823 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1824 // (D::*). We consider that to be a language defect.
1825 return false;
1826 }
1827 Path.pop_back();
1828 return true;
1829 }
1830 /// Perform a base-to-derived member pointer cast.
1831 bool castToDerived(const CXXRecordDecl *Derived) {
1832 if (!getDecl())
1833 return true;
1834 if (!isDerivedMember()) {
1835 Path.push_back(Derived);
1836 return true;
1837 }
1838 if (!castBack(Derived))
1839 return false;
1840 if (Path.empty())
1841 DeclAndIsDerivedMember.setInt(false);
1842 return true;
1843 }
1844 /// Perform a derived-to-base member pointer cast.
1845 bool castToBase(const CXXRecordDecl *Base) {
1846 if (!getDecl())
1847 return true;
1848 if (Path.empty())
1849 DeclAndIsDerivedMember.setInt(true);
1850 if (isDerivedMember()) {
1851 Path.push_back(Base);
1852 return true;
1853 }
1854 return castBack(Base);
1855 }
1856 };
1857
1858 /// Compare two member pointers, which are assumed to be of the same type.
1859 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1860 if (!LHS.getDecl() || !RHS.getDecl())
1861 return !LHS.getDecl() && !RHS.getDecl();
1862 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1863 return false;
1864 return LHS.Path == RHS.Path;
1865 }
1866}
1867
1868static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1869static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1870 const LValue &This, const Expr *E,
1871 bool AllowNonLiteralTypes = false);
1872static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1873 bool InvalidBaseOK = false);
1874static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1875 bool InvalidBaseOK = false);
1876static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1877 EvalInfo &Info);
1878static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1879static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1880static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1881 EvalInfo &Info);
1882static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1883static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1884static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1885 EvalInfo &Info);
1886static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1887static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1888 EvalInfo &Info,
1889 std::string *StringResult = nullptr);
1890
1891/// Evaluate an integer or fixed point expression into an APResult.
1892static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1893 EvalInfo &Info);
1894
1895/// Evaluate only a fixed point expression into an APResult.
1896static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1897 EvalInfo &Info);
1898
1899//===----------------------------------------------------------------------===//
1900// Misc utilities
1901//===----------------------------------------------------------------------===//
1902
1903/// Negate an APSInt in place, converting it to a signed form if necessary, and
1904/// preserving its value (by extending by up to one bit as needed).
1905static void negateAsSigned(APSInt &Int) {
1906 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1907 Int = Int.extend(Int.getBitWidth() + 1);
1908 Int.setIsSigned(true);
1909 }
1910 Int = -Int;
1911}
1912
1913template<typename KeyT>
1914APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1915 ScopeKind Scope, LValue &LV) {
1916 unsigned Version = getTempVersion();
1917 APValue::LValueBase Base(Key, Index, Version);
1918 LV.set(Base);
1919 return createLocal(Base, Key, T, Scope);
1920}
1921
1922/// Allocate storage for a parameter of a function call made in this frame.
1923APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1924 LValue &LV) {
1925 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1926 APValue::LValueBase Base(PVD, Index, Args.Version);
1927 LV.set(Base);
1928 // We always destroy parameters at the end of the call, even if we'd allow
1929 // them to live to the end of the full-expression at runtime, in order to
1930 // give portable results and match other compilers.
1931 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1932}
1933
1934APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1935 QualType T, ScopeKind Scope) {
1936 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1937 unsigned Version = Base.getVersion();
1938 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1939 assert(Result.isAbsent() && "local created multiple times");
1940
1941 // If we're creating a local immediately in the operand of a speculative
1942 // evaluation, don't register a cleanup to be run outside the speculative
1943 // evaluation context, since we won't actually be able to initialize this
1944 // object.
1945 if (Index <= Info.SpeculativeEvaluationDepth) {
1946 if (T.isDestructedType())
1947 Info.noteSideEffect();
1948 } else {
1949 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1950 }
1951 return Result;
1952}
1953
1954APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1955 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1956 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1957 return nullptr;
1958 }
1959
1960 DynamicAllocLValue DA(NumHeapAllocs++);
1962 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1963 std::forward_as_tuple(DA), std::tuple<>());
1964 assert(Result.second && "reused a heap alloc index?");
1965 Result.first->second.AllocExpr = E;
1966 return &Result.first->second.Value;
1967}
1968
1969/// Produce a string describing the given constexpr call.
1970void CallStackFrame::describe(raw_ostream &Out) const {
1971 unsigned ArgIndex = 0;
1972 bool IsMemberCall =
1973 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1974 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1975
1976 if (!IsMemberCall)
1977 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1978 /*Qualified=*/false);
1979
1980 if (This && IsMemberCall) {
1981 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1982 const Expr *Object = MCE->getImplicitObjectArgument();
1983 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1984 /*Indentation=*/0);
1985 if (Object->getType()->isPointerType())
1986 Out << "->";
1987 else
1988 Out << ".";
1989 } else if (const auto *OCE =
1990 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1991 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1992 Info.Ctx.getPrintingPolicy(),
1993 /*Indentation=*/0);
1994 Out << ".";
1995 } else {
1996 APValue Val;
1997 This->moveInto(Val);
1998 Val.printPretty(
1999 Out, Info.Ctx,
2000 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2001 Out << ".";
2002 }
2003 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2004 /*Qualified=*/false);
2005 IsMemberCall = false;
2006 }
2007
2008 Out << '(';
2009
2010 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2011 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2012 if (ArgIndex > (unsigned)IsMemberCall)
2013 Out << ", ";
2014
2015 const ParmVarDecl *Param = *I;
2016 APValue *V = Info.getParamSlot(Arguments, Param);
2017 if (V)
2018 V->printPretty(Out, Info.Ctx, Param->getType());
2019 else
2020 Out << "<...>";
2021
2022 if (ArgIndex == 0 && IsMemberCall)
2023 Out << "->" << *Callee << '(';
2024 }
2025
2026 Out << ')';
2027}
2028
2029/// Evaluate an expression to see if it had side-effects, and discard its
2030/// result.
2031/// \return \c true if the caller should keep evaluating.
2032static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2033 assert(!E->isValueDependent());
2034 APValue Scratch;
2035 if (!Evaluate(Scratch, Info, E))
2036 // We don't need the value, but we might have skipped a side effect here.
2037 return Info.noteSideEffect();
2038 return true;
2039}
2040
2041/// Should this call expression be treated as a no-op?
2042static bool IsNoOpCall(const CallExpr *E) {
2043 unsigned Builtin = E->getBuiltinCallee();
2044 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2045 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2046 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2047 Builtin == Builtin::BI__builtin_function_start);
2048}
2049
2051 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2052 // constant expression of pointer type that evaluates to...
2053
2054 // ... a null pointer value, or a prvalue core constant expression of type
2055 // std::nullptr_t.
2056 if (!B)
2057 return true;
2058
2059 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2060 // ... the address of an object with static storage duration,
2061 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2062 return VD->hasGlobalStorage();
2063 if (isa<TemplateParamObjectDecl>(D))
2064 return true;
2065 // ... the address of a function,
2066 // ... the address of a GUID [MS extension],
2067 // ... the address of an unnamed global constant
2068 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2069 }
2070
2071 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2072 return true;
2073
2074 const Expr *E = B.get<const Expr*>();
2075 switch (E->getStmtClass()) {
2076 default:
2077 return false;
2078 case Expr::CompoundLiteralExprClass: {
2079 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2080 return CLE->isFileScope() && CLE->isLValue();
2081 }
2082 case Expr::MaterializeTemporaryExprClass:
2083 // A materialized temporary might have been lifetime-extended to static
2084 // storage duration.
2085 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2086 // A string literal has static storage duration.
2087 case Expr::StringLiteralClass:
2088 case Expr::PredefinedExprClass:
2089 case Expr::ObjCStringLiteralClass:
2090 case Expr::ObjCEncodeExprClass:
2091 return true;
2092 case Expr::ObjCBoxedExprClass:
2093 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2094 case Expr::CallExprClass:
2095 return IsNoOpCall(cast<CallExpr>(E));
2096 // For GCC compatibility, &&label has static storage duration.
2097 case Expr::AddrLabelExprClass:
2098 return true;
2099 // A Block literal expression may be used as the initialization value for
2100 // Block variables at global or local static scope.
2101 case Expr::BlockExprClass:
2102 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2103 // The APValue generated from a __builtin_source_location will be emitted as a
2104 // literal.
2105 case Expr::SourceLocExprClass:
2106 return true;
2107 case Expr::ImplicitValueInitExprClass:
2108 // FIXME:
2109 // We can never form an lvalue with an implicit value initialization as its
2110 // base through expression evaluation, so these only appear in one case: the
2111 // implicit variable declaration we invent when checking whether a constexpr
2112 // constructor can produce a constant expression. We must assume that such
2113 // an expression might be a global lvalue.
2114 return true;
2115 }
2116}
2117
2118static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2119 return LVal.Base.dyn_cast<const ValueDecl*>();
2120}
2121
2122static bool IsLiteralLValue(const LValue &Value) {
2123 if (Value.getLValueCallIndex())
2124 return false;
2125 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2126 return E && !isa<MaterializeTemporaryExpr>(E);
2127}
2128
2129static bool IsWeakLValue(const LValue &Value) {
2131 return Decl && Decl->isWeak();
2132}
2133
2134static bool isZeroSized(const LValue &Value) {
2136 if (isa_and_nonnull<VarDecl>(Decl)) {
2137 QualType Ty = Decl->getType();
2138 if (Ty->isArrayType())
2139 return Ty->isIncompleteType() ||
2140 Decl->getASTContext().getTypeSize(Ty) == 0;
2141 }
2142 return false;
2143}
2144
2145static bool HasSameBase(const LValue &A, const LValue &B) {
2146 if (!A.getLValueBase())
2147 return !B.getLValueBase();
2148 if (!B.getLValueBase())
2149 return false;
2150
2151 if (A.getLValueBase().getOpaqueValue() !=
2152 B.getLValueBase().getOpaqueValue())
2153 return false;
2154
2155 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2156 A.getLValueVersion() == B.getLValueVersion();
2157}
2158
2159static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2160 assert(Base && "no location for a null lvalue");
2161 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2162
2163 // For a parameter, find the corresponding call stack frame (if it still
2164 // exists), and point at the parameter of the function definition we actually
2165 // invoked.
2166 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2167 unsigned Idx = PVD->getFunctionScopeIndex();
2168 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2169 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2170 F->Arguments.Version == Base.getVersion() && F->Callee &&
2171 Idx < F->Callee->getNumParams()) {
2172 VD = F->Callee->getParamDecl(Idx);
2173 break;
2174 }
2175 }
2176 }
2177
2178 if (VD)
2179 Info.Note(VD->getLocation(), diag::note_declared_at);
2180 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2181 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2182 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2183 // FIXME: Produce a note for dangling pointers too.
2184 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2185 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2186 diag::note_constexpr_dynamic_alloc_here);
2187 }
2188
2189 // We have no information to show for a typeid(T) object.
2190}
2191
2195};
2196
2197/// Materialized temporaries that we've already checked to determine if they're
2198/// initializsed by a constant expression.
2201
2203 EvalInfo &Info, SourceLocation DiagLoc,
2204 QualType Type, const APValue &Value,
2205 ConstantExprKind Kind,
2206 const FieldDecl *SubobjectDecl,
2207 CheckedTemporaries &CheckedTemps);
2208
2209/// Check that this reference or pointer core constant expression is a valid
2210/// value for an address or reference constant expression. Return true if we
2211/// can fold this expression, whether or not it's a constant expression.
2213 QualType Type, const LValue &LVal,
2214 ConstantExprKind Kind,
2215 CheckedTemporaries &CheckedTemps) {
2216 bool IsReferenceType = Type->isReferenceType();
2217
2218 APValue::LValueBase Base = LVal.getLValueBase();
2219 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2220
2221 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2222 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2223
2224 // Additional restrictions apply in a template argument. We only enforce the
2225 // C++20 restrictions here; additional syntactic and semantic restrictions
2226 // are applied elsewhere.
2227 if (isTemplateArgument(Kind)) {
2228 int InvalidBaseKind = -1;
2229 StringRef Ident;
2230 if (Base.is<TypeInfoLValue>())
2231 InvalidBaseKind = 0;
2232 else if (isa_and_nonnull<StringLiteral>(BaseE))
2233 InvalidBaseKind = 1;
2234 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2235 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2236 InvalidBaseKind = 2;
2237 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2238 InvalidBaseKind = 3;
2239 Ident = PE->getIdentKindName();
2240 }
2241
2242 if (InvalidBaseKind != -1) {
2243 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2244 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2245 << Ident;
2246 return false;
2247 }
2248 }
2249
2250 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2251 FD && FD->isImmediateFunction()) {
2252 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2253 << !Type->isAnyPointerType();
2254 Info.Note(FD->getLocation(), diag::note_declared_at);
2255 return false;
2256 }
2257
2258 // Check that the object is a global. Note that the fake 'this' object we
2259 // manufacture when checking potential constant expressions is conservatively
2260 // assumed to be global here.
2261 if (!IsGlobalLValue(Base)) {
2262 if (Info.getLangOpts().CPlusPlus11) {
2263 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2264 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2265 << BaseVD;
2266 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2267 if (VarD && VarD->isConstexpr()) {
2268 // Non-static local constexpr variables have unintuitive semantics:
2269 // constexpr int a = 1;
2270 // constexpr const int *p = &a;
2271 // ... is invalid because the address of 'a' is not constant. Suggest
2272 // adding a 'static' in this case.
2273 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2274 << VarD
2275 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2276 } else {
2277 NoteLValueLocation(Info, Base);
2278 }
2279 } else {
2280 Info.FFDiag(Loc);
2281 }
2282 // Don't allow references to temporaries to escape.
2283 return false;
2284 }
2285 assert((Info.checkingPotentialConstantExpression() ||
2286 LVal.getLValueCallIndex() == 0) &&
2287 "have call index for global lvalue");
2288
2289 if (Base.is<DynamicAllocLValue>()) {
2290 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2291 << IsReferenceType << !Designator.Entries.empty();
2292 NoteLValueLocation(Info, Base);
2293 return false;
2294 }
2295
2296 if (BaseVD) {
2297 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2298 // Check if this is a thread-local variable.
2299 if (Var->getTLSKind())
2300 // FIXME: Diagnostic!
2301 return false;
2302
2303 // A dllimport variable never acts like a constant, unless we're
2304 // evaluating a value for use only in name mangling.
2305 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2306 // FIXME: Diagnostic!
2307 return false;
2308
2309 // In CUDA/HIP device compilation, only device side variables have
2310 // constant addresses.
2311 if (Info.getCtx().getLangOpts().CUDA &&
2312 Info.getCtx().getLangOpts().CUDAIsDevice &&
2313 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2314 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2315 !Var->hasAttr<CUDAConstantAttr>() &&
2316 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2317 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2318 Var->hasAttr<HIPManagedAttr>())
2319 return false;
2320 }
2321 }
2322 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2323 // __declspec(dllimport) must be handled very carefully:
2324 // We must never initialize an expression with the thunk in C++.
2325 // Doing otherwise would allow the same id-expression to yield
2326 // different addresses for the same function in different translation
2327 // units. However, this means that we must dynamically initialize the
2328 // expression with the contents of the import address table at runtime.
2329 //
2330 // The C language has no notion of ODR; furthermore, it has no notion of
2331 // dynamic initialization. This means that we are permitted to
2332 // perform initialization with the address of the thunk.
2333 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2334 FD->hasAttr<DLLImportAttr>())
2335 // FIXME: Diagnostic!
2336 return false;
2337 }
2338 } else if (const auto *MTE =
2339 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2340 if (CheckedTemps.insert(MTE).second) {
2341 QualType TempType = getType(Base);
2342 if (TempType.isDestructedType()) {
2343 Info.FFDiag(MTE->getExprLoc(),
2344 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2345 << TempType;
2346 return false;
2347 }
2348
2349 APValue *V = MTE->getOrCreateValue(false);
2350 assert(V && "evasluation result refers to uninitialised temporary");
2351 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2352 Info, MTE->getExprLoc(), TempType, *V, Kind,
2353 /*SubobjectDecl=*/nullptr, CheckedTemps))
2354 return false;
2355 }
2356 }
2357
2358 // Allow address constant expressions to be past-the-end pointers. This is
2359 // an extension: the standard requires them to point to an object.
2360 if (!IsReferenceType)
2361 return true;
2362
2363 // A reference constant expression must refer to an object.
2364 if (!Base) {
2365 // FIXME: diagnostic
2366 Info.CCEDiag(Loc);
2367 return true;
2368 }
2369
2370 // Does this refer one past the end of some object?
2371 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2372 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2373 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2374 NoteLValueLocation(Info, Base);
2375 }
2376
2377 return true;
2378}
2379
2380/// Member pointers are constant expressions unless they point to a
2381/// non-virtual dllimport member function.
2382static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2384 QualType Type,
2385 const APValue &Value,
2386 ConstantExprKind Kind) {
2387 const ValueDecl *Member = Value.getMemberPointerDecl();
2388 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2389 if (!FD)
2390 return true;
2391 if (FD->isImmediateFunction()) {
2392 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2393 Info.Note(FD->getLocation(), diag::note_declared_at);
2394 return false;
2395 }
2396 return isForManglingOnly(Kind) || FD->isVirtual() ||
2397 !FD->hasAttr<DLLImportAttr>();
2398}
2399
2400/// Check that this core constant expression is of literal type, and if not,
2401/// produce an appropriate diagnostic.
2402static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2403 const LValue *This = nullptr) {
2404 // The restriction to literal types does not exist in C++23 anymore.
2405 if (Info.getLangOpts().CPlusPlus23)
2406 return true;
2407
2408 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2409 return true;
2410
2411 // C++1y: A constant initializer for an object o [...] may also invoke
2412 // constexpr constructors for o and its subobjects even if those objects
2413 // are of non-literal class types.
2414 //
2415 // C++11 missed this detail for aggregates, so classes like this:
2416 // struct foo_t { union { int i; volatile int j; } u; };
2417 // are not (obviously) initializable like so:
2418 // __attribute__((__require_constant_initialization__))
2419 // static const foo_t x = {{0}};
2420 // because "i" is a subobject with non-literal initialization (due to the
2421 // volatile member of the union). See:
2422 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2423 // Therefore, we use the C++1y behavior.
2424 if (This && Info.EvaluatingDecl == This->getLValueBase())
2425 return true;
2426
2427 // Prvalue constant expressions must be of literal types.
2428 if (Info.getLangOpts().CPlusPlus11)
2429 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2430 << E->getType();
2431 else
2432 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2433 return false;
2434}
2435
2437 EvalInfo &Info, SourceLocation DiagLoc,
2438 QualType Type, const APValue &Value,
2439 ConstantExprKind Kind,
2440 const FieldDecl *SubobjectDecl,
2441 CheckedTemporaries &CheckedTemps) {
2442 if (!Value.hasValue()) {
2443 if (SubobjectDecl) {
2444 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2445 << /*(name)*/ 1 << SubobjectDecl;
2446 Info.Note(SubobjectDecl->getLocation(),
2447 diag::note_constexpr_subobject_declared_here);
2448 } else {
2449 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2450 << /*of type*/ 0 << Type;
2451 }
2452 return false;
2453 }
2454
2455 // We allow _Atomic(T) to be initialized from anything that T can be
2456 // initialized from.
2457 if (const AtomicType *AT = Type->getAs<AtomicType>())
2458 Type = AT->getValueType();
2459
2460 // Core issue 1454: For a literal constant expression of array or class type,
2461 // each subobject of its value shall have been initialized by a constant
2462 // expression.
2463 if (Value.isArray()) {
2465 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2466 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2467 Value.getArrayInitializedElt(I), Kind,
2468 SubobjectDecl, CheckedTemps))
2469 return false;
2470 }
2471 if (!Value.hasArrayFiller())
2472 return true;
2473 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2474 Value.getArrayFiller(), Kind, SubobjectDecl,
2475 CheckedTemps);
2476 }
2477 if (Value.isUnion() && Value.getUnionField()) {
2478 return CheckEvaluationResult(
2479 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2480 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2481 }
2482 if (Value.isStruct()) {
2483 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2484 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2485 unsigned BaseIndex = 0;
2486 for (const CXXBaseSpecifier &BS : CD->bases()) {
2487 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2488 if (!BaseValue.hasValue()) {
2489 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2490 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2491 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2492 return false;
2493 }
2494 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2495 Kind, /*SubobjectDecl=*/nullptr,
2496 CheckedTemps))
2497 return false;
2498 ++BaseIndex;
2499 }
2500 }
2501 for (const auto *I : RD->fields()) {
2502 if (I->isUnnamedBitField())
2503 continue;
2504
2505 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2506 Value.getStructField(I->getFieldIndex()), Kind,
2507 I, CheckedTemps))
2508 return false;
2509 }
2510 }
2511
2512 if (Value.isLValue() &&
2513 CERK == CheckEvaluationResultKind::ConstantExpression) {
2514 LValue LVal;
2515 LVal.setFrom(Info.Ctx, Value);
2516 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2517 CheckedTemps);
2518 }
2519
2520 if (Value.isMemberPointer() &&
2521 CERK == CheckEvaluationResultKind::ConstantExpression)
2522 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2523
2524 // Everything else is fine.
2525 return true;
2526}
2527
2528/// Check that this core constant expression value is a valid value for a
2529/// constant expression. If not, report an appropriate diagnostic. Does not
2530/// check that the expression is of literal type.
2531static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2532 QualType Type, const APValue &Value,
2533 ConstantExprKind Kind) {
2534 // Nothing to check for a constant expression of type 'cv void'.
2535 if (Type->isVoidType())
2536 return true;
2537
2538 CheckedTemporaries CheckedTemps;
2539 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2540 Info, DiagLoc, Type, Value, Kind,
2541 /*SubobjectDecl=*/nullptr, CheckedTemps);
2542}
2543
2544/// Check that this evaluated value is fully-initialized and can be loaded by
2545/// an lvalue-to-rvalue conversion.
2546static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2547 QualType Type, const APValue &Value) {
2548 CheckedTemporaries CheckedTemps;
2549 return CheckEvaluationResult(
2550 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2551 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2552}
2553
2554/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2555/// "the allocated storage is deallocated within the evaluation".
2556static bool CheckMemoryLeaks(EvalInfo &Info) {
2557 if (!Info.HeapAllocs.empty()) {
2558 // We can still fold to a constant despite a compile-time memory leak,
2559 // so long as the heap allocation isn't referenced in the result (we check
2560 // that in CheckConstantExpression).
2561 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2562 diag::note_constexpr_memory_leak)
2563 << unsigned(Info.HeapAllocs.size() - 1);
2564 }
2565 return true;
2566}
2567
2568static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2569 // A null base expression indicates a null pointer. These are always
2570 // evaluatable, and they are false unless the offset is zero.
2571 if (!Value.getLValueBase()) {
2572 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2573 Result = !Value.getLValueOffset().isZero();
2574 return true;
2575 }
2576
2577 // We have a non-null base. These are generally known to be true, but if it's
2578 // a weak declaration it can be null at runtime.
2579 Result = true;
2580 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2581 return !Decl || !Decl->isWeak();
2582}
2583
2584static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2585 // TODO: This function should produce notes if it fails.
2586 switch (Val.getKind()) {
2587 case APValue::None:
2589 return false;
2590 case APValue::Int:
2591 Result = Val.getInt().getBoolValue();
2592 return true;
2594 Result = Val.getFixedPoint().getBoolValue();
2595 return true;
2596 case APValue::Float:
2597 Result = !Val.getFloat().isZero();
2598 return true;
2600 Result = Val.getComplexIntReal().getBoolValue() ||
2601 Val.getComplexIntImag().getBoolValue();
2602 return true;
2604 Result = !Val.getComplexFloatReal().isZero() ||
2605 !Val.getComplexFloatImag().isZero();
2606 return true;
2607 case APValue::LValue:
2608 return EvalPointerValueAsBool(Val, Result);
2610 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2611 return false;
2612 }
2613 Result = Val.getMemberPointerDecl();
2614 return true;
2615 case APValue::Vector:
2616 case APValue::Array:
2617 case APValue::Struct:
2618 case APValue::Union:
2620 return false;
2621 }
2622
2623 llvm_unreachable("unknown APValue kind");
2624}
2625
2626static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2627 EvalInfo &Info) {
2628 assert(!E->isValueDependent());
2629 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2630 APValue Val;
2631 if (!Evaluate(Val, Info, E))
2632 return false;
2633 return HandleConversionToBool(Val, Result);
2634}
2635
2636template<typename T>
2637static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2638 const T &SrcValue, QualType DestType) {
2639 Info.CCEDiag(E, diag::note_constexpr_overflow)
2640 << SrcValue << DestType;
2641 return Info.noteUndefinedBehavior();
2642}
2643
2644static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2645 QualType SrcType, const APFloat &Value,
2646 QualType DestType, APSInt &Result) {
2647 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2648 // Determine whether we are converting to unsigned or signed.
2649 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2650
2651 Result = APSInt(DestWidth, !DestSigned);
2652 bool ignored;
2653 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2654 & APFloat::opInvalidOp)
2655 return HandleOverflow(Info, E, Value, DestType);
2656 return true;
2657}
2658
2659/// Get rounding mode to use in evaluation of the specified expression.
2660///
2661/// If rounding mode is unknown at compile time, still try to evaluate the
2662/// expression. If the result is exact, it does not depend on rounding mode.
2663/// So return "tonearest" mode instead of "dynamic".
2664static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2665 llvm::RoundingMode RM =
2666 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2667 if (RM == llvm::RoundingMode::Dynamic)
2668 RM = llvm::RoundingMode::NearestTiesToEven;
2669 return RM;
2670}
2671
2672/// Check if the given evaluation result is allowed for constant evaluation.
2673static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2674 APFloat::opStatus St) {
2675 // In a constant context, assume that any dynamic rounding mode or FP
2676 // exception state matches the default floating-point environment.
2677 if (Info.InConstantContext)
2678 return true;
2679
2680 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2681 if ((St & APFloat::opInexact) &&
2682 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2683 // Inexact result means that it depends on rounding mode. If the requested
2684 // mode is dynamic, the evaluation cannot be made in compile time.
2685 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2686 return false;
2687 }
2688
2689 if ((St != APFloat::opOK) &&
2690 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2691 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2692 FPO.getAllowFEnvAccess())) {
2693 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2694 return false;
2695 }
2696
2697 if ((St & APFloat::opStatus::opInvalidOp) &&
2698 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2699 // There is no usefully definable result.
2700 Info.FFDiag(E);
2701 return false;
2702 }
2703
2704 // FIXME: if:
2705 // - evaluation triggered other FP exception, and
2706 // - exception mode is not "ignore", and
2707 // - the expression being evaluated is not a part of global variable
2708 // initializer,
2709 // the evaluation probably need to be rejected.
2710 return true;
2711}
2712
2713static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2714 QualType SrcType, QualType DestType,
2715 APFloat &Result) {
2716 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2717 isa<ConvertVectorExpr>(E)) &&
2718 "HandleFloatToFloatCast has been checked with only CastExpr, "
2719 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2720 "the new expression or address the root cause of this usage.");
2721 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2722 APFloat::opStatus St;
2723 APFloat Value = Result;
2724 bool ignored;
2725 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2726 return checkFloatingPointResult(Info, E, St);
2727}
2728
2729static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2730 QualType DestType, QualType SrcType,
2731 const APSInt &Value) {
2732 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2733 // Figure out if this is a truncate, extend or noop cast.
2734 // If the input is signed, do a sign extend, noop, or truncate.
2735 APSInt Result = Value.extOrTrunc(DestWidth);
2736 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2737 if (DestType->isBooleanType())
2738 Result = Value.getBoolValue();
2739 return Result;
2740}
2741
2742static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2743 const FPOptions FPO,
2744 QualType SrcType, const APSInt &Value,
2745 QualType DestType, APFloat &Result) {
2746 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2747 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2748 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2749 return checkFloatingPointResult(Info, E, St);
2750}
2751
2752static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2753 APValue &Value, const FieldDecl *FD) {
2754 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2755
2756 if (!Value.isInt()) {
2757 // Trying to store a pointer-cast-to-integer into a bitfield.
2758 // FIXME: In this case, we should provide the diagnostic for casting
2759 // a pointer to an integer.
2760 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2761 Info.FFDiag(E);
2762 return false;
2763 }
2764
2765 APSInt &Int = Value.getInt();
2766 unsigned OldBitWidth = Int.getBitWidth();
2767 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2768 if (NewBitWidth < OldBitWidth)
2769 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2770 return true;
2771}
2772
2773/// Perform the given integer operation, which is known to need at most BitWidth
2774/// bits, and check for overflow in the original type (if that type was not an
2775/// unsigned type).
2776template<typename Operation>
2777static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2778 const APSInt &LHS, const APSInt &RHS,
2779 unsigned BitWidth, Operation Op,
2780 APSInt &Result) {
2781 if (LHS.isUnsigned()) {
2782 Result = Op(LHS, RHS);
2783 return true;
2784 }
2785
2786 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2787 Result = Value.trunc(LHS.getBitWidth());
2788 if (Result.extend(BitWidth) != Value) {
2789 if (Info.checkingForUndefinedBehavior())
2790 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2791 diag::warn_integer_constant_overflow)
2792 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2793 /*UpperCase=*/true, /*InsertSeparators=*/true)
2794 << E->getType() << E->getSourceRange();
2795 return HandleOverflow(Info, E, Value, E->getType());
2796 }
2797 return true;
2798}
2799
2800/// Perform the given binary integer operation.
2801static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2802 const APSInt &LHS, BinaryOperatorKind Opcode,
2803 APSInt RHS, APSInt &Result) {
2804 bool HandleOverflowResult = true;
2805 switch (Opcode) {
2806 default:
2807 Info.FFDiag(E);
2808 return false;
2809 case BO_Mul:
2810 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2811 std::multiplies<APSInt>(), Result);
2812 case BO_Add:
2813 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2814 std::plus<APSInt>(), Result);
2815 case BO_Sub:
2816 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2817 std::minus<APSInt>(), Result);
2818 case BO_And: Result = LHS & RHS; return true;
2819 case BO_Xor: Result = LHS ^ RHS; return true;
2820 case BO_Or: Result = LHS | RHS; return true;
2821 case BO_Div:
2822 case BO_Rem:
2823 if (RHS == 0) {
2824 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2825 << E->getRHS()->getSourceRange();
2826 return false;
2827 }
2828 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2829 // this operation and gives the two's complement result.
2830 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2831 LHS.isMinSignedValue())
2832 HandleOverflowResult = HandleOverflow(
2833 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2834 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2835 return HandleOverflowResult;
2836 case BO_Shl: {
2837 if (Info.getLangOpts().OpenCL)
2838 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2839 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2840 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2841 RHS.isUnsigned());
2842 else if (RHS.isSigned() && RHS.isNegative()) {
2843 // During constant-folding, a negative shift is an opposite shift. Such
2844 // a shift is not a constant expression.
2845 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2846 if (!Info.noteUndefinedBehavior())
2847 return false;
2848 RHS = -RHS;
2849 goto shift_right;
2850 }
2851 shift_left:
2852 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2853 // the shifted type.
2854 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2855 if (SA != RHS) {
2856 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2857 << RHS << E->getType() << LHS.getBitWidth();
2858 if (!Info.noteUndefinedBehavior())
2859 return false;
2860 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2861 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2862 // operand, and must not overflow the corresponding unsigned type.
2863 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2864 // E1 x 2^E2 module 2^N.
2865 if (LHS.isNegative()) {
2866 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2867 if (!Info.noteUndefinedBehavior())
2868 return false;
2869 } else if (LHS.countl_zero() < SA) {
2870 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2871 if (!Info.noteUndefinedBehavior())
2872 return false;
2873 }
2874 }
2875 Result = LHS << SA;
2876 return true;
2877 }
2878 case BO_Shr: {
2879 if (Info.getLangOpts().OpenCL)
2880 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2881 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2882 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2883 RHS.isUnsigned());
2884 else if (RHS.isSigned() && RHS.isNegative()) {
2885 // During constant-folding, a negative shift is an opposite shift. Such a
2886 // shift is not a constant expression.
2887 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2888 if (!Info.noteUndefinedBehavior())
2889 return false;
2890 RHS = -RHS;
2891 goto shift_left;
2892 }
2893 shift_right:
2894 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2895 // shifted type.
2896 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2897 if (SA != RHS) {
2898 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2899 << RHS << E->getType() << LHS.getBitWidth();
2900 if (!Info.noteUndefinedBehavior())
2901 return false;
2902 }
2903
2904 Result = LHS >> SA;
2905 return true;
2906 }
2907
2908 case BO_LT: Result = LHS < RHS; return true;
2909 case BO_GT: Result = LHS > RHS; return true;
2910 case BO_LE: Result = LHS <= RHS; return true;
2911 case BO_GE: Result = LHS >= RHS; return true;
2912 case BO_EQ: Result = LHS == RHS; return true;
2913 case BO_NE: Result = LHS != RHS; return true;
2914 case BO_Cmp:
2915 llvm_unreachable("BO_Cmp should be handled elsewhere");
2916 }
2917}
2918
2919/// Perform the given binary floating-point operation, in-place, on LHS.
2920static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2921 APFloat &LHS, BinaryOperatorKind Opcode,
2922 const APFloat &RHS) {
2923 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2924 APFloat::opStatus St;
2925 switch (Opcode) {
2926 default:
2927 Info.FFDiag(E);
2928 return false;
2929 case BO_Mul:
2930 St = LHS.multiply(RHS, RM);
2931 break;
2932 case BO_Add:
2933 St = LHS.add(RHS, RM);
2934 break;
2935 case BO_Sub:
2936 St = LHS.subtract(RHS, RM);
2937 break;
2938 case BO_Div:
2939 // [expr.mul]p4:
2940 // If the second operand of / or % is zero the behavior is undefined.
2941 if (RHS.isZero())
2942 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2943 St = LHS.divide(RHS, RM);
2944 break;
2945 }
2946
2947 // [expr.pre]p4:
2948 // If during the evaluation of an expression, the result is not
2949 // mathematically defined [...], the behavior is undefined.
2950 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2951 if (LHS.isNaN()) {
2952 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2953 return Info.noteUndefinedBehavior();
2954 }
2955
2956 return checkFloatingPointResult(Info, E, St);
2957}
2958
2959static bool handleLogicalOpForVector(const APInt &LHSValue,
2960 BinaryOperatorKind Opcode,
2961 const APInt &RHSValue, APInt &Result) {
2962 bool LHS = (LHSValue != 0);
2963 bool RHS = (RHSValue != 0);
2964
2965 if (Opcode == BO_LAnd)
2966 Result = LHS && RHS;
2967 else
2968 Result = LHS || RHS;
2969 return true;
2970}
2971static bool handleLogicalOpForVector(const APFloat &LHSValue,
2972 BinaryOperatorKind Opcode,
2973 const APFloat &RHSValue, APInt &Result) {
2974 bool LHS = !LHSValue.isZero();
2975 bool RHS = !RHSValue.isZero();
2976
2977 if (Opcode == BO_LAnd)
2978 Result = LHS && RHS;
2979 else
2980 Result = LHS || RHS;
2981 return true;
2982}
2983
2984static bool handleLogicalOpForVector(const APValue &LHSValue,
2985 BinaryOperatorKind Opcode,
2986 const APValue &RHSValue, APInt &Result) {
2987 // The result is always an int type, however operands match the first.
2988 if (LHSValue.getKind() == APValue::Int)
2989 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2990 RHSValue.getInt(), Result);
2991 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2992 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2993 RHSValue.getFloat(), Result);
2994}
2995
2996template <typename APTy>
2997static bool
2999 const APTy &RHSValue, APInt &Result) {
3000 switch (Opcode) {
3001 default:
3002 llvm_unreachable("unsupported binary operator");
3003 case BO_EQ:
3004 Result = (LHSValue == RHSValue);
3005 break;
3006 case BO_NE:
3007 Result = (LHSValue != RHSValue);
3008 break;
3009 case BO_LT:
3010 Result = (LHSValue < RHSValue);
3011 break;
3012 case BO_GT:
3013 Result = (LHSValue > RHSValue);
3014 break;
3015 case BO_LE:
3016 Result = (LHSValue <= RHSValue);
3017 break;
3018 case BO_GE:
3019 Result = (LHSValue >= RHSValue);
3020 break;
3021 }
3022
3023 // The boolean operations on these vector types use an instruction that
3024 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3025 // to -1 to make sure that we produce the correct value.
3026 Result.negate();
3027
3028 return true;
3029}
3030
3031static bool handleCompareOpForVector(const APValue &LHSValue,
3032 BinaryOperatorKind Opcode,
3033 const APValue &RHSValue, APInt &Result) {
3034 // The result is always an int type, however operands match the first.
3035 if (LHSValue.getKind() == APValue::Int)
3036 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3037 RHSValue.getInt(), Result);
3038 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3039 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3040 RHSValue.getFloat(), Result);
3041}
3042
3043// Perform binary operations for vector types, in place on the LHS.
3044static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3045 BinaryOperatorKind Opcode,
3046 APValue &LHSValue,
3047 const APValue &RHSValue) {
3048 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3049 "Operation not supported on vector types");
3050
3051 const auto *VT = E->getType()->castAs<VectorType>();
3052 unsigned NumElements = VT->getNumElements();
3053 QualType EltTy = VT->getElementType();
3054
3055 // In the cases (typically C as I've observed) where we aren't evaluating
3056 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3057 // just give up.
3058 if (!LHSValue.isVector()) {
3059 assert(LHSValue.isLValue() &&
3060 "A vector result that isn't a vector OR uncalculated LValue");
3061 Info.FFDiag(E);
3062 return false;
3063 }
3064
3065 assert(LHSValue.getVectorLength() == NumElements &&
3066 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3067
3068 SmallVector<APValue, 4> ResultElements;
3069
3070 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3071 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3072 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3073
3074 if (EltTy->isIntegerType()) {
3075 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3076 EltTy->isUnsignedIntegerType()};
3077 bool Success = true;
3078
3079 if (BinaryOperator::isLogicalOp(Opcode))
3080 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3081 else if (BinaryOperator::isComparisonOp(Opcode))
3082 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3083 else
3084 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3085 RHSElt.getInt(), EltResult);
3086
3087 if (!Success) {
3088 Info.FFDiag(E);
3089 return false;
3090 }
3091 ResultElements.emplace_back(EltResult);
3092
3093 } else if (EltTy->isFloatingType()) {
3094 assert(LHSElt.getKind() == APValue::Float &&
3095 RHSElt.getKind() == APValue::Float &&
3096 "Mismatched LHS/RHS/Result Type");
3097 APFloat LHSFloat = LHSElt.getFloat();
3098
3099 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3100 RHSElt.getFloat())) {
3101 Info.FFDiag(E);
3102 return false;
3103 }
3104
3105 ResultElements.emplace_back(LHSFloat);
3106 }
3107 }
3108
3109 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3110 return true;
3111}
3112
3113/// Cast an lvalue referring to a base subobject to a derived class, by
3114/// truncating the lvalue's path to the given length.
3115static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3116 const RecordDecl *TruncatedType,
3117 unsigned TruncatedElements) {
3118 SubobjectDesignator &D = Result.Designator;
3119
3120 // Check we actually point to a derived class object.
3121 if (TruncatedElements == D.Entries.size())
3122 return true;
3123 assert(TruncatedElements >= D.MostDerivedPathLength &&
3124 "not casting to a derived class");
3125 if (!Result.checkSubobject(Info, E, CSK_Derived))
3126 return false;
3127
3128 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3129 const RecordDecl *RD = TruncatedType;
3130 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3131 if (RD->isInvalidDecl()) return false;
3132 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3133 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3134 if (isVirtualBaseClass(D.Entries[I]))
3135 Result.Offset -= Layout.getVBaseClassOffset(Base);
3136 else
3137 Result.Offset -= Layout.getBaseClassOffset(Base);
3138 RD = Base;
3139 }
3140 D.Entries.resize(TruncatedElements);
3141 return true;
3142}
3143
3144static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3145 const CXXRecordDecl *Derived,
3146 const CXXRecordDecl *Base,
3147 const ASTRecordLayout *RL = nullptr) {
3148 if (!RL) {
3149 if (Derived->isInvalidDecl()) return false;
3150 RL = &Info.Ctx.getASTRecordLayout(Derived);
3151 }
3152
3153 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3154 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3155 return true;
3156}
3157
3158static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3159 const CXXRecordDecl *DerivedDecl,
3160 const CXXBaseSpecifier *Base) {
3161 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3162
3163 if (!Base->isVirtual())
3164 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3165
3166 SubobjectDesignator &D = Obj.Designator;
3167 if (D.Invalid)
3168 return false;
3169
3170 // Extract most-derived object and corresponding type.
3171 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3172 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3173 return false;
3174
3175 // Find the virtual base class.
3176 if (DerivedDecl->isInvalidDecl()) return false;
3177 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3178 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3179 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3180 return true;
3181}
3182
3183static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3184 QualType Type, LValue &Result) {
3185 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3186 PathE = E->path_end();
3187 PathI != PathE; ++PathI) {
3188 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3189 *PathI))
3190 return false;
3191 Type = (*PathI)->getType();
3192 }
3193 return true;
3194}
3195
3196/// Cast an lvalue referring to a derived class to a known base subobject.
3197static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3198 const CXXRecordDecl *DerivedRD,
3199 const CXXRecordDecl *BaseRD) {
3200 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3201 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3202 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3203 llvm_unreachable("Class must be derived from the passed in base class!");
3204
3205 for (CXXBasePathElement &Elem : Paths.front())
3206 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3207 return false;
3208 return true;
3209}
3210
3211/// Update LVal to refer to the given field, which must be a member of the type
3212/// currently described by LVal.
3213static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3214 const FieldDecl *FD,
3215 const ASTRecordLayout *RL = nullptr) {
3216 if (!RL) {
3217 if (FD->getParent()->isInvalidDecl()) return false;
3218 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3219 }
3220
3221 unsigned I = FD->getFieldIndex();
3222 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3223 LVal.addDecl(Info, E, FD);
3224 return true;
3225}
3226
3227/// Update LVal to refer to the given indirect field.
3228static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3229 LValue &LVal,
3230 const IndirectFieldDecl *IFD) {
3231 for (const auto *C : IFD->chain())
3232 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3233 return false;
3234 return true;
3235}
3236
3237enum class SizeOfType {
3238 SizeOf,
3239 DataSizeOf,
3240};
3241
3242/// Get the size of the given type in char units.
3243static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3244 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3245 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3246 // extension.
3247 if (Type->isVoidType() || Type->isFunctionType()) {
3248 Size = CharUnits::One();
3249 return true;
3250 }
3251
3252 if (Type->isDependentType()) {
3253 Info.FFDiag(Loc);
3254 return false;
3255 }
3256
3257 if (!Type->isConstantSizeType()) {
3258 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3259 // FIXME: Better diagnostic.
3260 Info.FFDiag(Loc);
3261 return false;
3262 }
3263
3264 if (SOT == SizeOfType::SizeOf)
3265 Size = Info.Ctx.getTypeSizeInChars(Type);
3266 else
3267 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3268 return true;
3269}
3270
3271/// Update a pointer value to model pointer arithmetic.
3272/// \param Info - Information about the ongoing evaluation.
3273/// \param E - The expression being evaluated, for diagnostic purposes.
3274/// \param LVal - The pointer value to be updated.
3275/// \param EltTy - The pointee type represented by LVal.
3276/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3277static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3278 LValue &LVal, QualType EltTy,
3279 APSInt Adjustment) {
3280 CharUnits SizeOfPointee;
3281 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3282 return false;
3283
3284 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3285 return true;
3286}
3287
3288static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3289 LValue &LVal, QualType EltTy,
3290 int64_t Adjustment) {
3291 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3292 APSInt::get(Adjustment));
3293}
3294
3295/// Update an lvalue to refer to a component of a complex number.
3296/// \param Info - Information about the ongoing evaluation.
3297/// \param LVal - The lvalue to be updated.
3298/// \param EltTy - The complex number's component type.
3299/// \param Imag - False for the real component, true for the imaginary.
3300static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3301 LValue &LVal, QualType EltTy,
3302 bool Imag) {
3303 if (Imag) {
3304 CharUnits SizeOfComponent;
3305 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3306 return false;
3307 LVal.Offset += SizeOfComponent;
3308 }
3309 LVal.addComplex(Info, E, EltTy, Imag);
3310 return true;
3311}
3312
3313/// Try to evaluate the initializer for a variable declaration.
3314///
3315/// \param Info Information about the ongoing evaluation.
3316/// \param E An expression to be used when printing diagnostics.
3317/// \param VD The variable whose initializer should be obtained.
3318/// \param Version The version of the variable within the frame.
3319/// \param Frame The frame in which the variable was created. Must be null
3320/// if this variable is not local to the evaluation.
3321/// \param Result Filled in with a pointer to the value of the variable.
3322static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3323 const VarDecl *VD, CallStackFrame *Frame,
3324 unsigned Version, APValue *&Result) {
3325 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3326
3327 // If this is a local variable, dig out its value.
3328 if (Frame) {
3329 Result = Frame->getTemporary(VD, Version);
3330 if (Result)
3331 return true;
3332
3333 if (!isa<ParmVarDecl>(VD)) {
3334 // Assume variables referenced within a lambda's call operator that were
3335 // not declared within the call operator are captures and during checking
3336 // of a potential constant expression, assume they are unknown constant
3337 // expressions.
3338 assert(isLambdaCallOperator(Frame->Callee) &&
3339 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3340 "missing value for local variable");
3341 if (Info.checkingPotentialConstantExpression())
3342 return false;
3343 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3344 // still reachable at all?
3345 Info.FFDiag(E->getBeginLoc(),
3346 diag::note_unimplemented_constexpr_lambda_feature_ast)
3347 << "captures not currently allowed";
3348 return false;
3349 }
3350 }
3351
3352 // If we're currently evaluating the initializer of this declaration, use that
3353 // in-flight value.
3354 if (Info.EvaluatingDecl == Base) {
3355 Result = Info.EvaluatingDeclValue;
3356 return true;
3357 }
3358
3359 if (isa<ParmVarDecl>(VD)) {
3360 // Assume parameters of a potential constant expression are usable in
3361 // constant expressions.
3362 if (!Info.checkingPotentialConstantExpression() ||
3363 !Info.CurrentCall->Callee ||
3364 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3365 if (Info.getLangOpts().CPlusPlus11) {
3366 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3367 << VD;
3368 NoteLValueLocation(Info, Base);
3369 } else {
3370 Info.FFDiag(E);
3371 }
3372 }
3373 return false;
3374 }
3375
3376 if (E->isValueDependent())
3377 return false;
3378
3379 // Dig out the initializer, and use the declaration which it's attached to.
3380 // FIXME: We should eventually check whether the variable has a reachable
3381 // initializing declaration.
3382 const Expr *Init = VD->getAnyInitializer(VD);
3383 if (!Init) {
3384 // Don't diagnose during potential constant expression checking; an
3385 // initializer might be added later.
3386 if (!Info.checkingPotentialConstantExpression()) {
3387 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3388 << VD;
3389 NoteLValueLocation(Info, Base);
3390 }
3391 return false;
3392 }
3393
3394 if (Init->isValueDependent()) {
3395 // The DeclRefExpr is not value-dependent, but the variable it refers to
3396 // has a value-dependent initializer. This should only happen in
3397 // constant-folding cases, where the variable is not actually of a suitable
3398 // type for use in a constant expression (otherwise the DeclRefExpr would
3399 // have been value-dependent too), so diagnose that.
3400 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3401 if (!Info.checkingPotentialConstantExpression()) {
3402 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3403 ? diag::note_constexpr_ltor_non_constexpr
3404 : diag::note_constexpr_ltor_non_integral, 1)
3405 << VD << VD->getType();
3406 NoteLValueLocation(Info, Base);
3407 }
3408 return false;
3409 }
3410
3411 // Check that we can fold the initializer. In C++, we will have already done
3412 // this in the cases where it matters for conformance.
3413 if (!VD->evaluateValue()) {
3414 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3415 NoteLValueLocation(Info, Base);
3416 return false;
3417 }
3418
3419 // Check that the variable is actually usable in constant expressions. For a
3420 // const integral variable or a reference, we might have a non-constant
3421 // initializer that we can nonetheless evaluate the initializer for. Such
3422 // variables are not usable in constant expressions. In C++98, the
3423 // initializer also syntactically needs to be an ICE.
3424 //
3425 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3426 // expressions here; doing so would regress diagnostics for things like
3427 // reading from a volatile constexpr variable.
3428 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3429 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3430 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3431 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3432 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3433 NoteLValueLocation(Info, Base);
3434 }
3435
3436 // Never use the initializer of a weak variable, not even for constant
3437 // folding. We can't be sure that this is the definition that will be used.
3438 if (VD->isWeak()) {
3439 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3440 NoteLValueLocation(Info, Base);
3441 return false;
3442 }
3443
3444 Result = VD->getEvaluatedValue();
3445 return true;
3446}
3447
3448/// Get the base index of the given base class within an APValue representing
3449/// the given derived class.
3450static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3451 const CXXRecordDecl *Base) {
3452 Base = Base->getCanonicalDecl();
3453 unsigned Index = 0;
3455 E = Derived->bases_end(); I != E; ++I, ++Index) {
3456 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3457 return Index;
3458 }
3459
3460 llvm_unreachable("base class missing from derived class's bases list");
3461}
3462
3463/// Extract the value of a character from a string literal.
3464static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3465 uint64_t Index) {
3466 assert(!isa<SourceLocExpr>(Lit) &&
3467 "SourceLocExpr should have already been converted to a StringLiteral");
3468
3469 // FIXME: Support MakeStringConstant
3470 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3471 std::string Str;
3472 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3473 assert(Index <= Str.size() && "Index too large");
3474 return APSInt::getUnsigned(Str.c_str()[Index]);
3475 }
3476
3477 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3478 Lit = PE->getFunctionName();
3479 const StringLiteral *S = cast<StringLiteral>(Lit);
3480 const ConstantArrayType *CAT =
3481 Info.Ctx.getAsConstantArrayType(S->getType());
3482 assert(CAT && "string literal isn't an array");
3483 QualType CharType = CAT->getElementType();
3484 assert(CharType->isIntegerType() && "unexpected character type");
3485 APSInt Value(Info.Ctx.getTypeSize(CharType),
3486 CharType->isUnsignedIntegerType());
3487 if (Index < S->getLength())
3488 Value = S->getCodeUnit(Index);
3489 return Value;
3490}
3491
3492// Expand a string literal into an array of characters.
3493//
3494// FIXME: This is inefficient; we should probably introduce something similar
3495// to the LLVM ConstantDataArray to make this cheaper.
3496static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3497 APValue &Result,
3498 QualType AllocType = QualType()) {
3499 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3500 AllocType.isNull() ? S->getType() : AllocType);
3501 assert(CAT && "string literal isn't an array");
3502 QualType CharType = CAT->getElementType();
3503 assert(CharType->isIntegerType() && "unexpected character type");
3504
3505 unsigned Elts = CAT->getZExtSize();
3506 Result = APValue(APValue::UninitArray(),
3507 std::min(S->getLength(), Elts), Elts);
3508 APSInt Value(Info.Ctx.getTypeSize(CharType),
3509 CharType->isUnsignedIntegerType());
3510 if (Result.hasArrayFiller())
3511 Result.getArrayFiller() = APValue(Value);
3512 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3513 Value = S->getCodeUnit(I);
3514 Result.getArrayInitializedElt(I) = APValue(Value);
3515 }
3516}
3517
3518// Expand an array so that it has more than Index filled elements.
3519static void expandArray(APValue &Array, unsigned Index) {
3520 unsigned Size = Array.getArraySize();
3521 assert(Index < Size);
3522
3523 // Always at least double the number of elements for which we store a value.
3524 unsigned OldElts = Array.getArrayInitializedElts();
3525 unsigned NewElts = std::max(Index+1, OldElts * 2);
3526 NewElts = std::min(Size, std::max(NewElts, 8u));
3527
3528 // Copy the data across.
3529 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3530 for (unsigned I = 0; I != OldElts; ++I)
3531 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3532 for (unsigned I = OldElts; I != NewElts; ++I)
3533 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3534 if (NewValue.hasArrayFiller())
3535 NewValue.getArrayFiller() = Array.getArrayFiller();
3536 Array.swap(NewValue);
3537}
3538
3539/// Determine whether a type would actually be read by an lvalue-to-rvalue
3540/// conversion. If it's of class type, we may assume that the copy operation
3541/// is trivial. Note that this is never true for a union type with fields
3542/// (because the copy always "reads" the active member) and always true for
3543/// a non-class type.
3544static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3547 return !RD || isReadByLvalueToRvalueConversion(RD);
3548}
3550 // FIXME: A trivial copy of a union copies the object representation, even if
3551 // the union is empty.
3552 if (RD->isUnion())
3553 return !RD->field_empty();
3554 if (RD->isEmpty())
3555 return false;
3556
3557 for (auto *Field : RD->fields())
3558 if (!Field->isUnnamedBitField() &&
3559 isReadByLvalueToRvalueConversion(Field->getType()))
3560 return true;
3561
3562 for (auto &BaseSpec : RD->bases())
3563 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3564 return true;
3565
3566 return false;
3567}
3568
3569/// Diagnose an attempt to read from any unreadable field within the specified
3570/// type, which might be a class type.
3571static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3572 QualType T) {
3574 if (!RD)
3575 return false;
3576
3577 if (!RD->hasMutableFields())
3578 return false;
3579
3580 for (auto *Field : RD->fields()) {
3581 // If we're actually going to read this field in some way, then it can't
3582 // be mutable. If we're in a union, then assigning to a mutable field
3583 // (even an empty one) can change the active member, so that's not OK.
3584 // FIXME: Add core issue number for the union case.
3585 if (Field->isMutable() &&
3586 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3587 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3588 Info.Note(Field->getLocation(), diag::note_declared_at);
3589 return true;
3590 }
3591
3592 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3593 return true;
3594 }
3595
3596 for (auto &BaseSpec : RD->bases())
3597 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3598 return true;
3599
3600 // All mutable fields were empty, and thus not actually read.
3601 return false;
3602}
3603
3604static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3606 bool MutableSubobject = false) {
3607 // A temporary or transient heap allocation we created.
3608 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3609 return true;
3610
3611 switch (Info.IsEvaluatingDecl) {
3612 case EvalInfo::EvaluatingDeclKind::None:
3613 return false;
3614
3615 case EvalInfo::EvaluatingDeclKind::Ctor:
3616 // The variable whose initializer we're evaluating.
3617 if (Info.EvaluatingDecl == Base)
3618 return true;
3619
3620 // A temporary lifetime-extended by the variable whose initializer we're
3621 // evaluating.
3622 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3623 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3624 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3625 return false;
3626
3627 case EvalInfo::EvaluatingDeclKind::Dtor:
3628 // C++2a [expr.const]p6:
3629 // [during constant destruction] the lifetime of a and its non-mutable
3630 // subobjects (but not its mutable subobjects) [are] considered to start
3631 // within e.
3632 if (MutableSubobject || Base != Info.EvaluatingDecl)
3633 return false;
3634 // FIXME: We can meaningfully extend this to cover non-const objects, but
3635 // we will need special handling: we should be able to access only
3636 // subobjects of such objects that are themselves declared const.
3637 QualType T = getType(Base);
3638 return T.isConstQualified() || T->isReferenceType();
3639 }
3640
3641 llvm_unreachable("unknown evaluating decl kind");
3642}
3643
3644static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3645 SourceLocation CallLoc = {}) {
3646 return Info.CheckArraySize(
3647 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3648 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3649 /*Diag=*/true);
3650}
3651
3652namespace {
3653/// A handle to a complete object (an object that is not a subobject of
3654/// another object).
3655struct CompleteObject {
3656 /// The identity of the object.
3658 /// The value of the complete object.
3659 APValue *Value;
3660 /// The type of the complete object.
3661 QualType Type;
3662
3663 CompleteObject() : Value(nullptr) {}
3665 : Base(Base), Value(Value), Type(Type) {}
3666
3667 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3668 // If this isn't a "real" access (eg, if it's just accessing the type
3669 // info), allow it. We assume the type doesn't change dynamically for
3670 // subobjects of constexpr objects (even though we'd hit UB here if it
3671 // did). FIXME: Is this right?
3672 if (!isAnyAccess(AK))
3673 return true;
3674
3675 // In C++14 onwards, it is permitted to read a mutable member whose
3676 // lifetime began within the evaluation.
3677 // FIXME: Should we also allow this in C++11?
3678 if (!Info.getLangOpts().CPlusPlus14)
3679 return false;
3680 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3681 }
3682
3683 explicit operator bool() const { return !Type.isNull(); }
3684};
3685} // end anonymous namespace
3686
3687static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3688 bool IsMutable = false) {
3689 // C++ [basic.type.qualifier]p1:
3690 // - A const object is an object of type const T or a non-mutable subobject
3691 // of a const object.
3692 if (ObjType.isConstQualified() && !IsMutable)
3693 SubobjType.addConst();
3694 // - A volatile object is an object of type const T or a subobject of a
3695 // volatile object.
3696 if (ObjType.isVolatileQualified())
3697 SubobjType.addVolatile();
3698 return SubobjType;
3699}
3700
3701/// Find the designated sub-object of an rvalue.
3702template<typename SubobjectHandler>
3703typename SubobjectHandler::result_type
3704findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3705 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3706 if (Sub.Invalid)
3707 // A diagnostic will have already been produced.
3708 return handler.failed();
3709 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3710 if (Info.getLangOpts().CPlusPlus11)
3711 Info.FFDiag(E, Sub.isOnePastTheEnd()
3712 ? diag::note_constexpr_access_past_end
3713 : diag::note_constexpr_access_unsized_array)
3714 << handler.AccessKind;
3715 else
3716 Info.FFDiag(E);
3717 return handler.failed();
3718 }
3719
3720 APValue *O = Obj.Value;
3721 QualType ObjType = Obj.Type;
3722 const FieldDecl *LastField = nullptr;
3723 const FieldDecl *VolatileField = nullptr;
3724
3725 // Walk the designator's path to find the subobject.
3726 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3727 // Reading an indeterminate value is undefined, but assigning over one is OK.
3728 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3729 (O->isIndeterminate() &&
3730 !isValidIndeterminateAccess(handler.AccessKind))) {
3731 if (!Info.checkingPotentialConstantExpression())
3732 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3733 << handler.AccessKind << O->isIndeterminate()
3734 << E->getSourceRange();
3735 return handler.failed();
3736 }
3737
3738 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3739 // const and volatile semantics are not applied on an object under
3740 // {con,de}struction.
3741 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3742 ObjType->isRecordType() &&
3743 Info.isEvaluatingCtorDtor(
3744 Obj.Base,
3745 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3746 ConstructionPhase::None) {
3747 ObjType = Info.Ctx.getCanonicalType(ObjType);
3748 ObjType.removeLocalConst();
3749 ObjType.removeLocalVolatile();
3750 }
3751
3752 // If this is our last pass, check that the final object type is OK.
3753 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3754 // Accesses to volatile objects are prohibited.
3755 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3756 if (Info.getLangOpts().CPlusPlus) {
3757 int DiagKind;
3759 const NamedDecl *Decl = nullptr;
3760 if (VolatileField) {
3761 DiagKind = 2;
3762 Loc = VolatileField->getLocation();
3763 Decl = VolatileField;
3764 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3765 DiagKind = 1;
3766 Loc = VD->getLocation();
3767 Decl = VD;
3768 } else {
3769 DiagKind = 0;
3770 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3771 Loc = E->getExprLoc();
3772 }
3773 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3774 << handler.AccessKind << DiagKind << Decl;
3775 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3776 } else {
3777 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3778 }
3779 return handler.failed();
3780 }
3781
3782 // If we are reading an object of class type, there may still be more
3783 // things we need to check: if there are any mutable subobjects, we
3784 // cannot perform this read. (This only happens when performing a trivial
3785 // copy or assignment.)
3786 if (ObjType->isRecordType() &&
3787 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3788 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3789 return handler.failed();
3790 }
3791
3792 if (I == N) {
3793 if (!handler.found(*O, ObjType))
3794 return false;
3795
3796 // If we modified a bit-field, truncate it to the right width.
3797 if (isModification(handler.AccessKind) &&
3798 LastField && LastField->isBitField() &&
3799 !truncateBitfieldValue(Info, E, *O, LastField))
3800 return false;
3801
3802 return true;
3803 }
3804
3805 LastField = nullptr;
3806 if (ObjType->isArrayType()) {
3807 // Next subobject is an array element.
3808 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3809 assert(CAT && "vla in literal type?");
3810 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3811 if (CAT->getSize().ule(Index)) {
3812 // Note, it should not be possible to form a pointer with a valid
3813 // designator which points more than one past the end of the array.
3814 if (Info.getLangOpts().CPlusPlus11)
3815 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3816 << handler.AccessKind;
3817 else
3818 Info.FFDiag(E);
3819 return handler.failed();
3820 }
3821
3822 ObjType = CAT->getElementType();
3823
3824 if (O->getArrayInitializedElts() > Index)
3825 O = &O->getArrayInitializedElt(Index);
3826 else if (!isRead(handler.AccessKind)) {
3827 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3828 return handler.failed();
3829
3830 expandArray(*O, Index);
3831 O = &O->getArrayInitializedElt(Index);
3832 } else
3833 O = &O->getArrayFiller();
3834 } else if (ObjType->isAnyComplexType()) {
3835 // Next subobject is a complex number.
3836 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3837 if (Index > 1) {
3838 if (Info.getLangOpts().CPlusPlus11)
3839 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3840 << handler.AccessKind;
3841 else
3842 Info.FFDiag(E);
3843 return handler.failed();
3844 }
3845
3846 ObjType = getSubobjectType(
3847 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3848
3849 assert(I == N - 1 && "extracting subobject of scalar?");
3850 if (O->isComplexInt()) {
3851 return handler.found(Index ? O->getComplexIntImag()
3852 : O->getComplexIntReal(), ObjType);
3853 } else {
3854 assert(O->isComplexFloat());
3855 return handler.found(Index ? O->getComplexFloatImag()
3856 : O->getComplexFloatReal(), ObjType);
3857 }
3858 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3859 if (Field->isMutable() &&
3860 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3861 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3862 << handler.AccessKind << Field;
3863 Info.Note(Field->getLocation(), diag::note_declared_at);
3864 return handler.failed();
3865 }
3866
3867 // Next subobject is a class, struct or union field.
3868 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3869 if (RD->isUnion()) {
3870 const FieldDecl *UnionField = O->getUnionField();
3871 if (!UnionField ||
3872 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3873 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3874 // Placement new onto an inactive union member makes it active.
3875 O->setUnion(Field, APValue());
3876 } else {
3877 // FIXME: If O->getUnionValue() is absent, report that there's no
3878 // active union member rather than reporting the prior active union
3879 // member. We'll need to fix nullptr_t to not use APValue() as its
3880 // representation first.
3881 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3882 << handler.AccessKind << Field << !UnionField << UnionField;
3883 return handler.failed();
3884 }
3885 }
3886 O = &O->getUnionValue();
3887 } else
3888 O = &O->getStructField(Field->getFieldIndex());
3889
3890 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3891 LastField = Field;
3892 if (Field->getType().isVolatileQualified())
3893 VolatileField = Field;
3894 } else {
3895 // Next subobject is a base class.
3896 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3897 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3898 O = &O->getStructBase(getBaseIndex(Derived, Base));
3899
3900 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3901 }
3902 }
3903}
3904
3905namespace {
3906struct ExtractSubobjectHandler {
3907 EvalInfo &Info;
3908 const Expr *E;
3909 APValue &Result;
3910 const AccessKinds AccessKind;
3911
3912 typedef bool result_type;
3913 bool failed() { return false; }
3914 bool found(APValue &Subobj, QualType SubobjType) {
3915 Result = Subobj;
3916 if (AccessKind == AK_ReadObjectRepresentation)
3917 return true;
3918 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3919 }
3920 bool found(APSInt &Value, QualType SubobjType) {
3921 Result = APValue(Value);
3922 return true;
3923 }
3924 bool found(APFloat &Value, QualType SubobjType) {
3925 Result = APValue(Value);
3926 return true;
3927 }
3928};
3929} // end anonymous namespace
3930
3931/// Extract the designated sub-object of an rvalue.
3932static bool extractSubobject(EvalInfo &Info, const Expr *E,
3933 const CompleteObject &Obj,
3934 const SubobjectDesignator &Sub, APValue &Result,
3935 AccessKinds AK = AK_Read) {
3936 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3937 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3938 return findSubobject(Info, E, Obj, Sub, Handler);
3939}
3940
3941namespace {
3942struct ModifySubobjectHandler {
3943 EvalInfo &Info;
3944 APValue &NewVal;
3945 const Expr *E;
3946
3947 typedef bool result_type;
3948 static const AccessKinds AccessKind = AK_Assign;
3949
3950 bool checkConst(QualType QT) {
3951 // Assigning to a const object has undefined behavior.
3952 if (QT.isConstQualified()) {
3953 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3954 return false;
3955 }
3956 return true;
3957 }
3958
3959 bool failed() { return false; }
3960 bool found(APValue &Subobj, QualType SubobjType) {
3961 if (!checkConst(SubobjType))
3962 return false;
3963 // We've been given ownership of NewVal, so just swap it in.
3964 Subobj.swap(NewVal);
3965 return true;
3966 }
3967 bool found(APSInt &Value, QualType SubobjType) {
3968 if (!checkConst(SubobjType))
3969 return false;
3970 if (!NewVal.isInt()) {
3971 // Maybe trying to write a cast pointer value into a complex?
3972 Info.FFDiag(E);
3973 return false;
3974 }
3975 Value = NewVal.getInt();
3976 return true;
3977 }
3978 bool found(APFloat &Value, QualType SubobjType) {
3979 if (!checkConst(SubobjType))
3980 return false;
3981 Value = NewVal.getFloat();
3982 return true;
3983 }
3984};
3985} // end anonymous namespace
3986
3987const AccessKinds ModifySubobjectHandler::AccessKind;
3988
3989/// Update the designated sub-object of an rvalue to the given value.
3990static bool modifySubobject(EvalInfo &Info, const Expr *E,
3991 const CompleteObject &Obj,
3992 const SubobjectDesignator &Sub,
3993 APValue &NewVal) {
3994 ModifySubobjectHandler Handler = { Info, NewVal, E };
3995 return findSubobject(Info, E, Obj, Sub, Handler);
3996}
3997
3998/// Find the position where two subobject designators diverge, or equivalently
3999/// the length of the common initial subsequence.
4000static unsigned FindDesignatorMismatch(QualType ObjType,
4001 const SubobjectDesignator &A,
4002 const SubobjectDesignator &B,
4003 bool &WasArrayIndex) {
4004 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4005 for (/**/; I != N; ++I) {
4006 if (!ObjType.isNull() &&
4007 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4008 // Next subobject is an array element.
4009 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4010 WasArrayIndex = true;
4011 return I;
4012 }
4013 if (ObjType->isAnyComplexType())
4014 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4015 else
4016 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4017 } else {
4018 if (A.Entries[I].getAsBaseOrMember() !=
4019 B.Entries[I].getAsBaseOrMember()) {
4020 WasArrayIndex = false;
4021 return I;
4022 }
4023 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4024 // Next subobject is a field.
4025 ObjType = FD->getType();
4026 else
4027 // Next subobject is a base class.
4028 ObjType = QualType();
4029 }
4030 }
4031 WasArrayIndex = false;
4032 return I;
4033}
4034
4035/// Determine whether the given subobject designators refer to elements of the
4036/// same array object.
4038 const SubobjectDesignator &A,
4039 const SubobjectDesignator &B) {
4040 if (A.Entries.size() != B.Entries.size())
4041 return false;
4042
4043 bool IsArray = A.MostDerivedIsArrayElement;
4044 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4045 // A is a subobject of the array element.
4046 return false;
4047
4048 // If A (and B) designates an array element, the last entry will be the array
4049 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4050 // of length 1' case, and the entire path must match.
4051 bool WasArrayIndex;
4052 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4053 return CommonLength >= A.Entries.size() - IsArray;
4054}
4055
4056/// Find the complete object to which an LValue refers.
4057static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4058 AccessKinds AK, const LValue &LVal,
4059 QualType LValType) {
4060 if (LVal.InvalidBase) {
4061 Info.FFDiag(E);
4062 return CompleteObject();
4063 }
4064
4065 if (!LVal.Base) {
4066 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4067 return CompleteObject();
4068 }
4069
4070 CallStackFrame *Frame = nullptr;
4071 unsigned Depth = 0;
4072 if (LVal.getLValueCallIndex()) {
4073 std::tie(Frame, Depth) =
4074 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4075 if (!Frame) {
4076 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4077 << AK << LVal.Base.is<const ValueDecl*>();
4078 NoteLValueLocation(Info, LVal.Base);
4079 return CompleteObject();
4080 }
4081 }
4082
4083 bool IsAccess = isAnyAccess(AK);
4084
4085 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4086 // is not a constant expression (even if the object is non-volatile). We also
4087 // apply this rule to C++98, in order to conform to the expected 'volatile'
4088 // semantics.
4089 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4090 if (Info.getLangOpts().CPlusPlus)
4091 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4092 << AK << LValType;
4093 else
4094 Info.FFDiag(E);
4095 return CompleteObject();
4096 }
4097
4098 // Compute value storage location and type of base object.
4099 APValue *BaseVal = nullptr;
4100 QualType BaseType = getType(LVal.Base);
4101
4102 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4103 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4104 // This is the object whose initializer we're evaluating, so its lifetime
4105 // started in the current evaluation.
4106 BaseVal = Info.EvaluatingDeclValue;
4107 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4108 // Allow reading from a GUID declaration.
4109 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4110 if (isModification(AK)) {
4111 // All the remaining cases do not permit modification of the object.
4112 Info.FFDiag(E, diag::note_constexpr_modify_global);
4113 return CompleteObject();
4114 }
4115 APValue &V = GD->getAsAPValue();
4116 if (V.isAbsent()) {
4117 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4118 << GD->getType();
4119 return CompleteObject();
4120 }
4121 return CompleteObject(LVal.Base, &V, GD->getType());
4122 }
4123
4124 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4125 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4126 if (isModification(AK)) {
4127 Info.FFDiag(E, diag::note_constexpr_modify_global);
4128 return CompleteObject();
4129 }
4130 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4131 GCD->getType());
4132 }
4133
4134 // Allow reading from template parameter objects.
4135 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4136 if (isModification(AK)) {
4137 Info.FFDiag(E, diag::note_constexpr_modify_global);
4138 return CompleteObject();
4139 }
4140 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4141 TPO->getType());
4142 }
4143
4144 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4145 // In C++11, constexpr, non-volatile variables initialized with constant
4146 // expressions are constant expressions too. Inside constexpr functions,
4147 // parameters are constant expressions even if they're non-const.
4148 // In C++1y, objects local to a constant expression (those with a Frame) are
4149 // both readable and writable inside constant expressions.
4150 // In C, such things can also be folded, although they are not ICEs.
4151 const VarDecl *VD = dyn_cast<VarDecl>(D);
4152 if (VD) {
4153 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4154 VD = VDef;
4155 }
4156 if (!VD || VD->isInvalidDecl()) {
4157 Info.FFDiag(E);
4158 return CompleteObject();
4159 }
4160
4161 bool IsConstant = BaseType.isConstant(Info.Ctx);
4162 bool ConstexprVar = false;
4163 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4164 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4165 ConstexprVar = VD->isConstexpr();
4166
4167 // Unless we're looking at a local variable or argument in a constexpr call,
4168 // the variable we're reading must be const.
4169 if (!Frame) {
4170 if (IsAccess && isa<ParmVarDecl>(VD)) {
4171 // Access of a parameter that's not associated with a frame isn't going
4172 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4173 // suitable diagnostic.
4174 } else if (Info.getLangOpts().CPlusPlus14 &&
4175 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4176 // OK, we can read and modify an object if we're in the process of
4177 // evaluating its initializer, because its lifetime began in this
4178 // evaluation.
4179 } else if (isModification(AK)) {
4180 // All the remaining cases do not permit modification of the object.
4181 Info.FFDiag(E, diag::note_constexpr_modify_global);
4182 return CompleteObject();
4183 } else if (VD->isConstexpr()) {
4184 // OK, we can read this variable.
4185 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4186 Info.FFDiag(E);
4187 return CompleteObject();
4188 } else if (BaseType->isIntegralOrEnumerationType()) {
4189 if (!IsConstant) {
4190 if (!IsAccess)
4191 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4192 if (Info.getLangOpts().CPlusPlus) {
4193 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4194 Info.Note(VD->getLocation(), diag::note_declared_at);
4195 } else {
4196 Info.FFDiag(E);
4197 }
4198 return CompleteObject();
4199 }
4200 } else if (!IsAccess) {
4201 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4202 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4203 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4204 // This variable might end up being constexpr. Don't diagnose it yet.
4205 } else if (IsConstant) {
4206 // Keep evaluating to see what we can do. In particular, we support
4207 // folding of const floating-point types, in order to make static const
4208 // data members of such types (supported as an extension) more useful.
4209 if (Info.getLangOpts().CPlusPlus) {
4210 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4211 ? diag::note_constexpr_ltor_non_constexpr
4212 : diag::note_constexpr_ltor_non_integral, 1)
4213 << VD << BaseType;
4214 Info.Note(VD->getLocation(), diag::note_declared_at);
4215 } else {
4216 Info.CCEDiag(E);
4217 }
4218 } else {
4219 // Never allow reading a non-const value.
4220 if (Info.getLangOpts().CPlusPlus) {
4221 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4222 ? diag::note_constexpr_ltor_non_constexpr
4223 : diag::note_constexpr_ltor_non_integral, 1)
4224 << VD << BaseType;
4225 Info.Note(VD->getLocation(), diag::note_declared_at);
4226 } else {
4227 Info.FFDiag(E);
4228 }
4229 return CompleteObject();
4230 }
4231 }
4232
4233 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4234 return CompleteObject();
4235 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4236 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4237 if (!Alloc) {
4238 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4239 return CompleteObject();
4240 }
4241 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4242 LVal.Base.getDynamicAllocType());
4243 } else {
4244 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4245
4246 if (!Frame) {
4247 if (const MaterializeTemporaryExpr *MTE =
4248 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4249 assert(MTE->getStorageDuration() == SD_Static &&
4250 "should have a frame for a non-global materialized temporary");
4251
4252 // C++20 [expr.const]p4: [DR2126]
4253 // An object or reference is usable in constant expressions if it is
4254 // - a temporary object of non-volatile const-qualified literal type
4255 // whose lifetime is extended to that of a variable that is usable
4256 // in constant expressions
4257 //
4258 // C++20 [expr.const]p5:
4259 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4260 // - a non-volatile glvalue that refers to an object that is usable
4261 // in constant expressions, or
4262 // - a non-volatile glvalue of literal type that refers to a
4263 // non-volatile object whose lifetime began within the evaluation
4264 // of E;
4265 //
4266 // C++11 misses the 'began within the evaluation of e' check and
4267 // instead allows all temporaries, including things like:
4268 // int &&r = 1;
4269 // int x = ++r;
4270 // constexpr int k = r;
4271 // Therefore we use the C++14-onwards rules in C++11 too.
4272 //
4273 // Note that temporaries whose lifetimes began while evaluating a
4274 // variable's constructor are not usable while evaluating the
4275 // corresponding destructor, not even if they're of const-qualified
4276 // types.
4277 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4278 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4279 if (!IsAccess)
4280 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4281 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4282 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4283 return CompleteObject();
4284 }
4285
4286 BaseVal = MTE->getOrCreateValue(false);
4287 assert(BaseVal && "got reference to unevaluated temporary");
4288 } else {
4289 if (!IsAccess)
4290 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4291 APValue Val;
4292 LVal.moveInto(Val);
4293 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4294 << AK
4295 << Val.getAsString(Info.Ctx,
4296 Info.Ctx.getLValueReferenceType(LValType));
4297 NoteLValueLocation(Info, LVal.Base);
4298 return CompleteObject();
4299 }
4300 } else {
4301 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4302 assert(BaseVal && "missing value for temporary");
4303 }
4304 }
4305
4306 // In C++14, we can't safely access any mutable state when we might be
4307 // evaluating after an unmodeled side effect. Parameters are modeled as state
4308 // in the caller, but aren't visible once the call returns, so they can be
4309 // modified in a speculatively-evaluated call.
4310 //
4311 // FIXME: Not all local state is mutable. Allow local constant subobjects
4312 // to be read here (but take care with 'mutable' fields).
4313 unsigned VisibleDepth = Depth;
4314 if (llvm::isa_and_nonnull<ParmVarDecl>(
4315 LVal.Base.dyn_cast<const ValueDecl *>()))
4316 ++VisibleDepth;
4317 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4318 Info.EvalStatus.HasSideEffects) ||
4319 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4320 return CompleteObject();
4321
4322 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4323}
4324
4325/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4326/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4327/// glvalue referred to by an entity of reference type.
4328///
4329/// \param Info - Information about the ongoing evaluation.
4330/// \param Conv - The expression for which we are performing the conversion.
4331/// Used for diagnostics.
4332/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4333/// case of a non-class type).
4334/// \param LVal - The glvalue on which we are attempting to perform this action.
4335/// \param RVal - The produced value will be placed here.
4336/// \param WantObjectRepresentation - If true, we're looking for the object
4337/// representation rather than the value, and in particular,
4338/// there is no requirement that the result be fully initialized.
4339static bool
4341 const LValue &LVal, APValue &RVal,
4342 bool WantObjectRepresentation = false) {
4343 if (LVal.Designator.Invalid)
4344 return false;
4345
4346 // Check for special cases where there is no existing APValue to look at.
4347 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4348
4349 AccessKinds AK =
4350 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4351
4352 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4353 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4354 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4355 // initializer until now for such expressions. Such an expression can't be
4356 // an ICE in C, so this only matters for fold.
4357 if (Type.isVolatileQualified()) {
4358 Info.FFDiag(Conv);
4359 return false;
4360 }
4361
4362 APValue Lit;
4363 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4364 return false;
4365
4366 // According to GCC info page:
4367 //
4368 // 6.28 Compound Literals
4369 //
4370 // As an optimization, G++ sometimes gives array compound literals longer
4371 // lifetimes: when the array either appears outside a function or has a
4372 // const-qualified type. If foo and its initializer had elements of type
4373 // char *const rather than char *, or if foo were a global variable, the
4374 // array would have static storage duration. But it is probably safest
4375 // just to avoid the use of array compound literals in C++ code.
4376 //
4377 // Obey that rule by checking constness for converted array types.
4378
4379 QualType CLETy = CLE->getType();
4380 if (CLETy->isArrayType() && !Type->isArrayType()) {
4381 if (!CLETy.isConstant(Info.Ctx)) {
4382 Info.FFDiag(Conv);
4383 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4384 return false;
4385 }
4386 }
4387
4388 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4389 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4390 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4391 // Special-case character extraction so we don't have to construct an
4392 // APValue for the whole string.
4393 assert(LVal.Designator.Entries.size() <= 1 &&
4394 "Can only read characters from string literals");
4395 if (LVal.Designator.Entries.empty()) {
4396 // Fail for now for LValue to RValue conversion of an array.
4397 // (This shouldn't show up in C/C++, but it could be triggered by a
4398 // weird EvaluateAsRValue call from a tool.)
4399 Info.FFDiag(Conv);
4400 return false;
4401 }
4402 if (LVal.Designator.isOnePastTheEnd()) {
4403 if (Info.getLangOpts().CPlusPlus11)
4404 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4405 else
4406 Info.FFDiag(Conv);
4407 return false;
4408 }
4409 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4410 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4411 return true;
4412 }
4413 }
4414
4415 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4416 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4417}
4418
4419/// Perform an assignment of Val to LVal. Takes ownership of Val.
4420static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4421 QualType LValType, APValue &Val) {
4422 if (LVal.Designator.Invalid)
4423 return false;
4424
4425 if (!Info.getLangOpts().CPlusPlus14) {
4426 Info.FFDiag(E);
4427 return false;
4428 }
4429
4430 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4431 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4432}
4433
4434namespace {
4435struct CompoundAssignSubobjectHandler {
4436 EvalInfo &Info;
4438 QualType PromotedLHSType;
4440 const APValue &RHS;
4441
4442 static const AccessKinds AccessKind = AK_Assign;
4443
4444 typedef bool result_type;
4445
4446 bool checkConst(QualType QT) {
4447 // Assigning to a const object has undefined behavior.
4448 if (QT.isConstQualified()) {
4449 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4450 return false;
4451 }
4452 return true;
4453 }
4454
4455 bool failed() { return false; }
4456 bool found(APValue &Subobj, QualType SubobjType) {
4457 switch (Subobj.getKind()) {
4458 case APValue::Int:
4459 return found(Subobj.getInt(), SubobjType);
4460 case APValue::Float:
4461 return found(Subobj.getFloat(), SubobjType);
4464 // FIXME: Implement complex compound assignment.
4465 Info.FFDiag(E);
4466 return false;
4467 case APValue::LValue:
4468 return foundPointer(Subobj, SubobjType);
4469 case APValue::Vector:
4470 return foundVector(Subobj, SubobjType);
4472 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4473 << /*read of=*/0 << /*uninitialized object=*/1
4474 << E->getLHS()->getSourceRange();
4475 return false;
4476 default:
4477 // FIXME: can this happen?
4478 Info.FFDiag(E);
4479 return false;
4480 }
4481 }
4482
4483 bool foundVector(APValue &Value, QualType SubobjType) {
4484 if (!checkConst(SubobjType))
4485 return false;
4486
4487 if (!SubobjType->isVectorType()) {
4488 Info.FFDiag(E);
4489 return false;
4490 }
4491 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4492 }
4493
4494 bool found(APSInt &Value, QualType SubobjType) {
4495 if (!checkConst(SubobjType))
4496 return false;
4497
4498 if (!SubobjType->isIntegerType()) {
4499 // We don't support compound assignment on integer-cast-to-pointer
4500 // values.
4501 Info.FFDiag(E);
4502 return false;
4503 }
4504
4505 if (RHS.isInt()) {
4506 APSInt LHS =
4507 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4508 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4509 return false;
4510 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4511 return true;
4512 } else if (RHS.isFloat()) {
4513 const FPOptions FPO = E->getFPFeaturesInEffect(
4514 Info.Ctx.getLangOpts());
4515 APFloat FValue(0.0);
4516 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4517 PromotedLHSType, FValue) &&
4518 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4519 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4520 Value);
4521 }
4522
4523 Info.FFDiag(E);
4524 return false;
4525 }
4526 bool found(APFloat &Value, QualType SubobjType) {
4527 return checkConst(SubobjType) &&
4528 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4529 Value) &&
4530 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4531 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4532 }
4533 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4534 if (!checkConst(SubobjType))
4535 return false;
4536
4537 QualType PointeeType;
4538 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4539 PointeeType = PT->getPointeeType();
4540
4541 if (PointeeType.isNull() || !RHS.isInt() ||
4542 (Opcode != BO_Add && Opcode != BO_Sub)) {
4543 Info.FFDiag(E);
4544 return false;
4545 }
4546
4547 APSInt Offset = RHS.getInt();
4548 if (Opcode == BO_Sub)
4549 negateAsSigned(Offset);
4550
4551 LValue LVal;
4552 LVal.setFrom(Info.Ctx, Subobj);
4553 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4554 return false;
4555 LVal.moveInto(Subobj);
4556 return true;
4557 }
4558};
4559} // end anonymous namespace
4560
4561const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4562
4563/// Perform a compound assignment of LVal <op>= RVal.
4564static bool handleCompoundAssignment(EvalInfo &Info,
4566 const LValue &LVal, QualType LValType,
4567 QualType PromotedLValType,
4568 BinaryOperatorKind Opcode,
4569 const APValue &RVal) {
4570 if (LVal.Designator.Invalid)
4571 return false;
4572
4573 if (!Info.getLangOpts().CPlusPlus14) {
4574 Info.FFDiag(E);
4575 return false;
4576 }
4577
4578 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4579 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4580 RVal };
4581 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4582}
4583
4584namespace {
4585struct IncDecSubobjectHandler {
4586 EvalInfo &Info;
4587 const UnaryOperator *E;
4588 AccessKinds AccessKind;
4589 APValue *Old;
4590
4591 typedef bool result_type;
4592
4593 bool checkConst(QualType QT) {
4594 // Assigning to a const object has undefined behavior.
4595 if (QT.isConstQualified()) {
4596 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4597 return false;
4598 }
4599 return true;
4600 }
4601
4602 bool failed() { return false; }
4603 bool found(APValue &Subobj, QualType SubobjType) {
4604 // Stash the old value. Also clear Old, so we don't clobber it later
4605 // if we're post-incrementing a complex.
4606 if (Old) {
4607 *Old = Subobj;
4608 Old = nullptr;
4609 }
4610
4611 switch (Subobj.getKind()) {
4612 case APValue::Int:
4613 return found(Subobj.getInt(), SubobjType);
4614 case APValue::Float:
4615 return found(Subobj.getFloat(), SubobjType);
4617 return found(Subobj.getComplexIntReal(),
4618 SubobjType->castAs<ComplexType>()->getElementType()
4619 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4621 return found(Subobj.getComplexFloatReal(),
4622 SubobjType->castAs<ComplexType>()->getElementType()
4623 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4624 case APValue::LValue:
4625 return foundPointer(Subobj, SubobjType);
4626 default:
4627 // FIXME: can this happen?
4628 Info.FFDiag(E);
4629 return false;
4630 }
4631 }
4632 bool found(APSInt &Value, QualType SubobjType) {
4633 if (!checkConst(SubobjType))
4634 return false;
4635
4636 if (!SubobjType->isIntegerType()) {
4637 // We don't support increment / decrement on integer-cast-to-pointer
4638 // values.
4639 Info.FFDiag(E);
4640 return false;
4641 }
4642
4643 if (Old) *Old = APValue(Value);
4644
4645 // bool arithmetic promotes to int, and the conversion back to bool
4646 // doesn't reduce mod 2^n, so special-case it.
4647 if (SubobjType->isBooleanType()) {
4648 if (AccessKind == AK_Increment)
4649 Value = 1;
4650 else
4651 Value = !Value;
4652 return true;
4653 }
4654
4655 bool WasNegative = Value.isNegative();
4656 if (AccessKind == AK_Increment) {
4657 ++Value;
4658
4659 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4660 APSInt ActualValue(Value, /*IsUnsigned*/true);
4661 return HandleOverflow(Info, E, ActualValue, SubobjType);
4662 }
4663 } else {
4664 --Value;
4665
4666 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4667 unsigned BitWidth = Value.getBitWidth();
4668 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4669 ActualValue.setBit(BitWidth);
4670 return HandleOverflow(Info, E, ActualValue, SubobjType);
4671 }
4672 }
4673 return true;
4674 }
4675 bool found(APFloat &Value, QualType SubobjType) {
4676 if (!checkConst(SubobjType))
4677 return false;
4678
4679 if (Old) *Old = APValue(Value);
4680
4681 APFloat One(Value.getSemantics(), 1);
4682 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4683 APFloat::opStatus St;
4684 if (AccessKind == AK_Increment)
4685 St = Value.add(One, RM);
4686 else
4687 St = Value.subtract(One, RM);
4688 return checkFloatingPointResult(Info, E, St);
4689 }
4690 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4691 if (!checkConst(SubobjType))
4692 return false;
4693
4694 QualType PointeeType;
4695 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4696 PointeeType = PT->getPointeeType();
4697 else {
4698 Info.FFDiag(E);
4699 return false;
4700 }
4701
4702 LValue LVal;
4703 LVal.setFrom(Info.Ctx, Subobj);
4704 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4705 AccessKind == AK_Increment ? 1 : -1))
4706 return false;
4707 LVal.moveInto(Subobj);
4708 return true;
4709 }
4710};
4711} // end anonymous namespace
4712
4713/// Perform an increment or decrement on LVal.
4714static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4715 QualType LValType, bool IsIncrement, APValue *Old) {
4716 if (LVal.Designator.Invalid)
4717 return false;
4718
4719 if (!Info.getLangOpts().CPlusPlus14) {
4720 Info.FFDiag(E);
4721 return false;
4722 }
4723
4724 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4725 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4726 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4727 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4728}
4729
4730/// Build an lvalue for the object argument of a member function call.
4731static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4732 LValue &This) {
4733 if (Object->getType()->isPointerType() && Object->isPRValue())
4734 return EvaluatePointer(Object, This, Info);
4735
4736 if (Object->isGLValue())
4737 return EvaluateLValue(Object, This, Info);
4738
4739 if (Object->getType()->isLiteralType(Info.Ctx))
4740 return EvaluateTemporary(Object, This, Info);
4741
4742 if (Object->getType()->isRecordType() && Object->isPRValue())
4743 return EvaluateTemporary(Object, This, Info);
4744
4745 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4746 return false;
4747}
4748
4749/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4750/// lvalue referring to the result.
4751///
4752/// \param Info - Information about the ongoing evaluation.
4753/// \param LV - An lvalue referring to the base of the member pointer.
4754/// \param RHS - The member pointer expression.
4755/// \param IncludeMember - Specifies whether the member itself is included in
4756/// the resulting LValue subobject designator. This is not possible when
4757/// creating a bound member function.
4758/// \return The field or method declaration to which the member pointer refers,
4759/// or 0 if evaluation fails.
4760static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4761 QualType LVType,
4762 LValue &LV,
4763 const Expr *RHS,
4764 bool IncludeMember = true) {
4765 MemberPtr MemPtr;
4766 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4767 return nullptr;
4768
4769 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4770 // member value, the behavior is undefined.
4771 if (!MemPtr.getDecl()) {
4772 // FIXME: Specific diagnostic.
4773 Info.FFDiag(RHS);
4774 return nullptr;
4775 }
4776
4777 if (MemPtr.isDerivedMember()) {
4778 // This is a member of some derived class. Truncate LV appropriately.
4779 // The end of the derived-to-base path for the base object must match the
4780 // derived-to-base path for the member pointer.
4781 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4782 LV.Designator.Entries.size()) {
4783 Info.FFDiag(RHS);
4784 return nullptr;
4785 }
4786 unsigned PathLengthToMember =
4787 LV.Designator.Entries.size() - MemPtr.Path.size();
4788 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4789 const CXXRecordDecl *LVDecl = getAsBaseClass(
4790 LV.Designator.Entries[PathLengthToMember + I]);
4791 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4792 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4793 Info.FFDiag(RHS);
4794 return nullptr;
4795 }
4796 }
4797
4798 // Truncate the lvalue to the appropriate derived class.
4799 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4800 PathLengthToMember))
4801 return nullptr;
4802 } else if (!MemPtr.Path.empty()) {
4803 // Extend the LValue path with the member pointer's path.
4804 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4805 MemPtr.Path.size() + IncludeMember);
4806
4807 // Walk down to the appropriate base class.
4808 if (const PointerType *PT = LVType->getAs<PointerType>())
4809 LVType = PT->getPointeeType();
4810 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4811 assert(RD && "member pointer access on non-class-type expression");
4812 // The first class in the path is that of the lvalue.
4813 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4814 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4815 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4816 return nullptr;
4817 RD = Base;
4818 }
4819 // Finally cast to the class containing the member.
4820 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4821 MemPtr.getContainingRecord()))
4822 return nullptr;
4823 }
4824
4825 // Add the member. Note that we cannot build bound member functions here.
4826 if (IncludeMember) {
4827 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4828 if (!HandleLValueMember(Info, RHS, LV, FD))
4829 return nullptr;
4830 } else if (const IndirectFieldDecl *IFD =
4831 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4832 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4833 return nullptr;
4834 } else {
4835 llvm_unreachable("can't construct reference to bound member function");
4836 }
4837 }
4838
4839 return MemPtr.getDecl();
4840}
4841
4842static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4843 const BinaryOperator *BO,
4844 LValue &LV,
4845 bool IncludeMember = true) {
4846 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4847
4848 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4849 if (Info.noteFailure()) {
4850 MemberPtr MemPtr;
4851 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4852 }
4853 return nullptr;
4854 }
4855
4856 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4857 BO->getRHS(), IncludeMember);
4858}
4859
4860/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4861/// the provided lvalue, which currently refers to the base object.
4862static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4863 LValue &Result) {
4864 SubobjectDesignator &D = Result.Designator;
4865 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4866 return false;
4867
4868 QualType TargetQT = E->getType();
4869 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4870 TargetQT = PT->getPointeeType();
4871
4872 // Check this cast lands within the final derived-to-base subobject path.
4873 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4874 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4875 << D.MostDerivedType << TargetQT;
4876 return false;
4877 }
4878
4879 // Check the type of the final cast. We don't need to check the path,
4880 // since a cast can only be formed if the path is unique.
4881 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4882 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4883 const CXXRecordDecl *FinalType;
4884 if (NewEntriesSize == D.MostDerivedPathLength)
4885 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4886 else
4887 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4888 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4889 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4890 << D.MostDerivedType << TargetQT;
4891 return false;
4892 }
4893
4894 // Truncate the lvalue to the appropriate derived class.
4895 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4896}
4897
4898/// Get the value to use for a default-initialized object of type T.
4899/// Return false if it encounters something invalid.
4901 bool Success = true;
4902
4903 // If there is already a value present don't overwrite it.
4904 if (!Result.isAbsent())
4905 return true;
4906
4907 if (auto *RD = T->getAsCXXRecordDecl()) {
4908 if (RD->isInvalidDecl()) {
4909 Result = APValue();
4910 return false;
4911 }
4912 if (RD->isUnion()) {
4913 Result = APValue((const FieldDecl *)nullptr);
4914 return true;
4915 }
4916 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4917 std::distance(RD->field_begin(), RD->field_end()));
4918
4919 unsigned Index = 0;
4920 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4921 End = RD->bases_end();
4922 I != End; ++I, ++Index)
4923 Success &=
4924 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4925
4926 for (const auto *I : RD->fields()) {
4927 if (I->isUnnamedBitField())
4928 continue;
4930 I->getType(), Result.getStructField(I->getFieldIndex()));
4931 }
4932 return Success;
4933 }
4934
4935 if (auto *AT =
4936 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4937 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
4938 if (Result.hasArrayFiller())
4939 Success &=
4940 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4941
4942 return Success;
4943 }
4944
4945 Result = APValue::IndeterminateValue();
4946 return true;
4947}
4948
4949namespace {
4950enum EvalStmtResult {
4951 /// Evaluation failed.
4952 ESR_Failed,
4953 /// Hit a 'return' statement.
4954 ESR_Returned,
4955 /// Evaluation succeeded.
4956 ESR_Succeeded,
4957 /// Hit a 'continue' statement.
4958 ESR_Continue,
4959 /// Hit a 'break' statement.
4960 ESR_Break,
4961 /// Still scanning for 'case' or 'default' statement.
4962 ESR_CaseNotFound
4963};
4964}
4965
4966static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4967 if (VD->isInvalidDecl())
4968 return false;
4969 // We don't need to evaluate the initializer for a static local.
4970 if (!VD->hasLocalStorage())
4971 return true;
4972
4973 LValue Result;
4974 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4975 ScopeKind::Block, Result);
4976
4977 const Expr *InitE = VD->getInit();
4978 if (!InitE) {
4979 if (VD->getType()->isDependentType())
4980 return Info.noteSideEffect();
4981 return handleDefaultInitValue(VD->getType(), Val);
4982 }
4983 if (InitE->isValueDependent())
4984 return false;
4985
4986 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4987 // Wipe out any partially-computed value, to allow tracking that this
4988 // evaluation failed.
4989 Val = APValue();
4990 return false;
4991 }
4992
4993 return true;
4994}
4995
4996static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4997 bool OK = true;
4998
4999 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5000 OK &= EvaluateVarDecl(Info, VD);
5001
5002 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
5003 for (auto *BD : DD->bindings())
5004 if (auto *VD = BD->getHoldingVar())
5005 OK &= EvaluateDecl(Info, VD);
5006
5007 return OK;
5008}
5009
5010static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5011 assert(E->isValueDependent());
5012 if (Info.noteSideEffect())
5013 return true;
5014 assert(E->containsErrors() && "valid value-dependent expression should never "
5015 "reach invalid code path.");
5016 return false;
5017}
5018
5019/// Evaluate a condition (either a variable declaration or an expression).
5020static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5021 const Expr *Cond, bool &Result) {
5022 if (Cond->isValueDependent())
5023 return false;
5024 FullExpressionRAII Scope(Info);
5025 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5026 return false;
5027 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5028 return false;
5029 return Scope.destroy();
5030}
5031
5032namespace {
5033/// A location where the result (returned value) of evaluating a
5034/// statement should be stored.
5035struct StmtResult {
5036 /// The APValue that should be filled in with the returned value.
5037 APValue &Value;
5038 /// The location containing the result, if any (used to support RVO).
5039 const LValue *Slot;
5040};
5041
5042struct TempVersionRAII {
5043 CallStackFrame &Frame;
5044
5045 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5046 Frame.pushTempVersion();
5047 }
5048
5049 ~TempVersionRAII() {
5050 Frame.popTempVersion();
5051 }
5052};
5053
5054}
5055
5056static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5057 const Stmt *S,
5058 const SwitchCase *SC = nullptr);
5059
5060/// Evaluate the body of a loop, and translate the result as appropriate.
5061static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5062 const Stmt *Body,
5063 const SwitchCase *Case = nullptr) {
5064 BlockScopeRAII Scope(Info);
5065
5066 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5067 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5068 ESR = ESR_Failed;
5069
5070 switch (ESR) {
5071 case ESR_Break:
5072 return ESR_Succeeded;
5073 case ESR_Succeeded:
5074 case ESR_Continue:
5075 return ESR_Continue;
5076 case ESR_Failed:
5077 case ESR_Returned:
5078 case ESR_CaseNotFound:
5079 return ESR;
5080 }
5081 llvm_unreachable("Invalid EvalStmtResult!");
5082}
5083
5084/// Evaluate a switch statement.
5085static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5086 const SwitchStmt *SS) {
5087 BlockScopeRAII Scope(Info);
5088
5089 // Evaluate the switch condition.
5090 APSInt Value;
5091 {
5092 if (const Stmt *Init = SS->getInit()) {
5093 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5094 if (ESR != ESR_Succeeded) {
5095 if (ESR != ESR_Failed && !Scope.destroy())
5096 ESR = ESR_Failed;
5097 return ESR;
5098 }
5099 }
5100
5101 FullExpressionRAII CondScope(Info);
5102 if (SS->getConditionVariable() &&
5103 !EvaluateDecl(Info, SS->getConditionVariable()))
5104 return ESR_Failed;
5105 if (SS->getCond()->isValueDependent()) {
5106 // We don't know what the value is, and which branch should jump to.
5107 EvaluateDependentExpr(SS->getCond(), Info);
5108 return ESR_Failed;
5109 }
5110 if (!EvaluateInteger(SS->getCond(), Value, Info))
5111 return ESR_Failed;
5112
5113 if (!CondScope.destroy())
5114 return ESR_Failed;
5115 }
5116
5117 // Find the switch case corresponding to the value of the condition.
5118 // FIXME: Cache this lookup.
5119 const SwitchCase *Found = nullptr;
5120 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5121 SC = SC->getNextSwitchCase()) {
5122 if (isa<DefaultStmt>(SC)) {
5123 Found = SC;
5124 continue;
5125 }
5126
5127 const CaseStmt *CS = cast<CaseStmt>(SC);
5128 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5129 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5130 : LHS;
5131 if (LHS <= Value && Value <= RHS) {
5132 Found = SC;
5133 break;
5134 }
5135 }
5136
5137 if (!Found)
5138 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5139
5140 // Search the switch body for the switch case and evaluate it from there.
5141 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5142 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5143 return ESR_Failed;
5144
5145 switch (ESR) {
5146 case ESR_Break:
5147 return ESR_Succeeded;
5148 case ESR_Succeeded:
5149 case ESR_Continue:
5150 case ESR_Failed:
5151 case ESR_Returned:
5152 return ESR;
5153 case ESR_CaseNotFound:
5154 // This can only happen if the switch case is nested within a statement
5155 // expression. We have no intention of supporting that.
5156 Info.FFDiag(Found->getBeginLoc(),
5157 diag::note_constexpr_stmt_expr_unsupported);
5158 return ESR_Failed;
5159 }
5160 llvm_unreachable("Invalid EvalStmtResult!");
5161}
5162
5163static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5164 // An expression E is a core constant expression unless the evaluation of E
5165 // would evaluate one of the following: [C++23] - a control flow that passes
5166 // through a declaration of a variable with static or thread storage duration
5167 // unless that variable is usable in constant expressions.
5168 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5169 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5170 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5171 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5172 return false;
5173 }
5174 return true;
5175}
5176
5177// Evaluate a statement.
5178static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5179 const Stmt *S, const SwitchCase *Case) {
5180 if (!Info.nextStep(S))
5181 return ESR_Failed;
5182
5183 // If we're hunting down a 'case' or 'default' label, recurse through
5184 // substatements until we hit the label.
5185 if (Case) {
5186 switch (S->getStmtClass()) {
5187 case Stmt::CompoundStmtClass:
5188 // FIXME: Precompute which substatement of a compound statement we
5189 // would jump to, and go straight there rather than performing a
5190 // linear scan each time.
5191 case Stmt::LabelStmtClass:
5192 case Stmt::AttributedStmtClass:
5193 case Stmt::DoStmtClass:
5194 break;
5195
5196 case Stmt::CaseStmtClass:
5197 case Stmt::DefaultStmtClass:
5198 if (Case == S)
5199 Case = nullptr;
5200 break;
5201
5202 case Stmt::IfStmtClass: {
5203 // FIXME: Precompute which side of an 'if' we would jump to, and go
5204 // straight there rather than scanning both sides.
5205 const IfStmt *IS = cast<IfStmt>(S);
5206
5207 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5208 // preceded by our switch label.
5209 BlockScopeRAII Scope(Info);
5210
5211 // Step into the init statement in case it brings an (uninitialized)
5212 // variable into scope.
5213 if (const Stmt *Init = IS->getInit()) {
5214 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5215 if (ESR != ESR_CaseNotFound) {
5216 assert(ESR != ESR_Succeeded);
5217 return ESR;
5218 }
5219 }
5220
5221 // Condition variable must be initialized if it exists.
5222 // FIXME: We can skip evaluating the body if there's a condition
5223 // variable, as there can't be any case labels within it.
5224 // (The same is true for 'for' statements.)
5225
5226 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5227 if (ESR == ESR_Failed)
5228 return ESR;
5229 if (ESR != ESR_CaseNotFound)
5230 return Scope.destroy() ? ESR : ESR_Failed;
5231 if (!IS->getElse())
5232 return ESR_CaseNotFound;
5233
5234 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5235 if (ESR == ESR_Failed)
5236 return ESR;
5237 if (ESR != ESR_CaseNotFound)
5238 return Scope.destroy() ? ESR : ESR_Failed;
5239 return ESR_CaseNotFound;
5240 }
5241
5242 case Stmt::WhileStmtClass: {
5243 EvalStmtResult ESR =
5244 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5245 if (ESR != ESR_Continue)
5246 return ESR;
5247 break;
5248 }
5249
5250 case Stmt::ForStmtClass: {
5251 const ForStmt *FS = cast<ForStmt>(S);
5252 BlockScopeRAII Scope(Info);
5253
5254 // Step into the init statement in case it brings an (uninitialized)
5255 // variable into scope.
5256 if (const Stmt *Init = FS->getInit()) {
5257 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5258 if (ESR != ESR_CaseNotFound) {
5259 assert(ESR != ESR_Succeeded);
5260 return ESR;
5261 }
5262 }
5263
5264 EvalStmtResult ESR =
5265 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5266 if (ESR != ESR_Continue)
5267 return ESR;
5268 if (const auto *Inc = FS->getInc()) {
5269 if (Inc->isValueDependent()) {
5270 if (!EvaluateDependentExpr(Inc, Info))
5271 return ESR_Failed;
5272 } else {
5273 FullExpressionRAII IncScope(Info);
5274 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5275 return ESR_Failed;
5276 }
5277 }
5278 break;
5279 }
5280
5281 case Stmt::DeclStmtClass: {
5282 // Start the lifetime of any uninitialized variables we encounter. They
5283 // might be used by the selected branch of the switch.
5284 const DeclStmt *DS = cast<DeclStmt>(S);
5285 for (const auto *D : DS->decls()) {
5286 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5287 if (!CheckLocalVariableDeclaration(Info, VD))
5288 return ESR_Failed;
5289 if (VD->hasLocalStorage() && !VD->getInit())
5290 if (!EvaluateVarDecl(Info, VD))
5291 return ESR_Failed;
5292 // FIXME: If the variable has initialization that can't be jumped
5293 // over, bail out of any immediately-surrounding compound-statement
5294 // too. There can't be any case labels here.
5295 }
5296 }
5297 return ESR_CaseNotFound;
5298 }
5299
5300 default:
5301 return ESR_CaseNotFound;
5302 }
5303 }
5304
5305 switch (S->getStmtClass()) {
5306 default:
5307 if (const Expr *E = dyn_cast<Expr>(S)) {
5308 if (E->isValueDependent()) {
5309 if (!EvaluateDependentExpr(E, Info))
5310 return ESR_Failed;
5311 } else {
5312 // Don't bother evaluating beyond an expression-statement which couldn't
5313 // be evaluated.
5314 // FIXME: Do we need the FullExpressionRAII object here?
5315 // VisitExprWithCleanups should create one when necessary.
5316 FullExpressionRAII Scope(Info);
5317 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5318 return ESR_Failed;
5319 }
5320 return ESR_Succeeded;
5321 }
5322
5323 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5324 return ESR_Failed;
5325
5326 case Stmt::NullStmtClass:
5327 return ESR_Succeeded;
5328
5329 case Stmt::DeclStmtClass: {
5330 const DeclStmt *DS = cast<DeclStmt>(S);
5331 for (const auto *D : DS->decls()) {
5332 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5333 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5334 return ESR_Failed;
5335 // Each declaration initialization is its own full-expression.
5336 FullExpressionRAII Scope(Info);
5337 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5338 return ESR_Failed;
5339 if (!Scope.destroy())
5340 return ESR_Failed;
5341 }
5342 return ESR_Succeeded;
5343 }
5344
5345 case Stmt::ReturnStmtClass: {
5346 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5347 FullExpressionRAII Scope(Info);
5348 if (RetExpr && RetExpr->isValueDependent()) {
5349 EvaluateDependentExpr(RetExpr, Info);
5350 // We know we returned, but we don't know what the value is.
5351 return ESR_Failed;
5352 }
5353 if (RetExpr &&
5354 !(Result.Slot
5355 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5356 : Evaluate(Result.Value, Info, RetExpr)))
5357 return ESR_Failed;
5358 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5359 }
5360
5361 case Stmt::CompoundStmtClass: {
5362 BlockScopeRAII Scope(Info);
5363
5364 const CompoundStmt *CS = cast<CompoundStmt>(S);
5365 for (const auto *BI : CS->body()) {
5366 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5367 if (ESR == ESR_Succeeded)
5368 Case = nullptr;
5369 else if (ESR != ESR_CaseNotFound) {
5370 if (ESR != ESR_Failed && !Scope.destroy())
5371 return ESR_Failed;
5372 return ESR;
5373 }
5374 }
5375 if (Case)
5376 return ESR_CaseNotFound;
5377 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5378 }
5379
5380 case Stmt::IfStmtClass: {
5381 const IfStmt *IS = cast<IfStmt>(S);
5382
5383 // Evaluate the condition, as either a var decl or as an expression.
5384 BlockScopeRAII Scope(Info);
5385 if (const Stmt *Init = IS->getInit()) {
5386 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5387 if (ESR != ESR_Succeeded) {
5388 if (ESR != ESR_Failed && !Scope.destroy())
5389 return ESR_Failed;
5390 return ESR;
5391 }
5392 }
5393 bool Cond;
5394 if (IS->isConsteval()) {
5395 Cond = IS->isNonNegatedConsteval();
5396 // If we are not in a constant context, if consteval should not evaluate
5397 // to true.
5398 if (!Info.InConstantContext)
5399 Cond = !Cond;
5400 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5401 Cond))
5402 return ESR_Failed;
5403
5404 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5405 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5406 if (ESR != ESR_Succeeded) {
5407 if (ESR != ESR_Failed && !Scope.destroy())
5408 return ESR_Failed;
5409 return ESR;
5410 }
5411 }
5412 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5413 }
5414
5415 case Stmt::WhileStmtClass: {
5416 const WhileStmt *WS = cast<WhileStmt>(S);
5417 while (true) {
5418 BlockScopeRAII Scope(Info);
5419 bool Continue;
5420 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5421 Continue))
5422 return ESR_Failed;
5423 if (!Continue)
5424 break;
5425
5426 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5427 if (ESR != ESR_Continue) {
5428 if (ESR != ESR_Failed && !Scope.destroy())
5429 return ESR_Failed;
5430 return ESR;
5431 }
5432 if (!Scope.destroy())
5433 return ESR_Failed;
5434 }
5435 return ESR_Succeeded;
5436 }
5437
5438 case Stmt::DoStmtClass: {
5439 const DoStmt *DS = cast<DoStmt>(S);
5440 bool Continue;
5441 do {
5442 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5443 if (ESR != ESR_Continue)
5444 return ESR;
5445 Case = nullptr;
5446
5447 if (DS->getCond()->isValueDependent()) {
5448 EvaluateDependentExpr(DS->getCond(), Info);
5449 // Bailout as we don't know whether to keep going or terminate the loop.
5450 return ESR_Failed;
5451 }
5452 FullExpressionRAII CondScope(Info);
5453 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5454 !CondScope.destroy())
5455 return ESR_Failed;
5456 } while (Continue);
5457 return ESR_Succeeded;
5458 }
5459
5460 case Stmt::ForStmtClass: {
5461 const ForStmt *FS = cast<ForStmt>(S);
5462 BlockScopeRAII ForScope(Info);
5463 if (FS->getInit()) {
5464 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5465 if (ESR != ESR_Succeeded) {
5466 if (ESR != ESR_Failed && !ForScope.destroy())
5467 return ESR_Failed;
5468 return ESR;
5469 }
5470 }
5471 while (true) {
5472 BlockScopeRAII IterScope(Info);
5473 bool Continue = true;
5474 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5475 FS->getCond(), Continue))
5476 return ESR_Failed;
5477 if (!Continue)
5478 break;
5479
5480 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5481 if (ESR != ESR_Continue) {
5482 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5483 return ESR_Failed;
5484 return ESR;
5485 }
5486
5487 if (const auto *Inc = FS->getInc()) {
5488 if (Inc->isValueDependent()) {
5489 if (!EvaluateDependentExpr(Inc, Info))
5490 return ESR_Failed;
5491 } else {
5492 FullExpressionRAII IncScope(Info);
5493 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5494 return ESR_Failed;
5495 }
5496 }
5497
5498 if (!IterScope.destroy())
5499 return ESR_Failed;
5500 }
5501 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5502 }
5503
5504 case Stmt::CXXForRangeStmtClass: {
5505 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5506 BlockScopeRAII Scope(Info);
5507
5508 // Evaluate the init-statement if present.
5509 if (FS->getInit()) {
5510 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5511 if (ESR != ESR_Succeeded) {
5512 if (ESR != ESR_Failed && !Scope.destroy())
5513 return ESR_Failed;
5514 return ESR;
5515 }
5516 }
5517
5518 // Initialize the __range variable.
5519 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5520 if (ESR != ESR_Succeeded) {
5521 if (ESR != ESR_Failed && !Scope.destroy())
5522 return ESR_Failed;
5523 return ESR;
5524 }
5525
5526 // In error-recovery cases it's possible to get here even if we failed to
5527 // synthesize the __begin and __end variables.
5528 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5529 return ESR_Failed;
5530
5531 // Create the __begin and __end iterators.
5532 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5533 if (ESR != ESR_Succeeded) {
5534 if (ESR != ESR_Failed && !Scope.destroy())
5535 return ESR_Failed;
5536 return ESR;
5537 }
5538 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5539 if (ESR != ESR_Succeeded) {
5540 if (ESR != ESR_Failed && !Scope.destroy())
5541 return ESR_Failed;
5542 return ESR;
5543 }
5544
5545 while (true) {
5546 // Condition: __begin != __end.
5547 {
5548 if (FS->getCond()->isValueDependent()) {
5549 EvaluateDependentExpr(FS->getCond(), Info);
5550 // We don't know whether to keep going or terminate the loop.
5551 return ESR_Failed;
5552 }
5553 bool Continue = true;
5554 FullExpressionRAII CondExpr(Info);
5555 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5556 return ESR_Failed;
5557 if (!Continue)
5558 break;
5559 }
5560
5561 // User's variable declaration, initialized by *__begin.
5562 BlockScopeRAII InnerScope(Info);
5563 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5564 if (ESR != ESR_Succeeded) {
5565 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5566 return ESR_Failed;
5567 return ESR;
5568 }
5569
5570 // Loop body.
5571 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5572 if (ESR != ESR_Continue) {
5573 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5574 return ESR_Failed;
5575 return ESR;
5576 }
5577 if (FS->getInc()->isValueDependent()) {
5578 if (!EvaluateDependentExpr(FS->getInc(), Info))
5579 return ESR_Failed;
5580 } else {
5581 // Increment: ++__begin
5582 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5583 return ESR_Failed;
5584 }
5585
5586 if (!InnerScope.destroy())
5587 return ESR_Failed;
5588 }
5589
5590 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5591 }
5592
5593 case Stmt::SwitchStmtClass:
5594 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5595
5596 case Stmt::ContinueStmtClass:
5597 return ESR_Continue;
5598
5599 case Stmt::BreakStmtClass:
5600 return ESR_Break;
5601
5602 case Stmt::LabelStmtClass:
5603 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5604
5605 case Stmt::AttributedStmtClass: {
5606 const auto *AS = cast<AttributedStmt>(S);
5607 const auto *SS = AS->getSubStmt();
5608 MSConstexprContextRAII ConstexprContext(
5609 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5610 isa<ReturnStmt>(SS));
5611
5612 auto LO = Info.getCtx().getLangOpts();
5613 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5614 for (auto *Attr : AS->getAttrs()) {
5615 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5616 if (!AA)
5617 continue;
5618
5619 auto *Assumption = AA->getAssumption();
5620 if (Assumption->isValueDependent())
5621 return ESR_Failed;
5622
5623 if (Assumption->HasSideEffects(Info.getCtx()))
5624 continue;
5625
5626 bool Value;
5627 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5628 return ESR_Failed;
5629 if (!Value) {
5630 Info.CCEDiag(Assumption->getExprLoc(),
5631 diag::note_constexpr_assumption_failed);
5632 return ESR_Failed;
5633 }
5634 }
5635 }
5636
5637 return EvaluateStmt(Result, Info, SS, Case);
5638 }
5639
5640 case Stmt::CaseStmtClass:
5641 case Stmt::DefaultStmtClass:
5642 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5643 case Stmt::CXXTryStmtClass:
5644 // Evaluate try blocks by evaluating all sub statements.
5645 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5646 }
5647}
5648
5649/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5650/// default constructor. If so, we'll fold it whether or not it's marked as
5651/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5652/// so we need special handling.
5654 const CXXConstructorDecl *CD,
5655 bool IsValueInitialization) {
5656 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5657 return false;
5658
5659 // Value-initialization does not call a trivial default constructor, so such a
5660 // call is a core constant expression whether or not the constructor is
5661 // constexpr.
5662 if (!CD->isConstexpr() && !IsValueInitialization) {
5663 if (Info.getLangOpts().CPlusPlus11) {
5664 // FIXME: If DiagDecl is an implicitly-declared special member function,
5665 // we should be much more explicit about why it's not constexpr.
5666 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5667 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5668 Info.Note(CD->getLocation(), diag::note_declared_at);
5669 } else {
5670 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5671 }
5672 }
5673 return true;
5674}
5675
5676/// CheckConstexprFunction - Check that a function can be called in a constant
5677/// expression.
5678static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5680 const FunctionDecl *Definition,
5681 const Stmt *Body) {
5682 // Potential constant expressions can contain calls to declared, but not yet
5683 // defined, constexpr functions.
5684 if (Info.checkingPotentialConstantExpression() && !Definition &&
5685 Declaration->isConstexpr())
5686 return false;
5687
5688 // Bail out if the function declaration itself is invalid. We will
5689 // have produced a relevant diagnostic while parsing it, so just
5690 // note the problematic sub-expression.
5691 if (Declaration->isInvalidDecl()) {
5692 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5693 return false;
5694 }
5695
5696 // DR1872: An instantiated virtual constexpr function can't be called in a
5697 // constant expression (prior to C++20). We can still constant-fold such a
5698 // call.
5699 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5700 cast<CXXMethodDecl>(Declaration)->isVirtual())
5701 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5702
5703 if (Definition && Definition->isInvalidDecl()) {
5704 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5705 return false;
5706 }
5707
5708 // Can we evaluate this function call?
5709 if (Definition && Body &&
5710 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5711 Definition->hasAttr<MSConstexprAttr>())))
5712 return true;
5713
5714 if (Info.getLangOpts().CPlusPlus11) {
5715 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5716
5717 // If this function is not constexpr because it is an inherited
5718 // non-constexpr constructor, diagnose that directly.
5719 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5720 if (CD && CD->isInheritingConstructor()) {
5721 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5722 if (!Inherited->isConstexpr())
5723 DiagDecl = CD = Inherited;
5724 }
5725
5726 // FIXME: If DiagDecl is an implicitly-declared special member function
5727 // or an inheriting constructor, we should be much more explicit about why
5728 // it's not constexpr.
5729 if (CD && CD->isInheritingConstructor())
5730 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5731 << CD->getInheritedConstructor().getConstructor()->getParent();
5732 else
5733 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5734 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5735 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5736 } else {
5737 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5738 }
5739 return false;
5740}
5741
5742namespace {
5743struct CheckDynamicTypeHandler {
5744 AccessKinds AccessKind;
5745 typedef bool result_type;
5746 bool failed() { return false; }
5747 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5748 bool found(APSInt &Value, QualType SubobjType) { return true; }
5749 bool found(APFloat &Value, QualType SubobjType) { return true; }
5750};
5751} // end anonymous namespace
5752
5753/// Check that we can access the notional vptr of an object / determine its
5754/// dynamic type.
5755static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5756 AccessKinds AK, bool Polymorphic) {
5757 if (This.Designator.Invalid)
5758 return false;
5759
5760 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5761
5762 if (!Obj)
5763 return false;
5764
5765 if (!Obj.Value) {
5766 // The object is not usable in constant expressions, so we can't inspect
5767 // its value to see if it's in-lifetime or what the active union members
5768 // are. We can still check for a one-past-the-end lvalue.
5769 if (This.Designator.isOnePastTheEnd() ||
5770 This.Designator.isMostDerivedAnUnsizedArray()) {
5771 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5772 ? diag::note_constexpr_access_past_end
5773 : diag::note_constexpr_access_unsized_array)
5774 << AK;
5775 return false;
5776 } else if (Polymorphic) {
5777 // Conservatively refuse to perform a polymorphic operation if we would
5778 // not be able to read a notional 'vptr' value.
5779 APValue Val;
5780 This.moveInto(Val);
5781 QualType StarThisType =
5782 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5783 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5784 << AK << Val.getAsString(Info.Ctx, StarThisType);
5785 return false;
5786 }
5787 return true;
5788 }
5789
5790 CheckDynamicTypeHandler Handler{AK};
5791 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5792}
5793
5794/// Check that the pointee of the 'this' pointer in a member function call is
5795/// either within its lifetime or in its period of construction or destruction.
5796static bool
5798 const LValue &This,
5799 const CXXMethodDecl *NamedMember) {
5800 return checkDynamicType(
5801 Info, E, This,
5802 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5803}
5804
5806 /// The dynamic class type of the object.
5808 /// The corresponding path length in the lvalue.
5809 unsigned PathLength;
5810};
5811
5812static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5813 unsigned PathLength) {
5814 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5815 Designator.Entries.size() && "invalid path length");
5816 return (PathLength == Designator.MostDerivedPathLength)
5817 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5818 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5819}
5820
5821/// Determine the dynamic type of an object.
5822static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5823 const Expr *E,
5824 LValue &This,
5825 AccessKinds AK) {
5826 // If we don't have an lvalue denoting an object of class type, there is no
5827 // meaningful dynamic type. (We consider objects of non-class type to have no
5828 // dynamic type.)
5829 if (!checkDynamicType(Info, E, This, AK, true))
5830 return std::nullopt;
5831
5832 // Refuse to compute a dynamic type in the presence of virtual bases. This
5833 // shouldn't happen other than in constant-folding situations, since literal
5834 // types can't have virtual bases.
5835 //
5836 // Note that consumers of DynamicType assume that the type has no virtual
5837 // bases, and will need modifications if this restriction is relaxed.
5838 const CXXRecordDecl *Class =
5839 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5840 if (!Class || Class->getNumVBases()) {
5841 Info.FFDiag(E);
5842 return std::nullopt;
5843 }
5844
5845 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5846 // binary search here instead. But the overwhelmingly common case is that
5847 // we're not in the middle of a constructor, so it probably doesn't matter
5848 // in practice.
5849 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5850 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5851 PathLength <= Path.size(); ++PathLength) {
5852 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5853 Path.slice(0, PathLength))) {
5854 case ConstructionPhase::Bases:
5855 case ConstructionPhase::DestroyingBases:
5856 // We're constructing or destroying a base class. This is not the dynamic
5857 // type.
5858 break;
5859
5860 case ConstructionPhase::None:
5861 case ConstructionPhase::AfterBases:
5862 case ConstructionPhase::AfterFields:
5863 case ConstructionPhase::Destroying:
5864 // We've finished constructing the base classes and not yet started
5865 // destroying them again, so this is the dynamic type.
5866 return DynamicType{getBaseClassType(This.Designator, PathLength),
5867 PathLength};
5868 }
5869 }
5870
5871 // CWG issue 1517: we're constructing a base class of the object described by
5872 // 'This', so that object has not yet begun its period of construction and
5873 // any polymorphic operation on it results in undefined behavior.
5874 Info.FFDiag(E);
5875 return std::nullopt;
5876}
5877
5878/// Perform virtual dispatch.
5880 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5881 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5882 std::optional<DynamicType> DynType = ComputeDynamicType(
5883 Info, E, This,
5884 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5885 if (!DynType)
5886 return nullptr;
5887
5888 // Find the final overrider. It must be declared in one of the classes on the
5889 // path from the dynamic type to the static type.
5890 // FIXME: If we ever allow literal types to have virtual base classes, that
5891 // won't be true.
5892 const CXXMethodDecl *Callee = Found;
5893 unsigned PathLength = DynType->PathLength;
5894 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5895 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5896 const CXXMethodDecl *Overrider =
5897 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5898 if (Overrider) {
5899 Callee = Overrider;
5900 break;
5901 }
5902 }
5903
5904 // C++2a [class.abstract]p6:
5905 // the effect of making a virtual call to a pure virtual function [...] is
5906 // undefined
5907 if (Callee->isPureVirtual()) {
5908 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5909 Info.Note(Callee->getLocation(), diag::note_declared_at);
5910 return nullptr;
5911 }
5912
5913 // If necessary, walk the rest of the path to determine the sequence of
5914 // covariant adjustment steps to apply.
5915 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5916 Found->getReturnType())) {
5917 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5918 for (unsigned CovariantPathLength = PathLength + 1;
5919 CovariantPathLength != This.Designator.Entries.size();
5920 ++CovariantPathLength) {
5921 const CXXRecordDecl *NextClass =
5922 getBaseClassType(This.Designator, CovariantPathLength);
5923 const CXXMethodDecl *Next =
5924 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5925 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5926 Next->getReturnType(), CovariantAdjustmentPath.back()))
5927 CovariantAdjustmentPath.push_back(Next->getReturnType());
5928 }
5929 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5930 CovariantAdjustmentPath.back()))
5931 CovariantAdjustmentPath.push_back(Found->getReturnType());
5932 }
5933
5934 // Perform 'this' adjustment.
5935 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5936 return nullptr;
5937
5938 return Callee;
5939}
5940
5941/// Perform the adjustment from a value returned by a virtual function to
5942/// a value of the statically expected type, which may be a pointer or
5943/// reference to a base class of the returned type.
5944static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5945 APValue &Result,
5947 assert(Result.isLValue() &&
5948 "unexpected kind of APValue for covariant return");
5949 if (Result.isNullPointer())
5950 return true;
5951
5952 LValue LVal;
5953 LVal.setFrom(Info.Ctx, Result);
5954
5955 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5956 for (unsigned I = 1; I != Path.size(); ++I) {
5957 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5958 assert(OldClass && NewClass && "unexpected kind of covariant return");
5959 if (OldClass != NewClass &&
5960 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5961 return false;
5962 OldClass = NewClass;
5963 }
5964
5965 LVal.moveInto(Result);
5966 return true;
5967}
5968
5969/// Determine whether \p Base, which is known to be a direct base class of
5970/// \p Derived, is a public base class.
5971static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5972 const CXXRecordDecl *Base) {
5973 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5974 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5975 if (BaseClass && declaresSameEntity(BaseClass, Base))
5976 return BaseSpec.getAccessSpecifier() == AS_public;
5977 }
5978 llvm_unreachable("Base is not a direct base of Derived");
5979}
5980
5981/// Apply the given dynamic cast operation on the provided lvalue.
5982///
5983/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5984/// to find a suitable target subobject.
5985static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5986 LValue &Ptr) {
5987 // We can't do anything with a non-symbolic pointer value.
5988 SubobjectDesignator &D = Ptr.Designator;
5989 if (D.Invalid)
5990 return false;
5991
5992 // C++ [expr.dynamic.cast]p6:
5993 // If v is a null pointer value, the result is a null pointer value.
5994 if (Ptr.isNullPointer() && !E->isGLValue())
5995 return true;
5996
5997 // For all the other cases, we need the pointer to point to an object within
5998 // its lifetime / period of construction / destruction, and we need to know
5999 // its dynamic type.
6000 std::optional<DynamicType> DynType =
6001 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6002 if (!DynType)
6003 return false;
6004
6005 // C++ [expr.dynamic.cast]p7:
6006 // If T is "pointer to cv void", then the result is a pointer to the most
6007 // derived object
6008 if (E->getType()->isVoidPointerType())
6009 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6010
6011 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6012 assert(C && "dynamic_cast target is not void pointer nor class");
6013 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
6014
6015 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6016 // C++ [expr.dynamic.cast]p9:
6017 if (!E->isGLValue()) {
6018 // The value of a failed cast to pointer type is the null pointer value
6019 // of the required result type.
6020 Ptr.setNull(Info.Ctx, E->getType());
6021 return true;
6022 }
6023
6024 // A failed cast to reference type throws [...] std::bad_cast.
6025 unsigned DiagKind;
6026 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6027 DynType->Type->isDerivedFrom(C)))
6028 DiagKind = 0;
6029 else if (!Paths || Paths->begin() == Paths->end())
6030 DiagKind = 1;
6031 else if (Paths->isAmbiguous(CQT))
6032 DiagKind = 2;
6033 else {
6034 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6035 DiagKind = 3;
6036 }
6037 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6038 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6039 << Info.Ctx.getRecordType(DynType->Type)
6041 return false;
6042 };
6043
6044 // Runtime check, phase 1:
6045 // Walk from the base subobject towards the derived object looking for the
6046 // target type.
6047 for (int PathLength = Ptr.Designator.Entries.size();
6048 PathLength >= (int)DynType->PathLength; --PathLength) {
6049 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6051 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6052 // We can only walk across public inheritance edges.
6053 if (PathLength > (int)DynType->PathLength &&
6054 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6055 Class))
6056 return RuntimeCheckFailed(nullptr);
6057 }
6058
6059 // Runtime check, phase 2:
6060 // Search the dynamic type for an unambiguous public base of type C.
6061 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6062 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6063 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6064 Paths.front().Access == AS_public) {
6065 // Downcast to the dynamic type...
6066 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6067 return false;
6068 // ... then upcast to the chosen base class subobject.
6069 for (CXXBasePathElement &Elem : Paths.front())
6070 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6071 return false;
6072 return true;
6073 }
6074
6075 // Otherwise, the runtime check fails.
6076 return RuntimeCheckFailed(&Paths);
6077}
6078
6079namespace {
6080struct StartLifetimeOfUnionMemberHandler {
6081 EvalInfo &Info;
6082 const Expr *LHSExpr;
6083 const FieldDecl *Field;
6084 bool DuringInit;
6085 bool Failed = false;
6086 static const AccessKinds AccessKind = AK_Assign;
6087
6088 typedef bool result_type;
6089 bool failed() { return Failed; }
6090 bool found(APValue &Subobj, QualType SubobjType) {
6091 // We are supposed to perform no initialization but begin the lifetime of
6092 // the object. We interpret that as meaning to do what default
6093 // initialization of the object would do if all constructors involved were
6094 // trivial:
6095 // * All base, non-variant member, and array element subobjects' lifetimes
6096 // begin
6097 // * No variant members' lifetimes begin
6098 // * All scalar subobjects whose lifetimes begin have indeterminate values
6099 assert(SubobjType->isUnionType());
6100 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6101 // This union member is already active. If it's also in-lifetime, there's
6102 // nothing to do.
6103 if (Subobj.getUnionValue().hasValue())
6104 return true;
6105 } else if (DuringInit) {
6106 // We're currently in the process of initializing a different union
6107 // member. If we carried on, that initialization would attempt to
6108 // store to an inactive union member, resulting in undefined behavior.
6109 Info.FFDiag(LHSExpr,
6110 diag::note_constexpr_union_member_change_during_init);
6111 return false;
6112 }
6113 APValue Result;
6114 Failed = !handleDefaultInitValue(Field->getType(), Result);
6115 Subobj.setUnion(Field, Result);
6116 return true;
6117 }
6118 bool found(APSInt &Value, QualType SubobjType) {
6119 llvm_unreachable("wrong value kind for union object");
6120 }
6121 bool found(APFloat &Value, QualType SubobjType) {
6122 llvm_unreachable("wrong value kind for union object");
6123 }
6124};
6125} // end anonymous namespace
6126
6127const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6128
6129/// Handle a builtin simple-assignment or a call to a trivial assignment
6130/// operator whose left-hand side might involve a union member access. If it
6131/// does, implicitly start the lifetime of any accessed union elements per
6132/// C++20 [class.union]5.
6133static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6134 const Expr *LHSExpr,
6135 const LValue &LHS) {
6136 if (LHS.InvalidBase || LHS.Designator.Invalid)
6137 return false;
6138
6140 // C++ [class.union]p5:
6141 // define the set S(E) of subexpressions of E as follows:
6142 unsigned PathLength = LHS.Designator.Entries.size();
6143 for (const Expr *E = LHSExpr; E != nullptr;) {
6144 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6145 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6146 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6147 // Note that we can't implicitly start the lifetime of a reference,
6148 // so we don't need to proceed any further if we reach one.
6149 if (!FD || FD->getType()->isReferenceType())
6150 break;
6151
6152 // ... and also contains A.B if B names a union member ...
6153 if (FD->getParent()->isUnion()) {
6154 // ... of a non-class, non-array type, or of a class type with a
6155 // trivial default constructor that is not deleted, or an array of
6156 // such types.
6157 auto *RD =
6158 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6159 if (!RD || RD->hasTrivialDefaultConstructor())
6160 UnionPathLengths.push_back({PathLength - 1, FD});
6161 }
6162
6163 E = ME->getBase();
6164 --PathLength;
6165 assert(declaresSameEntity(FD,
6166 LHS.Designator.Entries[PathLength]
6167 .getAsBaseOrMember().getPointer()));
6168
6169 // -- If E is of the form A[B] and is interpreted as a built-in array
6170 // subscripting operator, S(E) is [S(the array operand, if any)].
6171 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6172 // Step over an ArrayToPointerDecay implicit cast.
6173 auto *Base = ASE->getBase()->IgnoreImplicit();
6174 if (!Base->getType()->isArrayType())
6175 break;
6176
6177 E = Base;
6178 --PathLength;
6179
6180 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6181 // Step over a derived-to-base conversion.
6182 E = ICE->getSubExpr();
6183 if (ICE->getCastKind() == CK_NoOp)
6184 continue;
6185 if (ICE->getCastKind() != CK_DerivedToBase &&
6186 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6187 break;
6188 // Walk path backwards as we walk up from the base to the derived class.
6189 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6190 if (Elt->isVirtual()) {
6191 // A class with virtual base classes never has a trivial default
6192 // constructor, so S(E) is empty in this case.
6193 E = nullptr;
6194 break;
6195 }
6196
6197 --PathLength;
6198 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6199 LHS.Designator.Entries[PathLength]
6200 .getAsBaseOrMember().getPointer()));
6201 }
6202
6203 // -- Otherwise, S(E) is empty.
6204 } else {
6205 break;
6206 }
6207 }
6208
6209 // Common case: no unions' lifetimes are started.
6210 if (UnionPathLengths.empty())
6211 return true;
6212
6213 // if modification of X [would access an inactive union member], an object
6214 // of the type of X is implicitly created
6215 CompleteObject Obj =
6216 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6217 if (!Obj)
6218 return false;
6219 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6220 llvm::reverse(UnionPathLengths)) {
6221 // Form a designator for the union object.
6222 SubobjectDesignator D = LHS.Designator;
6223 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6224
6225 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6226 ConstructionPhase::AfterBases;
6227 StartLifetimeOfUnionMemberHandler StartLifetime{
6228 Info, LHSExpr, LengthAndField.second, DuringInit};
6229 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6230 return false;
6231 }
6232
6233 return true;
6234}
6235
6236static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6237 CallRef Call, EvalInfo &Info,
6238 bool NonNull = false) {
6239 LValue LV;
6240 // Create the parameter slot and register its destruction. For a vararg
6241 // argument, create a temporary.
6242 // FIXME: For calling conventions that destroy parameters in the callee,
6243 // should we consider performing destruction when the function returns
6244 // instead?
6245 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6246 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6247 ScopeKind::Call, LV);
6248 if (!EvaluateInPlace(V, Info, LV, Arg))
6249 return false;
6250
6251 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6252 // undefined behavior, so is non-constant.
6253 if (NonNull && V.isLValue() && V.isNullPointer()) {
6254 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6255 return false;
6256 }
6257
6258 return true;
6259}
6260
6261/// Evaluate the arguments to a function call.
6262static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6263 EvalInfo &Info, const FunctionDecl *Callee,
6264 bool RightToLeft = false) {
6265 bool Success = true;
6266 llvm::SmallBitVector ForbiddenNullArgs;
6267 if (Callee->hasAttr<NonNullAttr>()) {
6268 ForbiddenNullArgs.resize(Args.size());
6269 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6270 if (!Attr->args_size()) {
6271 ForbiddenNullArgs.set();
6272 break;
6273 } else
6274 for (auto Idx : Attr->args()) {
6275 unsigned ASTIdx = Idx.getASTIndex();
6276 if (ASTIdx >= Args.size())
6277 continue;
6278 ForbiddenNullArgs[ASTIdx] = true;
6279 }
6280 }
6281 }
6282 for (unsigned I = 0; I < Args.size(); I++) {
6283 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6284 const ParmVarDecl *PVD =
6285 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6286 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6287 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6288 // If we're checking for a potential constant expression, evaluate all
6289 // initializers even if some of them fail.
6290 if (!Info.noteFailure())
6291 return false;
6292 Success = false;
6293 }
6294 }
6295 return Success;
6296}
6297
6298/// Perform a trivial copy from Param, which is the parameter of a copy or move
6299/// constructor or assignment operator.
6300static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6301 const Expr *E, APValue &Result,
6302 bool CopyObjectRepresentation) {
6303 // Find the reference argument.
6304 CallStackFrame *Frame = Info.CurrentCall;
6305 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6306 if (!RefValue) {
6307 Info.FFDiag(E);
6308 return false;
6309 }
6310
6311 // Copy out the contents of the RHS object.
6312 LValue RefLValue;
6313 RefLValue.setFrom(Info.Ctx, *RefValue);
6315 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6316 CopyObjectRepresentation);
6317}
6318
6319/// Evaluate a function call.
6321 const FunctionDecl *Callee, const LValue *This,
6322 const Expr *E, ArrayRef<const Expr *> Args,
6323 CallRef Call, const Stmt *Body, EvalInfo &Info,
6324 APValue &Result, const LValue *ResultSlot) {
6325 if (!Info.CheckCallLimit(CallLoc))
6326 return false;
6327
6328 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6329
6330 // For a trivial copy or move assignment, perform an APValue copy. This is
6331 // essential for unions, where the operations performed by the assignment
6332 // operator cannot be represented as statements.
6333 //
6334 // Skip this for non-union classes with no fields; in that case, the defaulted
6335 // copy/move does not actually read the object.
6336 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6337 if (MD && MD->isDefaulted() &&
6338 (MD->getParent()->isUnion() ||
6339 (MD->isTrivial() &&
6341 assert(This &&
6343 APValue RHSValue;
6344 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6345 MD->getParent()->isUnion()))
6346 return false;
6347 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6348 RHSValue))
6349 return false;
6350 This->moveInto(Result);
6351 return true;
6352 } else if (MD && isLambdaCallOperator(MD)) {
6353 // We're in a lambda; determine the lambda capture field maps unless we're
6354 // just constexpr checking a lambda's call operator. constexpr checking is
6355 // done before the captures have been added to the closure object (unless
6356 // we're inferring constexpr-ness), so we don't have access to them in this
6357 // case. But since we don't need the captures to constexpr check, we can
6358 // just ignore them.
6359 if (!Info.checkingPotentialConstantExpression())
6360 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6361 Frame.LambdaThisCaptureField);
6362 }
6363
6364 StmtResult Ret = {Result, ResultSlot};
6365 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6366 if (ESR == ESR_Succeeded) {
6367 if (Callee->getReturnType()->isVoidType())
6368 return true;
6369 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6370 }
6371 return ESR == ESR_Returned;
6372}
6373
6374/// Evaluate a constructor call.
6375static bool HandleConstructorCall(const Expr *E, const LValue &This,
6376 CallRef Call,
6378 EvalInfo &Info, APValue &Result) {
6379 SourceLocation CallLoc = E->getExprLoc();
6380 if (!Info.CheckCallLimit(CallLoc))
6381 return false;
6382
6383 const CXXRecordDecl *RD = Definition->getParent();
6384 if (RD->getNumVBases()) {
6385 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6386 return false;
6387 }
6388
6389 EvalInfo::EvaluatingConstructorRAII EvalObj(
6390 Info,
6391 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6392 RD->getNumBases());
6393 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6394
6395 // FIXME: Creating an APValue just to hold a nonexistent return value is
6396 // wasteful.
6397 APValue RetVal;
6398 StmtResult Ret = {RetVal, nullptr};
6399
6400 // If it's a delegating constructor, delegate.
6401 if (Definition->isDelegatingConstructor()) {
6403 if ((*I)->getInit()->isValueDependent()) {
6404 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6405 return false;
6406 } else {
6407 FullExpressionRAII InitScope(Info);
6408 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6409 !InitScope.destroy())
6410 return false;
6411 }
6412 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6413 }
6414
6415 // For a trivial copy or move constructor, perform an APValue copy. This is
6416 // essential for unions (or classes with anonymous union members), where the
6417 // operations performed by the constructor cannot be represented by
6418 // ctor-initializers.
6419 //
6420 // Skip this for empty non-union classes; we should not perform an
6421 // lvalue-to-rvalue conversion on them because their copy constructor does not
6422 // actually read them.
6423 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6424 (Definition->getParent()->isUnion() ||
6425 (Definition->isTrivial() &&
6427 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6428 Definition->getParent()->isUnion());
6429 }
6430
6431 // Reserve space for the struct members.
6432 if (!Result.hasValue()) {
6433 if (!RD->isUnion())
6434 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6435 std::distance(RD->field_begin(), RD->field_end()));
6436 else
6437 // A union starts with no active member.
6438 Result = APValue((const FieldDecl*)nullptr);
6439 }
6440
6441 if (RD->isInvalidDecl()) return false;
6442 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6443
6444 // A scope for temporaries lifetime-extended by reference members.
6445 BlockScopeRAII LifetimeExtendedScope(Info);
6446
6447 bool Success = true;
6448 unsigned BasesSeen = 0;
6449#ifndef NDEBUG
6451#endif
6453 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6454 // We might be initializing the same field again if this is an indirect
6455 // field initialization.
6456 if (FieldIt == RD->field_end() ||
6457 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6458 assert(Indirect && "fields out of order?");
6459 return;
6460 }
6461
6462 // Default-initialize any fields with no explicit initializer.
6463 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6464 assert(FieldIt != RD->field_end() && "missing field?");
6465 if (!FieldIt->isUnnamedBitField())
6467 FieldIt->getType(),
6468 Result.getStructField(FieldIt->getFieldIndex()));
6469 }
6470 ++FieldIt;
6471 };
6472 for (const auto *I : Definition->inits()) {
6473 LValue Subobject = This;
6474 LValue SubobjectParent = This;
6475 APValue *Value = &Result;
6476
6477 // Determine the subobject to initialize.
6478 FieldDecl *FD = nullptr;
6479 if (I->isBaseInitializer()) {
6480 QualType BaseType(I->getBaseClass(), 0);
6481#ifndef NDEBUG
6482 // Non-virtual base classes are initialized in the order in the class
6483 // definition. We have already checked for virtual base classes.
6484 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6485 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6486 "base class initializers not in expected order");
6487 ++BaseIt;
6488#endif
6489 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6490 BaseType->getAsCXXRecordDecl(), &Layout))
6491 return false;
6492 Value = &Result.getStructBase(BasesSeen++);
6493 } else if ((FD = I->getMember())) {
6494 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6495 return false;
6496 if (RD->isUnion()) {
6497 Result = APValue(FD);
6498 Value = &Result.getUnionValue();
6499 } else {
6500 SkipToField(FD, false);
6501 Value = &Result.getStructField(FD->getFieldIndex());
6502 }
6503 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6504 // Walk the indirect field decl's chain to find the object to initialize,
6505 // and make sure we've initialized every step along it.
6506 auto IndirectFieldChain = IFD->chain();
6507 for (auto *C : IndirectFieldChain) {
6508 FD = cast<FieldDecl>(C);
6509 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6510 // Switch the union field if it differs. This happens if we had
6511 // preceding zero-initialization, and we're now initializing a union
6512 // subobject other than the first.
6513 // FIXME: In this case, the values of the other subobjects are
6514 // specified, since zero-initialization sets all padding bits to zero.
6515 if (!Value->hasValue() ||
6516 (Value->isUnion() && Value->getUnionField() != FD)) {
6517 if (CD->isUnion())
6518 *Value = APValue(FD);
6519 else
6520 // FIXME: This immediately starts the lifetime of all members of
6521 // an anonymous struct. It would be preferable to strictly start
6522 // member lifetime in initialization order.
6523 Success &=
6524 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6525 }
6526 // Store Subobject as its parent before updating it for the last element
6527 // in the chain.
6528 if (C == IndirectFieldChain.back())
6529 SubobjectParent = Subobject;
6530 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6531 return false;
6532 if (CD->isUnion())
6533 Value = &Value->getUnionValue();
6534 else {
6535 if (C == IndirectFieldChain.front() && !RD->isUnion())
6536 SkipToField(FD, true);
6537 Value = &Value->getStructField(FD->getFieldIndex());
6538 }
6539 }
6540 } else {
6541 llvm_unreachable("unknown base initializer kind");
6542 }
6543
6544 // Need to override This for implicit field initializers as in this case
6545 // This refers to innermost anonymous struct/union containing initializer,
6546 // not to currently constructed class.
6547 const Expr *Init = I->getInit();
6548 if (Init->isValueDependent()) {
6549 if (!EvaluateDependentExpr(Init, Info))
6550 return false;
6551 } else {
6552 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6553 isa<CXXDefaultInitExpr>(Init));
6554 FullExpressionRAII InitScope(Info);
6555 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6556 (FD && FD->isBitField() &&
6557 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6558 // If we're checking for a potential constant expression, evaluate all
6559 // initializers even if some of them fail.
6560 if (!Info.noteFailure())
6561 return false;
6562 Success = false;
6563 }
6564 }
6565
6566 // This is the point at which the dynamic type of the object becomes this
6567 // class type.
6568 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6569 EvalObj.finishedConstructingBases();
6570 }
6571
6572 // Default-initialize any remaining fields.
6573 if (!RD->isUnion()) {
6574 for (; FieldIt != RD->field_end(); ++FieldIt) {
6575 if (!FieldIt->isUnnamedBitField())
6577 FieldIt->getType(),
6578 Result.getStructField(FieldIt->getFieldIndex()));
6579 }
6580 }
6581
6582 EvalObj.finishedConstructingFields();
6583
6584 return Success &&
6585 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6586 LifetimeExtendedScope.destroy();
6587}
6588
6589static bool HandleConstructorCall(const Expr *E, const LValue &This,
6592 EvalInfo &Info, APValue &Result) {
6593 CallScopeRAII CallScope(Info);
6594 CallRef Call = Info.CurrentCall->createCall(Definition);
6595 if (!EvaluateArgs(Args, Call, Info, Definition))
6596 return false;
6597
6598 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6599 CallScope.destroy();
6600}
6601
6602static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6603 const LValue &This, APValue &Value,
6604 QualType T) {
6605 // Objects can only be destroyed while they're within their lifetimes.
6606 // FIXME: We have no representation for whether an object of type nullptr_t
6607 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6608 // as indeterminate instead?
6609 if (Value.isAbsent() && !T->isNullPtrType()) {
6610 APValue Printable;
6611 This.moveInto(Printable);
6612 Info.FFDiag(CallRange.getBegin(),
6613 diag::note_constexpr_destroy_out_of_lifetime)
6614 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6615 return false;
6616 }
6617
6618 // Invent an expression for location purposes.
6619 // FIXME: We shouldn't need to do this.
6620 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6621
6622 // For arrays, destroy elements right-to-left.
6623 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6624 uint64_t Size = CAT->getZExtSize();
6625 QualType ElemT = CAT->getElementType();
6626
6627 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6628 return false;
6629
6630 LValue ElemLV = This;
6631 ElemLV.addArray(Info, &LocE, CAT);
6632 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6633 return false;
6634
6635 // Ensure that we have actual array elements available to destroy; the
6636 // destructors might mutate the value, so we can't run them on the array
6637 // filler.
6638 if (Size && Size > Value.getArrayInitializedElts())
6639 expandArray(Value, Value.getArraySize() - 1);
6640
6641 for (; Size != 0; --Size) {
6642 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6643 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6644 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6645 return false;
6646 }
6647
6648 // End the lifetime of this array now.
6649 Value = APValue();
6650 return true;
6651 }
6652
6653 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6654 if (!RD) {
6655 if (T.isDestructedType()) {
6656 Info.FFDiag(CallRange.getBegin(),
6657 diag::note_constexpr_unsupported_destruction)
6658 << T;
6659 return false;
6660 }
6661
6662 Value = APValue();
6663 return true;
6664 }
6665
6666 if (RD->getNumVBases()) {
6667 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6668 return false;
6669 }
6670
6671 const CXXDestructorDecl *DD = RD->getDestructor();
6672 if (!DD && !RD->hasTrivialDestructor()) {
6673 Info.FFDiag(CallRange.getBegin());
6674 return false;
6675 }
6676
6677 if (!DD || DD->isTrivial() ||
6678 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6679 // A trivial destructor just ends the lifetime of the object. Check for
6680 // this case before checking for a body, because we might not bother
6681 // building a body for a trivial destructor. Note that it doesn't matter
6682 // whether the destructor is constexpr in this case; all trivial
6683 // destructors are constexpr.
6684 //
6685 // If an anonymous union would be destroyed, some enclosing destructor must
6686 // have been explicitly defined, and the anonymous union destruction should
6687 // have no effect.
6688 Value = APValue();
6689 return true;
6690 }
6691
6692 if (!Info.CheckCallLimit(CallRange.getBegin()))
6693 return false;
6694
6695 const FunctionDecl *Definition = nullptr;
6696 const Stmt *Body = DD->getBody(Definition);
6697
6698 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6699 return false;
6700
6701 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6702 CallRef());
6703
6704 // We're now in the period of destruction of this object.
6705 unsigned BasesLeft = RD->getNumBases();
6706 EvalInfo::EvaluatingDestructorRAII EvalObj(
6707 Info,
6708 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6709 if (!EvalObj.DidInsert) {
6710 // C++2a [class.dtor]p19:
6711 // the behavior is undefined if the destructor is invoked for an object
6712 // whose lifetime has ended
6713 // (Note that formally the lifetime ends when the period of destruction
6714 // begins, even though certain uses of the object remain valid until the
6715 // period of destruction ends.)
6716 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6717 return false;
6718 }
6719
6720 // FIXME: Creating an APValue just to hold a nonexistent return value is
6721 // wasteful.
6722 APValue RetVal;
6723 StmtResult Ret = {RetVal, nullptr};
6724 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6725 return false;
6726
6727 // A union destructor does not implicitly destroy its members.
6728 if (RD->isUnion())
6729 return true;
6730
6731 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6732
6733 // We don't have a good way to iterate fields in reverse, so collect all the
6734 // fields first and then walk them backwards.
6735 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6736 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6737 if (FD->isUnnamedBitField())
6738 continue;
6739
6740 LValue Subobject = This;
6741 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6742 return false;
6743
6744 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6745 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6746 FD->getType()))
6747 return false;
6748 }
6749
6750 if (BasesLeft != 0)
6751 EvalObj.startedDestroyingBases();
6752
6753 // Destroy base classes in reverse order.
6754 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6755 --BasesLeft;
6756
6757 QualType BaseType = Base.getType();
6758 LValue Subobject = This;
6759 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6760 BaseType->getAsCXXRecordDecl(), &Layout))
6761 return false;
6762
6763 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6764 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6765 BaseType))
6766 return false;
6767 }
6768 assert(BasesLeft == 0 && "NumBases was wrong?");
6769
6770 // The period of destruction ends now. The object is gone.
6771 Value = APValue();
6772 return true;
6773}
6774
6775namespace {
6776struct DestroyObjectHandler {
6777 EvalInfo &Info;
6778 const Expr *E;
6779 const LValue &This;
6780 const AccessKinds AccessKind;
6781
6782 typedef bool result_type;
6783 bool failed() { return false; }
6784 bool found(APValue &Subobj, QualType SubobjType) {
6785 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6786 SubobjType);
6787 }
6788 bool found(APSInt &Value, QualType SubobjType) {
6789 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6790 return false;
6791 }
6792 bool found(APFloat &Value, QualType SubobjType) {
6793 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6794 return false;
6795 }
6796};
6797}
6798
6799/// Perform a destructor or pseudo-destructor call on the given object, which
6800/// might in general not be a complete object.
6801static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6802 const LValue &This, QualType ThisType) {
6803 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6804 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6805 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6806}
6807
6808/// Destroy and end the lifetime of the given complete object.
6809static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6811 QualType T) {
6812 // If we've had an unmodeled side-effect, we can't rely on mutable state
6813 // (such as the object we're about to destroy) being correct.
6814 if (Info.EvalStatus.HasSideEffects)
6815 return false;
6816
6817 LValue LV;
6818 LV.set({LVBase});
6819 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6820}
6821
6822/// Perform a call to 'operator new' or to `__builtin_operator_new'.
6823static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6824 LValue &Result) {
6825 if (Info.checkingPotentialConstantExpression() ||
6826 Info.SpeculativeEvaluationDepth)
6827 return false;
6828
6829 // This is permitted only within a call to std::allocator<T>::allocate.
6830 auto Caller = Info.getStdAllocatorCaller("allocate");
6831 if (!Caller) {
6832 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6833 ? diag::note_constexpr_new_untyped
6834 : diag::note_constexpr_new);
6835 return false;
6836 }
6837
6838 QualType ElemType = Caller.ElemType;
6839 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6840 Info.FFDiag(E->getExprLoc(),
6841 diag::note_constexpr_new_not_complete_object_type)
6842 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6843 return false;
6844 }
6845
6846 APSInt ByteSize;
6847 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6848 return false;
6849 bool IsNothrow = false;
6850 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6851 EvaluateIgnoredValue(Info, E->getArg(I));
6852 IsNothrow |= E->getType()->isNothrowT();
6853 }
6854
6855 CharUnits ElemSize;
6856 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6857 return false;
6858 APInt Size, Remainder;
6859 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6860 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6861 if (Remainder != 0) {
6862 // This likely indicates a bug in the implementation of 'std::allocator'.
6863 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6864 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6865 return false;
6866 }
6867
6868 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
6869 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
6870 if (IsNothrow) {
6871 Result.setNull(Info.Ctx, E->getType());
6872 return true;
6873 }
6874 return false;
6875 }
6876
6877 QualType AllocType = Info.Ctx.getConstantArrayType(
6878 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
6879 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6880 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6881 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6882 return true;
6883}
6884
6886 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6887 if (CXXDestructorDecl *DD = RD->getDestructor())
6888 return DD->isVirtual();
6889 return false;
6890}
6891
6893 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6894 if (CXXDestructorDecl *DD = RD->getDestructor())
6895 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6896 return nullptr;
6897}
6898
6899/// Check that the given object is a suitable pointer to a heap allocation that
6900/// still exists and is of the right kind for the purpose of a deletion.
6901///
6902/// On success, returns the heap allocation to deallocate. On failure, produces
6903/// a diagnostic and returns std::nullopt.
6904static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6905 const LValue &Pointer,
6906 DynAlloc::Kind DeallocKind) {
6907 auto PointerAsString = [&] {
6908 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6909 };
6910
6911 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6912 if (!DA) {
6913 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6914 << PointerAsString();
6915 if (Pointer.Base)
6916 NoteLValueLocation(Info, Pointer.Base);
6917 return std::nullopt;
6918 }
6919
6920 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6921 if (!Alloc) {
6922 Info.FFDiag(E, diag::note_constexpr_double_delete);
6923 return std::nullopt;
6924 }
6925
6926 if (DeallocKind != (*Alloc)->getKind()) {
6927 QualType AllocType = Pointer.Base.getDynamicAllocType();
6928 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6929 << DeallocKind << (*Alloc)->getKind() << AllocType;
6930 NoteLValueLocation(Info, Pointer.Base);
6931 return std::nullopt;
6932 }
6933
6934 bool Subobject = false;
6935 if (DeallocKind == DynAlloc::New) {
6936 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6937 Pointer.Designator.isOnePastTheEnd();
6938 } else {
6939 Subobject = Pointer.Designator.Entries.size() != 1 ||
6940 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6941 }
6942 if (Subobject) {
6943 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6944 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6945 return std::nullopt;
6946 }
6947
6948 return Alloc;
6949}
6950
6951// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6952bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6953 if (Info.checkingPotentialConstantExpression() ||
6954 Info.SpeculativeEvaluationDepth)
6955 return false;
6956
6957 // This is permitted only within a call to std::allocator<T>::deallocate.
6958 if (!Info.getStdAllocatorCaller("deallocate")) {
6959 Info.FFDiag(E->getExprLoc());
6960 return true;
6961 }
6962
6963 LValue Pointer;
6964 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6965 return false;
6966 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6967 EvaluateIgnoredValue(Info, E->getArg(I));
6968
6969 if (Pointer.Designator.Invalid)
6970 return false;
6971
6972 // Deleting a null pointer would have no effect, but it's not permitted by
6973 // std::allocator<T>::deallocate's contract.
6974 if (Pointer.isNullPointer()) {
6975 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6976 return true;
6977 }
6978
6979 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6980 return false;
6981
6982 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6983 return true;
6984}
6985
6986//===----------------------------------------------------------------------===//
6987// Generic Evaluation
6988//===----------------------------------------------------------------------===//
6989namespace {
6990
6991class BitCastBuffer {
6992 // FIXME: We're going to need bit-level granularity when we support
6993 // bit-fields.
6994 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6995 // we don't support a host or target where that is the case. Still, we should
6996 // use a more generic type in case we ever do.
6998
6999 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7000 "Need at least 8 bit unsigned char");
7001
7002 bool TargetIsLittleEndian;
7003
7004public:
7005 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7006 : Bytes(Width.getQuantity()),
7007 TargetIsLittleEndian(TargetIsLittleEndian) {}
7008
7009 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7010 SmallVectorImpl<unsigned char> &Output) const {
7011 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7012 // If a byte of an integer is uninitialized, then the whole integer is
7013 // uninitialized.
7014 if (!Bytes[I.getQuantity()])
7015 return false;
7016 Output.push_back(*Bytes[I.getQuantity()]);
7017 }
7018 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7019 std::reverse(Output.begin(), Output.end());
7020 return true;
7021 }
7022
7023 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7024 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7025 std::reverse(Input.begin(), Input.end());
7026
7027 size_t Index = 0;
7028 for (unsigned char Byte : Input) {
7029 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7030 Bytes[Offset.getQuantity() + Index] = Byte;
7031 ++Index;
7032 }
7033 }
7034
7035 size_t size() { return Bytes.size(); }
7036};
7037
7038/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7039/// target would represent the value at runtime.
7040class APValueToBufferConverter {
7041 EvalInfo &Info;
7042 BitCastBuffer Buffer;
7043 const CastExpr *BCE;
7044
7045 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7046 const CastExpr *BCE)
7047 : Info(Info),
7048 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7049 BCE(BCE) {}
7050
7051 bool visit(const APValue &Val, QualType Ty) {
7052 return visit(Val, Ty, CharUnits::fromQuantity(0));
7053 }
7054
7055 // Write out Val with type Ty into Buffer starting at Offset.
7056 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7057 assert((size_t)Offset.getQuantity() <= Buffer.size());
7058
7059 // As a special case, nullptr_t has an indeterminate value.
7060 if (Ty->isNullPtrType())
7061 return true;
7062
7063 // Dig through Src to find the byte at SrcOffset.
7064 switch (Val.getKind()) {
7066 case APValue::None:
7067 return true;
7068
7069 case APValue::Int:
7070 return visitInt(Val.getInt(), Ty, Offset);
7071 case APValue::Float:
7072 return visitFloat(Val.getFloat(), Ty, Offset);
7073 case APValue::Array:
7074 return visitArray(Val, Ty, Offset);
7075 case APValue::Struct:
7076 return visitRecord(Val, Ty, Offset);
7077 case APValue::Vector:
7078 return visitVector(Val, Ty, Offset);
7079
7083 // FIXME: We should support these.
7084
7085 case APValue::Union:
7088 Info.FFDiag(BCE->getBeginLoc(),
7089 diag::note_constexpr_bit_cast_unsupported_type)
7090 << Ty;
7091 return false;
7092 }
7093
7094 case APValue::LValue:
7095 llvm_unreachable("LValue subobject in bit_cast?");
7096 }
7097 llvm_unreachable("Unhandled APValue::ValueKind");
7098 }
7099
7100 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7101 const RecordDecl *RD = Ty->getAsRecordDecl();
7102 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7103
7104 // Visit the base classes.
7105 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7106 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7107 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7108 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7109
7110 if (!visitRecord(Val.getStructBase(I), BS.getType(),
7111 Layout.getBaseClassOffset(BaseDecl) + Offset))
7112 return false;
7113 }
7114 }
7115
7116 // Visit the fields.
7117 unsigned FieldIdx = 0;
7118 for (FieldDecl *FD : RD->fields()) {
7119 if (FD->isBitField()) {
7120 Info.FFDiag(BCE->getBeginLoc(),
7121 diag::note_constexpr_bit_cast_unsupported_bitfield);
7122 return false;
7123 }
7124
7125 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7126
7127 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7128 "only bit-fields can have sub-char alignment");
7129 CharUnits FieldOffset =
7130 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7131 QualType FieldTy = FD->getType();
7132 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7133 return false;
7134 ++FieldIdx;
7135 }
7136
7137 return true;
7138 }
7139
7140 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7141 const auto *CAT =
7142 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7143 if (!CAT)
7144 return false;
7145
7146 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7147 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7148 unsigned ArraySize = Val.getArraySize();
7149 // First, initialize the initialized elements.
7150 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7151 const APValue &SubObj = Val.getArrayInitializedElt(I);
7152 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7153 return false;
7154 }
7155
7156 // Next, initialize the rest of the array using the filler.
7157 if (Val.hasArrayFiller()) {
7158 const APValue &Filler = Val.getArrayFiller();
7159 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7160 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7161 return false;
7162 }
7163 }
7164
7165 return true;
7166 }
7167
7168 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7169 const VectorType *VTy = Ty->castAs<VectorType>();
7170 QualType EltTy = VTy->getElementType();
7171 unsigned NElts = VTy->getNumElements();
7172 unsigned EltSize =
7173 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7174
7175 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7176 // The vector's size in bits is not a multiple of the target's byte size,
7177 // so its layout is unspecified. For now, we'll simply treat these cases
7178 // as unsupported (this should only be possible with OpenCL bool vectors
7179 // whose element count isn't a multiple of the byte size).
7180 Info.FFDiag(BCE->getBeginLoc(),
7181 diag::note_constexpr_bit_cast_invalid_vector)
7182 << Ty.getCanonicalType() << EltSize << NElts
7183 << Info.Ctx.getCharWidth();
7184 return false;
7185 }
7186
7187 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7188 &APFloat::x87DoubleExtended()) {
7189 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7190 // by both clang and LLVM, so for now we won't allow bit_casts involving
7191 // it in a constexpr context.
7192 Info.FFDiag(BCE->getBeginLoc(),
7193 diag::note_constexpr_bit_cast_unsupported_type)
7194 << EltTy;
7195 return false;
7196 }
7197
7198 if (VTy->isExtVectorBoolType()) {
7199 // Special handling for OpenCL bool vectors:
7200 // Since these vectors are stored as packed bits, but we can't write
7201 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7202 // together into an appropriately sized APInt and write them all out at
7203 // once. Because we don't accept vectors where NElts * EltSize isn't a
7204 // multiple of the char size, there will be no padding space, so we don't
7205 // have to worry about writing data which should have been left
7206 // uninitialized.
7207 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7208
7209 llvm::APInt Res = llvm::APInt::getZero(NElts);
7210 for (unsigned I = 0; I < NElts; ++I) {
7211 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7212 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7213 "bool vector element must be 1-bit unsigned integer!");
7214
7215 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7216 }
7217
7218 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7219 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7220 Buffer.writeObject(Offset, Bytes);
7221 } else {
7222 // Iterate over each of the elements and write them out to the buffer at
7223 // the appropriate offset.
7224 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7225 for (unsigned I = 0; I < NElts; ++I) {
7226 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7227 return false;
7228 }
7229 }
7230
7231 return true;
7232 }
7233
7234 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7235 APSInt AdjustedVal = Val;
7236 unsigned Width = AdjustedVal.getBitWidth();
7237 if (Ty->isBooleanType()) {
7238 Width = Info.Ctx.getTypeSize(Ty);
7239 AdjustedVal = AdjustedVal.extend(Width);
7240 }
7241
7242 SmallVector<uint8_t, 8> Bytes(Width / 8);
7243 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7244 Buffer.writeObject(Offset, Bytes);
7245 return true;
7246 }
7247
7248 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7249 APSInt AsInt(Val.bitcastToAPInt());
7250 return visitInt(AsInt, Ty, Offset);
7251 }
7252
7253public:
7254 static std::optional<BitCastBuffer>
7255 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7256 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7257 APValueToBufferConverter Converter(Info, DstSize, BCE);
7258 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7259 return std::nullopt;
7260 return Converter.Buffer;
7261 }
7262};
7263
7264/// Write an BitCastBuffer into an APValue.
7265class BufferToAPValueConverter {
7266 EvalInfo &Info;
7267 const BitCastBuffer &Buffer;
7268 const CastExpr *BCE;
7269
7270 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7271 const CastExpr *BCE)
7272 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7273
7274 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7275 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7276 // Ideally this will be unreachable.
7277 std::nullopt_t unsupportedType(QualType Ty) {
7278 Info.FFDiag(BCE->getBeginLoc(),
7279 diag::note_constexpr_bit_cast_unsupported_type)
7280 << Ty;
7281 return std::nullopt;
7282 }
7283
7284 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7285 Info.FFDiag(BCE->getBeginLoc(),
7286 diag::note_constexpr_bit_cast_unrepresentable_value)
7287 << Ty << toString(Val, /*Radix=*/10);
7288 return std::nullopt;
7289 }
7290
7291 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7292 const EnumType *EnumSugar = nullptr) {
7293 if (T->isNullPtrType()) {
7294 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7295 return APValue((Expr *)nullptr,
7296 /*Offset=*/CharUnits::fromQuantity(NullValue),
7297 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7298 }
7299
7300 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7301
7302 // Work around floating point types that contain unused padding bytes. This
7303 // is really just `long double` on x86, which is the only fundamental type
7304 // with padding bytes.
7305 if (T->isRealFloatingType()) {
7306 const llvm::fltSemantics &Semantics =
7307 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7308 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7309 assert(NumBits % 8 == 0);
7310 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7311 if (NumBytes != SizeOf)
7312 SizeOf = NumBytes;
7313 }
7314
7316 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7317 // If this is std::byte or unsigned char, then its okay to store an
7318 // indeterminate value.
7319 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7320 bool IsUChar =
7321 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7322 T->isSpecificBuiltinType(BuiltinType::Char_U));
7323 if (!IsStdByte && !IsUChar) {
7324 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7325 Info.FFDiag(BCE->getExprLoc(),
7326 diag::note_constexpr_bit_cast_indet_dest)
7327 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7328 return std::nullopt;
7329 }
7330
7332 }
7333
7334 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7335 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7336
7338 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7339
7340 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7341 if (IntWidth != Val.getBitWidth()) {
7342 APSInt Truncated = Val.trunc(IntWidth);
7343 if (Truncated.extend(Val.getBitWidth()) != Val)
7344 return unrepresentableValue(QualType(T, 0), Val);
7345 Val = Truncated;
7346 }
7347
7348 return APValue(Val);
7349 }
7350
7351 if (T->isRealFloatingType()) {
7352 const llvm::fltSemantics &Semantics =
7353 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7354 return APValue(APFloat(Semantics, Val));
7355 }
7356
7357 return unsupportedType(QualType(T, 0));
7358 }
7359
7360 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7361 const RecordDecl *RD = RTy->getAsRecordDecl();
7362 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7363
7364 unsigned NumBases = 0;
7365 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7366 NumBases = CXXRD->getNumBases();
7367
7368 APValue ResultVal(APValue::UninitStruct(), NumBases,
7369 std::distance(RD->field_begin(), RD->field_end()));
7370
7371 // Visit the base classes.
7372 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7373 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7374 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7375 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7376
7377 std::optional<APValue> SubObj = visitType(
7378 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7379 if (!SubObj)
7380 return std::nullopt;
7381 ResultVal.getStructBase(I) = *SubObj;
7382 }
7383 }
7384
7385 // Visit the fields.
7386 unsigned FieldIdx = 0;
7387 for (FieldDecl *FD : RD->fields()) {
7388 // FIXME: We don't currently support bit-fields. A lot of the logic for
7389 // this is in CodeGen, so we need to factor it around.
7390 if (FD->isBitField()) {
7391 Info.FFDiag(BCE->getBeginLoc(),
7392 diag::note_constexpr_bit_cast_unsupported_bitfield);
7393 return std::nullopt;
7394 }
7395
7396 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7397 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7398
7399 CharUnits FieldOffset =
7400 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7401 Offset;
7402 QualType FieldTy = FD->getType();
7403 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7404 if (!SubObj)
7405 return std::nullopt;
7406 ResultVal.getStructField(FieldIdx) = *SubObj;
7407 ++FieldIdx;
7408 }
7409
7410 return ResultVal;
7411 }
7412
7413 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7414 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7415 assert(!RepresentationType.isNull() &&
7416 "enum forward decl should be caught by Sema");
7417 const auto *AsBuiltin =
7418 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7419 // Recurse into the underlying type. Treat std::byte transparently as
7420 // unsigned char.
7421 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7422 }
7423
7424 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7425 size_t Size = Ty->getLimitedSize();
7426 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7427
7428 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7429 for (size_t I = 0; I != Size; ++I) {
7430 std::optional<APValue> ElementValue =
7431 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7432 if (!ElementValue)
7433 return std::nullopt;
7434 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7435 }
7436
7437 return ArrayValue;
7438 }
7439
7440 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7441 QualType EltTy = VTy->getElementType();
7442 unsigned NElts = VTy->getNumElements();
7443 unsigned EltSize =
7444 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7445
7446 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7447 // The vector's size in bits is not a multiple of the target's byte size,
7448 // so its layout is unspecified. For now, we'll simply treat these cases
7449 // as unsupported (this should only be possible with OpenCL bool vectors
7450 // whose element count isn't a multiple of the byte size).
7451 Info.FFDiag(BCE->getBeginLoc(),
7452 diag::note_constexpr_bit_cast_invalid_vector)
7453 << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();
7454 return std::nullopt;
7455 }
7456
7457 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7458 &APFloat::x87DoubleExtended()) {
7459 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7460 // by both clang and LLVM, so for now we won't allow bit_casts involving
7461 // it in a constexpr context.
7462 Info.FFDiag(BCE->getBeginLoc(),
7463 diag::note_constexpr_bit_cast_unsupported_type)
7464 << EltTy;
7465 return std::nullopt;
7466 }
7467
7469 Elts.reserve(NElts);
7470 if (VTy->isExtVectorBoolType()) {
7471 // Special handling for OpenCL bool vectors:
7472 // Since these vectors are stored as packed bits, but we can't read
7473 // individual bits from the BitCastBuffer, we'll buffer all of the
7474 // elements together into an appropriately sized APInt and write them all
7475 // out at once. Because we don't accept vectors where NElts * EltSize
7476 // isn't a multiple of the char size, there will be no padding space, so
7477 // we don't have to worry about reading any padding data which didn't
7478 // actually need to be accessed.
7479 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7480
7482 Bytes.reserve(NElts / 8);
7483 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7484 return std::nullopt;
7485
7486 APSInt SValInt(NElts, true);
7487 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7488
7489 for (unsigned I = 0; I < NElts; ++I) {
7490 llvm::APInt Elt =
7491 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7492 Elts.emplace_back(
7493 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7494 }
7495 } else {
7496 // Iterate over each of the elements and read them from the buffer at
7497 // the appropriate offset.
7498 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7499 for (unsigned I = 0; I < NElts; ++I) {
7500 std::optional<APValue> EltValue =
7501 visitType(EltTy, Offset + I * EltSizeChars);
7502 if (!EltValue)
7503 return std::nullopt;
7504 Elts.push_back(std::move(*EltValue));
7505 }
7506 }
7507
7508 return APValue(Elts.data(), Elts.size());
7509 }
7510
7511 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7512 return unsupportedType(QualType(Ty, 0));
7513 }
7514
7515 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7516 QualType Can = Ty.getCanonicalType();
7517
7518 switch (Can->getTypeClass()) {
7519#define TYPE(Class, Base) \
7520 case Type::Class: \
7521 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7522#define ABSTRACT_TYPE(Class, Base)
7523#define NON_CANONICAL_TYPE(Class, Base) \
7524 case Type::Class: \
7525 llvm_unreachable("non-canonical type should be impossible!");
7526#define DEPENDENT_TYPE(Class, Base) \
7527 case Type::Class: \
7528 llvm_unreachable( \
7529 "dependent types aren't supported in the constant evaluator!");
7530#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7531 case Type::Class: \
7532 llvm_unreachable("either dependent or not canonical!");
7533#include "clang/AST/TypeNodes.inc"
7534 }
7535 llvm_unreachable("Unhandled Type::TypeClass");
7536 }
7537
7538public:
7539 // Pull out a full value of type DstType.
7540 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7541 const CastExpr *BCE) {
7542 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7543 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7544 }
7545};
7546
7547static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7548 QualType Ty, EvalInfo *Info,
7549 const ASTContext &Ctx,
7550 bool CheckingDest) {
7551 Ty = Ty.getCanonicalType();
7552
7553 auto diag = [&](int Reason) {
7554 if (Info)
7555 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7556 << CheckingDest << (Reason == 4) << Reason;
7557 return false;
7558 };
7559 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7560 if (Info)
7561 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7562 << NoteTy << Construct << Ty;
7563 return false;
7564 };
7565
7566 if (Ty->isUnionType())
7567 return diag(0);
7568 if (Ty->isPointerType())
7569 return diag(1);
7570 if (Ty->isMemberPointerType())
7571 return diag(2);
7572 if (Ty.isVolatileQualified())
7573 return diag(3);
7574
7575 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7576 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7577 for (CXXBaseSpecifier &BS : CXXRD->bases())
7578 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7579 CheckingDest))
7580 return note(1, BS.getType(), BS.getBeginLoc());
7581 }
7582 for (FieldDecl *FD : Record->fields()) {
7583 if (FD->getType()->isReferenceType())
7584 return diag(4);
7585 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7586 CheckingDest))
7587 return note(0, FD->getType(), FD->getBeginLoc());
7588 }
7589 }
7590
7591 if (Ty->isArrayType() &&
7592 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7593 Info, Ctx, CheckingDest))
7594 return false;
7595
7596 return true;
7597}
7598
7599static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7600 const ASTContext &Ctx,
7601 const CastExpr *BCE) {
7602 bool DestOK = checkBitCastConstexprEligibilityType(
7603 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7604 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7605 BCE->getBeginLoc(),
7606 BCE->getSubExpr()->getType(), Info, Ctx, false);
7607 return SourceOK;
7608}
7609
7610static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7611 const APValue &SourceRValue,
7612 const CastExpr *BCE) {
7613 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7614 "no host or target supports non 8-bit chars");
7615
7616 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7617 return false;
7618
7619 // Read out SourceValue into a char buffer.
7620 std::optional<BitCastBuffer> Buffer =
7621 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7622 if (!Buffer)
7623 return false;
7624
7625 // Write out the buffer into a new APValue.
7626 std::optional<APValue> MaybeDestValue =
7627 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7628 if (!MaybeDestValue)
7629 return false;
7630
7631 DestValue = std::move(*MaybeDestValue);
7632 return true;
7633}
7634
7635static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7636 APValue &SourceValue,
7637 const CastExpr *BCE) {
7638 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7639 "no host or target supports non 8-bit chars");
7640 assert(SourceValue.isLValue() &&
7641 "LValueToRValueBitcast requires an lvalue operand!");
7642
7643 LValue SourceLValue;
7644 APValue SourceRValue;
7645 SourceLValue.setFrom(Info.Ctx, SourceValue);
7647 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7648 SourceRValue, /*WantObjectRepresentation=*/true))
7649 return false;
7650
7651 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7652}
7653
7654template <class Derived>
7655class ExprEvaluatorBase
7656 : public ConstStmtVisitor<Derived, bool> {
7657private:
7658 Derived &getDerived() { return static_cast<Derived&>(*this); }
7659 bool DerivedSuccess(const APValue &V, const Expr *E) {
7660 return getDerived().Success(V, E);
7661 }
7662 bool DerivedZeroInitialization(const Expr *E) {
7663 return getDerived().ZeroInitialization(E);
7664 }
7665
7666 // Check whether a conditional operator with a non-constant condition is a
7667 // potential constant expression. If neither arm is a potential constant
7668 // expression, then the conditional operator is not either.
7669 template<typename ConditionalOperator>
7670 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7671 assert(Info.checkingPotentialConstantExpression());
7672
7673 // Speculatively evaluate both arms.
7675 {
7676 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7677 StmtVisitorTy::Visit(E->getFalseExpr());
7678 if (Diag.empty())
7679 return;
7680 }
7681
7682 {
7683 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7684 Diag.clear();
7685 StmtVisitorTy::Visit(E->getTrueExpr());
7686 if (Diag.empty())
7687 return;
7688 }
7689
7690 Error(E, diag::note_constexpr_conditional_never_const);
7691 }
7692
7693
7694 template<typename ConditionalOperator>
7695 bool HandleConditionalOperator(const ConditionalOperator *E) {
7696 bool BoolResult;
7697 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7698 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7699 CheckPotentialConstantConditional(E);
7700 return false;
7701 }
7702 if (Info.noteFailure()) {
7703 StmtVisitorTy::Visit(E->getTrueExpr());
7704 StmtVisitorTy::Visit(E->getFalseExpr());
7705 }
7706 return false;
7707 }
7708
7709 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7710 return StmtVisitorTy::Visit(EvalExpr);
7711 }
7712
7713protected:
7714 EvalInfo &Info;
7715 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7716 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7717
7718 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7719 return Info.CCEDiag(E, D);
7720 }
7721
7722 bool ZeroInitialization(const Expr *E) { return Error(E); }
7723
7724 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7725 unsigned BuiltinOp = E->getBuiltinCallee();
7726 return BuiltinOp != 0 &&
7727 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7728 }
7729
7730public:
7731 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7732
7733 EvalInfo &getEvalInfo() { return Info; }
7734
7735 /// Report an evaluation error. This should only be called when an error is
7736 /// first discovered. When propagating an error, just return false.
7737 bool Error(const Expr *E, diag::kind D) {
7738 Info.FFDiag(E, D) << E->getSourceRange();
7739 return false;
7740 }
7741 bool Error(const Expr *E) {
7742 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7743 }
7744
7745 bool VisitStmt(const Stmt *) {
7746 llvm_unreachable("Expression evaluator should not be called on stmts");
7747 }
7748 bool VisitExpr(const Expr *E) {
7749 return Error(E);
7750 }
7751
7752 bool VisitEmbedExpr(const EmbedExpr *E) {
7753 const auto It = E->begin();
7754 return StmtVisitorTy::Visit(*It);
7755 }
7756
7757 bool VisitPredefinedExpr(const PredefinedExpr *E) {
7758 return StmtVisitorTy::Visit(E->getFunctionName());
7759 }
7760 bool VisitConstantExpr(const ConstantExpr *E) {
7761 if (E->hasAPValueResult())
7762 return DerivedSuccess(E->getAPValueResult(), E);
7763
7764 return StmtVisitorTy::Visit(E->getSubExpr());
7765 }
7766
7767 bool VisitParenExpr(const ParenExpr *E)
7768 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7769 bool VisitUnaryExtension(const UnaryOperator *E)
7770 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7771 bool VisitUnaryPlus(const UnaryOperator *E)
7772 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7773 bool VisitChooseExpr(const ChooseExpr *E)
7774 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7775 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7776 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7777 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7778 { return StmtVisitorTy::Visit(E->getReplacement()); }
7779 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7780 TempVersionRAII RAII(*Info.CurrentCall);
7781 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7782 return StmtVisitorTy::Visit(E->getExpr());
7783 }
7784 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7785 TempVersionRAII RAII(*Info.CurrentCall);
7786 // The initializer may not have been parsed yet, or might be erroneous.
7787 if (!E->getExpr())
7788 return Error(E);
7789 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7790 return StmtVisitorTy::Visit(E->getExpr());
7791 }
7792
7793 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7794 FullExpressionRAII Scope(Info);
7795 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7796 }
7797
7798 // Temporaries are registered when created, so we don't care about
7799 // CXXBindTemporaryExpr.
7800 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7801 return StmtVisitorTy::Visit(E->getSubExpr());
7802 }
7803
7804 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7805 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7806 return static_cast<Derived*>(this)->VisitCastExpr(E);
7807 }
7808 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7809 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7810 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7811 return static_cast<Derived*>(this)->VisitCastExpr(E);
7812 }
7813 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7814 return static_cast<Derived*>(this)->VisitCastExpr(E);
7815 }
7816
7817 bool VisitBinaryOperator(const BinaryOperator *E) {
7818 switch (E->getOpcode()) {
7819 default:
7820 return Error(E);
7821
7822 case BO_Comma:
7823 VisitIgnoredValue(E->getLHS());
7824 return StmtVisitorTy::Visit(E->getRHS());
7825
7826 case BO_PtrMemD:
7827 case BO_PtrMemI: {
7828 LValue Obj;
7829 if (!HandleMemberPointerAccess(Info, E, Obj))
7830 return false;
7831 APValue Result;
7832 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7833 return false;
7834 return DerivedSuccess(Result, E);
7835 }
7836 }
7837 }
7838
7839 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7840 return StmtVisitorTy::Visit(E->getSemanticForm());
7841 }
7842
7843 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7844 // Evaluate and cache the common expression. We treat it as a temporary,
7845 // even though it's not quite the same thing.
7846 LValue CommonLV;
7847 if (!Evaluate(Info.CurrentCall->createTemporary(
7848 E->getOpaqueValue(),
7849 getStorageType(Info.Ctx, E->getOpaqueValue()),
7850 ScopeKind::FullExpression, CommonLV),
7851 Info, E->getCommon()))
7852 return false;
7853
7854 return HandleConditionalOperator(E);
7855 }
7856
7857 bool VisitConditionalOperator(const ConditionalOperator *E) {
7858 bool IsBcpCall = false;
7859 // If the condition (ignoring parens) is a __builtin_constant_p call,
7860 // the result is a constant expression if it can be folded without
7861 // side-effects. This is an important GNU extension. See GCC PR38377
7862 // for discussion.
7863 if (const CallExpr *CallCE =
7864 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7865 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7866 IsBcpCall = true;
7867
7868 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7869 // constant expression; we can't check whether it's potentially foldable.
7870 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7871 // it would return 'false' in this mode.
7872 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7873 return false;
7874
7875 FoldConstant Fold(Info, IsBcpCall);
7876 if (!HandleConditionalOperator(E)) {
7877 Fold.keepDiagnostics();
7878 return false;
7879 }
7880
7881 return true;
7882 }
7883
7884 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7885 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7886 Value && !Value->isAbsent())
7887 return DerivedSuccess(*Value, E);
7888
7889 const Expr *Source = E->getSourceExpr();
7890 if (!Source)
7891 return Error(E);
7892 if (Source == E) {
7893 assert(0 && "OpaqueValueExpr recursively refers to itself");
7894 return Error(E);
7895 }
7896 return StmtVisitorTy::Visit(Source);
7897 }
7898
7899 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7900 for (const Expr *SemE : E->semantics()) {
7901 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7902 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7903 // result expression: there could be two different LValues that would
7904 // refer to the same object in that case, and we can't model that.
7905 if (SemE == E->getResultExpr())
7906 return Error(E);
7907
7908 // Unique OVEs get evaluated if and when we encounter them when
7909 // emitting the rest of the semantic form, rather than eagerly.
7910 if (OVE->isUnique())
7911 continue;
7912
7913 LValue LV;
7914 if (!Evaluate(Info.CurrentCall->createTemporary(
7915 OVE, getStorageType(Info.Ctx, OVE),
7916 ScopeKind::FullExpression, LV),
7917 Info, OVE->getSourceExpr()))
7918 return false;
7919 } else if (SemE == E->getResultExpr()) {
7920 if (!StmtVisitorTy::Visit(SemE))
7921 return false;
7922 } else {
7923 if (!EvaluateIgnoredValue(Info, SemE))
7924 return false;
7925 }
7926 }
7927 return true;
7928 }
7929
7930 bool VisitCallExpr(const CallExpr *E) {
7931 APValue Result;
7932 if (!handleCallExpr(E, Result, nullptr))
7933 return false;
7934 return DerivedSuccess(Result, E);
7935 }
7936
7937 bool handleCallExpr(const CallExpr *E, APValue &Result,
7938 const LValue *ResultSlot) {
7939 CallScopeRAII CallScope(Info);
7940
7941 const Expr *Callee = E->getCallee()->IgnoreParens();
7942 QualType CalleeType = Callee->getType();
7943
7944 const FunctionDecl *FD = nullptr;
7945 LValue *This = nullptr, ThisVal;
7946 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7947 bool HasQualifier = false;
7948
7949 CallRef Call;
7950
7951 // Extract function decl and 'this' pointer from the callee.
7952 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7953 const CXXMethodDecl *Member = nullptr;
7954 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7955 // Explicit bound member calls, such as x.f() or p->g();
7956 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7957 return false;
7958 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7959 if (!Member)
7960 return Error(Callee);
7961 This = &ThisVal;
7962 HasQualifier = ME->hasQualifier();
7963 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7964 // Indirect bound member calls ('.*' or '->*').
7965 const ValueDecl *D =
7966 HandleMemberPointerAccess(Info, BE, ThisVal, false);
7967 if (!D)
7968 return false;
7969 Member = dyn_cast<CXXMethodDecl>(D);
7970 if (!Member)
7971 return Error(Callee);
7972 This = &ThisVal;
7973 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7974 if (!Info.getLangOpts().CPlusPlus20)
7975 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7976 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7977 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7978 } else
7979 return Error(Callee);
7980 FD = Member;
7981 } else if (CalleeType->isFunctionPointerType()) {
7982 LValue CalleeLV;
7983 if (!EvaluatePointer(Callee, CalleeLV, Info))
7984 return false;
7985
7986 if (!CalleeLV.getLValueOffset().isZero())
7987 return Error(Callee);
7988 if (CalleeLV.isNullPointer()) {
7989 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7990 << const_cast<Expr *>(Callee);
7991 return false;
7992 }
7993 FD = dyn_cast_or_null<FunctionDecl>(
7994 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7995 if (!FD)
7996 return Error(Callee);
7997 // Don't call function pointers which have been cast to some other type.
7998 // Per DR (no number yet), the caller and callee can differ in noexcept.
7999 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8000 CalleeType->getPointeeType(), FD->getType())) {
8001 return Error(E);
8002 }
8003
8004 // For an (overloaded) assignment expression, evaluate the RHS before the
8005 // LHS.
8006 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8007 if (OCE && OCE->isAssignmentOp()) {
8008 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8009 Call = Info.CurrentCall->createCall(FD);
8010 bool HasThis = false;
8011 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8012 HasThis = MD->isImplicitObjectMemberFunction();
8013 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8014 /*RightToLeft=*/true))
8015 return false;
8016 }
8017
8018 // Overloaded operator calls to member functions are represented as normal
8019 // calls with '*this' as the first argument.
8020 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8021 if (MD &&
8022 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8023 // FIXME: When selecting an implicit conversion for an overloaded
8024 // operator delete, we sometimes try to evaluate calls to conversion
8025 // operators without a 'this' parameter!
8026 if (Args.empty())
8027 return Error(E);
8028
8029 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
8030 return false;
8031
8032 // If we are calling a static operator, the 'this' argument needs to be
8033 // ignored after being evaluated.
8034 if (MD->isInstance())
8035 This = &ThisVal;
8036
8037 // If this is syntactically a simple assignment using a trivial
8038 // assignment operator, start the lifetimes of union members as needed,
8039 // per C++20 [class.union]5.
8040 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8041 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8042 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
8043 return false;
8044
8045 Args = Args.slice(1);
8046 } else if (MD && MD->isLambdaStaticInvoker()) {
8047 // Map the static invoker for the lambda back to the call operator.
8048 // Conveniently, we don't have to slice out the 'this' argument (as is
8049 // being done for the non-static case), since a static member function
8050 // doesn't have an implicit argument passed in.
8051 const CXXRecordDecl *ClosureClass = MD->getParent();
8052 assert(
8053 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8054 "Number of captures must be zero for conversion to function-ptr");
8055
8056 const CXXMethodDecl *LambdaCallOp =
8057 ClosureClass->getLambdaCallOperator();
8058
8059 // Set 'FD', the function that will be called below, to the call
8060 // operator. If the closure object represents a generic lambda, find
8061 // the corresponding specialization of the call operator.
8062
8063 if (ClosureClass->isGenericLambda()) {
8064 assert(MD->isFunctionTemplateSpecialization() &&
8065 "A generic lambda's static-invoker function must be a "
8066 "template specialization");
8068 FunctionTemplateDecl *CallOpTemplate =
8069 LambdaCallOp->getDescribedFunctionTemplate();
8070 void *InsertPos = nullptr;
8071 FunctionDecl *CorrespondingCallOpSpecialization =
8072 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8073 assert(CorrespondingCallOpSpecialization &&
8074 "We must always have a function call operator specialization "
8075 "that corresponds to our static invoker specialization");
8076 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8077 FD = CorrespondingCallOpSpecialization;
8078 } else
8079 FD = LambdaCallOp;
8080 } else if (FD->isReplaceableGlobalAllocationFunction()) {
8081 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8082 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8083 LValue Ptr;
8084 if (!HandleOperatorNewCall(Info, E, Ptr))
8085 return false;
8086 Ptr.moveInto(Result);
8087 return CallScope.destroy();
8088 } else {
8089 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8090 }
8091 }
8092 } else
8093 return Error(E);
8094
8095 // Evaluate the arguments now if we've not already done so.
8096 if (!Call) {
8097 Call = Info.CurrentCall->createCall(FD);
8098 if (!EvaluateArgs(Args, Call, Info, FD))
8099 return false;
8100 }
8101
8102 SmallVector<QualType, 4> CovariantAdjustmentPath;
8103 if (This) {
8104 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8105 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8106 // Perform virtual dispatch, if necessary.
8107 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8108 CovariantAdjustmentPath);
8109 if (!FD)
8110 return false;
8111 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8112 // Check that the 'this' pointer points to an object of the right type.
8113 // FIXME: If this is an assignment operator call, we may need to change
8114 // the active union member before we check this.
8115 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8116 return false;
8117 }
8118 }
8119
8120 // Destructor calls are different enough that they have their own codepath.
8121 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8122 assert(This && "no 'this' pointer for destructor call");
8123 return HandleDestruction(Info, E, *This,
8124 Info.Ctx.getRecordType(DD->getParent())) &&
8125 CallScope.destroy();
8126 }
8127
8128 const FunctionDecl *Definition = nullptr;
8129 Stmt *Body = FD->getBody(Definition);
8130
8131 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8132 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8133 Body, Info, Result, ResultSlot))
8134 return false;
8135
8136 if (!CovariantAdjustmentPath.empty() &&
8137 !HandleCovariantReturnAdjustment(Info, E, Result,
8138 CovariantAdjustmentPath))
8139 return false;
8140
8141 return CallScope.destroy();
8142 }
8143
8144 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8145 return StmtVisitorTy::Visit(E->getInitializer());
8146 }
8147 bool VisitInitListExpr(const InitListExpr *E) {
8148 if (E->getNumInits() == 0)
8149 return DerivedZeroInitialization(E);
8150 if (E->getNumInits() == 1)
8151 return StmtVisitorTy::Visit(E->getInit(0));
8152 return Error(E);
8153 }
8154 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8155 return DerivedZeroInitialization(E);
8156 }
8157 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8158 return DerivedZeroInitialization(E);
8159 }
8160 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8161 return DerivedZeroInitialization(E);
8162 }
8163
8164 /// A member expression where the object is a prvalue is itself a prvalue.
8165 bool VisitMemberExpr(const MemberExpr *E) {
8166 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8167 "missing temporary materialization conversion");
8168 assert(!E->isArrow() && "missing call to bound member function?");
8169
8170 APValue Val;
8171 if (!Evaluate(Val, Info, E->getBase()))
8172 return false;
8173
8174 QualType BaseTy = E->getBase()->getType();
8175
8176 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8177 if (!FD) return Error(E);
8178 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8179 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8180 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8181
8182 // Note: there is no lvalue base here. But this case should only ever
8183 // happen in C or in C++98, where we cannot be evaluating a constexpr
8184 // constructor, which is the only case the base matters.
8185 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8186 SubobjectDesignator Designator(BaseTy);
8187 Designator.addDeclUnchecked(FD);
8188
8189 APValue Result;
8190 return extractSubobject(Info, E, Obj, Designator, Result) &&
8191 DerivedSuccess(Result, E);
8192 }
8193
8194 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8195 APValue Val;
8196 if (!Evaluate(Val, Info, E->getBase()))
8197 return false;
8198
8199 if (Val.isVector()) {
8201 E->getEncodedElementAccess(Indices);
8202 if (Indices.size() == 1) {
8203 // Return scalar.
8204 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8205 } else {
8206 // Construct new APValue vector.
8208 for (unsigned I = 0; I < Indices.size(); ++I) {
8209 Elts.push_back(Val.getVectorElt(Indices[I]));
8210 }
8211 APValue VecResult(Elts.data(), Indices.size());
8212 return DerivedSuccess(VecResult, E);
8213 }
8214 }
8215
8216 return false;
8217 }
8218
8219 bool VisitCastExpr(const CastExpr *E) {
8220 switch (E->getCastKind()) {
8221 default:
8222 break;
8223
8224 case CK_AtomicToNonAtomic: {
8225 APValue AtomicVal;
8226 // This does not need to be done in place even for class/array types:
8227 // atomic-to-non-atomic conversion implies copying the object
8228 // representation.
8229 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8230 return false;
8231 return DerivedSuccess(AtomicVal, E);
8232 }
8233
8234 case CK_NoOp:
8235 case CK_UserDefinedConversion:
8236 return StmtVisitorTy::Visit(E->getSubExpr());
8237
8238 case CK_LValueToRValue: {
8239 LValue LVal;
8240 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8241 return false;
8242 APValue RVal;
8243 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8244 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8245 LVal, RVal))
8246 return false;
8247 return DerivedSuccess(RVal, E);
8248 }
8249 case CK_LValueToRValueBitCast: {
8250 APValue DestValue, SourceValue;
8251 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8252 return false;
8253 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8254 return false;
8255 return DerivedSuccess(DestValue, E);
8256 }
8257
8258 case CK_AddressSpaceConversion: {
8259 APValue Value;
8260 if (!Evaluate(Value, Info, E->getSubExpr()))
8261 return false;
8262 return DerivedSuccess(Value, E);
8263 }
8264 }
8265
8266 return Error(E);
8267 }
8268
8269 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8270 return VisitUnaryPostIncDec(UO);
8271 }
8272 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8273 return VisitUnaryPostIncDec(UO);
8274 }
8275 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8276 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8277 return Error(UO);
8278
8279 LValue LVal;
8280 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8281 return false;
8282 APValue RVal;
8283 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8284 UO->isIncrementOp(), &RVal))
8285 return false;
8286 return DerivedSuccess(RVal, UO);
8287 }
8288
8289 bool VisitStmtExpr(const StmtExpr *E) {
8290 // We will have checked the full-expressions inside the statement expression
8291 // when they were completed, and don't need to check them again now.
8292 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8293 false);
8294
8295 const CompoundStmt *CS = E->getSubStmt();
8296 if (CS->body_empty())
8297 return true;
8298
8299 BlockScopeRAII Scope(Info);
8301 BE = CS->body_end();
8302 /**/; ++BI) {
8303 if (BI + 1 == BE) {
8304 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8305 if (!FinalExpr) {
8306 Info.FFDiag((*BI)->getBeginLoc(),
8307 diag::note_constexpr_stmt_expr_unsupported);
8308 return false;
8309 }
8310 return this->Visit(FinalExpr) && Scope.destroy();
8311 }
8312
8314 StmtResult Result = { ReturnValue, nullptr };
8315 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8316 if (ESR != ESR_Succeeded) {
8317 // FIXME: If the statement-expression terminated due to 'return',
8318 // 'break', or 'continue', it would be nice to propagate that to
8319 // the outer statement evaluation rather than bailing out.
8320 if (ESR != ESR_Failed)
8321 Info.FFDiag((*BI)->getBeginLoc(),
8322 diag::note_constexpr_stmt_expr_unsupported);
8323 return false;
8324 }
8325 }
8326
8327 llvm_unreachable("Return from function from the loop above.");
8328 }
8329
8330 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8331 return StmtVisitorTy::Visit(E->getSelectedExpr());
8332 }
8333
8334 /// Visit a value which is evaluated, but whose value is ignored.
8335 void VisitIgnoredValue(const Expr *E) {
8336 EvaluateIgnoredValue(Info, E);
8337 }
8338
8339 /// Potentially visit a MemberExpr's base expression.
8340 void VisitIgnoredBaseExpression(const Expr *E) {
8341 // While MSVC doesn't evaluate the base expression, it does diagnose the
8342 // presence of side-effecting behavior.
8343 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8344 return;
8345 VisitIgnoredValue(E);
8346 }
8347};
8348
8349} // namespace
8350
8351//===----------------------------------------------------------------------===//
8352// Common base class for lvalue and temporary evaluation.
8353//===----------------------------------------------------------------------===//
8354namespace {
8355template<class Derived>
8356class LValueExprEvaluatorBase
8357 : public ExprEvaluatorBase<Derived> {
8358protected:
8359 LValue &Result;
8360 bool InvalidBaseOK;
8361 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8362 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8363
8365 Result.set(B);
8366 return true;
8367 }
8368
8369 bool evaluatePointer(const Expr *E, LValue &Result) {
8370 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8371 }
8372
8373public:
8374 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8375 : ExprEvaluatorBaseTy(Info), Result(Result),
8376 InvalidBaseOK(InvalidBaseOK) {}
8377
8378 bool Success(const APValue &V, const Expr *E) {
8379 Result.setFrom(this->Info.Ctx, V);
8380 return true;
8381 }
8382
8383 bool VisitMemberExpr(const MemberExpr *E) {
8384 // Handle non-static data members.
8385 QualType BaseTy;
8386 bool EvalOK;
8387 if (E->isArrow()) {
8388 EvalOK = evaluatePointer(E->getBase(), Result);
8389 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8390 } else if (E->getBase()->isPRValue()) {
8391 assert(E->getBase()->getType()->isRecordType());
8392 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8393 BaseTy = E->getBase()->getType();
8394 } else {
8395 EvalOK = this->Visit(E->getBase());
8396 BaseTy = E->getBase()->getType();
8397 }
8398 if (!EvalOK) {
8399 if (!InvalidBaseOK)
8400 return false;
8401 Result.setInvalid(E);
8402 return true;
8403 }
8404
8405 const ValueDecl *MD = E->getMemberDecl();
8406 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8407 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8408 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8409 (void)BaseTy;
8410 if (!HandleLValueMember(this->Info, E, Result, FD))
8411 return false;
8412 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8413 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8414 return false;
8415 } else
8416 return this->Error(E);
8417
8418 if (MD->getType()->isReferenceType()) {
8419 APValue RefValue;
8420 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8421 RefValue))
8422 return false;
8423 return Success(RefValue, E);
8424 }
8425 return true;
8426 }
8427
8428 bool VisitBinaryOperator(const BinaryOperator *E) {
8429 switch (E->getOpcode()) {
8430 default:
8431 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8432
8433 case BO_PtrMemD:
8434 case BO_PtrMemI:
8435 return HandleMemberPointerAccess(this->Info, E, Result);
8436 }
8437 }
8438
8439 bool VisitCastExpr(const CastExpr *E) {
8440 switch (E->getCastKind()) {
8441 default:
8442 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8443
8444 case CK_DerivedToBase:
8445 case CK_UncheckedDerivedToBase:
8446 if (!this->Visit(E->getSubExpr()))
8447 return false;
8448
8449 // Now figure out the necessary offset to add to the base LV to get from
8450 // the derived class to the base class.
8451 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8452 Result);
8453 }
8454 }
8455};
8456}
8457
8458//===----------------------------------------------------------------------===//
8459// LValue Evaluation
8460//
8461// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8462// function designators (in C), decl references to void objects (in C), and
8463// temporaries (if building with -Wno-address-of-temporary).
8464//
8465// LValue evaluation produces values comprising a base expression of one of the
8466// following types:
8467// - Declarations
8468// * VarDecl
8469// * FunctionDecl
8470// - Literals
8471// * CompoundLiteralExpr in C (and in global scope in C++)
8472// * StringLiteral
8473// * PredefinedExpr
8474// * ObjCStringLiteralExpr
8475// * ObjCEncodeExpr
8476// * AddrLabelExpr
8477// * BlockExpr
8478// * CallExpr for a MakeStringConstant builtin
8479// - typeid(T) expressions, as TypeInfoLValues
8480// - Locals and temporaries
8481// * MaterializeTemporaryExpr
8482// * Any Expr, with a CallIndex indicating the function in which the temporary
8483// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8484// from the AST (FIXME).
8485// * A MaterializeTemporaryExpr that has static storage duration, with no
8486// CallIndex, for a lifetime-extended temporary.
8487// * The ConstantExpr that is currently being evaluated during evaluation of an
8488// immediate invocation.
8489// plus an offset in bytes.
8490//===----------------------------------------------------------------------===//
8491namespace {
8492class LValueExprEvaluator
8493 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8494public:
8495 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8496 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8497
8498 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8499 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8500
8501 bool VisitCallExpr(const CallExpr *E);
8502 bool VisitDeclRefExpr(const DeclRefExpr *E);
8503 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8504 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8505 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8506 bool VisitMemberExpr(const MemberExpr *E);
8507 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8508 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8509 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8510 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8511 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8512 bool VisitUnaryDeref(const UnaryOperator *E);
8513 bool VisitUnaryReal(const UnaryOperator *E);
8514 bool VisitUnaryImag(const UnaryOperator *E);
8515 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8516 return VisitUnaryPreIncDec(UO);
8517 }
8518 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8519 return VisitUnaryPreIncDec(UO);
8520 }
8521 bool VisitBinAssign(const BinaryOperator *BO);
8522 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8523
8524 bool VisitCastExpr(const CastExpr *E) {
8525 switch (E->getCastKind()) {
8526 default:
8527 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8528
8529 case CK_LValueBitCast:
8530 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8531 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8532 if (!Visit(E->getSubExpr()))
8533 return false;
8534 Result.Designator.setInvalid();
8535 return true;
8536
8537 case CK_BaseToDerived:
8538 if (!Visit(E->getSubExpr()))
8539 return false;
8540 return HandleBaseToDerivedCast(Info, E, Result);
8541
8542 case CK_Dynamic:
8543 if (!Visit(E->getSubExpr()))
8544 return false;
8545 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8546 }
8547 }
8548};
8549} // end anonymous namespace
8550
8551/// Get an lvalue to a field of a lambda's closure type.
8552static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8553 const CXXMethodDecl *MD, const FieldDecl *FD,
8554 bool LValueToRValueConversion) {
8555 // Static lambda function call operators can't have captures. We already
8556 // diagnosed this, so bail out here.
8557 if (MD->isStatic()) {
8558 assert(Info.CurrentCall->This == nullptr &&
8559 "This should not be set for a static call operator");
8560 return false;
8561 }
8562
8563 // Start with 'Result' referring to the complete closure object...
8565 // Self may be passed by reference or by value.
8566 const ParmVarDecl *Self = MD->getParamDecl(0);
8567 if (Self->getType()->isReferenceType()) {
8568 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8569 Result.setFrom(Info.Ctx, *RefValue);
8570 } else {
8571 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8572 CallStackFrame *Frame =
8573 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8574 .first;
8575 unsigned Version = Info.CurrentCall->Arguments.Version;
8576 Result.set({VD, Frame->Index, Version});
8577 }
8578 } else
8579 Result = *Info.CurrentCall->This;
8580
8581 // ... then update it to refer to the field of the closure object
8582 // that represents the capture.
8583 if (!HandleLValueMember(Info, E, Result, FD))
8584 return false;
8585
8586 // And if the field is of reference type (or if we captured '*this' by
8587 // reference), update 'Result' to refer to what
8588 // the field refers to.
8589 if (LValueToRValueConversion) {
8590 APValue RVal;
8591 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8592 return false;
8593 Result.setFrom(Info.Ctx, RVal);
8594 }
8595 return true;
8596}
8597
8598/// Evaluate an expression as an lvalue. This can be legitimately called on
8599/// expressions which are not glvalues, in three cases:
8600/// * function designators in C, and
8601/// * "extern void" objects
8602/// * @selector() expressions in Objective-C
8603static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8604 bool InvalidBaseOK) {
8605 assert(!E->isValueDependent());
8606 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8607 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8608 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8609}
8610
8611bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8612 const NamedDecl *D = E->getDecl();
8615 return Success(cast<ValueDecl>(D));
8616 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8617 return VisitVarDecl(E, VD);
8618 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8619 return Visit(BD->getBinding());
8620 return Error(E);
8621}
8622
8623
8624bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8625
8626 // If we are within a lambda's call operator, check whether the 'VD' referred
8627 // to within 'E' actually represents a lambda-capture that maps to a
8628 // data-member/field within the closure object, and if so, evaluate to the
8629 // field or what the field refers to.
8630 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8631 isa<DeclRefExpr>(E) &&
8632 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8633 // We don't always have a complete capture-map when checking or inferring if
8634 // the function call operator meets the requirements of a constexpr function
8635 // - but we don't need to evaluate the captures to determine constexprness
8636 // (dcl.constexpr C++17).
8637 if (Info.checkingPotentialConstantExpression())
8638 return false;
8639
8640 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8641 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8642 return HandleLambdaCapture(Info, E, Result, MD, FD,
8643 FD->getType()->isReferenceType());
8644 }
8645 }
8646
8647 CallStackFrame *Frame = nullptr;
8648 unsigned Version = 0;
8649 if (VD->hasLocalStorage()) {
8650 // Only if a local variable was declared in the function currently being
8651 // evaluated, do we expect to be able to find its value in the current
8652 // frame. (Otherwise it was likely declared in an enclosing context and
8653 // could either have a valid evaluatable value (for e.g. a constexpr
8654 // variable) or be ill-formed (and trigger an appropriate evaluation
8655 // diagnostic)).
8656 CallStackFrame *CurrFrame = Info.CurrentCall;
8657 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8658 // Function parameters are stored in some caller's frame. (Usually the
8659 // immediate caller, but for an inherited constructor they may be more
8660 // distant.)
8661 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8662 if (CurrFrame->Arguments) {
8663 VD = CurrFrame->Arguments.getOrigParam(PVD);
8664 Frame =
8665 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8666 Version = CurrFrame->Arguments.Version;
8667 }
8668 } else {
8669 Frame = CurrFrame;
8670 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8671 }
8672 }
8673 }
8674
8675 if (!VD->getType()->isReferenceType()) {
8676 if (Frame) {
8677 Result.set({VD, Frame->Index, Version});
8678 return true;
8679 }
8680 return Success(VD);
8681 }
8682
8683 if (!Info.getLangOpts().CPlusPlus11) {
8684 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8685 << VD << VD->getType();
8686 Info.Note(VD->getLocation(), diag::note_declared_at);
8687 }
8688
8689 APValue *V;
8690 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8691 return false;
8692 if (!V->hasValue()) {
8693 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8694 // adjust the diagnostic to say that.
8695 if (!Info.checkingPotentialConstantExpression())
8696 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8697 return false;
8698 }
8699 return Success(*V, E);
8700}
8701
8702bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8703 if (!IsConstantEvaluatedBuiltinCall(E))
8704 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8705
8706 switch (E->getBuiltinCallee()) {
8707 default:
8708 return false;
8709 case Builtin::BIas_const:
8710 case Builtin::BIforward:
8711 case Builtin::BIforward_like:
8712 case Builtin::BImove:
8713 case Builtin::BImove_if_noexcept:
8714 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8715 return Visit(E->getArg(0));
8716 break;
8717 }
8718
8719 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8720}
8721
8722bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8723 const MaterializeTemporaryExpr *E) {
8724 // Walk through the expression to find the materialized temporary itself.
8727 const Expr *Inner =
8728 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8729
8730 // If we passed any comma operators, evaluate their LHSs.
8731 for (const Expr *E : CommaLHSs)
8732 if (!EvaluateIgnoredValue(Info, E))
8733 return false;
8734
8735 // A materialized temporary with static storage duration can appear within the
8736 // result of a constant expression evaluation, so we need to preserve its
8737 // value for use outside this evaluation.
8738 APValue *Value;
8739 if (E->getStorageDuration() == SD_Static) {
8740 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8741 return false;
8742 // FIXME: What about SD_Thread?
8743 Value = E->getOrCreateValue(true);
8744 *Value = APValue();
8745 Result.set(E);
8746 } else {
8747 Value = &Info.CurrentCall->createTemporary(
8748 E, Inner->getType(),
8749 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8750 : ScopeKind::Block,
8751 Result);
8752 }
8753
8754 QualType Type = Inner->getType();
8755
8756 // Materialize the temporary itself.
8757 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8758 *Value = APValue();
8759 return false;
8760 }
8761
8762 // Adjust our lvalue to refer to the desired subobject.
8763 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8764 --I;
8765 switch (Adjustments[I].Kind) {
8767 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8768 Type, Result))
8769 return false;
8770 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8771 break;
8772
8774 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8775 return false;
8776 Type = Adjustments[I].Field->getType();
8777 break;
8778
8780 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8781 Adjustments[I].Ptr.RHS))
8782 return false;
8783 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8784 break;
8785 }
8786 }
8787
8788 return true;
8789}
8790
8791bool
8792LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8793 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8794 "lvalue compound literal in c++?");
8795 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8796 // only see this when folding in C, so there's no standard to follow here.
8797 return Success(E);
8798}
8799
8800bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8802
8803 if (!E->isPotentiallyEvaluated()) {
8804 if (E->isTypeOperand())
8805 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8806 else
8807 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8808 } else {
8809 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8810 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8811 << E->getExprOperand()->getType()
8812 << E->getExprOperand()->getSourceRange();
8813 }
8814
8815 if (!Visit(E->getExprOperand()))
8816 return false;
8817
8818 std::optional<DynamicType> DynType =
8819 ComputeDynamicType(Info, E, Result, AK_TypeId);
8820 if (!DynType)
8821 return false;
8822
8823 TypeInfo =
8824 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8825 }
8826
8828}
8829
8830bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8831 return Success(E->getGuidDecl());
8832}
8833
8834bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8835 // Handle static data members.
8836 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8837 VisitIgnoredBaseExpression(E->getBase());
8838 return VisitVarDecl(E, VD);
8839 }
8840
8841 // Handle static member functions.
8842 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8843 if (MD->isStatic()) {
8844 VisitIgnoredBaseExpression(E->getBase());
8845 return Success(MD);
8846 }
8847 }
8848
8849 // Handle non-static data members.
8850 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8851}
8852
8853bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8854 // FIXME: Deal with vectors as array subscript bases.
8855 if (E->getBase()->getType()->isVectorType() ||
8856 E->getBase()->getType()->isSveVLSBuiltinType())
8857 return Error(E);
8858
8859 APSInt Index;
8860 bool Success = true;
8861
8862 // C++17's rules require us to evaluate the LHS first, regardless of which
8863 // side is the base.
8864 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8865 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8866 : !EvaluateInteger(SubExpr, Index, Info)) {
8867 if (!Info.noteFailure())
8868 return false;
8869 Success = false;
8870 }
8871 }
8872
8873 return Success &&
8874 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8875}
8876
8877bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8878 return evaluatePointer(E->getSubExpr(), Result);
8879}
8880
8881bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8882 if (!Visit(E->getSubExpr()))
8883 return false;
8884 // __real is a no-op on scalar lvalues.
8885 if (E->getSubExpr()->getType()->isAnyComplexType())
8886 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8887 return true;
8888}
8889
8890bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8891 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8892 "lvalue __imag__ on scalar?");
8893 if (!Visit(E->getSubExpr()))
8894 return false;
8895 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8896 return true;
8897}
8898
8899bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8900 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8901 return Error(UO);
8902
8903 if (!this->Visit(UO->getSubExpr()))
8904 return false;
8905
8906 return handleIncDec(
8907 this->Info, UO, Result, UO->getSubExpr()->getType(),
8908 UO->isIncrementOp(), nullptr);
8909}
8910
8911bool LValueExprEvaluator::VisitCompoundAssignOperator(
8912 const CompoundAssignOperator *CAO) {
8913 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8914 return Error(CAO);
8915
8916 bool Success = true;
8917
8918 // C++17 onwards require that we evaluate the RHS first.
8919 APValue RHS;
8920 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8921 if (!Info.noteFailure())
8922 return false;
8923 Success = false;
8924 }
8925
8926 // The overall lvalue result is the result of evaluating the LHS.
8927 if (!this->Visit(CAO->getLHS()) || !Success)
8928 return false;
8929
8931 this->Info, CAO,
8932 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8933 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8934}
8935
8936bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8937 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8938 return Error(E);
8939
8940 bool Success = true;
8941
8942 // C++17 onwards require that we evaluate the RHS first.
8943 APValue NewVal;
8944 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8945 if (!Info.noteFailure())
8946 return false;
8947 Success = false;
8948 }
8949
8950 if (!this->Visit(E->getLHS()) || !Success)
8951 return false;
8952
8953 if (Info.getLangOpts().CPlusPlus20 &&
8954 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8955 return false;
8956
8957 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8958 NewVal);
8959}
8960
8961//===----------------------------------------------------------------------===//
8962// Pointer Evaluation
8963//===----------------------------------------------------------------------===//
8964
8965/// Attempts to compute the number of bytes available at the pointer
8966/// returned by a function with the alloc_size attribute. Returns true if we
8967/// were successful. Places an unsigned number into `Result`.
8968///
8969/// This expects the given CallExpr to be a call to a function with an
8970/// alloc_size attribute.
8972 const CallExpr *Call,
8973 llvm::APInt &Result) {
8974 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8975
8976 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8977 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8978 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8979 if (Call->getNumArgs() <= SizeArgNo)
8980 return false;
8981
8982 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8985 return false;
8986 Into = ExprResult.Val.getInt();
8987 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8988 return false;
8989 Into = Into.zext(BitsInSizeT);
8990 return true;
8991 };
8992
8993 APSInt SizeOfElem;
8994 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8995 return false;
8996
8997 if (!AllocSize->getNumElemsParam().isValid()) {
8998 Result = std::move(SizeOfElem);
8999 return true;
9000 }
9001
9002 APSInt NumberOfElems;
9003 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9004 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9005 return false;
9006
9007 bool Overflow;
9008 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
9009 if (Overflow)
9010 return false;
9011
9012 Result = std::move(BytesAvailable);
9013 return true;
9014}
9015
9016/// Convenience function. LVal's base must be a call to an alloc_size
9017/// function.
9019 const LValue &LVal,
9020 llvm::APInt &Result) {
9021 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9022 "Can't get the size of a non alloc_size function");
9023 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9024 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9025 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
9026}
9027
9028/// Attempts to evaluate the given LValueBase as the result of a call to
9029/// a function with the alloc_size attribute. If it was possible to do so, this
9030/// function will return true, make Result's Base point to said function call,
9031/// and mark Result's Base as invalid.
9033 LValue &Result) {
9034 if (Base.isNull())
9035 return false;
9036
9037 // Because we do no form of static analysis, we only support const variables.
9038 //
9039 // Additionally, we can't support parameters, nor can we support static
9040 // variables (in the latter case, use-before-assign isn't UB; in the former,
9041 // we have no clue what they'll be assigned to).
9042 const auto *VD =
9043 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9044 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9045 return false;
9046
9047 const Expr *Init = VD->getAnyInitializer();
9048 if (!Init || Init->getType().isNull())
9049 return false;
9050
9051 const Expr *E = Init->IgnoreParens();
9052 if (!tryUnwrapAllocSizeCall(E))
9053 return false;
9054
9055 // Store E instead of E unwrapped so that the type of the LValue's base is
9056 // what the user wanted.
9057 Result.setInvalid(E);
9058
9059 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9060 Result.addUnsizedArray(Info, E, Pointee);
9061 return true;
9062}
9063
9064namespace {
9065class PointerExprEvaluator
9066 : public ExprEvaluatorBase<PointerExprEvaluator> {
9067 LValue &Result;
9068 bool InvalidBaseOK;
9069
9070 bool Success(const Expr *E) {
9071 Result.set(E);
9072 return true;
9073 }
9074
9075 bool evaluateLValue(const Expr *E, LValue &Result) {
9076 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9077 }
9078
9079 bool evaluatePointer(const Expr *E, LValue &Result) {
9080 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9081 }
9082
9083 bool visitNonBuiltinCallExpr(const CallExpr *E);
9084public:
9085
9086 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9087 : ExprEvaluatorBaseTy(info), Result(Result),
9088 InvalidBaseOK(InvalidBaseOK) {}
9089
9090 bool Success(const APValue &V, const Expr *E) {
9091 Result.setFrom(Info.Ctx, V);
9092 return true;
9093 }
9094 bool ZeroInitialization(const Expr *E) {
9095 Result.setNull(Info.Ctx, E->getType());
9096 return true;
9097 }
9098
9099 bool VisitBinaryOperator(const BinaryOperator *E);
9100 bool VisitCastExpr(const CastExpr* E);
9101 bool VisitUnaryAddrOf(const UnaryOperator *E);
9102 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9103 { return Success(E); }
9104 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9105 if (E->isExpressibleAsConstantInitializer())
9106 return Success(E);
9107 if (Info.noteFailure())
9108 EvaluateIgnoredValue(Info, E->getSubExpr());
9109 return Error(E);
9110 }
9111 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9112 { return Success(E); }
9113 bool VisitCallExpr(const CallExpr *E);
9114 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9115 bool VisitBlockExpr(const BlockExpr *E) {
9116 if (!E->getBlockDecl()->hasCaptures())
9117 return Success(E);
9118 return Error(E);
9119 }
9120 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9121 auto DiagnoseInvalidUseOfThis = [&] {
9122 if (Info.getLangOpts().CPlusPlus11)
9123 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9124 else
9125 Info.FFDiag(E);
9126 };
9127
9128 // Can't look at 'this' when checking a potential constant expression.
9129 if (Info.checkingPotentialConstantExpression())
9130 return false;
9131
9132 bool IsExplicitLambda =
9133 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9134 if (!IsExplicitLambda) {
9135 if (!Info.CurrentCall->This) {
9136 DiagnoseInvalidUseOfThis();
9137 return false;
9138 }
9139
9140 Result = *Info.CurrentCall->This;
9141 }
9142
9143 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9144 // Ensure we actually have captured 'this'. If something was wrong with
9145 // 'this' capture, the error would have been previously reported.
9146 // Otherwise we can be inside of a default initialization of an object
9147 // declared by lambda's body, so no need to return false.
9148 if (!Info.CurrentCall->LambdaThisCaptureField) {
9149 if (IsExplicitLambda && !Info.CurrentCall->This) {
9150 DiagnoseInvalidUseOfThis();
9151 return false;
9152 }
9153
9154 return true;
9155 }
9156
9157 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9158 return HandleLambdaCapture(
9159 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9160 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9161 }
9162 return true;
9163 }
9164
9165 bool VisitCXXNewExpr(const CXXNewExpr *E);
9166
9167 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9168 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9169 APValue LValResult = E->EvaluateInContext(
9170 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9171 Result.setFrom(Info.Ctx, LValResult);
9172 return true;
9173 }
9174
9175 bool VisitEmbedExpr(const EmbedExpr *E) {
9176 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9177 return true;
9178 }
9179
9180 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9181 std::string ResultStr = E->ComputeName(Info.Ctx);
9182
9183 QualType CharTy = Info.Ctx.CharTy.withConst();
9184 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9185 ResultStr.size() + 1);
9186 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9187 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9188
9189 StringLiteral *SL =
9190 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9191 /*Pascal*/ false, ArrayTy, E->getLocation());
9192
9193 evaluateLValue(SL, Result);
9194 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9195 return true;
9196 }
9197
9198 // FIXME: Missing: @protocol, @selector
9199};
9200} // end anonymous namespace
9201
9202static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9203 bool InvalidBaseOK) {
9204 assert(!E->isValueDependent());
9205 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9206 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9207}
9208
9209bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9210 if (E->getOpcode() != BO_Add &&
9211 E->getOpcode() != BO_Sub)
9212 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9213
9214 const Expr *PExp = E->getLHS();
9215 const Expr *IExp = E->getRHS();
9216 if (IExp->getType()->isPointerType())
9217 std::swap(PExp, IExp);
9218
9219 bool EvalPtrOK = evaluatePointer(PExp, Result);
9220 if (!EvalPtrOK && !Info.noteFailure())
9221 return false;
9222
9223 llvm::APSInt Offset;
9224 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9225 return false;
9226
9227 if (E->getOpcode() == BO_Sub)
9228 negateAsSigned(Offset);
9229
9230 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9231 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9232}
9233
9234bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9235 return evaluateLValue(E->getSubExpr(), Result);
9236}
9237
9238// Is the provided decl 'std::source_location::current'?
9240 if (!FD)
9241 return false;
9242 const IdentifierInfo *FnII = FD->getIdentifier();
9243 if (!FnII || !FnII->isStr("current"))
9244 return false;
9245
9246 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9247 if (!RD)
9248 return false;
9249
9250 const IdentifierInfo *ClassII = RD->getIdentifier();
9251 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9252}
9253
9254bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9255 const Expr *SubExpr = E->getSubExpr();
9256
9257 switch (E->getCastKind()) {
9258 default:
9259 break;
9260 case CK_BitCast:
9261 case CK_CPointerToObjCPointerCast:
9262 case CK_BlockPointerToObjCPointerCast:
9263 case CK_AnyPointerToBlockPointerCast:
9264 case CK_AddressSpaceConversion:
9265 if (!Visit(SubExpr))
9266 return false;
9267 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9268 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9269 // also static_casts, but we disallow them as a resolution to DR1312.
9270 if (!E->getType()->isVoidPointerType()) {
9271 // In some circumstances, we permit casting from void* to cv1 T*, when the
9272 // actual pointee object is actually a cv2 T.
9273 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9274 !Result.IsNullPtr;
9275 bool VoidPtrCastMaybeOK =
9276 Result.IsNullPtr ||
9277 (HasValidResult &&
9278 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9279 E->getType()->getPointeeType()));
9280 // 1. We'll allow it in std::allocator::allocate, and anything which that
9281 // calls.
9282 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9283 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9284 // We'll allow it in the body of std::source_location::current. GCC's
9285 // implementation had a parameter of type `void*`, and casts from
9286 // that back to `const __impl*` in its body.
9287 if (VoidPtrCastMaybeOK &&
9288 (Info.getStdAllocatorCaller("allocate") ||
9289 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9290 Info.getLangOpts().CPlusPlus26)) {
9291 // Permitted.
9292 } else {
9293 if (SubExpr->getType()->isVoidPointerType() &&
9294 Info.getLangOpts().CPlusPlus) {
9295 if (HasValidResult)
9296 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9297 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9298 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9299 << E->getType()->getPointeeType();
9300 else
9301 CCEDiag(E, diag::note_constexpr_invalid_cast)
9302 << 3 << SubExpr->getType();
9303 } else
9304 CCEDiag(E, diag::note_constexpr_invalid_cast)
9305 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9306 Result.Designator.setInvalid();
9307 }
9308 }
9309 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9310 ZeroInitialization(E);
9311 return true;
9312
9313 case CK_DerivedToBase:
9314 case CK_UncheckedDerivedToBase:
9315 if (!evaluatePointer(E->getSubExpr(), Result))
9316 return false;
9317 if (!Result.Base && Result.Offset.isZero())
9318 return true;
9319
9320 // Now figure out the necessary offset to add to the base LV to get from
9321 // the derived class to the base class.
9322 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9323 castAs<PointerType>()->getPointeeType(),
9324 Result);
9325
9326 case CK_BaseToDerived:
9327 if (!Visit(E->getSubExpr()))
9328 return false;
9329 if (!Result.Base && Result.Offset.isZero())
9330 return true;
9331 return HandleBaseToDerivedCast(Info, E, Result);
9332
9333 case CK_Dynamic:
9334 if (!Visit(E->getSubExpr()))
9335 return false;
9336 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9337
9338 case CK_NullToPointer:
9339 VisitIgnoredValue(E->getSubExpr());
9340 return ZeroInitialization(E);
9341
9342 case CK_IntegralToPointer: {
9343 CCEDiag(E, diag::note_constexpr_invalid_cast)
9344 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9345
9346 APValue Value;
9347 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9348 break;
9349
9350 if (Value.isInt()) {
9351 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9352 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9353 Result.Base = (Expr*)nullptr;
9354 Result.InvalidBase = false;
9355 Result.Offset = CharUnits::fromQuantity(N);
9356 Result.Designator.setInvalid();
9357 Result.IsNullPtr = false;
9358 return true;
9359 } else {
9360 // In rare instances, the value isn't an lvalue.
9361 // For example, when the value is the difference between the addresses of
9362 // two labels. We reject that as a constant expression because we can't
9363 // compute a valid offset to convert into a pointer.
9364 if (!Value.isLValue())
9365 return false;
9366
9367 // Cast is of an lvalue, no need to change value.
9368 Result.setFrom(Info.Ctx, Value);
9369 return true;
9370 }
9371 }
9372
9373 case CK_ArrayToPointerDecay: {
9374 if (SubExpr->isGLValue()) {
9375 if (!evaluateLValue(SubExpr, Result))
9376 return false;
9377 } else {
9378 APValue &Value = Info.CurrentCall->createTemporary(
9379 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9380 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9381 return false;
9382 }
9383 // The result is a pointer to the first element of the array.
9384 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9385 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9386 Result.addArray(Info, E, CAT);
9387 else
9388 Result.addUnsizedArray(Info, E, AT->getElementType());
9389 return true;
9390 }
9391
9392 case CK_FunctionToPointerDecay:
9393 return evaluateLValue(SubExpr, Result);
9394
9395 case CK_LValueToRValue: {
9396 LValue LVal;
9397 if (!evaluateLValue(E->getSubExpr(), LVal))
9398 return false;
9399
9400 APValue RVal;
9401 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9402 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9403 LVal, RVal))
9404 return InvalidBaseOK &&
9405 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9406 return Success(RVal, E);
9407 }
9408 }
9409
9410 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9411}
9412
9413static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9414 UnaryExprOrTypeTrait ExprKind) {
9415 // C++ [expr.alignof]p3:
9416 // When alignof is applied to a reference type, the result is the
9417 // alignment of the referenced type.
9418 T = T.getNonReferenceType();
9419
9420 if (T.getQualifiers().hasUnaligned())
9421 return CharUnits::One();
9422
9423 const bool AlignOfReturnsPreferred =
9424 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9425
9426 // __alignof is defined to return the preferred alignment.
9427 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9428 // as well.
9429 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9430 return Info.Ctx.toCharUnitsFromBits(
9431 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9432 // alignof and _Alignof are defined to return the ABI alignment.
9433 else if (ExprKind == UETT_AlignOf)
9434 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9435 else
9436 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9437}
9438
9439static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9440 UnaryExprOrTypeTrait ExprKind) {
9441 E = E->IgnoreParens();
9442
9443 // The kinds of expressions that we have special-case logic here for
9444 // should be kept up to date with the special checks for those
9445 // expressions in Sema.
9446
9447 // alignof decl is always accepted, even if it doesn't make sense: we default
9448 // to 1 in those cases.
9449 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9450 return Info.Ctx.getDeclAlign(DRE->getDecl(),
9451 /*RefAsPointee*/true);
9452
9453 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9454 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9455 /*RefAsPointee*/true);
9456
9457 return GetAlignOfType(Info, E->getType(), ExprKind);
9458}
9459
9460static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9461 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9462 return Info.Ctx.getDeclAlign(VD);
9463 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9464 return GetAlignOfExpr(Info, E, UETT_AlignOf);
9465 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9466}
9467
9468/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9469/// __builtin_is_aligned and __builtin_assume_aligned.
9470static bool getAlignmentArgument(const Expr *E, QualType ForType,
9471 EvalInfo &Info, APSInt &Alignment) {
9472 if (!EvaluateInteger(E, Alignment, Info))
9473 return false;
9474 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9475 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9476 return false;
9477 }
9478 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9479 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9480 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9481 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9482 << MaxValue << ForType << Alignment;
9483 return false;
9484 }
9485 // Ensure both alignment and source value have the same bit width so that we
9486 // don't assert when computing the resulting value.
9487 APSInt ExtAlignment =
9488 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9489 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9490 "Alignment should not be changed by ext/trunc");
9491 Alignment = ExtAlignment;
9492 assert(Alignment.getBitWidth() == SrcWidth);
9493 return true;
9494}
9495
9496// To be clear: this happily visits unsupported builtins. Better name welcomed.
9497bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9498 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9499 return true;
9500
9501 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9502 return false;
9503
9504 Result.setInvalid(E);
9505 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9506 Result.addUnsizedArray(Info, E, PointeeTy);
9507 return true;
9508}
9509
9510bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9511 if (!IsConstantEvaluatedBuiltinCall(E))
9512 return visitNonBuiltinCallExpr(E);
9513 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9514}
9515
9516// Determine if T is a character type for which we guarantee that
9517// sizeof(T) == 1.
9519 return T->isCharType() || T->isChar8Type();
9520}
9521
9522bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9523 unsigned BuiltinOp) {
9524 if (IsNoOpCall(E))
9525 return Success(E);
9526
9527 switch (BuiltinOp) {
9528 case Builtin::BIaddressof:
9529 case Builtin::BI__addressof:
9530 case Builtin::BI__builtin_addressof:
9531 return evaluateLValue(E->getArg(0), Result);
9532 case Builtin::BI__builtin_assume_aligned: {
9533 // We need to be very careful here because: if the pointer does not have the
9534 // asserted alignment, then the behavior is undefined, and undefined
9535 // behavior is non-constant.
9536 if (!evaluatePointer(E->getArg(0), Result))
9537 return false;
9538
9539 LValue OffsetResult(Result);
9540 APSInt Alignment;
9541 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9542 Alignment))
9543 return false;
9544 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9545
9546 if (E->getNumArgs() > 2) {
9547 APSInt Offset;
9548 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9549 return false;
9550
9551 int64_t AdditionalOffset = -Offset.getZExtValue();
9552 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9553 }
9554
9555 // If there is a base object, then it must have the correct alignment.
9556 if (OffsetResult.Base) {
9557 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9558
9559 if (BaseAlignment < Align) {
9560 Result.Designator.setInvalid();
9561 // FIXME: Add support to Diagnostic for long / long long.
9562 CCEDiag(E->getArg(0),
9563 diag::note_constexpr_baa_insufficient_alignment) << 0
9564 << (unsigned)BaseAlignment.getQuantity()
9565 << (unsigned)Align.getQuantity();
9566 return false;
9567 }
9568 }
9569
9570 // The offset must also have the correct alignment.
9571 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9572 Result.Designator.setInvalid();
9573
9574 (OffsetResult.Base
9575 ? CCEDiag(E->getArg(0),
9576 diag::note_constexpr_baa_insufficient_alignment) << 1
9577 : CCEDiag(E->getArg(0),
9578 diag::note_constexpr_baa_value_insufficient_alignment))
9579 << (int)OffsetResult.Offset.getQuantity()
9580 << (unsigned)Align.getQuantity();
9581 return false;
9582 }
9583
9584 return true;
9585 }
9586 case Builtin::BI__builtin_align_up:
9587 case Builtin::BI__builtin_align_down: {
9588 if (!evaluatePointer(E->getArg(0), Result))
9589 return false;
9590 APSInt Alignment;
9591 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9592 Alignment))
9593 return false;
9594 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9595 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9596 // For align_up/align_down, we can return the same value if the alignment
9597 // is known to be greater or equal to the requested value.
9598 if (PtrAlign.getQuantity() >= Alignment)
9599 return true;
9600
9601 // The alignment could be greater than the minimum at run-time, so we cannot
9602 // infer much about the resulting pointer value. One case is possible:
9603 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9604 // can infer the correct index if the requested alignment is smaller than
9605 // the base alignment so we can perform the computation on the offset.
9606 if (BaseAlignment.getQuantity() >= Alignment) {
9607 assert(Alignment.getBitWidth() <= 64 &&
9608 "Cannot handle > 64-bit address-space");
9609 uint64_t Alignment64 = Alignment.getZExtValue();
9611 BuiltinOp == Builtin::BI__builtin_align_down
9612 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9613 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9614 Result.adjustOffset(NewOffset - Result.Offset);
9615 // TODO: diagnose out-of-bounds values/only allow for arrays?
9616 return true;
9617 }
9618 // Otherwise, we cannot constant-evaluate the result.
9619 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9620 << Alignment;
9621 return false;
9622 }
9623 case Builtin::BI__builtin_operator_new:
9624 return HandleOperatorNewCall(Info, E, Result);
9625 case Builtin::BI__builtin_launder:
9626 return evaluatePointer(E->getArg(0), Result);
9627 case Builtin::BIstrchr:
9628 case Builtin::BIwcschr:
9629 case Builtin::BImemchr:
9630 case Builtin::BIwmemchr:
9631 if (Info.getLangOpts().CPlusPlus11)
9632 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9633 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9634 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9635 else
9636 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9637 [[fallthrough]];
9638 case Builtin::BI__builtin_strchr:
9639 case Builtin::BI__builtin_wcschr:
9640 case Builtin::BI__builtin_memchr:
9641 case Builtin::BI__builtin_char_memchr:
9642 case Builtin::BI__builtin_wmemchr: {
9643 if (!Visit(E->getArg(0)))
9644 return false;
9645 APSInt Desired;
9646 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9647 return false;
9648 uint64_t MaxLength = uint64_t(-1);
9649 if (BuiltinOp != Builtin::BIstrchr &&
9650 BuiltinOp != Builtin::BIwcschr &&
9651 BuiltinOp != Builtin::BI__builtin_strchr &&
9652 BuiltinOp != Builtin::BI__builtin_wcschr) {
9653 APSInt N;
9654 if (!EvaluateInteger(E->getArg(2), N, Info))
9655 return false;
9656 MaxLength = N.getZExtValue();
9657 }
9658 // We cannot find the value if there are no candidates to match against.
9659 if (MaxLength == 0u)
9660 return ZeroInitialization(E);
9661 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9662 Result.Designator.Invalid)
9663 return false;
9664 QualType CharTy = Result.Designator.getType(Info.Ctx);
9665 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9666 BuiltinOp == Builtin::BI__builtin_memchr;
9667 assert(IsRawByte ||
9668 Info.Ctx.hasSameUnqualifiedType(
9669 CharTy, E->getArg(0)->getType()->getPointeeType()));
9670 // Pointers to const void may point to objects of incomplete type.
9671 if (IsRawByte && CharTy->isIncompleteType()) {
9672 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9673 return false;
9674 }
9675 // Give up on byte-oriented matching against multibyte elements.
9676 // FIXME: We can compare the bytes in the correct order.
9677 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9678 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9679 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9680 << CharTy;
9681 return false;
9682 }
9683 // Figure out what value we're actually looking for (after converting to
9684 // the corresponding unsigned type if necessary).
9685 uint64_t DesiredVal;
9686 bool StopAtNull = false;
9687 switch (BuiltinOp) {
9688 case Builtin::BIstrchr:
9689 case Builtin::BI__builtin_strchr:
9690 // strchr compares directly to the passed integer, and therefore
9691 // always fails if given an int that is not a char.
9692 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9693 E->getArg(1)->getType(),
9694 Desired),
9695 Desired))
9696 return ZeroInitialization(E);
9697 StopAtNull = true;
9698 [[fallthrough]];
9699 case Builtin::BImemchr:
9700 case Builtin::BI__builtin_memchr:
9701 case Builtin::BI__builtin_char_memchr:
9702 // memchr compares by converting both sides to unsigned char. That's also
9703 // correct for strchr if we get this far (to cope with plain char being
9704 // unsigned in the strchr case).
9705 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9706 break;
9707
9708 case Builtin::BIwcschr:
9709 case Builtin::BI__builtin_wcschr:
9710 StopAtNull = true;
9711 [[fallthrough]];
9712 case Builtin::BIwmemchr:
9713 case Builtin::BI__builtin_wmemchr:
9714 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9715 DesiredVal = Desired.getZExtValue();
9716 break;
9717 }
9718
9719 for (; MaxLength; --MaxLength) {
9720 APValue Char;
9721 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9722 !Char.isInt())
9723 return false;
9724 if (Char.getInt().getZExtValue() == DesiredVal)
9725 return true;
9726 if (StopAtNull && !Char.getInt())
9727 break;
9728 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9729 return false;
9730 }
9731 // Not found: return nullptr.
9732 return ZeroInitialization(E);
9733 }
9734
9735 case Builtin::BImemcpy:
9736 case Builtin::BImemmove:
9737 case Builtin::BIwmemcpy:
9738 case Builtin::BIwmemmove:
9739 if (Info.getLangOpts().CPlusPlus11)
9740 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9741 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9742 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9743 else
9744 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9745 [[fallthrough]];
9746 case Builtin::BI__builtin_memcpy:
9747 case Builtin::BI__builtin_memmove:
9748 case Builtin::BI__builtin_wmemcpy:
9749 case Builtin::BI__builtin_wmemmove: {
9750 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9751 BuiltinOp == Builtin::BIwmemmove ||
9752 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9753 BuiltinOp == Builtin::BI__builtin_wmemmove;
9754 bool Move = BuiltinOp == Builtin::BImemmove ||
9755 BuiltinOp == Builtin::BIwmemmove ||
9756 BuiltinOp == Builtin::BI__builtin_memmove ||
9757 BuiltinOp == Builtin::BI__builtin_wmemmove;
9758
9759 // The result of mem* is the first argument.
9760 if (!Visit(E->getArg(0)))
9761 return false;
9762 LValue Dest = Result;
9763
9764 LValue Src;
9765 if (!EvaluatePointer(E->getArg(1), Src, Info))
9766 return false;
9767
9768 APSInt N;
9769 if (!EvaluateInteger(E->getArg(2), N, Info))
9770 return false;
9771 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9772
9773 // If the size is zero, we treat this as always being a valid no-op.
9774 // (Even if one of the src and dest pointers is null.)
9775 if (!N)
9776 return true;
9777
9778 // Otherwise, if either of the operands is null, we can't proceed. Don't
9779 // try to determine the type of the copied objects, because there aren't
9780 // any.
9781 if (!Src.Base || !Dest.Base) {
9782 APValue Val;
9783 (!Src.Base ? Src : Dest).moveInto(Val);
9784 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9785 << Move << WChar << !!Src.Base
9786 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9787 return false;
9788 }
9789 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9790 return false;
9791
9792 // We require that Src and Dest are both pointers to arrays of
9793 // trivially-copyable type. (For the wide version, the designator will be
9794 // invalid if the designated object is not a wchar_t.)
9795 QualType T = Dest.Designator.getType(Info.Ctx);
9796 QualType SrcT = Src.Designator.getType(Info.Ctx);
9797 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9798 // FIXME: Consider using our bit_cast implementation to support this.
9799 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9800 return false;
9801 }
9802 if (T->isIncompleteType()) {
9803 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9804 return false;
9805 }
9806 if (!T.isTriviallyCopyableType(Info.Ctx)) {
9807 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9808 return false;
9809 }
9810
9811 // Figure out how many T's we're copying.
9812 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9813 if (TSize == 0)
9814 return false;
9815 if (!WChar) {
9816 uint64_t Remainder;
9817 llvm::APInt OrigN = N;
9818 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9819 if (Remainder) {
9820 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9821 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9822 << (unsigned)TSize;
9823 return false;
9824 }
9825 }
9826
9827 // Check that the copying will remain within the arrays, just so that we
9828 // can give a more meaningful diagnostic. This implicitly also checks that
9829 // N fits into 64 bits.
9830 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9831 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9832 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9833 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9834 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9835 << toString(N, 10, /*Signed*/false);
9836 return false;
9837 }
9838 uint64_t NElems = N.getZExtValue();
9839 uint64_t NBytes = NElems * TSize;
9840
9841 // Check for overlap.
9842 int Direction = 1;
9843 if (HasSameBase(Src, Dest)) {
9844 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9845 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9846 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9847 // Dest is inside the source region.
9848 if (!Move) {
9849 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9850 return false;
9851 }
9852 // For memmove and friends, copy backwards.
9853 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9854 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9855 return false;
9856 Direction = -1;
9857 } else if (!Move && SrcOffset >= DestOffset &&
9858 SrcOffset - DestOffset < NBytes) {
9859 // Src is inside the destination region for memcpy: invalid.
9860 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9861 return false;
9862 }
9863 }
9864
9865 while (true) {
9866 APValue Val;
9867 // FIXME: Set WantObjectRepresentation to true if we're copying a
9868 // char-like type?
9869 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9870 !handleAssignment(Info, E, Dest, T, Val))
9871 return false;
9872 // Do not iterate past the last element; if we're copying backwards, that
9873 // might take us off the start of the array.
9874 if (--NElems == 0)
9875 return true;
9876 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9877 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9878 return false;
9879 }
9880 }
9881
9882 default:
9883 return false;
9884 }
9885}
9886
9887static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9888 APValue &Result, const InitListExpr *ILE,
9889 QualType AllocType);
9890static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9891 APValue &Result,
9892 const CXXConstructExpr *CCE,
9893 QualType AllocType);
9894
9895bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9896 if (!Info.getLangOpts().CPlusPlus20)
9897 Info.CCEDiag(E, diag::note_constexpr_new);
9898
9899 // We cannot speculatively evaluate a delete expression.
9900 if (Info.SpeculativeEvaluationDepth)
9901 return false;
9902
9903 FunctionDecl *OperatorNew = E->getOperatorNew();
9904
9905 bool IsNothrow = false;
9906 bool IsPlacement = false;
9907 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9908 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9909 // FIXME Support array placement new.
9910 assert(E->getNumPlacementArgs() == 1);
9911 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9912 return false;
9913 if (Result.Designator.Invalid)
9914 return false;
9915 IsPlacement = true;
9916 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9917 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9918 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9919 return false;
9920 } else if (E->getNumPlacementArgs()) {
9921 // The only new-placement list we support is of the form (std::nothrow).
9922 //
9923 // FIXME: There is no restriction on this, but it's not clear that any
9924 // other form makes any sense. We get here for cases such as:
9925 //
9926 // new (std::align_val_t{N}) X(int)
9927 //
9928 // (which should presumably be valid only if N is a multiple of
9929 // alignof(int), and in any case can't be deallocated unless N is
9930 // alignof(X) and X has new-extended alignment).
9931 if (E->getNumPlacementArgs() != 1 ||
9932 !E->getPlacementArg(0)->getType()->isNothrowT())
9933 return Error(E, diag::note_constexpr_new_placement);
9934
9935 LValue Nothrow;
9936 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9937 return false;
9938 IsNothrow = true;
9939 }
9940
9941 const Expr *Init = E->getInitializer();
9942 const InitListExpr *ResizedArrayILE = nullptr;
9943 const CXXConstructExpr *ResizedArrayCCE = nullptr;
9944 bool ValueInit = false;
9945
9946 QualType AllocType = E->getAllocatedType();
9947 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9948 const Expr *Stripped = *ArraySize;
9949 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9950 Stripped = ICE->getSubExpr())
9951 if (ICE->getCastKind() != CK_NoOp &&
9952 ICE->getCastKind() != CK_IntegralCast)
9953 break;
9954
9955 llvm::APSInt ArrayBound;
9956 if (!EvaluateInteger(Stripped, ArrayBound, Info))
9957 return false;
9958
9959 // C++ [expr.new]p9:
9960 // The expression is erroneous if:
9961 // -- [...] its value before converting to size_t [or] applying the
9962 // second standard conversion sequence is less than zero
9963 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9964 if (IsNothrow)
9965 return ZeroInitialization(E);
9966
9967 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9968 << ArrayBound << (*ArraySize)->getSourceRange();
9969 return false;
9970 }
9971
9972 // -- its value is such that the size of the allocated object would
9973 // exceed the implementation-defined limit
9974 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
9976 Info.Ctx, AllocType, ArrayBound),
9977 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
9978 if (IsNothrow)
9979 return ZeroInitialization(E);
9980 return false;
9981 }
9982
9983 // -- the new-initializer is a braced-init-list and the number of
9984 // array elements for which initializers are provided [...]
9985 // exceeds the number of elements to initialize
9986 if (!Init) {
9987 // No initialization is performed.
9988 } else if (isa<CXXScalarValueInitExpr>(Init) ||
9989 isa<ImplicitValueInitExpr>(Init)) {
9990 ValueInit = true;
9991 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9992 ResizedArrayCCE = CCE;
9993 } else {
9994 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9995 assert(CAT && "unexpected type for array initializer");
9996
9997 unsigned Bits =
9998 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
9999 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10000 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10001 if (InitBound.ugt(AllocBound)) {
10002 if (IsNothrow)
10003 return ZeroInitialization(E);
10004
10005 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10006 << toString(AllocBound, 10, /*Signed=*/false)
10007 << toString(InitBound, 10, /*Signed=*/false)
10008 << (*ArraySize)->getSourceRange();
10009 return false;
10010 }
10011
10012 // If the sizes differ, we must have an initializer list, and we need
10013 // special handling for this case when we initialize.
10014 if (InitBound != AllocBound)
10015 ResizedArrayILE = cast<InitListExpr>(Init);
10016 }
10017
10018 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10019 ArraySizeModifier::Normal, 0);
10020 } else {
10021 assert(!AllocType->isArrayType() &&
10022 "array allocation with non-array new");
10023 }
10024
10025 APValue *Val;
10026 if (IsPlacement) {
10028 struct FindObjectHandler {
10029 EvalInfo &Info;
10030 const Expr *E;
10031 QualType AllocType;
10032 const AccessKinds AccessKind;
10033 APValue *Value;
10034
10035 typedef bool result_type;
10036 bool failed() { return false; }
10037 bool found(APValue &Subobj, QualType SubobjType) {
10038 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10039 // old name of the object to be used to name the new object.
10040 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
10041 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
10042 SubobjType << AllocType;
10043 return false;
10044 }
10045 Value = &Subobj;
10046 return true;
10047 }
10048 bool found(APSInt &Value, QualType SubobjType) {
10049 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10050 return false;
10051 }
10052 bool found(APFloat &Value, QualType SubobjType) {
10053 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10054 return false;
10055 }
10056 } Handler = {Info, E, AllocType, AK, nullptr};
10057
10058 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10059 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10060 return false;
10061
10062 Val = Handler.Value;
10063
10064 // [basic.life]p1:
10065 // The lifetime of an object o of type T ends when [...] the storage
10066 // which the object occupies is [...] reused by an object that is not
10067 // nested within o (6.6.2).
10068 *Val = APValue();
10069 } else {
10070 // Perform the allocation and obtain a pointer to the resulting object.
10071 Val = Info.createHeapAlloc(E, AllocType, Result);
10072 if (!Val)
10073 return false;
10074 }
10075
10076 if (ValueInit) {
10077 ImplicitValueInitExpr VIE(AllocType);
10078 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10079 return false;
10080 } else if (ResizedArrayILE) {
10081 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10082 AllocType))
10083 return false;
10084 } else if (ResizedArrayCCE) {
10085 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10086 AllocType))
10087 return false;
10088 } else if (Init) {
10089 if (!EvaluateInPlace(*Val, Info, Result, Init))
10090 return false;
10091 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10092 return false;
10093 }
10094
10095 // Array new returns a pointer to the first element, not a pointer to the
10096 // array.
10097 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10098 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10099
10100 return true;
10101}
10102//===----------------------------------------------------------------------===//
10103// Member Pointer Evaluation
10104//===----------------------------------------------------------------------===//
10105
10106namespace {
10107class MemberPointerExprEvaluator
10108 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10109 MemberPtr &Result;
10110
10111 bool Success(const ValueDecl *D) {
10112 Result = MemberPtr(D);
10113 return true;
10114 }
10115public:
10116
10117 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10118 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10119
10120 bool Success(const APValue &V, const Expr *E) {
10121 Result.setFrom(V);
10122 return true;
10123 }
10124 bool ZeroInitialization(const Expr *E) {
10125 return Success((const ValueDecl*)nullptr);
10126 }
10127
10128 bool VisitCastExpr(const CastExpr *E);
10129 bool VisitUnaryAddrOf(const UnaryOperator *E);
10130};
10131} // end anonymous namespace
10132
10133static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10134 EvalInfo &Info) {
10135 assert(!E->isValueDependent());
10136 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10137 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10138}
10139
10140bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10141 switch (E->getCastKind()) {
10142 default:
10143 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10144
10145 case CK_NullToMemberPointer:
10146 VisitIgnoredValue(E->getSubExpr());
10147 return ZeroInitialization(E);
10148
10149 case CK_BaseToDerivedMemberPointer: {
10150 if (!Visit(E->getSubExpr()))
10151 return false;
10152 if (E->path_empty())
10153 return true;
10154 // Base-to-derived member pointer casts store the path in derived-to-base
10155 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10156 // the wrong end of the derived->base arc, so stagger the path by one class.
10157 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10158 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10159 PathI != PathE; ++PathI) {
10160 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10161 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10162 if (!Result.castToDerived(Derived))
10163 return Error(E);
10164 }
10165 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10166 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10167 return Error(E);
10168 return true;
10169 }
10170
10171 case CK_DerivedToBaseMemberPointer:
10172 if (!Visit(E->getSubExpr()))
10173 return false;
10174 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10175 PathE = E->path_end(); PathI != PathE; ++PathI) {
10176 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10177 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10178 if (!Result.castToBase(Base))
10179 return Error(E);
10180 }
10181 return true;
10182 }
10183}
10184
10185bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10186 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10187 // member can be formed.
10188 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10189}
10190
10191//===----------------------------------------------------------------------===//
10192// Record Evaluation
10193//===----------------------------------------------------------------------===//
10194
10195namespace {
10196 class RecordExprEvaluator
10197 : public ExprEvaluatorBase<RecordExprEvaluator> {
10198 const LValue &This;
10199 APValue &Result;
10200 public:
10201
10202 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10203 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10204
10205 bool Success(const APValue &V, const Expr *E) {
10206 Result = V;
10207 return true;
10208 }
10209 bool ZeroInitialization(const Expr *E) {
10210 return ZeroInitialization(E, E->getType());
10211 }
10212 bool ZeroInitialization(const Expr *E, QualType T);
10213
10214 bool VisitCallExpr(const CallExpr *E) {
10215 return handleCallExpr(E, Result, &This);
10216 }
10217 bool VisitCastExpr(const CastExpr *E);
10218 bool VisitInitListExpr(const InitListExpr *E);
10219 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10220 return VisitCXXConstructExpr(E, E->getType());
10221 }
10222 bool VisitLambdaExpr(const LambdaExpr *E);
10223 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10224 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10225 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10226 bool VisitBinCmp(const BinaryOperator *E);
10227 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10228 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10229 ArrayRef<Expr *> Args);
10230 };
10231}
10232
10233/// Perform zero-initialization on an object of non-union class type.
10234/// C++11 [dcl.init]p5:
10235/// To zero-initialize an object or reference of type T means:
10236/// [...]
10237/// -- if T is a (possibly cv-qualified) non-union class type,
10238/// each non-static data member and each base-class subobject is
10239/// zero-initialized
10240static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10241 const RecordDecl *RD,
10242 const LValue &This, APValue &Result) {
10243 assert(!RD->isUnion() && "Expected non-union class type");
10244 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10245 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10246 std::distance(RD->field_begin(), RD->field_end()));
10247
10248 if (RD->isInvalidDecl()) return false;
10249 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10250
10251 if (CD) {
10252 unsigned Index = 0;
10254 End = CD->bases_end(); I != End; ++I, ++Index) {
10255 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10256 LValue Subobject = This;
10257 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10258 return false;
10259 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10260 Result.getStructBase(Index)))
10261 return false;
10262 }
10263 }
10264
10265 for (const auto *I : RD->fields()) {
10266 // -- if T is a reference type, no initialization is performed.
10267 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10268 continue;
10269
10270 LValue Subobject = This;
10271 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10272 return false;
10273
10274 ImplicitValueInitExpr VIE(I->getType());
10275 if (!EvaluateInPlace(
10276 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10277 return false;
10278 }
10279
10280 return true;
10281}
10282
10283bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10284 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10285 if (RD->isInvalidDecl()) return false;
10286 if (RD->isUnion()) {
10287 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10288 // object's first non-static named data member is zero-initialized
10290 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10291 ++I;
10292 if (I == RD->field_end()) {
10293 Result = APValue((const FieldDecl*)nullptr);
10294 return true;
10295 }
10296
10297 LValue Subobject = This;
10298 if (!HandleLValueMember(Info, E, Subobject, *I))
10299 return false;
10300 Result = APValue(*I);
10301 ImplicitValueInitExpr VIE(I->getType());
10302 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10303 }
10304
10305 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10306 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10307 return false;
10308 }
10309
10310 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10311}
10312
10313bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10314 switch (E->getCastKind()) {
10315 default:
10316 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10317
10318 case CK_ConstructorConversion:
10319 return Visit(E->getSubExpr());
10320
10321 case CK_DerivedToBase:
10322 case CK_UncheckedDerivedToBase: {
10323 APValue DerivedObject;
10324 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10325 return false;
10326 if (!DerivedObject.isStruct())
10327 return Error(E->getSubExpr());
10328
10329 // Derived-to-base rvalue conversion: just slice off the derived part.
10330 APValue *Value = &DerivedObject;
10331 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10332 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10333 PathE = E->path_end(); PathI != PathE; ++PathI) {
10334 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10335 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10336 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10337 RD = Base;
10338 }
10339 Result = *Value;
10340 return true;
10341 }
10342 }
10343}
10344
10345bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10346 if (E->isTransparent())
10347 return Visit(E->getInit(0));
10348 return VisitCXXParenListOrInitListExpr(E, E->inits());
10349}
10350
10351bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10352 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10353 const RecordDecl *RD =
10354 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10355 if (RD->isInvalidDecl()) return false;
10356 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10357 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10358
10359 EvalInfo::EvaluatingConstructorRAII EvalObj(
10360 Info,
10361 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10362 CXXRD && CXXRD->getNumBases());
10363
10364 if (RD->isUnion()) {
10365 const FieldDecl *Field;
10366 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10367 Field = ILE->getInitializedFieldInUnion();
10368 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10369 Field = PLIE->getInitializedFieldInUnion();
10370 } else {
10371 llvm_unreachable(
10372 "Expression is neither an init list nor a C++ paren list");
10373 }
10374
10375 Result = APValue(Field);
10376 if (!Field)
10377 return true;
10378
10379 // If the initializer list for a union does not contain any elements, the
10380 // first element of the union is value-initialized.
10381 // FIXME: The element should be initialized from an initializer list.
10382 // Is this difference ever observable for initializer lists which
10383 // we don't build?
10384 ImplicitValueInitExpr VIE(Field->getType());
10385 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10386
10387 LValue Subobject = This;
10388 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10389 return false;
10390
10391 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10392 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10393 isa<CXXDefaultInitExpr>(InitExpr));
10394
10395 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10396 if (Field->isBitField())
10397 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10398 Field);
10399 return true;
10400 }
10401
10402 return false;
10403 }
10404
10405 if (!Result.hasValue())
10406 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10407 std::distance(RD->field_begin(), RD->field_end()));
10408 unsigned ElementNo = 0;
10409 bool Success = true;
10410
10411 // Initialize base classes.
10412 if (CXXRD && CXXRD->getNumBases()) {
10413 for (const auto &Base : CXXRD->bases()) {
10414 assert(ElementNo < Args.size() && "missing init for base class");
10415 const Expr *Init = Args[ElementNo];
10416
10417 LValue Subobject = This;
10418 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10419 return false;
10420
10421 APValue &FieldVal = Result.getStructBase(ElementNo);
10422 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10423 if (!Info.noteFailure())
10424 return false;
10425 Success = false;
10426 }
10427 ++ElementNo;
10428 }
10429
10430 EvalObj.finishedConstructingBases();
10431 }
10432
10433 // Initialize members.
10434 for (const auto *Field : RD->fields()) {
10435 // Anonymous bit-fields are not considered members of the class for
10436 // purposes of aggregate initialization.
10437 if (Field->isUnnamedBitField())
10438 continue;
10439
10440 LValue Subobject = This;
10441
10442 bool HaveInit = ElementNo < Args.size();
10443
10444 // FIXME: Diagnostics here should point to the end of the initializer
10445 // list, not the start.
10446 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10447 Subobject, Field, &Layout))
10448 return false;
10449
10450 // Perform an implicit value-initialization for members beyond the end of
10451 // the initializer list.
10452 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10453 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10454
10455 if (Field->getType()->isIncompleteArrayType()) {
10456 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10457 if (!CAT->isZeroSize()) {
10458 // Bail out for now. This might sort of "work", but the rest of the
10459 // code isn't really prepared to handle it.
10460 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10461 return false;
10462 }
10463 }
10464 }
10465
10466 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10467 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10468 isa<CXXDefaultInitExpr>(Init));
10469
10470 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10471 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10472 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10473 FieldVal, Field))) {
10474 if (!Info.noteFailure())
10475 return false;
10476 Success = false;
10477 }
10478 }
10479
10480 EvalObj.finishedConstructingFields();
10481
10482 return Success;
10483}
10484
10485bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10486 QualType T) {
10487 // Note that E's type is not necessarily the type of our class here; we might
10488 // be initializing an array element instead.
10489 const CXXConstructorDecl *FD = E->getConstructor();
10490 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10491
10492 bool ZeroInit = E->requiresZeroInitialization();
10493 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10494 // If we've already performed zero-initialization, we're already done.
10495 if (Result.hasValue())
10496 return true;
10497
10498 if (ZeroInit)
10499 return ZeroInitialization(E, T);
10500
10501 return handleDefaultInitValue(T, Result);
10502 }
10503
10504 const FunctionDecl *Definition = nullptr;
10505 auto Body = FD->getBody(Definition);
10506
10507 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10508 return false;
10509
10510 // Avoid materializing a temporary for an elidable copy/move constructor.
10511 if (E->isElidable() && !ZeroInit) {
10512 // FIXME: This only handles the simplest case, where the source object
10513 // is passed directly as the first argument to the constructor.
10514 // This should also handle stepping though implicit casts and
10515 // and conversion sequences which involve two steps, with a
10516 // conversion operator followed by a converting constructor.
10517 const Expr *SrcObj = E->getArg(0);
10518 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10519 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10520 if (const MaterializeTemporaryExpr *ME =
10521 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10522 return Visit(ME->getSubExpr());
10523 }
10524
10525 if (ZeroInit && !ZeroInitialization(E, T))
10526 return false;
10527
10528 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10529 return HandleConstructorCall(E, This, Args,
10530 cast<CXXConstructorDecl>(Definition), Info,
10531 Result);
10532}
10533
10534bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10535 const CXXInheritedCtorInitExpr *E) {
10536 if (!Info.CurrentCall) {
10537 assert(Info.checkingPotentialConstantExpression());
10538 return false;
10539 }
10540
10541 const CXXConstructorDecl *FD = E->getConstructor();
10542 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10543 return false;
10544
10545 const FunctionDecl *Definition = nullptr;
10546 auto Body = FD->getBody(Definition);
10547
10548 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10549 return false;
10550
10551 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10552 cast<CXXConstructorDecl>(Definition), Info,
10553 Result);
10554}
10555
10556bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10559 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10560
10561 LValue Array;
10562 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10563 return false;
10564
10565 assert(ArrayType && "unexpected type for array initializer");
10566
10567 // Get a pointer to the first element of the array.
10568 Array.addArray(Info, E, ArrayType);
10569
10570 // FIXME: What if the initializer_list type has base classes, etc?
10571 Result = APValue(APValue::UninitStruct(), 0, 2);
10572 Array.moveInto(Result.getStructField(0));
10573
10574 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10575 RecordDecl::field_iterator Field = Record->field_begin();
10576 assert(Field != Record->field_end() &&
10577 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10579 "Expected std::initializer_list first field to be const E *");
10580 ++Field;
10581 assert(Field != Record->field_end() &&
10582 "Expected std::initializer_list to have two fields");
10583
10584 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
10585 // Length.
10586 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10587 } else {
10588 // End pointer.
10589 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10591 "Expected std::initializer_list second field to be const E *");
10592 if (!HandleLValueArrayAdjustment(Info, E, Array,
10594 ArrayType->getZExtSize()))
10595 return false;
10596 Array.moveInto(Result.getStructField(1));
10597 }
10598
10599 assert(++Field == Record->field_end() &&
10600 "Expected std::initializer_list to only have two fields");
10601
10602 return true;
10603}
10604
10605bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10606 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10607 if (ClosureClass->isInvalidDecl())
10608 return false;
10609
10610 const size_t NumFields =
10611 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10612
10613 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10614 E->capture_init_end()) &&
10615 "The number of lambda capture initializers should equal the number of "
10616 "fields within the closure type");
10617
10618 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10619 // Iterate through all the lambda's closure object's fields and initialize
10620 // them.
10621 auto *CaptureInitIt = E->capture_init_begin();
10622 bool Success = true;
10623 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10624 for (const auto *Field : ClosureClass->fields()) {
10625 assert(CaptureInitIt != E->capture_init_end());
10626 // Get the initializer for this field
10627 Expr *const CurFieldInit = *CaptureInitIt++;
10628
10629 // If there is no initializer, either this is a VLA or an error has
10630 // occurred.
10631 if (!CurFieldInit)
10632 return Error(E);
10633
10634 LValue Subobject = This;
10635
10636 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10637 return false;
10638
10639 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10640 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10641 if (!Info.keepEvaluatingAfterFailure())
10642 return false;
10643 Success = false;
10644 }
10645 }
10646 return Success;
10647}
10648
10649static bool EvaluateRecord(const Expr *E, const LValue &This,
10650 APValue &Result, EvalInfo &Info) {
10651 assert(!E->isValueDependent());
10652 assert(E->isPRValue() && E->getType()->isRecordType() &&
10653 "can't evaluate expression as a record rvalue");
10654 return RecordExprEvaluator(Info, This, Result).Visit(E);
10655}
10656
10657//===----------------------------------------------------------------------===//
10658// Temporary Evaluation
10659//
10660// Temporaries are represented in the AST as rvalues, but generally behave like
10661// lvalues. The full-object of which the temporary is a subobject is implicitly
10662// materialized so that a reference can bind to it.
10663//===----------------------------------------------------------------------===//
10664namespace {
10665class TemporaryExprEvaluator
10666 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10667public:
10668 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10669 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10670
10671 /// Visit an expression which constructs the value of this temporary.
10672 bool VisitConstructExpr(const Expr *E) {
10673 APValue &Value = Info.CurrentCall->createTemporary(
10674 E, E->getType(), ScopeKind::FullExpression, Result);
10675 return EvaluateInPlace(Value, Info, Result, E);
10676 }
10677
10678 bool VisitCastExpr(const CastExpr *E) {
10679 switch (E->getCastKind()) {
10680 default:
10681 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10682
10683 case CK_ConstructorConversion:
10684 return VisitConstructExpr(E->getSubExpr());
10685 }
10686 }
10687 bool VisitInitListExpr(const InitListExpr *E) {
10688 return VisitConstructExpr(E);
10689 }
10690 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10691 return VisitConstructExpr(E);
10692 }
10693 bool VisitCallExpr(const CallExpr *E) {
10694 return VisitConstructExpr(E);
10695 }
10696 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10697 return VisitConstructExpr(E);
10698 }
10699 bool VisitLambdaExpr(const LambdaExpr *E) {
10700 return VisitConstructExpr(E);
10701 }
10702};
10703} // end anonymous namespace
10704
10705/// Evaluate an expression of record type as a temporary.
10706static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10707 assert(!E->isValueDependent());
10708 assert(E->isPRValue() && E->getType()->isRecordType());
10709 return TemporaryExprEvaluator(Info, Result).Visit(E);
10710}
10711
10712//===----------------------------------------------------------------------===//
10713// Vector Evaluation
10714//===----------------------------------------------------------------------===//
10715
10716namespace {
10717 class VectorExprEvaluator
10718 : public ExprEvaluatorBase<VectorExprEvaluator> {
10719 APValue &Result;
10720 public:
10721
10722 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10723 : ExprEvaluatorBaseTy(info), Result(Result) {}
10724
10725 bool Success(ArrayRef<APValue> V, const Expr *E) {
10726 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10727 // FIXME: remove this APValue copy.
10728 Result = APValue(V.data(), V.size());
10729 return true;
10730 }
10731 bool Success(const APValue &V, const Expr *E) {
10732 assert(V.isVector());
10733 Result = V;
10734 return true;
10735 }
10736 bool ZeroInitialization(const Expr *E);
10737
10738 bool VisitUnaryReal(const UnaryOperator *E)
10739 { return Visit(E->getSubExpr()); }
10740 bool VisitCastExpr(const CastExpr* E);
10741 bool VisitInitListExpr(const InitListExpr *E);
10742 bool VisitUnaryImag(const UnaryOperator *E);
10743 bool VisitBinaryOperator(const BinaryOperator *E);
10744 bool VisitUnaryOperator(const UnaryOperator *E);
10745 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
10746 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
10747
10748 // FIXME: Missing: conditional operator (for GNU
10749 // conditional select), ExtVectorElementExpr
10750 };
10751} // end anonymous namespace
10752
10753static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10754 assert(E->isPRValue() && E->getType()->isVectorType() &&
10755 "not a vector prvalue");
10756 return VectorExprEvaluator(Info, Result).Visit(E);
10757}
10758
10759bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10760 const VectorType *VTy = E->getType()->castAs<VectorType>();
10761 unsigned NElts = VTy->getNumElements();
10762
10763 const Expr *SE = E->getSubExpr();
10764 QualType SETy = SE->getType();
10765
10766 switch (E->getCastKind()) {
10767 case CK_VectorSplat: {
10768 APValue Val = APValue();
10769 if (SETy->isIntegerType()) {
10770 APSInt IntResult;
10771 if (!EvaluateInteger(SE, IntResult, Info))
10772 return false;
10773 Val = APValue(std::move(IntResult));
10774 } else if (SETy->isRealFloatingType()) {
10775 APFloat FloatResult(0.0);
10776 if (!EvaluateFloat(SE, FloatResult, Info))
10777 return false;
10778 Val = APValue(std::move(FloatResult));
10779 } else {
10780 return Error(E);
10781 }
10782
10783 // Splat and create vector APValue.
10784 SmallVector<APValue, 4> Elts(NElts, Val);
10785 return Success(Elts, E);
10786 }
10787 case CK_BitCast: {
10788 APValue SVal;
10789 if (!Evaluate(SVal, Info, SE))
10790 return false;
10791
10792 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
10793 // Give up if the input isn't an int, float, or vector. For example, we
10794 // reject "(v4i16)(intptr_t)&a".
10795 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
10796 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
10797 return false;
10798 }
10799
10800 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
10801 return false;
10802
10803 return true;
10804 }
10805 default:
10806 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10807 }
10808}
10809
10810bool
10811VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10812 const VectorType *VT = E->getType()->castAs<VectorType>();
10813 unsigned NumInits = E->getNumInits();
10814 unsigned NumElements = VT->getNumElements();
10815
10816 QualType EltTy = VT->getElementType();
10817 SmallVector<APValue, 4> Elements;
10818
10819 // The number of initializers can be less than the number of
10820 // vector elements. For OpenCL, this can be due to nested vector
10821 // initialization. For GCC compatibility, missing trailing elements
10822 // should be initialized with zeroes.
10823 unsigned CountInits = 0, CountElts = 0;
10824 while (CountElts < NumElements) {
10825 // Handle nested vector initialization.
10826 if (CountInits < NumInits
10827 && E->getInit(CountInits)->getType()->isVectorType()) {
10828 APValue v;
10829 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10830 return Error(E);
10831 unsigned vlen = v.getVectorLength();
10832 for (unsigned j = 0; j < vlen; j++)
10833 Elements.push_back(v.getVectorElt(j));
10834 CountElts += vlen;
10835 } else if (EltTy->isIntegerType()) {
10836 llvm::APSInt sInt(32);
10837 if (CountInits < NumInits) {
10838 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10839 return false;
10840 } else // trailing integer zero.
10841 sInt = Info.Ctx.MakeIntValue(0, EltTy);
10842 Elements.push_back(APValue(sInt));
10843 CountElts++;
10844 } else {
10845 llvm::APFloat f(0.0);
10846 if (CountInits < NumInits) {
10847 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10848 return false;
10849 } else // trailing float zero.
10850 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10851 Elements.push_back(APValue(f));
10852 CountElts++;
10853 }
10854 CountInits++;
10855 }
10856 return Success(Elements, E);
10857}
10858
10859bool
10860VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10861 const auto *VT = E->getType()->castAs<VectorType>();
10862 QualType EltTy = VT->getElementType();
10863 APValue ZeroElement;
10864 if (EltTy->isIntegerType())
10865 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10866 else
10867 ZeroElement =
10868 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10869
10870 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10871 return Success(Elements, E);
10872}
10873
10874bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10875 VisitIgnoredValue(E->getSubExpr());
10876 return ZeroInitialization(E);
10877}
10878
10879bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10880 BinaryOperatorKind Op = E->getOpcode();
10881 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10882 "Operation not supported on vector types");
10883
10884 if (Op == BO_Comma)
10885 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10886
10887 Expr *LHS = E->getLHS();
10888 Expr *RHS = E->getRHS();
10889
10890 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10891 "Must both be vector types");
10892 // Checking JUST the types are the same would be fine, except shifts don't
10893 // need to have their types be the same (since you always shift by an int).
10894 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10896 RHS->getType()->castAs<VectorType>()->getNumElements() ==
10898 "All operands must be the same size.");
10899
10900 APValue LHSValue;
10901 APValue RHSValue;
10902 bool LHSOK = Evaluate(LHSValue, Info, LHS);
10903 if (!LHSOK && !Info.noteFailure())
10904 return false;
10905 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10906 return false;
10907
10908 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10909 return false;
10910
10911 return Success(LHSValue, E);
10912}
10913
10914static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10915 QualType ResultTy,
10917 APValue Elt) {
10918 switch (Op) {
10919 case UO_Plus:
10920 // Nothing to do here.
10921 return Elt;
10922 case UO_Minus:
10923 if (Elt.getKind() == APValue::Int) {
10924 Elt.getInt().negate();
10925 } else {
10926 assert(Elt.getKind() == APValue::Float &&
10927 "Vector can only be int or float type");
10928 Elt.getFloat().changeSign();
10929 }
10930 return Elt;
10931 case UO_Not:
10932 // This is only valid for integral types anyway, so we don't have to handle
10933 // float here.
10934 assert(Elt.getKind() == APValue::Int &&
10935 "Vector operator ~ can only be int");
10936 Elt.getInt().flipAllBits();
10937 return Elt;
10938 case UO_LNot: {
10939 if (Elt.getKind() == APValue::Int) {
10940 Elt.getInt() = !Elt.getInt();
10941 // operator ! on vectors returns -1 for 'truth', so negate it.
10942 Elt.getInt().negate();
10943 return Elt;
10944 }
10945 assert(Elt.getKind() == APValue::Float &&
10946 "Vector can only be int or float type");
10947 // Float types result in an int of the same size, but -1 for true, or 0 for
10948 // false.
10949 APSInt EltResult{Ctx.getIntWidth(ResultTy),
10950 ResultTy->isUnsignedIntegerType()};
10951 if (Elt.getFloat().isZero())
10952 EltResult.setAllBits();
10953 else
10954 EltResult.clearAllBits();
10955
10956 return APValue{EltResult};
10957 }
10958 default:
10959 // FIXME: Implement the rest of the unary operators.
10960 return std::nullopt;
10961 }
10962}
10963
10964bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10965 Expr *SubExpr = E->getSubExpr();
10966 const auto *VD = SubExpr->getType()->castAs<VectorType>();
10967 // This result element type differs in the case of negating a floating point
10968 // vector, since the result type is the a vector of the equivilant sized
10969 // integer.
10970 const QualType ResultEltTy = VD->getElementType();
10971 UnaryOperatorKind Op = E->getOpcode();
10972
10973 APValue SubExprValue;
10974 if (!Evaluate(SubExprValue, Info, SubExpr))
10975 return false;
10976
10977 // FIXME: This vector evaluator someday needs to be changed to be LValue
10978 // aware/keep LValue information around, rather than dealing with just vector
10979 // types directly. Until then, we cannot handle cases where the operand to
10980 // these unary operators is an LValue. The only case I've been able to see
10981 // cause this is operator++ assigning to a member expression (only valid in
10982 // altivec compilations) in C mode, so this shouldn't limit us too much.
10983 if (SubExprValue.isLValue())
10984 return false;
10985
10986 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10987 "Vector length doesn't match type?");
10988
10989 SmallVector<APValue, 4> ResultElements;
10990 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10991 std::optional<APValue> Elt = handleVectorUnaryOperator(
10992 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10993 if (!Elt)
10994 return false;
10995 ResultElements.push_back(*Elt);
10996 }
10997 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10998}
10999
11000static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11001 const Expr *E, QualType SourceTy,
11002 QualType DestTy, APValue const &Original,
11003 APValue &Result) {
11004 if (SourceTy->isIntegerType()) {
11005 if (DestTy->isRealFloatingType()) {
11006 Result = APValue(APFloat(0.0));
11007 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11008 DestTy, Result.getFloat());
11009 }
11010 if (DestTy->isIntegerType()) {
11011 Result = APValue(
11012 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11013 return true;
11014 }
11015 } else if (SourceTy->isRealFloatingType()) {
11016 if (DestTy->isRealFloatingType()) {
11017 Result = Original;
11018 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11019 Result.getFloat());
11020 }
11021 if (DestTy->isIntegerType()) {
11022 Result = APValue(APSInt());
11023 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11024 DestTy, Result.getInt());
11025 }
11026 }
11027
11028 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11029 << SourceTy << DestTy;
11030 return false;
11031}
11032
11033bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11034 APValue Source;
11035 QualType SourceVecType = E->getSrcExpr()->getType();
11036 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11037 return false;
11038
11039 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11040 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11041
11042 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11043
11044 auto SourceLen = Source.getVectorLength();
11045 SmallVector<APValue, 4> ResultElements;
11046 ResultElements.reserve(SourceLen);
11047 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11048 APValue Elt;
11049 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11050 Source.getVectorElt(EltNum), Elt))
11051 return false;
11052 ResultElements.push_back(std::move(Elt));
11053 }
11054
11055 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11056}
11057
11058static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11059 QualType ElemType, APValue const &VecVal1,
11060 APValue const &VecVal2, unsigned EltNum,
11061 APValue &Result) {
11062 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11063 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11064
11065 APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11066 int64_t index = IndexVal.getExtValue();
11067 // The spec says that -1 should be treated as undef for optimizations,
11068 // but in constexpr we'd have to produce an APValue::Indeterminate,
11069 // which is prohibited from being a top-level constant value. Emit a
11070 // diagnostic instead.
11071 if (index == -1) {
11072 Info.FFDiag(
11073 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11074 << EltNum;
11075 return false;
11076 }
11077
11078 if (index < 0 ||
11079 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11080 llvm_unreachable("Out of bounds shuffle index");
11081
11082 if (index >= TotalElementsInInputVector1)
11083 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11084 else
11085 Result = VecVal1.getVectorElt(index);
11086 return true;
11087}
11088
11089bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11090 APValue VecVal1;
11091 const Expr *Vec1 = E->getExpr(0);
11092 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11093 return false;
11094 APValue VecVal2;
11095 const Expr *Vec2 = E->getExpr(1);
11096 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11097 return false;
11098
11099 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11100 QualType DestElTy = DestVecTy->getElementType();
11101
11102 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11103
11104 SmallVector<APValue, 4> ResultElements;
11105 ResultElements.reserve(TotalElementsInOutputVector);
11106 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11107 APValue Elt;
11108 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11109 return false;
11110 ResultElements.push_back(std::move(Elt));
11111 }
11112
11113 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11114}
11115
11116//===----------------------------------------------------------------------===//
11117// Array Evaluation
11118//===----------------------------------------------------------------------===//
11119
11120namespace {
11121 class ArrayExprEvaluator
11122 : public ExprEvaluatorBase<ArrayExprEvaluator> {
11123 const LValue &This;
11124 APValue &Result;
11125 public:
11126
11127 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11128 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11129
11130 bool Success(const APValue &V, const Expr *E) {
11131 assert(V.isArray() && "expected array");
11132 Result = V;
11133 return true;
11134 }
11135
11136 bool ZeroInitialization(const Expr *E) {
11137 const ConstantArrayType *CAT =
11138 Info.Ctx.getAsConstantArrayType(E->getType());
11139 if (!CAT) {
11140 if (E->getType()->isIncompleteArrayType()) {
11141 // We can be asked to zero-initialize a flexible array member; this
11142 // is represented as an ImplicitValueInitExpr of incomplete array
11143 // type. In this case, the array has zero elements.
11144 Result = APValue(APValue::UninitArray(), 0, 0);
11145 return true;
11146 }
11147 // FIXME: We could handle VLAs here.
11148 return Error(E);
11149 }
11150
11151 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11152 if (!Result.hasArrayFiller())
11153 return true;
11154
11155 // Zero-initialize all elements.
11156 LValue Subobject = This;
11157 Subobject.addArray(Info, E, CAT);
11159 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11160 }
11161
11162 bool VisitCallExpr(const CallExpr *E) {
11163 return handleCallExpr(E, Result, &This);
11164 }
11165 bool VisitInitListExpr(const InitListExpr *E,
11166 QualType AllocType = QualType());
11167 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11168 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11169 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11170 const LValue &Subobject,
11172 bool VisitStringLiteral(const StringLiteral *E,
11173 QualType AllocType = QualType()) {
11174 expandStringLiteral(Info, E, Result, AllocType);
11175 return true;
11176 }
11177 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11178 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11179 ArrayRef<Expr *> Args,
11180 const Expr *ArrayFiller,
11181 QualType AllocType = QualType());
11182 };
11183} // end anonymous namespace
11184
11185static bool EvaluateArray(const Expr *E, const LValue &This,
11186 APValue &Result, EvalInfo &Info) {
11187 assert(!E->isValueDependent());
11188 assert(E->isPRValue() && E->getType()->isArrayType() &&
11189 "not an array prvalue");
11190 return ArrayExprEvaluator(Info, This, Result).Visit(E);
11191}
11192
11193static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11194 APValue &Result, const InitListExpr *ILE,
11195 QualType AllocType) {
11196 assert(!ILE->isValueDependent());
11197 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11198 "not an array prvalue");
11199 return ArrayExprEvaluator(Info, This, Result)
11200 .VisitInitListExpr(ILE, AllocType);
11201}
11202
11203static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11204 APValue &Result,
11205 const CXXConstructExpr *CCE,
11206 QualType AllocType) {
11207 assert(!CCE->isValueDependent());
11208 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11209 "not an array prvalue");
11210 return ArrayExprEvaluator(Info, This, Result)
11211 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11212}
11213
11214// Return true iff the given array filler may depend on the element index.
11215static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11216 // For now, just allow non-class value-initialization and initialization
11217 // lists comprised of them.
11218 if (isa<ImplicitValueInitExpr>(FillerExpr))
11219 return false;
11220 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11221 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11222 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11223 return true;
11224 }
11225
11226 if (ILE->hasArrayFiller() &&
11227 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11228 return true;
11229
11230 return false;
11231 }
11232 return true;
11233}
11234
11235bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11236 QualType AllocType) {
11237 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11238 AllocType.isNull() ? E->getType() : AllocType);
11239 if (!CAT)
11240 return Error(E);
11241
11242 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11243 // an appropriately-typed string literal enclosed in braces.
11244 if (E->isStringLiteralInit()) {
11245 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11246 // FIXME: Support ObjCEncodeExpr here once we support it in
11247 // ArrayExprEvaluator generally.
11248 if (!SL)
11249 return Error(E);
11250 return VisitStringLiteral(SL, AllocType);
11251 }
11252 // Any other transparent list init will need proper handling of the
11253 // AllocType; we can't just recurse to the inner initializer.
11254 assert(!E->isTransparent() &&
11255 "transparent array list initialization is not string literal init?");
11256
11257 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11258 AllocType);
11259}
11260
11261bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11262 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11263 QualType AllocType) {
11264 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11265 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11266
11267 bool Success = true;
11268
11269 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11270 "zero-initialized array shouldn't have any initialized elts");
11271 APValue Filler;
11272 if (Result.isArray() && Result.hasArrayFiller())
11273 Filler = Result.getArrayFiller();
11274
11275 unsigned NumEltsToInit = Args.size();
11276 unsigned NumElts = CAT->getZExtSize();
11277
11278 // If the initializer might depend on the array index, run it for each
11279 // array element.
11280 if (NumEltsToInit != NumElts &&
11281 MaybeElementDependentArrayFiller(ArrayFiller)) {
11282 NumEltsToInit = NumElts;
11283 } else {
11284 for (auto *Init : Args) {
11285 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11286 NumEltsToInit += EmbedS->getDataElementCount() - 1;
11287 }
11288 if (NumEltsToInit > NumElts)
11289 NumEltsToInit = NumElts;
11290 }
11291
11292 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11293 << NumEltsToInit << ".\n");
11294
11295 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11296
11297 // If the array was previously zero-initialized, preserve the
11298 // zero-initialized values.
11299 if (Filler.hasValue()) {
11300 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11301 Result.getArrayInitializedElt(I) = Filler;
11302 if (Result.hasArrayFiller())
11303 Result.getArrayFiller() = Filler;
11304 }
11305
11306 LValue Subobject = This;
11307 Subobject.addArray(Info, ExprToVisit, CAT);
11308 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11309 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
11310 Subobject, Init) ||
11311 !HandleLValueArrayAdjustment(Info, Init, Subobject,
11312 CAT->getElementType(), 1)) {
11313 if (!Info.noteFailure())
11314 return false;
11315 Success = false;
11316 }
11317 return true;
11318 };
11319 unsigned ArrayIndex = 0;
11320 QualType DestTy = CAT->getElementType();
11321 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11322 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11323 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11324 if (ArrayIndex >= NumEltsToInit)
11325 break;
11326 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11327 StringLiteral *SL = EmbedS->getDataStringLiteral();
11328 for (unsigned I = EmbedS->getStartingElementPos(),
11329 N = EmbedS->getDataElementCount();
11330 I != EmbedS->getStartingElementPos() + N; ++I) {
11331 Value = SL->getCodeUnit(I);
11332 if (DestTy->isIntegerType()) {
11333 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
11334 } else {
11335 assert(DestTy->isFloatingType() && "unexpected type");
11336 const FPOptions FPO =
11337 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11338 APFloat FValue(0.0);
11339 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11340 DestTy, FValue))
11341 return false;
11342 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
11343 }
11344 ArrayIndex++;
11345 }
11346 } else {
11347 if (!Eval(Init, ArrayIndex))
11348 return false;
11349 ++ArrayIndex;
11350 }
11351 }
11352
11353 if (!Result.hasArrayFiller())
11354 return Success;
11355
11356 // If we get here, we have a trivial filler, which we can just evaluate
11357 // once and splat over the rest of the array elements.
11358 assert(ArrayFiller && "no array filler for incomplete init list");
11359 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11360 ArrayFiller) &&
11361 Success;
11362}
11363
11364bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11365 LValue CommonLV;
11366 if (E->getCommonExpr() &&
11367 !Evaluate(Info.CurrentCall->createTemporary(
11368 E->getCommonExpr(),
11369 getStorageType(Info.Ctx, E->getCommonExpr()),
11370 ScopeKind::FullExpression, CommonLV),
11371 Info, E->getCommonExpr()->getSourceExpr()))
11372 return false;
11373
11374 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11375
11376 uint64_t Elements = CAT->getZExtSize();
11377 Result = APValue(APValue::UninitArray(), Elements, Elements);
11378
11379 LValue Subobject = This;
11380 Subobject.addArray(Info, E, CAT);
11381
11382 bool Success = true;
11383 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11384 // C++ [class.temporary]/5
11385 // There are four contexts in which temporaries are destroyed at a different
11386 // point than the end of the full-expression. [...] The second context is
11387 // when a copy constructor is called to copy an element of an array while
11388 // the entire array is copied [...]. In either case, if the constructor has
11389 // one or more default arguments, the destruction of every temporary created
11390 // in a default argument is sequenced before the construction of the next
11391 // array element, if any.
11392 FullExpressionRAII Scope(Info);
11393
11394 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11395 Info, Subobject, E->getSubExpr()) ||
11396 !HandleLValueArrayAdjustment(Info, E, Subobject,
11397 CAT->getElementType(), 1)) {
11398 if (!Info.noteFailure())
11399 return false;
11400 Success = false;
11401 }
11402
11403 // Make sure we run the destructors too.
11404 Scope.destroy();
11405 }
11406
11407 return Success;
11408}
11409
11410bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11411 return VisitCXXConstructExpr(E, This, &Result, E->getType());
11412}
11413
11414bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11415 const LValue &Subobject,
11416 APValue *Value,
11417 QualType Type) {
11418 bool HadZeroInit = Value->hasValue();
11419
11420 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11421 unsigned FinalSize = CAT->getZExtSize();
11422
11423 // Preserve the array filler if we had prior zero-initialization.
11424 APValue Filler =
11425 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11426 : APValue();
11427
11428 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11429 if (FinalSize == 0)
11430 return true;
11431
11432 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11433 Info, E->getExprLoc(), E->getConstructor(),
11434 E->requiresZeroInitialization());
11435 LValue ArrayElt = Subobject;
11436 ArrayElt.addArray(Info, E, CAT);
11437 // We do the whole initialization in two passes, first for just one element,
11438 // then for the whole array. It's possible we may find out we can't do const
11439 // init in the first pass, in which case we avoid allocating a potentially
11440 // large array. We don't do more passes because expanding array requires
11441 // copying the data, which is wasteful.
11442 for (const unsigned N : {1u, FinalSize}) {
11443 unsigned OldElts = Value->getArrayInitializedElts();
11444 if (OldElts == N)
11445 break;
11446
11447 // Expand the array to appropriate size.
11448 APValue NewValue(APValue::UninitArray(), N, FinalSize);
11449 for (unsigned I = 0; I < OldElts; ++I)
11450 NewValue.getArrayInitializedElt(I).swap(
11451 Value->getArrayInitializedElt(I));
11452 Value->swap(NewValue);
11453
11454 if (HadZeroInit)
11455 for (unsigned I = OldElts; I < N; ++I)
11456 Value->getArrayInitializedElt(I) = Filler;
11457
11458 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11459 // If we have a trivial constructor, only evaluate it once and copy
11460 // the result into all the array elements.
11461 APValue &FirstResult = Value->getArrayInitializedElt(0);
11462 for (unsigned I = OldElts; I < FinalSize; ++I)
11463 Value->getArrayInitializedElt(I) = FirstResult;
11464 } else {
11465 for (unsigned I = OldElts; I < N; ++I) {
11466 if (!VisitCXXConstructExpr(E, ArrayElt,
11467 &Value->getArrayInitializedElt(I),
11468 CAT->getElementType()) ||
11469 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11470 CAT->getElementType(), 1))
11471 return false;
11472 // When checking for const initilization any diagnostic is considered
11473 // an error.
11474 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11475 !Info.keepEvaluatingAfterFailure())
11476 return false;
11477 }
11478 }
11479 }
11480
11481 return true;
11482 }
11483
11484 if (!Type->isRecordType())
11485 return Error(E);
11486
11487 return RecordExprEvaluator(Info, Subobject, *Value)
11488 .VisitCXXConstructExpr(E, Type);
11489}
11490
11491bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11492 const CXXParenListInitExpr *E) {
11493 assert(E->getType()->isConstantArrayType() &&
11494 "Expression result is not a constant array type");
11495
11496 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11497 E->getArrayFiller());
11498}
11499
11500//===----------------------------------------------------------------------===//
11501// Integer Evaluation
11502//
11503// As a GNU extension, we support casting pointers to sufficiently-wide integer
11504// types and back in constant folding. Integer values are thus represented
11505// either as an integer-valued APValue, or as an lvalue-valued APValue.
11506//===----------------------------------------------------------------------===//
11507
11508namespace {
11509class IntExprEvaluator
11510 : public ExprEvaluatorBase<IntExprEvaluator> {
11511 APValue &Result;
11512public:
11513 IntExprEvaluator(EvalInfo &info, APValue &result)
11514 : ExprEvaluatorBaseTy(info), Result(result) {}
11515
11516 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11517 assert(E->getType()->isIntegralOrEnumerationType() &&
11518 "Invalid evaluation result.");
11519 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11520 "Invalid evaluation result.");
11521 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11522 "Invalid evaluation result.");
11523 Result = APValue(SI);
11524 return true;
11525 }
11526 bool Success(const llvm::APSInt &SI, const Expr *E) {
11527 return Success(SI, E, Result);
11528 }
11529
11530 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11531 assert(E->getType()->isIntegralOrEnumerationType() &&
11532 "Invalid evaluation result.");
11533 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11534 "Invalid evaluation result.");
11535 Result = APValue(APSInt(I));
11536 Result.getInt().setIsUnsigned(
11538 return true;
11539 }
11540 bool Success(const llvm::APInt &I, const Expr *E) {
11541 return Success(I, E, Result);
11542 }
11543
11544 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11545 assert(E->getType()->isIntegralOrEnumerationType() &&
11546 "Invalid evaluation result.");
11547 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11548 return true;
11549 }
11550 bool Success(uint64_t Value, const Expr *E) {
11551 return Success(Value, E, Result);
11552 }
11553
11554 bool Success(CharUnits Size, const Expr *E) {
11555 return Success(Size.getQuantity(), E);
11556 }
11557
11558 bool Success(const APValue &V, const Expr *E) {
11559 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11560 Result = V;
11561 return true;
11562 }
11563 return Success(V.getInt(), E);
11564 }
11565
11566 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11567
11568 //===--------------------------------------------------------------------===//
11569 // Visitor Methods
11570 //===--------------------------------------------------------------------===//
11571
11572 bool VisitIntegerLiteral(const IntegerLiteral *E) {
11573 return Success(E->getValue(), E);
11574 }
11575 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11576 return Success(E->getValue(), E);
11577 }
11578
11579 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11580 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11581 if (CheckReferencedDecl(E, E->getDecl()))
11582 return true;
11583
11584 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11585 }
11586 bool VisitMemberExpr(const MemberExpr *E) {
11587 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11588 VisitIgnoredBaseExpression(E->getBase());
11589 return true;
11590 }
11591
11592 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11593 }
11594
11595 bool VisitCallExpr(const CallExpr *E);
11596 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11597 bool VisitBinaryOperator(const BinaryOperator *E);
11598 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11599 bool VisitUnaryOperator(const UnaryOperator *E);
11600
11601 bool VisitCastExpr(const CastExpr* E);
11602 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11603
11604 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11605 return Success(E->getValue(), E);
11606 }
11607
11608 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11609 return Success(E->getValue(), E);
11610 }
11611
11612 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11613 if (Info.ArrayInitIndex == uint64_t(-1)) {
11614 // We were asked to evaluate this subexpression independent of the
11615 // enclosing ArrayInitLoopExpr. We can't do that.
11616 Info.FFDiag(E);
11617 return false;
11618 }
11619 return Success(Info.ArrayInitIndex, E);
11620 }
11621
11622 // Note, GNU defines __null as an integer, not a pointer.
11623 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11624 return ZeroInitialization(E);
11625 }
11626
11627 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11628 return Success(E->getValue(), E);
11629 }
11630
11631 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11632 return Success(E->getValue(), E);
11633 }
11634
11635 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11636 return Success(E->getValue(), E);
11637 }
11638
11639 bool VisitUnaryReal(const UnaryOperator *E);
11640 bool VisitUnaryImag(const UnaryOperator *E);
11641
11642 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11643 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11644 bool VisitSourceLocExpr(const SourceLocExpr *E);
11645 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11646 bool VisitRequiresExpr(const RequiresExpr *E);
11647 // FIXME: Missing: array subscript of vector, member of vector
11648};
11649
11650class FixedPointExprEvaluator
11651 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11652 APValue &Result;
11653
11654 public:
11655 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11656 : ExprEvaluatorBaseTy(info), Result(result) {}
11657
11658 bool Success(const llvm::APInt &I, const Expr *E) {
11659 return Success(
11660 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11661 }
11662
11663 bool Success(uint64_t Value, const Expr *E) {
11664 return Success(
11665 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11666 }
11667
11668 bool Success(const APValue &V, const Expr *E) {
11669 return Success(V.getFixedPoint(), E);
11670 }
11671
11672 bool Success(const APFixedPoint &V, const Expr *E) {
11673 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11674 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11675 "Invalid evaluation result.");
11676 Result = APValue(V);
11677 return true;
11678 }
11679
11680 bool ZeroInitialization(const Expr *E) {
11681 return Success(0, E);
11682 }
11683
11684 //===--------------------------------------------------------------------===//
11685 // Visitor Methods
11686 //===--------------------------------------------------------------------===//
11687
11688 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11689 return Success(E->getValue(), E);
11690 }
11691
11692 bool VisitCastExpr(const CastExpr *E);
11693 bool VisitUnaryOperator(const UnaryOperator *E);
11694 bool VisitBinaryOperator(const BinaryOperator *E);
11695};
11696} // end anonymous namespace
11697
11698/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11699/// produce either the integer value or a pointer.
11700///
11701/// GCC has a heinous extension which folds casts between pointer types and
11702/// pointer-sized integral types. We support this by allowing the evaluation of
11703/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11704/// Some simple arithmetic on such values is supported (they are treated much
11705/// like char*).
11706static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11707 EvalInfo &Info) {
11708 assert(!E->isValueDependent());
11709 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11710 return IntExprEvaluator(Info, Result).Visit(E);
11711}
11712
11713static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11714 assert(!E->isValueDependent());
11715 APValue Val;
11716 if (!EvaluateIntegerOrLValue(E, Val, Info))
11717 return false;
11718 if (!Val.isInt()) {
11719 // FIXME: It would be better to produce the diagnostic for casting
11720 // a pointer to an integer.
11721 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11722 return false;
11723 }
11724 Result = Val.getInt();
11725 return true;
11726}
11727
11728bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11729 APValue Evaluated = E->EvaluateInContext(
11730 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11731 return Success(Evaluated, E);
11732}
11733
11734static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11735 EvalInfo &Info) {
11736 assert(!E->isValueDependent());
11737 if (E->getType()->isFixedPointType()) {
11738 APValue Val;
11739 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11740 return false;
11741 if (!Val.isFixedPoint())
11742 return false;
11743
11744 Result = Val.getFixedPoint();
11745 return true;
11746 }
11747 return false;
11748}
11749
11750static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11751 EvalInfo &Info) {
11752 assert(!E->isValueDependent());
11753 if (E->getType()->isIntegerType()) {
11754 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11755 APSInt Val;
11756 if (!EvaluateInteger(E, Val, Info))
11757 return false;
11758 Result = APFixedPoint(Val, FXSema);
11759 return true;
11760 } else if (E->getType()->isFixedPointType()) {
11761 return EvaluateFixedPoint(E, Result, Info);
11762 }
11763 return false;
11764}
11765
11766/// Check whether the given declaration can be directly converted to an integral
11767/// rvalue. If not, no diagnostic is produced; there are other things we can
11768/// try.
11769bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11770 // Enums are integer constant exprs.
11771 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11772 // Check for signedness/width mismatches between E type and ECD value.
11773 bool SameSign = (ECD->getInitVal().isSigned()
11775 bool SameWidth = (ECD->getInitVal().getBitWidth()
11776 == Info.Ctx.getIntWidth(E->getType()));
11777 if (SameSign && SameWidth)
11778 return Success(ECD->getInitVal(), E);
11779 else {
11780 // Get rid of mismatch (otherwise Success assertions will fail)
11781 // by computing a new value matching the type of E.
11782 llvm::APSInt Val = ECD->getInitVal();
11783 if (!SameSign)
11784 Val.setIsSigned(!ECD->getInitVal().isSigned());
11785 if (!SameWidth)
11786 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11787 return Success(Val, E);
11788 }
11789 }
11790 return false;
11791}
11792
11793/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11794/// as GCC.
11796 const LangOptions &LangOpts) {
11797 assert(!T->isDependentType() && "unexpected dependent type");
11798
11799 QualType CanTy = T.getCanonicalType();
11800
11801 switch (CanTy->getTypeClass()) {
11802#define TYPE(ID, BASE)
11803#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11804#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11805#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11806#include "clang/AST/TypeNodes.inc"
11807 case Type::Auto:
11808 case Type::DeducedTemplateSpecialization:
11809 llvm_unreachable("unexpected non-canonical or dependent type");
11810
11811 case Type::Builtin:
11812 switch (cast<BuiltinType>(CanTy)->getKind()) {
11813#define BUILTIN_TYPE(ID, SINGLETON_ID)
11814#define SIGNED_TYPE(ID, SINGLETON_ID) \
11815 case BuiltinType::ID: return GCCTypeClass::Integer;
11816#define FLOATING_TYPE(ID, SINGLETON_ID) \
11817 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11818#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11819 case BuiltinType::ID: break;
11820#include "clang/AST/BuiltinTypes.def"
11821 case BuiltinType::Void:
11822 return GCCTypeClass::Void;
11823
11824 case BuiltinType::Bool:
11825 return GCCTypeClass::Bool;
11826
11827 case BuiltinType::Char_U:
11828 case BuiltinType::UChar:
11829 case BuiltinType::WChar_U:
11830 case BuiltinType::Char8:
11831 case BuiltinType::Char16:
11832 case BuiltinType::Char32:
11833 case BuiltinType::UShort:
11834 case BuiltinType::UInt:
11835 case BuiltinType::ULong:
11836 case BuiltinType::ULongLong:
11837 case BuiltinType::UInt128:
11838 return GCCTypeClass::Integer;
11839
11840 case BuiltinType::UShortAccum:
11841 case BuiltinType::UAccum:
11842 case BuiltinType::ULongAccum:
11843 case BuiltinType::UShortFract:
11844 case BuiltinType::UFract:
11845 case BuiltinType::ULongFract:
11846 case BuiltinType::SatUShortAccum:
11847 case BuiltinType::SatUAccum:
11848 case BuiltinType::SatULongAccum:
11849 case BuiltinType::SatUShortFract:
11850 case BuiltinType::SatUFract:
11851 case BuiltinType::SatULongFract:
11852 return GCCTypeClass::None;
11853
11854 case BuiltinType::NullPtr:
11855
11856 case BuiltinType::ObjCId:
11857 case BuiltinType::ObjCClass:
11858 case BuiltinType::ObjCSel:
11859#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11860 case BuiltinType::Id:
11861#include "clang/Basic/OpenCLImageTypes.def"
11862#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11863 case BuiltinType::Id:
11864#include "clang/Basic/OpenCLExtensionTypes.def"
11865 case BuiltinType::OCLSampler:
11866 case BuiltinType::OCLEvent:
11867 case BuiltinType::OCLClkEvent:
11868 case BuiltinType::OCLQueue:
11869 case BuiltinType::OCLReserveID:
11870#define SVE_TYPE(Name, Id, SingletonId) \
11871 case BuiltinType::Id:
11872#include "clang/Basic/AArch64SVEACLETypes.def"
11873#define PPC_VECTOR_TYPE(Name, Id, Size) \
11874 case BuiltinType::Id:
11875#include "clang/Basic/PPCTypes.def"
11876#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11877#include "clang/Basic/RISCVVTypes.def"
11878#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11879#include "clang/Basic/WebAssemblyReferenceTypes.def"
11880#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11881#include "clang/Basic/AMDGPUTypes.def"
11882 return GCCTypeClass::None;
11883
11884 case BuiltinType::Dependent:
11885 llvm_unreachable("unexpected dependent type");
11886 };
11887 llvm_unreachable("unexpected placeholder type");
11888
11889 case Type::Enum:
11890 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11891
11892 case Type::Pointer:
11893 case Type::ConstantArray:
11894 case Type::VariableArray:
11895 case Type::IncompleteArray:
11896 case Type::FunctionNoProto:
11897 case Type::FunctionProto:
11898 case Type::ArrayParameter:
11899 return GCCTypeClass::Pointer;
11900
11901 case Type::MemberPointer:
11902 return CanTy->isMemberDataPointerType()
11903 ? GCCTypeClass::PointerToDataMember
11904 : GCCTypeClass::PointerToMemberFunction;
11905
11906 case Type::Complex:
11907 return GCCTypeClass::Complex;
11908
11909 case Type::Record:
11910 return CanTy->isUnionType() ? GCCTypeClass::Union
11911 : GCCTypeClass::ClassOrStruct;
11912
11913 case Type::Atomic:
11914 // GCC classifies _Atomic T the same as T.
11916 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11917
11918 case Type::Vector:
11919 case Type::ExtVector:
11920 return GCCTypeClass::Vector;
11921
11922 case Type::BlockPointer:
11923 case Type::ConstantMatrix:
11924 case Type::ObjCObject:
11925 case Type::ObjCInterface:
11926 case Type::ObjCObjectPointer:
11927 case Type::Pipe:
11928 // Classify all other types that don't fit into the regular
11929 // classification the same way.
11930 return GCCTypeClass::None;
11931
11932 case Type::BitInt:
11933 return GCCTypeClass::BitInt;
11934
11935 case Type::LValueReference:
11936 case Type::RValueReference:
11937 llvm_unreachable("invalid type for expression");
11938 }
11939
11940 llvm_unreachable("unexpected type class");
11941}
11942
11943/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11944/// as GCC.
11945static GCCTypeClass
11947 // If no argument was supplied, default to None. This isn't
11948 // ideal, however it is what gcc does.
11949 if (E->getNumArgs() == 0)
11950 return GCCTypeClass::None;
11951
11952 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11953 // being an ICE, but still folds it to a constant using the type of the first
11954 // argument.
11955 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11956}
11957
11958/// EvaluateBuiltinConstantPForLValue - Determine the result of
11959/// __builtin_constant_p when applied to the given pointer.
11960///
11961/// A pointer is only "constant" if it is null (or a pointer cast to integer)
11962/// or it points to the first character of a string literal.
11965 if (Base.isNull()) {
11966 // A null base is acceptable.
11967 return true;
11968 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11969 if (!isa<StringLiteral>(E))
11970 return false;
11971 return LV.getLValueOffset().isZero();
11972 } else if (Base.is<TypeInfoLValue>()) {
11973 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11974 // evaluate to true.
11975 return true;
11976 } else {
11977 // Any other base is not constant enough for GCC.
11978 return false;
11979 }
11980}
11981
11982/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11983/// GCC as we can manage.
11984static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11985 // This evaluation is not permitted to have side-effects, so evaluate it in
11986 // a speculative evaluation context.
11987 SpeculativeEvaluationRAII SpeculativeEval(Info);
11988
11989 // Constant-folding is always enabled for the operand of __builtin_constant_p
11990 // (even when the enclosing evaluation context otherwise requires a strict
11991 // language-specific constant expression).
11992 FoldConstant Fold(Info, true);
11993
11994 QualType ArgType = Arg->getType();
11995
11996 // __builtin_constant_p always has one operand. The rules which gcc follows
11997 // are not precisely documented, but are as follows:
11998 //
11999 // - If the operand is of integral, floating, complex or enumeration type,
12000 // and can be folded to a known value of that type, it returns 1.
12001 // - If the operand can be folded to a pointer to the first character
12002 // of a string literal (or such a pointer cast to an integral type)
12003 // or to a null pointer or an integer cast to a pointer, it returns 1.
12004 //
12005 // Otherwise, it returns 0.
12006 //
12007 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12008 // its support for this did not work prior to GCC 9 and is not yet well
12009 // understood.
12010 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12011 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12012 ArgType->isNullPtrType()) {
12013 APValue V;
12014 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12015 Fold.keepDiagnostics();
12016 return false;
12017 }
12018
12019 // For a pointer (possibly cast to integer), there are special rules.
12020 if (V.getKind() == APValue::LValue)
12022
12023 // Otherwise, any constant value is good enough.
12024 return V.hasValue();
12025 }
12026
12027 // Anything else isn't considered to be sufficiently constant.
12028 return false;
12029}
12030
12031/// Retrieves the "underlying object type" of the given expression,
12032/// as used by __builtin_object_size.
12034 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12035 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
12036 return VD->getType();
12037 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12038 if (isa<CompoundLiteralExpr>(E))
12039 return E->getType();
12040 } else if (B.is<TypeInfoLValue>()) {
12041 return B.getTypeInfoType();
12042 } else if (B.is<DynamicAllocLValue>()) {
12043 return B.getDynamicAllocType();
12044 }
12045
12046 return QualType();
12047}
12048
12049/// A more selective version of E->IgnoreParenCasts for
12050/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12051/// to change the type of E.
12052/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12053///
12054/// Always returns an RValue with a pointer representation.
12056 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12057
12058 const Expr *NoParens = E->IgnoreParens();
12059 const auto *Cast = dyn_cast<CastExpr>(NoParens);
12060 if (Cast == nullptr)
12061 return NoParens;
12062
12063 // We only conservatively allow a few kinds of casts, because this code is
12064 // inherently a simple solution that seeks to support the common case.
12065 auto CastKind = Cast->getCastKind();
12066 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12067 CastKind != CK_AddressSpaceConversion)
12068 return NoParens;
12069
12070 const auto *SubExpr = Cast->getSubExpr();
12071 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12072 return NoParens;
12073 return ignorePointerCastsAndParens(SubExpr);
12074}
12075
12076/// Checks to see if the given LValue's Designator is at the end of the LValue's
12077/// record layout. e.g.
12078/// struct { struct { int a, b; } fst, snd; } obj;
12079/// obj.fst // no
12080/// obj.snd // yes
12081/// obj.fst.a // no
12082/// obj.fst.b // no
12083/// obj.snd.a // no
12084/// obj.snd.b // yes
12085///
12086/// Please note: this function is specialized for how __builtin_object_size
12087/// views "objects".
12088///
12089/// If this encounters an invalid RecordDecl or otherwise cannot determine the
12090/// correct result, it will always return true.
12091static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12092 assert(!LVal.Designator.Invalid);
12093
12094 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12095 const RecordDecl *Parent = FD->getParent();
12096 Invalid = Parent->isInvalidDecl();
12097 if (Invalid || Parent->isUnion())
12098 return true;
12099 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12100 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12101 };
12102
12103 auto &Base = LVal.getLValueBase();
12104 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12105 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12106 bool Invalid;
12107 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12108 return Invalid;
12109 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12110 for (auto *FD : IFD->chain()) {
12111 bool Invalid;
12112 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
12113 return Invalid;
12114 }
12115 }
12116 }
12117
12118 unsigned I = 0;
12119 QualType BaseType = getType(Base);
12120 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12121 // If we don't know the array bound, conservatively assume we're looking at
12122 // the final array element.
12123 ++I;
12124 if (BaseType->isIncompleteArrayType())
12125 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12126 else
12127 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12128 }
12129
12130 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12131 const auto &Entry = LVal.Designator.Entries[I];
12132 if (BaseType->isArrayType()) {
12133 // Because __builtin_object_size treats arrays as objects, we can ignore
12134 // the index iff this is the last array in the Designator.
12135 if (I + 1 == E)
12136 return true;
12137 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12138 uint64_t Index = Entry.getAsArrayIndex();
12139 if (Index + 1 != CAT->getZExtSize())
12140 return false;
12141 BaseType = CAT->getElementType();
12142 } else if (BaseType->isAnyComplexType()) {
12143 const auto *CT = BaseType->castAs<ComplexType>();
12144 uint64_t Index = Entry.getAsArrayIndex();
12145 if (Index != 1)
12146 return false;
12147 BaseType = CT->getElementType();
12148 } else if (auto *FD = getAsField(Entry)) {
12149 bool Invalid;
12150 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12151 return Invalid;
12152 BaseType = FD->getType();
12153 } else {
12154 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12155 return false;
12156 }
12157 }
12158 return true;
12159}
12160
12161/// Tests to see if the LValue has a user-specified designator (that isn't
12162/// necessarily valid). Note that this always returns 'true' if the LValue has
12163/// an unsized array as its first designator entry, because there's currently no
12164/// way to tell if the user typed *foo or foo[0].
12165static bool refersToCompleteObject(const LValue &LVal) {
12166 if (LVal.Designator.Invalid)
12167 return false;
12168
12169 if (!LVal.Designator.Entries.empty())
12170 return LVal.Designator.isMostDerivedAnUnsizedArray();
12171
12172 if (!LVal.InvalidBase)
12173 return true;
12174
12175 // If `E` is a MemberExpr, then the first part of the designator is hiding in
12176 // the LValueBase.
12177 const auto *E = LVal.Base.dyn_cast<const Expr *>();
12178 return !E || !isa<MemberExpr>(E);
12179}
12180
12181/// Attempts to detect a user writing into a piece of memory that's impossible
12182/// to figure out the size of by just using types.
12183static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12184 const SubobjectDesignator &Designator = LVal.Designator;
12185 // Notes:
12186 // - Users can only write off of the end when we have an invalid base. Invalid
12187 // bases imply we don't know where the memory came from.
12188 // - We used to be a bit more aggressive here; we'd only be conservative if
12189 // the array at the end was flexible, or if it had 0 or 1 elements. This
12190 // broke some common standard library extensions (PR30346), but was
12191 // otherwise seemingly fine. It may be useful to reintroduce this behavior
12192 // with some sort of list. OTOH, it seems that GCC is always
12193 // conservative with the last element in structs (if it's an array), so our
12194 // current behavior is more compatible than an explicit list approach would
12195 // be.
12196 auto isFlexibleArrayMember = [&] {
12198 FAMKind StrictFlexArraysLevel =
12199 Ctx.getLangOpts().getStrictFlexArraysLevel();
12200
12201 if (Designator.isMostDerivedAnUnsizedArray())
12202 return true;
12203
12204 if (StrictFlexArraysLevel == FAMKind::Default)
12205 return true;
12206
12207 if (Designator.getMostDerivedArraySize() == 0 &&
12208 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12209 return true;
12210
12211 if (Designator.getMostDerivedArraySize() == 1 &&
12212 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12213 return true;
12214
12215 return false;
12216 };
12217
12218 return LVal.InvalidBase &&
12219 Designator.Entries.size() == Designator.MostDerivedPathLength &&
12220 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12221 isDesignatorAtObjectEnd(Ctx, LVal);
12222}
12223
12224/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12225/// Fails if the conversion would cause loss of precision.
12226static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12227 CharUnits &Result) {
12228 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12229 if (Int.ugt(CharUnitsMax))
12230 return false;
12231 Result = CharUnits::fromQuantity(Int.getZExtValue());
12232 return true;
12233}
12234
12235/// If we're evaluating the object size of an instance of a struct that
12236/// contains a flexible array member, add the size of the initializer.
12237static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12238 const LValue &LV, CharUnits &Size) {
12239 if (!T.isNull() && T->isStructureType() &&
12241 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12242 if (const auto *VD = dyn_cast<VarDecl>(V))
12243 if (VD->hasInit())
12244 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12245}
12246
12247/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12248/// determine how many bytes exist from the beginning of the object to either
12249/// the end of the current subobject, or the end of the object itself, depending
12250/// on what the LValue looks like + the value of Type.
12251///
12252/// If this returns false, the value of Result is undefined.
12253static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12254 unsigned Type, const LValue &LVal,
12255 CharUnits &EndOffset) {
12256 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12257
12258 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12259 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12260 return false;
12261 return HandleSizeof(Info, ExprLoc, Ty, Result);
12262 };
12263
12264 // We want to evaluate the size of the entire object. This is a valid fallback
12265 // for when Type=1 and the designator is invalid, because we're asked for an
12266 // upper-bound.
12267 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12268 // Type=3 wants a lower bound, so we can't fall back to this.
12269 if (Type == 3 && !DetermineForCompleteObject)
12270 return false;
12271
12272 llvm::APInt APEndOffset;
12273 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12274 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12275 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12276
12277 if (LVal.InvalidBase)
12278 return false;
12279
12280 QualType BaseTy = getObjectType(LVal.getLValueBase());
12281 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12282 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12283 return Ret;
12284 }
12285
12286 // We want to evaluate the size of a subobject.
12287 const SubobjectDesignator &Designator = LVal.Designator;
12288
12289 // The following is a moderately common idiom in C:
12290 //
12291 // struct Foo { int a; char c[1]; };
12292 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12293 // strcpy(&F->c[0], Bar);
12294 //
12295 // In order to not break too much legacy code, we need to support it.
12296 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12297 // If we can resolve this to an alloc_size call, we can hand that back,
12298 // because we know for certain how many bytes there are to write to.
12299 llvm::APInt APEndOffset;
12300 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12301 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12302 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12303
12304 // If we cannot determine the size of the initial allocation, then we can't
12305 // given an accurate upper-bound. However, we are still able to give
12306 // conservative lower-bounds for Type=3.
12307 if (Type == 1)
12308 return false;
12309 }
12310
12311 CharUnits BytesPerElem;
12312 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12313 return false;
12314
12315 // According to the GCC documentation, we want the size of the subobject
12316 // denoted by the pointer. But that's not quite right -- what we actually
12317 // want is the size of the immediately-enclosing array, if there is one.
12318 int64_t ElemsRemaining;
12319 if (Designator.MostDerivedIsArrayElement &&
12320 Designator.Entries.size() == Designator.MostDerivedPathLength) {
12321 uint64_t ArraySize = Designator.getMostDerivedArraySize();
12322 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12323 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12324 } else {
12325 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12326 }
12327
12328 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12329 return true;
12330}
12331
12332/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12333/// returns true and stores the result in @p Size.
12334///
12335/// If @p WasError is non-null, this will report whether the failure to evaluate
12336/// is to be treated as an Error in IntExprEvaluator.
12337static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12338 EvalInfo &Info, uint64_t &Size) {
12339 // Determine the denoted object.
12340 LValue LVal;
12341 {
12342 // The operand of __builtin_object_size is never evaluated for side-effects.
12343 // If there are any, but we can determine the pointed-to object anyway, then
12344 // ignore the side-effects.
12345 SpeculativeEvaluationRAII SpeculativeEval(Info);
12346 IgnoreSideEffectsRAII Fold(Info);
12347
12348 if (E->isGLValue()) {
12349 // It's possible for us to be given GLValues if we're called via
12350 // Expr::tryEvaluateObjectSize.
12351 APValue RVal;
12352 if (!EvaluateAsRValue(Info, E, RVal))
12353 return false;
12354 LVal.setFrom(Info.Ctx, RVal);
12355 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12356 /*InvalidBaseOK=*/true))
12357 return false;
12358 }
12359
12360 // If we point to before the start of the object, there are no accessible
12361 // bytes.
12362 if (LVal.getLValueOffset().isNegative()) {
12363 Size = 0;
12364 return true;
12365 }
12366
12367 CharUnits EndOffset;
12368 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12369 return false;
12370
12371 // If we've fallen outside of the end offset, just pretend there's nothing to
12372 // write to/read from.
12373 if (EndOffset <= LVal.getLValueOffset())
12374 Size = 0;
12375 else
12376 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12377 return true;
12378}
12379
12380bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12381 if (!IsConstantEvaluatedBuiltinCall(E))
12382 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12383 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12384}
12385
12386static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12387 APValue &Val, APSInt &Alignment) {
12388 QualType SrcTy = E->getArg(0)->getType();
12389 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12390 return false;
12391 // Even though we are evaluating integer expressions we could get a pointer
12392 // argument for the __builtin_is_aligned() case.
12393 if (SrcTy->isPointerType()) {
12394 LValue Ptr;
12395 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12396 return false;
12397 Ptr.moveInto(Val);
12398 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12399 Info.FFDiag(E->getArg(0));
12400 return false;
12401 } else {
12402 APSInt SrcInt;
12403 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12404 return false;
12405 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12406 "Bit widths must be the same");
12407 Val = APValue(SrcInt);
12408 }
12409 assert(Val.hasValue());
12410 return true;
12411}
12412
12413bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12414 unsigned BuiltinOp) {
12415 switch (BuiltinOp) {
12416 default:
12417 return false;
12418
12419 case Builtin::BI__builtin_dynamic_object_size:
12420 case Builtin::BI__builtin_object_size: {
12421 // The type was checked when we built the expression.
12422 unsigned Type =
12423 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12424 assert(Type <= 3 && "unexpected type");
12425
12426 uint64_t Size;
12427 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12428 return Success(Size, E);
12429
12430 if (E->getArg(0)->HasSideEffects(Info.Ctx))
12431 return Success((Type & 2) ? 0 : -1, E);
12432
12433 // Expression had no side effects, but we couldn't statically determine the
12434 // size of the referenced object.
12435 switch (Info.EvalMode) {
12436 case EvalInfo::EM_ConstantExpression:
12437 case EvalInfo::EM_ConstantFold:
12438 case EvalInfo::EM_IgnoreSideEffects:
12439 // Leave it to IR generation.
12440 return Error(E);
12441 case EvalInfo::EM_ConstantExpressionUnevaluated:
12442 // Reduce it to a constant now.
12443 return Success((Type & 2) ? 0 : -1, E);
12444 }
12445
12446 llvm_unreachable("unexpected EvalMode");
12447 }
12448
12449 case Builtin::BI__builtin_os_log_format_buffer_size: {
12452 return Success(Layout.size().getQuantity(), E);
12453 }
12454
12455 case Builtin::BI__builtin_is_aligned: {
12456 APValue Src;
12457 APSInt Alignment;
12458 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12459 return false;
12460 if (Src.isLValue()) {
12461 // If we evaluated a pointer, check the minimum known alignment.
12462 LValue Ptr;
12463 Ptr.setFrom(Info.Ctx, Src);
12464 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12465 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12466 // We can return true if the known alignment at the computed offset is
12467 // greater than the requested alignment.
12468 assert(PtrAlign.isPowerOfTwo());
12469 assert(Alignment.isPowerOf2());
12470 if (PtrAlign.getQuantity() >= Alignment)
12471 return Success(1, E);
12472 // If the alignment is not known to be sufficient, some cases could still
12473 // be aligned at run time. However, if the requested alignment is less or
12474 // equal to the base alignment and the offset is not aligned, we know that
12475 // the run-time value can never be aligned.
12476 if (BaseAlignment.getQuantity() >= Alignment &&
12477 PtrAlign.getQuantity() < Alignment)
12478 return Success(0, E);
12479 // Otherwise we can't infer whether the value is sufficiently aligned.
12480 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12481 // in cases where we can't fully evaluate the pointer.
12482 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12483 << Alignment;
12484 return false;
12485 }
12486 assert(Src.isInt());
12487 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12488 }
12489 case Builtin::BI__builtin_align_up: {
12490 APValue Src;
12491 APSInt Alignment;
12492 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12493 return false;
12494 if (!Src.isInt())
12495 return Error(E);
12496 APSInt AlignedVal =
12497 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12498 Src.getInt().isUnsigned());
12499 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12500 return Success(AlignedVal, E);
12501 }
12502 case Builtin::BI__builtin_align_down: {
12503 APValue Src;
12504 APSInt Alignment;
12505 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12506 return false;
12507 if (!Src.isInt())
12508 return Error(E);
12509 APSInt AlignedVal =
12510 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12511 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12512 return Success(AlignedVal, E);
12513 }
12514
12515 case Builtin::BI__builtin_bitreverse8:
12516 case Builtin::BI__builtin_bitreverse16:
12517 case Builtin::BI__builtin_bitreverse32:
12518 case Builtin::BI__builtin_bitreverse64: {
12519 APSInt Val;
12520 if (!EvaluateInteger(E->getArg(0), Val, Info))
12521 return false;
12522
12523 return Success(Val.reverseBits(), E);
12524 }
12525
12526 case Builtin::BI__builtin_bswap16:
12527 case Builtin::BI__builtin_bswap32:
12528 case Builtin::BI__builtin_bswap64: {
12529 APSInt Val;
12530 if (!EvaluateInteger(E->getArg(0), Val, Info))
12531 return false;
12532
12533 return Success(Val.byteSwap(), E);
12534 }
12535
12536 case Builtin::BI__builtin_classify_type:
12537 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12538
12539 case Builtin::BI__builtin_clrsb:
12540 case Builtin::BI__builtin_clrsbl:
12541 case Builtin::BI__builtin_clrsbll: {
12542 APSInt Val;
12543 if (!EvaluateInteger(E->getArg(0), Val, Info))
12544 return false;
12545
12546 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12547 }
12548
12549 case Builtin::BI__builtin_clz:
12550 case Builtin::BI__builtin_clzl:
12551 case Builtin::BI__builtin_clzll:
12552 case Builtin::BI__builtin_clzs:
12553 case Builtin::BI__builtin_clzg:
12554 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12555 case Builtin::BI__lzcnt:
12556 case Builtin::BI__lzcnt64: {
12557 APSInt Val;
12558 if (!EvaluateInteger(E->getArg(0), Val, Info))
12559 return false;
12560
12561 std::optional<APSInt> Fallback;
12562 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
12563 APSInt FallbackTemp;
12564 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12565 return false;
12566 Fallback = FallbackTemp;
12567 }
12568
12569 if (!Val) {
12570 if (Fallback)
12571 return Success(*Fallback, E);
12572
12573 // When the argument is 0, the result of GCC builtins is undefined,
12574 // whereas for Microsoft intrinsics, the result is the bit-width of the
12575 // argument.
12576 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12577 BuiltinOp != Builtin::BI__lzcnt &&
12578 BuiltinOp != Builtin::BI__lzcnt64;
12579
12580 if (ZeroIsUndefined)
12581 return Error(E);
12582 }
12583
12584 return Success(Val.countl_zero(), E);
12585 }
12586
12587 case Builtin::BI__builtin_constant_p: {
12588 const Expr *Arg = E->getArg(0);
12589 if (EvaluateBuiltinConstantP(Info, Arg))
12590 return Success(true, E);
12591 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12592 // Outside a constant context, eagerly evaluate to false in the presence
12593 // of side-effects in order to avoid -Wunsequenced false-positives in
12594 // a branch on __builtin_constant_p(expr).
12595 return Success(false, E);
12596 }
12597 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12598 return false;
12599 }
12600
12601 case Builtin::BI__builtin_is_constant_evaluated: {
12602 const auto *Callee = Info.CurrentCall->getCallee();
12603 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12604 (Info.CallStackDepth == 1 ||
12605 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12606 Callee->getIdentifier() &&
12607 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12608 // FIXME: Find a better way to avoid duplicated diagnostics.
12609 if (Info.EvalStatus.Diag)
12610 Info.report((Info.CallStackDepth == 1)
12611 ? E->getExprLoc()
12612 : Info.CurrentCall->getCallRange().getBegin(),
12613 diag::warn_is_constant_evaluated_always_true_constexpr)
12614 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12615 : "std::is_constant_evaluated");
12616 }
12617
12618 return Success(Info.InConstantContext, E);
12619 }
12620
12621 case Builtin::BI__builtin_ctz:
12622 case Builtin::BI__builtin_ctzl:
12623 case Builtin::BI__builtin_ctzll:
12624 case Builtin::BI__builtin_ctzs:
12625 case Builtin::BI__builtin_ctzg: {
12626 APSInt Val;
12627 if (!EvaluateInteger(E->getArg(0), Val, Info))
12628 return false;
12629
12630 std::optional<APSInt> Fallback;
12631 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
12632 APSInt FallbackTemp;
12633 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12634 return false;
12635 Fallback = FallbackTemp;
12636 }
12637
12638 if (!Val) {
12639 if (Fallback)
12640 return Success(*Fallback, E);
12641
12642 return Error(E);
12643 }
12644
12645 return Success(Val.countr_zero(), E);
12646 }
12647
12648 case Builtin::BI__builtin_eh_return_data_regno: {
12649 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12650 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12651 return Success(Operand, E);
12652 }
12653
12654 case Builtin::BI__builtin_expect:
12655 case Builtin::BI__builtin_expect_with_probability:
12656 return Visit(E->getArg(0));
12657
12658 case Builtin::BI__builtin_ptrauth_string_discriminator: {
12659 const auto *Literal =
12660 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
12661 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
12662 return Success(Result, E);
12663 }
12664
12665 case Builtin::BI__builtin_ffs:
12666 case Builtin::BI__builtin_ffsl:
12667 case Builtin::BI__builtin_ffsll: {
12668 APSInt Val;
12669 if (!EvaluateInteger(E->getArg(0), Val, Info))
12670 return false;
12671
12672 unsigned N = Val.countr_zero();
12673 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12674 }
12675
12676 case Builtin::BI__builtin_fpclassify: {
12677 APFloat Val(0.0);
12678 if (!EvaluateFloat(E->getArg(5), Val, Info))
12679 return false;
12680 unsigned Arg;
12681 switch (Val.getCategory()) {
12682 case APFloat::fcNaN: Arg = 0; break;
12683 case APFloat::fcInfinity: Arg = 1; break;
12684 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12685 case APFloat::fcZero: Arg = 4; break;
12686 }
12687 return Visit(E->getArg(Arg));
12688 }
12689
12690 case Builtin::BI__builtin_isinf_sign: {
12691 APFloat Val(0.0);
12692 return EvaluateFloat(E->getArg(0), Val, Info) &&
12693 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12694 }
12695
12696 case Builtin::BI__builtin_isinf: {
12697 APFloat Val(0.0);
12698 return EvaluateFloat(E->getArg(0), Val, Info) &&
12699 Success(Val.isInfinity() ? 1 : 0, E);
12700 }
12701
12702 case Builtin::BI__builtin_isfinite: {
12703 APFloat Val(0.0);
12704 return EvaluateFloat(E->getArg(0), Val, Info) &&
12705 Success(Val.isFinite() ? 1 : 0, E);
12706 }
12707
12708 case Builtin::BI__builtin_isnan: {
12709 APFloat Val(0.0);
12710 return EvaluateFloat(E->getArg(0), Val, Info) &&
12711 Success(Val.isNaN() ? 1 : 0, E);
12712 }
12713
12714 case Builtin::BI__builtin_isnormal: {
12715 APFloat Val(0.0);
12716 return EvaluateFloat(E->getArg(0), Val, Info) &&
12717 Success(Val.isNormal() ? 1 : 0, E);
12718 }
12719
12720 case Builtin::BI__builtin_issubnormal: {
12721 APFloat Val(0.0);
12722 return EvaluateFloat(E->getArg(0), Val, Info) &&
12723 Success(Val.isDenormal() ? 1 : 0, E);
12724 }
12725
12726 case Builtin::BI__builtin_iszero: {
12727 APFloat Val(0.0);
12728 return EvaluateFloat(E->getArg(0), Val, Info) &&
12729 Success(Val.isZero() ? 1 : 0, E);
12730 }
12731
12732 case Builtin::BI__builtin_issignaling: {
12733 APFloat Val(0.0);
12734 return EvaluateFloat(E->getArg(0), Val, Info) &&
12735 Success(Val.isSignaling() ? 1 : 0, E);
12736 }
12737
12738 case Builtin::BI__builtin_isfpclass: {
12739 APSInt MaskVal;
12740 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
12741 return false;
12742 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
12743 APFloat Val(0.0);
12744 return EvaluateFloat(E->getArg(0), Val, Info) &&
12745 Success((Val.classify() & Test) ? 1 : 0, E);
12746 }
12747
12748 case Builtin::BI__builtin_parity:
12749 case Builtin::BI__builtin_parityl:
12750 case Builtin::BI__builtin_parityll: {
12751 APSInt Val;
12752 if (!EvaluateInteger(E->getArg(0), Val, Info))
12753 return false;
12754
12755 return Success(Val.popcount() % 2, E);
12756 }
12757
12758 case Builtin::BI__builtin_popcount:
12759 case Builtin::BI__builtin_popcountl:
12760 case Builtin::BI__builtin_popcountll:
12761 case Builtin::BI__builtin_popcountg:
12762 case Builtin::BI__popcnt16: // Microsoft variants of popcount
12763 case Builtin::BI__popcnt:
12764 case Builtin::BI__popcnt64: {
12765 APSInt Val;
12766 if (!EvaluateInteger(E->getArg(0), Val, Info))
12767 return false;
12768
12769 return Success(Val.popcount(), E);
12770 }
12771
12772 case Builtin::BI__builtin_rotateleft8:
12773 case Builtin::BI__builtin_rotateleft16:
12774 case Builtin::BI__builtin_rotateleft32:
12775 case Builtin::BI__builtin_rotateleft64:
12776 case Builtin::BI_rotl8: // Microsoft variants of rotate right
12777 case Builtin::BI_rotl16:
12778 case Builtin::BI_rotl:
12779 case Builtin::BI_lrotl:
12780 case Builtin::BI_rotl64: {
12781 APSInt Val, Amt;
12782 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12783 !EvaluateInteger(E->getArg(1), Amt, Info))
12784 return false;
12785
12786 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12787 }
12788
12789 case Builtin::BI__builtin_rotateright8:
12790 case Builtin::BI__builtin_rotateright16:
12791 case Builtin::BI__builtin_rotateright32:
12792 case Builtin::BI__builtin_rotateright64:
12793 case Builtin::BI_rotr8: // Microsoft variants of rotate right
12794 case Builtin::BI_rotr16:
12795 case Builtin::BI_rotr:
12796 case Builtin::BI_lrotr:
12797 case Builtin::BI_rotr64: {
12798 APSInt Val, Amt;
12799 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12800 !EvaluateInteger(E->getArg(1), Amt, Info))
12801 return false;
12802
12803 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12804 }
12805
12806 case Builtin::BIstrlen:
12807 case Builtin::BIwcslen:
12808 // A call to strlen is not a constant expression.
12809 if (Info.getLangOpts().CPlusPlus11)
12810 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12811 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12812 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12813 else
12814 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12815 [[fallthrough]];
12816 case Builtin::BI__builtin_strlen:
12817 case Builtin::BI__builtin_wcslen: {
12818 // As an extension, we support __builtin_strlen() as a constant expression,
12819 // and support folding strlen() to a constant.
12820 uint64_t StrLen;
12821 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12822 return Success(StrLen, E);
12823 return false;
12824 }
12825
12826 case Builtin::BIstrcmp:
12827 case Builtin::BIwcscmp:
12828 case Builtin::BIstrncmp:
12829 case Builtin::BIwcsncmp:
12830 case Builtin::BImemcmp:
12831 case Builtin::BIbcmp:
12832 case Builtin::BIwmemcmp:
12833 // A call to strlen is not a constant expression.
12834 if (Info.getLangOpts().CPlusPlus11)
12835 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12836 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12837 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12838 else
12839 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12840 [[fallthrough]];
12841 case Builtin::BI__builtin_strcmp:
12842 case Builtin::BI__builtin_wcscmp:
12843 case Builtin::BI__builtin_strncmp:
12844 case Builtin::BI__builtin_wcsncmp:
12845 case Builtin::BI__builtin_memcmp:
12846 case Builtin::BI__builtin_bcmp:
12847 case Builtin::BI__builtin_wmemcmp: {
12848 LValue String1, String2;
12849 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12850 !EvaluatePointer(E->getArg(1), String2, Info))
12851 return false;
12852
12853 uint64_t MaxLength = uint64_t(-1);
12854 if (BuiltinOp != Builtin::BIstrcmp &&
12855 BuiltinOp != Builtin::BIwcscmp &&
12856 BuiltinOp != Builtin::BI__builtin_strcmp &&
12857 BuiltinOp != Builtin::BI__builtin_wcscmp) {
12858 APSInt N;
12859 if (!EvaluateInteger(E->getArg(2), N, Info))
12860 return false;
12861 MaxLength = N.getZExtValue();
12862 }
12863
12864 // Empty substrings compare equal by definition.
12865 if (MaxLength == 0u)
12866 return Success(0, E);
12867
12868 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12869 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12870 String1.Designator.Invalid || String2.Designator.Invalid)
12871 return false;
12872
12873 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12874 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12875
12876 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12877 BuiltinOp == Builtin::BIbcmp ||
12878 BuiltinOp == Builtin::BI__builtin_memcmp ||
12879 BuiltinOp == Builtin::BI__builtin_bcmp;
12880
12881 assert(IsRawByte ||
12882 (Info.Ctx.hasSameUnqualifiedType(
12883 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12884 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12885
12886 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12887 // 'char8_t', but no other types.
12888 if (IsRawByte &&
12889 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12890 // FIXME: Consider using our bit_cast implementation to support this.
12891 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12892 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12893 << CharTy1 << CharTy2;
12894 return false;
12895 }
12896
12897 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12898 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12899 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12900 Char1.isInt() && Char2.isInt();
12901 };
12902 const auto &AdvanceElems = [&] {
12903 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12904 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12905 };
12906
12907 bool StopAtNull =
12908 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12909 BuiltinOp != Builtin::BIwmemcmp &&
12910 BuiltinOp != Builtin::BI__builtin_memcmp &&
12911 BuiltinOp != Builtin::BI__builtin_bcmp &&
12912 BuiltinOp != Builtin::BI__builtin_wmemcmp);
12913 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12914 BuiltinOp == Builtin::BIwcsncmp ||
12915 BuiltinOp == Builtin::BIwmemcmp ||
12916 BuiltinOp == Builtin::BI__builtin_wcscmp ||
12917 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12918 BuiltinOp == Builtin::BI__builtin_wmemcmp;
12919
12920 for (; MaxLength; --MaxLength) {
12921 APValue Char1, Char2;
12922 if (!ReadCurElems(Char1, Char2))
12923 return false;
12924 if (Char1.getInt().ne(Char2.getInt())) {
12925 if (IsWide) // wmemcmp compares with wchar_t signedness.
12926 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12927 // memcmp always compares unsigned chars.
12928 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12929 }
12930 if (StopAtNull && !Char1.getInt())
12931 return Success(0, E);
12932 assert(!(StopAtNull && !Char2.getInt()));
12933 if (!AdvanceElems())
12934 return false;
12935 }
12936 // We hit the strncmp / memcmp limit.
12937 return Success(0, E);
12938 }
12939
12940 case Builtin::BI__atomic_always_lock_free:
12941 case Builtin::BI__atomic_is_lock_free:
12942 case Builtin::BI__c11_atomic_is_lock_free: {
12943 APSInt SizeVal;
12944 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12945 return false;
12946
12947 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12948 // of two less than or equal to the maximum inline atomic width, we know it
12949 // is lock-free. If the size isn't a power of two, or greater than the
12950 // maximum alignment where we promote atomics, we know it is not lock-free
12951 // (at least not in the sense of atomic_is_lock_free). Otherwise,
12952 // the answer can only be determined at runtime; for example, 16-byte
12953 // atomics have lock-free implementations on some, but not all,
12954 // x86-64 processors.
12955
12956 // Check power-of-two.
12957 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12958 if (Size.isPowerOfTwo()) {
12959 // Check against inlining width.
12960 unsigned InlineWidthBits =
12961 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12962 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12963 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12964 Size == CharUnits::One())
12965 return Success(1, E);
12966
12967 // If the pointer argument can be evaluated to a compile-time constant
12968 // integer (or nullptr), check if that value is appropriately aligned.
12969 const Expr *PtrArg = E->getArg(1);
12971 APSInt IntResult;
12972 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
12973 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
12974 Info.Ctx) &&
12975 IntResult.isAligned(Size.getAsAlign()))
12976 return Success(1, E);
12977
12978 // Otherwise, check if the type's alignment against Size.
12979 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
12980 // Drop the potential implicit-cast to 'const volatile void*', getting
12981 // the underlying type.
12982 if (ICE->getCastKind() == CK_BitCast)
12983 PtrArg = ICE->getSubExpr();
12984 }
12985
12986 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
12987 QualType PointeeType = PtrTy->getPointeeType();
12988 if (!PointeeType->isIncompleteType() &&
12989 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12990 // OK, we will inline operations on this object.
12991 return Success(1, E);
12992 }
12993 }
12994 }
12995 }
12996
12997 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12998 Success(0, E) : Error(E);
12999 }
13000 case Builtin::BI__builtin_addcb:
13001 case Builtin::BI__builtin_addcs:
13002 case Builtin::BI__builtin_addc:
13003 case Builtin::BI__builtin_addcl:
13004 case Builtin::BI__builtin_addcll:
13005 case Builtin::BI__builtin_subcb:
13006 case Builtin::BI__builtin_subcs:
13007 case Builtin::BI__builtin_subc:
13008 case Builtin::BI__builtin_subcl:
13009 case Builtin::BI__builtin_subcll: {
13010 LValue CarryOutLValue;
13011 APSInt LHS, RHS, CarryIn, CarryOut, Result;
13012 QualType ResultType = E->getArg(0)->getType();
13013 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13014 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13015 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13016 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13017 return false;
13018 // Copy the number of bits and sign.
13019 Result = LHS;
13020 CarryOut = LHS;
13021
13022 bool FirstOverflowed = false;
13023 bool SecondOverflowed = false;
13024 switch (BuiltinOp) {
13025 default:
13026 llvm_unreachable("Invalid value for BuiltinOp");
13027 case Builtin::BI__builtin_addcb:
13028 case Builtin::BI__builtin_addcs:
13029 case Builtin::BI__builtin_addc:
13030 case Builtin::BI__builtin_addcl:
13031 case Builtin::BI__builtin_addcll:
13032 Result =
13033 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
13034 break;
13035 case Builtin::BI__builtin_subcb:
13036 case Builtin::BI__builtin_subcs:
13037 case Builtin::BI__builtin_subc:
13038 case Builtin::BI__builtin_subcl:
13039 case Builtin::BI__builtin_subcll:
13040 Result =
13041 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
13042 break;
13043 }
13044
13045 // It is possible for both overflows to happen but CGBuiltin uses an OR so
13046 // this is consistent.
13047 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13048 APValue APV{CarryOut};
13049 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
13050 return false;
13051 return Success(Result, E);
13052 }
13053 case Builtin::BI__builtin_add_overflow:
13054 case Builtin::BI__builtin_sub_overflow:
13055 case Builtin::BI__builtin_mul_overflow:
13056 case Builtin::BI__builtin_sadd_overflow:
13057 case Builtin::BI__builtin_uadd_overflow:
13058 case Builtin::BI__builtin_uaddl_overflow:
13059 case Builtin::BI__builtin_uaddll_overflow:
13060 case Builtin::BI__builtin_usub_overflow:
13061 case Builtin::BI__builtin_usubl_overflow:
13062 case Builtin::BI__builtin_usubll_overflow:
13063 case Builtin::BI__builtin_umul_overflow:
13064 case Builtin::BI__builtin_umull_overflow:
13065 case Builtin::BI__builtin_umulll_overflow:
13066 case Builtin::BI__builtin_saddl_overflow:
13067 case Builtin::BI__builtin_saddll_overflow:
13068 case Builtin::BI__builtin_ssub_overflow:
13069 case Builtin::BI__builtin_ssubl_overflow:
13070 case Builtin::BI__builtin_ssubll_overflow:
13071 case Builtin::BI__builtin_smul_overflow:
13072 case Builtin::BI__builtin_smull_overflow:
13073 case Builtin::BI__builtin_smulll_overflow: {
13074 LValue ResultLValue;
13075 APSInt LHS, RHS;
13076
13077 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13078 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13079 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13080 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13081 return false;
13082
13083 APSInt Result;
13084 bool DidOverflow = false;
13085
13086 // If the types don't have to match, enlarge all 3 to the largest of them.
13087 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13088 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13089 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13090 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13092 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13094 uint64_t LHSSize = LHS.getBitWidth();
13095 uint64_t RHSSize = RHS.getBitWidth();
13096 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13097 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13098
13099 // Add an additional bit if the signedness isn't uniformly agreed to. We
13100 // could do this ONLY if there is a signed and an unsigned that both have
13101 // MaxBits, but the code to check that is pretty nasty. The issue will be
13102 // caught in the shrink-to-result later anyway.
13103 if (IsSigned && !AllSigned)
13104 ++MaxBits;
13105
13106 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13107 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13108 Result = APSInt(MaxBits, !IsSigned);
13109 }
13110
13111 // Find largest int.
13112 switch (BuiltinOp) {
13113 default:
13114 llvm_unreachable("Invalid value for BuiltinOp");
13115 case Builtin::BI__builtin_add_overflow:
13116 case Builtin::BI__builtin_sadd_overflow:
13117 case Builtin::BI__builtin_saddl_overflow:
13118 case Builtin::BI__builtin_saddll_overflow:
13119 case Builtin::BI__builtin_uadd_overflow:
13120 case Builtin::BI__builtin_uaddl_overflow:
13121 case Builtin::BI__builtin_uaddll_overflow:
13122 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13123 : LHS.uadd_ov(RHS, DidOverflow);
13124 break;
13125 case Builtin::BI__builtin_sub_overflow:
13126 case Builtin::BI__builtin_ssub_overflow:
13127 case Builtin::BI__builtin_ssubl_overflow:
13128 case Builtin::BI__builtin_ssubll_overflow:
13129 case Builtin::BI__builtin_usub_overflow:
13130 case Builtin::BI__builtin_usubl_overflow:
13131 case Builtin::BI__builtin_usubll_overflow:
13132 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13133 : LHS.usub_ov(RHS, DidOverflow);
13134 break;
13135 case Builtin::BI__builtin_mul_overflow:
13136 case Builtin::BI__builtin_smul_overflow:
13137 case Builtin::BI__builtin_smull_overflow:
13138 case Builtin::BI__builtin_smulll_overflow:
13139 case Builtin::BI__builtin_umul_overflow:
13140 case Builtin::BI__builtin_umull_overflow:
13141 case Builtin::BI__builtin_umulll_overflow:
13142 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13143 : LHS.umul_ov(RHS, DidOverflow);
13144 break;
13145 }
13146
13147 // In the case where multiple sizes are allowed, truncate and see if
13148 // the values are the same.
13149 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13150 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13151 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13152 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13153 // since it will give us the behavior of a TruncOrSelf in the case where
13154 // its parameter <= its size. We previously set Result to be at least the
13155 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13156 // will work exactly like TruncOrSelf.
13157 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13158 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13159
13160 if (!APSInt::isSameValue(Temp, Result))
13161 DidOverflow = true;
13162 Result = Temp;
13163 }
13164
13165 APValue APV{Result};
13166 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13167 return false;
13168 return Success(DidOverflow, E);
13169 }
13170 }
13171}
13172
13173/// Determine whether this is a pointer past the end of the complete
13174/// object referred to by the lvalue.
13176 const LValue &LV) {
13177 // A null pointer can be viewed as being "past the end" but we don't
13178 // choose to look at it that way here.
13179 if (!LV.getLValueBase())
13180 return false;
13181
13182 // If the designator is valid and refers to a subobject, we're not pointing
13183 // past the end.
13184 if (!LV.getLValueDesignator().Invalid &&
13185 !LV.getLValueDesignator().isOnePastTheEnd())
13186 return false;
13187
13188 // A pointer to an incomplete type might be past-the-end if the type's size is
13189 // zero. We cannot tell because the type is incomplete.
13190 QualType Ty = getType(LV.getLValueBase());
13191 if (Ty->isIncompleteType())
13192 return true;
13193
13194 // Can't be past the end of an invalid object.
13195 if (LV.getLValueDesignator().Invalid)
13196 return false;
13197
13198 // We're a past-the-end pointer if we point to the byte after the object,
13199 // no matter what our type or path is.
13200 auto Size = Ctx.getTypeSizeInChars(Ty);
13201 return LV.getLValueOffset() == Size;
13202}
13203
13204namespace {
13205
13206/// Data recursive integer evaluator of certain binary operators.
13207///
13208/// We use a data recursive algorithm for binary operators so that we are able
13209/// to handle extreme cases of chained binary operators without causing stack
13210/// overflow.
13211class DataRecursiveIntBinOpEvaluator {
13212 struct EvalResult {
13213 APValue Val;
13214 bool Failed = false;
13215
13216 EvalResult() = default;
13217
13218 void swap(EvalResult &RHS) {
13219 Val.swap(RHS.Val);
13220 Failed = RHS.Failed;
13221 RHS.Failed = false;
13222 }
13223 };
13224
13225 struct Job {
13226 const Expr *E;
13227 EvalResult LHSResult; // meaningful only for binary operator expression.
13228 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13229
13230 Job() = default;
13231 Job(Job &&) = default;
13232
13233 void startSpeculativeEval(EvalInfo &Info) {
13234 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13235 }
13236
13237 private:
13238 SpeculativeEvaluationRAII SpecEvalRAII;
13239 };
13240
13242
13243 IntExprEvaluator &IntEval;
13244 EvalInfo &Info;
13245 APValue &FinalResult;
13246
13247public:
13248 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13249 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13250
13251 /// True if \param E is a binary operator that we are going to handle
13252 /// data recursively.
13253 /// We handle binary operators that are comma, logical, or that have operands
13254 /// with integral or enumeration type.
13255 static bool shouldEnqueue(const BinaryOperator *E) {
13256 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13258 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13259 E->getRHS()->getType()->isIntegralOrEnumerationType());
13260 }
13261
13262 bool Traverse(const BinaryOperator *E) {
13263 enqueue(E);
13264 EvalResult PrevResult;
13265 while (!Queue.empty())
13266 process(PrevResult);
13267
13268 if (PrevResult.Failed) return false;
13269
13270 FinalResult.swap(PrevResult.Val);
13271 return true;
13272 }
13273
13274private:
13275 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13276 return IntEval.Success(Value, E, Result);
13277 }
13278 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13279 return IntEval.Success(Value, E, Result);
13280 }
13281 bool Error(const Expr *E) {
13282 return IntEval.Error(E);
13283 }
13284 bool Error(const Expr *E, diag::kind D) {
13285 return IntEval.Error(E, D);
13286 }
13287
13288 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
13289 return Info.CCEDiag(E, D);
13290 }
13291
13292 // Returns true if visiting the RHS is necessary, false otherwise.
13293 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13294 bool &SuppressRHSDiags);
13295
13296 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13297 const BinaryOperator *E, APValue &Result);
13298
13299 void EvaluateExpr(const Expr *E, EvalResult &Result) {
13300 Result.Failed = !Evaluate(Result.Val, Info, E);
13301 if (Result.Failed)
13302 Result.Val = APValue();
13303 }
13304
13305 void process(EvalResult &Result);
13306
13307 void enqueue(const Expr *E) {
13308 E = E->IgnoreParens();
13309 Queue.resize(Queue.size()+1);
13310 Queue.back().E = E;
13311 Queue.back().Kind = Job::AnyExprKind;
13312 }
13313};
13314
13315}
13316
13317bool DataRecursiveIntBinOpEvaluator::
13318 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13319 bool &SuppressRHSDiags) {
13320 if (E->getOpcode() == BO_Comma) {
13321 // Ignore LHS but note if we could not evaluate it.
13322 if (LHSResult.Failed)
13323 return Info.noteSideEffect();
13324 return true;
13325 }
13326
13327 if (E->isLogicalOp()) {
13328 bool LHSAsBool;
13329 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
13330 // We were able to evaluate the LHS, see if we can get away with not
13331 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
13332 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
13333 Success(LHSAsBool, E, LHSResult.Val);
13334 return false; // Ignore RHS
13335 }
13336 } else {
13337 LHSResult.Failed = true;
13338
13339 // Since we weren't able to evaluate the left hand side, it
13340 // might have had side effects.
13341 if (!Info.noteSideEffect())
13342 return false;
13343
13344 // We can't evaluate the LHS; however, sometimes the result
13345 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13346 // Don't ignore RHS and suppress diagnostics from this arm.
13347 SuppressRHSDiags = true;
13348 }
13349
13350 return true;
13351 }
13352
13353 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13354 E->getRHS()->getType()->isIntegralOrEnumerationType());
13355
13356 if (LHSResult.Failed && !Info.noteFailure())
13357 return false; // Ignore RHS;
13358
13359 return true;
13360}
13361
13362static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
13363 bool IsSub) {
13364 // Compute the new offset in the appropriate width, wrapping at 64 bits.
13365 // FIXME: When compiling for a 32-bit target, we should use 32-bit
13366 // offsets.
13367 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
13368 CharUnits &Offset = LVal.getLValueOffset();
13369 uint64_t Offset64 = Offset.getQuantity();
13370 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
13371 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
13372 : Offset64 + Index64);
13373}
13374
13375bool DataRecursiveIntBinOpEvaluator::
13376 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13377 const BinaryOperator *E, APValue &Result) {
13378 if (E->getOpcode() == BO_Comma) {
13379 if (RHSResult.Failed)
13380 return false;
13381 Result = RHSResult.Val;
13382 return true;
13383 }
13384
13385 if (E->isLogicalOp()) {
13386 bool lhsResult, rhsResult;
13387 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
13388 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
13389
13390 if (LHSIsOK) {
13391 if (RHSIsOK) {
13392 if (E->getOpcode() == BO_LOr)
13393 return Success(lhsResult || rhsResult, E, Result);
13394 else
13395 return Success(lhsResult && rhsResult, E, Result);
13396 }
13397 } else {
13398 if (RHSIsOK) {
13399 // We can't evaluate the LHS; however, sometimes the result
13400 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13401 if (rhsResult == (E->getOpcode() == BO_LOr))
13402 return Success(rhsResult, E, Result);
13403 }
13404 }
13405
13406 return false;
13407 }
13408
13409 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13410 E->getRHS()->getType()->isIntegralOrEnumerationType());
13411
13412 if (LHSResult.Failed || RHSResult.Failed)
13413 return false;
13414
13415 const APValue &LHSVal = LHSResult.Val;
13416 const APValue &RHSVal = RHSResult.Val;
13417
13418 // Handle cases like (unsigned long)&a + 4.
13419 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
13420 Result = LHSVal;
13421 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
13422 return true;
13423 }
13424
13425 // Handle cases like 4 + (unsigned long)&a
13426 if (E->getOpcode() == BO_Add &&
13427 RHSVal.isLValue() && LHSVal.isInt()) {
13428 Result = RHSVal;
13429 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
13430 return true;
13431 }
13432
13433 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
13434 // Handle (intptr_t)&&A - (intptr_t)&&B.
13435 if (!LHSVal.getLValueOffset().isZero() ||
13436 !RHSVal.getLValueOffset().isZero())
13437 return false;
13438 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
13439 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
13440 if (!LHSExpr || !RHSExpr)
13441 return false;
13442 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13443 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13444 if (!LHSAddrExpr || !RHSAddrExpr)
13445 return false;
13446 // Make sure both labels come from the same function.
13447 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13448 RHSAddrExpr->getLabel()->getDeclContext())
13449 return false;
13450 Result = APValue(LHSAddrExpr, RHSAddrExpr);
13451 return true;
13452 }
13453
13454 // All the remaining cases expect both operands to be an integer
13455 if (!LHSVal.isInt() || !RHSVal.isInt())
13456 return Error(E);
13457
13458 // Set up the width and signedness manually, in case it can't be deduced
13459 // from the operation we're performing.
13460 // FIXME: Don't do this in the cases where we can deduce it.
13461 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
13463 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
13464 RHSVal.getInt(), Value))
13465 return false;
13466 return Success(Value, E, Result);
13467}
13468
13469void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
13470 Job &job = Queue.back();
13471
13472 switch (job.Kind) {
13473 case Job::AnyExprKind: {
13474 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
13475 if (shouldEnqueue(Bop)) {
13476 job.Kind = Job::BinOpKind;
13477 enqueue(Bop->getLHS());
13478 return;
13479 }
13480 }
13481
13482 EvaluateExpr(job.E, Result);
13483 Queue.pop_back();
13484 return;
13485 }
13486
13487 case Job::BinOpKind: {
13488 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13489 bool SuppressRHSDiags = false;
13490 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
13491 Queue.pop_back();
13492 return;
13493 }
13494 if (SuppressRHSDiags)
13495 job.startSpeculativeEval(Info);
13496 job.LHSResult.swap(Result);
13497 job.Kind = Job::BinOpVisitedLHSKind;
13498 enqueue(Bop->getRHS());
13499 return;
13500 }
13501
13502 case Job::BinOpVisitedLHSKind: {
13503 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13504 EvalResult RHS;
13505 RHS.swap(Result);
13506 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
13507 Queue.pop_back();
13508 return;
13509 }
13510 }
13511
13512 llvm_unreachable("Invalid Job::Kind!");
13513}
13514
13515namespace {
13516enum class CmpResult {
13517 Unequal,
13518 Less,
13519 Equal,
13520 Greater,
13521 Unordered,
13522};
13523}
13524
13525template <class SuccessCB, class AfterCB>
13526static bool
13528 SuccessCB &&Success, AfterCB &&DoAfter) {
13529 assert(!E->isValueDependent());
13530 assert(E->isComparisonOp() && "expected comparison operator");
13531 assert((E->getOpcode() == BO_Cmp ||
13533 "unsupported binary expression evaluation");
13534 auto Error = [&](const Expr *E) {
13535 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13536 return false;
13537 };
13538
13539 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
13540 bool IsEquality = E->isEqualityOp();
13541
13542 QualType LHSTy = E->getLHS()->getType();
13543 QualType RHSTy = E->getRHS()->getType();
13544
13545 if (LHSTy->isIntegralOrEnumerationType() &&
13546 RHSTy->isIntegralOrEnumerationType()) {
13547 APSInt LHS, RHS;
13548 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13549 if (!LHSOK && !Info.noteFailure())
13550 return false;
13551 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
13552 return false;
13553 if (LHS < RHS)
13554 return Success(CmpResult::Less, E);
13555 if (LHS > RHS)
13556 return Success(CmpResult::Greater, E);
13557 return Success(CmpResult::Equal, E);
13558 }
13559
13560 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
13561 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
13562 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
13563
13564 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13565 if (!LHSOK && !Info.noteFailure())
13566 return false;
13567 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
13568 return false;
13569 if (LHSFX < RHSFX)
13570 return Success(CmpResult::Less, E);
13571 if (LHSFX > RHSFX)
13572 return Success(CmpResult::Greater, E);
13573 return Success(CmpResult::Equal, E);
13574 }
13575
13576 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
13577 ComplexValue LHS, RHS;
13578 bool LHSOK;
13579 if (E->isAssignmentOp()) {
13580 LValue LV;
13581 EvaluateLValue(E->getLHS(), LV, Info);
13582 LHSOK = false;
13583 } else if (LHSTy->isRealFloatingType()) {
13584 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13585 if (LHSOK) {
13586 LHS.makeComplexFloat();
13587 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13588 }
13589 } else {
13590 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13591 }
13592 if (!LHSOK && !Info.noteFailure())
13593 return false;
13594
13595 if (E->getRHS()->getType()->isRealFloatingType()) {
13596 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
13597 return false;
13598 RHS.makeComplexFloat();
13599 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13600 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13601 return false;
13602
13603 if (LHS.isComplexFloat()) {
13604 APFloat::cmpResult CR_r =
13605 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13606 APFloat::cmpResult CR_i =
13607 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13608 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
13609 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13610 } else {
13611 assert(IsEquality && "invalid complex comparison");
13612 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13613 LHS.getComplexIntImag() == RHS.getComplexIntImag();
13614 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13615 }
13616 }
13617
13618 if (LHSTy->isRealFloatingType() &&
13619 RHSTy->isRealFloatingType()) {
13620 APFloat RHS(0.0), LHS(0.0);
13621
13622 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13623 if (!LHSOK && !Info.noteFailure())
13624 return false;
13625
13626 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
13627 return false;
13628
13629 assert(E->isComparisonOp() && "Invalid binary operator!");
13630 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13631 if (!Info.InConstantContext &&
13632 APFloatCmpResult == APFloat::cmpUnordered &&
13633 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
13634 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13635 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13636 return false;
13637 }
13638 auto GetCmpRes = [&]() {
13639 switch (APFloatCmpResult) {
13640 case APFloat::cmpEqual:
13641 return CmpResult::Equal;
13642 case APFloat::cmpLessThan:
13643 return CmpResult::Less;
13644 case APFloat::cmpGreaterThan:
13645 return CmpResult::Greater;
13646 case APFloat::cmpUnordered:
13647 return CmpResult::Unordered;
13648 }
13649 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13650 };
13651 return Success(GetCmpRes(), E);
13652 }
13653
13654 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13655 LValue LHSValue, RHSValue;
13656
13657 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13658 if (!LHSOK && !Info.noteFailure())
13659 return false;
13660
13661 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13662 return false;
13663
13664 // Reject differing bases from the normal codepath; we special-case
13665 // comparisons to null.
13666 if (!HasSameBase(LHSValue, RHSValue)) {
13667 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13668 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13669 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13670 Info.FFDiag(E, DiagID)
13671 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13672 return false;
13673 };
13674 // Inequalities and subtractions between unrelated pointers have
13675 // unspecified or undefined behavior.
13676 if (!IsEquality)
13677 return DiagComparison(
13678 diag::note_constexpr_pointer_comparison_unspecified);
13679 // A constant address may compare equal to the address of a symbol.
13680 // The one exception is that address of an object cannot compare equal
13681 // to a null pointer constant.
13682 // TODO: Should we restrict this to actual null pointers, and exclude the
13683 // case of zero cast to pointer type?
13684 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13685 (!RHSValue.Base && !RHSValue.Offset.isZero()))
13686 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13687 !RHSValue.Base);
13688 // It's implementation-defined whether distinct literals will have
13689 // distinct addresses. In clang, the result of such a comparison is
13690 // unspecified, so it is not a constant expression. However, we do know
13691 // that the address of a literal will be non-null.
13692 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13693 LHSValue.Base && RHSValue.Base)
13694 return DiagComparison(diag::note_constexpr_literal_comparison);
13695 // We can't tell whether weak symbols will end up pointing to the same
13696 // object.
13697 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13698 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13699 !IsWeakLValue(LHSValue));
13700 // We can't compare the address of the start of one object with the
13701 // past-the-end address of another object, per C++ DR1652.
13702 if (LHSValue.Base && LHSValue.Offset.isZero() &&
13703 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13704 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13705 true);
13706 if (RHSValue.Base && RHSValue.Offset.isZero() &&
13707 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13708 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13709 false);
13710 // We can't tell whether an object is at the same address as another
13711 // zero sized object.
13712 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13713 (LHSValue.Base && isZeroSized(RHSValue)))
13714 return DiagComparison(
13715 diag::note_constexpr_pointer_comparison_zero_sized);
13716 return Success(CmpResult::Unequal, E);
13717 }
13718
13719 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13720 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13721
13722 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13723 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13724
13725 // C++11 [expr.rel]p3:
13726 // Pointers to void (after pointer conversions) can be compared, with a
13727 // result defined as follows: If both pointers represent the same
13728 // address or are both the null pointer value, the result is true if the
13729 // operator is <= or >= and false otherwise; otherwise the result is
13730 // unspecified.
13731 // We interpret this as applying to pointers to *cv* void.
13732 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13733 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13734
13735 // C++11 [expr.rel]p2:
13736 // - If two pointers point to non-static data members of the same object,
13737 // or to subobjects or array elements fo such members, recursively, the
13738 // pointer to the later declared member compares greater provided the
13739 // two members have the same access control and provided their class is
13740 // not a union.
13741 // [...]
13742 // - Otherwise pointer comparisons are unspecified.
13743 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13744 bool WasArrayIndex;
13745 unsigned Mismatch = FindDesignatorMismatch(
13746 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13747 // At the point where the designators diverge, the comparison has a
13748 // specified value if:
13749 // - we are comparing array indices
13750 // - we are comparing fields of a union, or fields with the same access
13751 // Otherwise, the result is unspecified and thus the comparison is not a
13752 // constant expression.
13753 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13754 Mismatch < RHSDesignator.Entries.size()) {
13755 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13756 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13757 if (!LF && !RF)
13758 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13759 else if (!LF)
13760 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13761 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13762 << RF->getParent() << RF;
13763 else if (!RF)
13764 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13765 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13766 << LF->getParent() << LF;
13767 else if (!LF->getParent()->isUnion() &&
13768 LF->getAccess() != RF->getAccess())
13769 Info.CCEDiag(E,
13770 diag::note_constexpr_pointer_comparison_differing_access)
13771 << LF << LF->getAccess() << RF << RF->getAccess()
13772 << LF->getParent();
13773 }
13774 }
13775
13776 // The comparison here must be unsigned, and performed with the same
13777 // width as the pointer.
13778 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13779 uint64_t CompareLHS = LHSOffset.getQuantity();
13780 uint64_t CompareRHS = RHSOffset.getQuantity();
13781 assert(PtrSize <= 64 && "Unexpected pointer width");
13782 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13783 CompareLHS &= Mask;
13784 CompareRHS &= Mask;
13785
13786 // If there is a base and this is a relational operator, we can only
13787 // compare pointers within the object in question; otherwise, the result
13788 // depends on where the object is located in memory.
13789 if (!LHSValue.Base.isNull() && IsRelational) {
13790 QualType BaseTy = getType(LHSValue.Base);
13791 if (BaseTy->isIncompleteType())
13792 return Error(E);
13793 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13794 uint64_t OffsetLimit = Size.getQuantity();
13795 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13796 return Error(E);
13797 }
13798
13799 if (CompareLHS < CompareRHS)
13800 return Success(CmpResult::Less, E);
13801 if (CompareLHS > CompareRHS)
13802 return Success(CmpResult::Greater, E);
13803 return Success(CmpResult::Equal, E);
13804 }
13805
13806 if (LHSTy->isMemberPointerType()) {
13807 assert(IsEquality && "unexpected member pointer operation");
13808 assert(RHSTy->isMemberPointerType() && "invalid comparison");
13809
13810 MemberPtr LHSValue, RHSValue;
13811
13812 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13813 if (!LHSOK && !Info.noteFailure())
13814 return false;
13815
13816 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13817 return false;
13818
13819 // If either operand is a pointer to a weak function, the comparison is not
13820 // constant.
13821 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13822 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13823 << LHSValue.getDecl();
13824 return false;
13825 }
13826 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13827 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13828 << RHSValue.getDecl();
13829 return false;
13830 }
13831
13832 // C++11 [expr.eq]p2:
13833 // If both operands are null, they compare equal. Otherwise if only one is
13834 // null, they compare unequal.
13835 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13836 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13837 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13838 }
13839
13840 // Otherwise if either is a pointer to a virtual member function, the
13841 // result is unspecified.
13842 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13843 if (MD->isVirtual())
13844 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13845 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13846 if (MD->isVirtual())
13847 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13848
13849 // Otherwise they compare equal if and only if they would refer to the
13850 // same member of the same most derived object or the same subobject if
13851 // they were dereferenced with a hypothetical object of the associated
13852 // class type.
13853 bool Equal = LHSValue == RHSValue;
13854 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13855 }
13856
13857 if (LHSTy->isNullPtrType()) {
13858 assert(E->isComparisonOp() && "unexpected nullptr operation");
13859 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13860 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13861 // are compared, the result is true of the operator is <=, >= or ==, and
13862 // false otherwise.
13863 LValue Res;
13864 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
13865 !EvaluatePointer(E->getRHS(), Res, Info))
13866 return false;
13867 return Success(CmpResult::Equal, E);
13868 }
13869
13870 return DoAfter();
13871}
13872
13873bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13874 if (!CheckLiteralType(Info, E))
13875 return false;
13876
13877 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13879 switch (CR) {
13880 case CmpResult::Unequal:
13881 llvm_unreachable("should never produce Unequal for three-way comparison");
13882 case CmpResult::Less:
13883 CCR = ComparisonCategoryResult::Less;
13884 break;
13885 case CmpResult::Equal:
13886 CCR = ComparisonCategoryResult::Equal;
13887 break;
13888 case CmpResult::Greater:
13889 CCR = ComparisonCategoryResult::Greater;
13890 break;
13891 case CmpResult::Unordered:
13892 CCR = ComparisonCategoryResult::Unordered;
13893 break;
13894 }
13895 // Evaluation succeeded. Lookup the information for the comparison category
13896 // type and fetch the VarDecl for the result.
13897 const ComparisonCategoryInfo &CmpInfo =
13899 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13900 // Check and evaluate the result as a constant expression.
13901 LValue LV;
13902 LV.set(VD);
13903 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13904 return false;
13905 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13906 ConstantExprKind::Normal);
13907 };
13908 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13909 return ExprEvaluatorBaseTy::VisitBinCmp(E);
13910 });
13911}
13912
13913bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13914 const CXXParenListInitExpr *E) {
13915 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13916}
13917
13918bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13919 // We don't support assignment in C. C++ assignments don't get here because
13920 // assignment is an lvalue in C++.
13921 if (E->isAssignmentOp()) {
13922 Error(E);
13923 if (!Info.noteFailure())
13924 return false;
13925 }
13926
13927 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13928 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13929
13930 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13931 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13932 "DataRecursiveIntBinOpEvaluator should have handled integral types");
13933
13934 if (E->isComparisonOp()) {
13935 // Evaluate builtin binary comparisons by evaluating them as three-way
13936 // comparisons and then translating the result.
13937 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13938 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13939 "should only produce Unequal for equality comparisons");
13940 bool IsEqual = CR == CmpResult::Equal,
13941 IsLess = CR == CmpResult::Less,
13942 IsGreater = CR == CmpResult::Greater;
13943 auto Op = E->getOpcode();
13944 switch (Op) {
13945 default:
13946 llvm_unreachable("unsupported binary operator");
13947 case BO_EQ:
13948 case BO_NE:
13949 return Success(IsEqual == (Op == BO_EQ), E);
13950 case BO_LT:
13951 return Success(IsLess, E);
13952 case BO_GT:
13953 return Success(IsGreater, E);
13954 case BO_LE:
13955 return Success(IsEqual || IsLess, E);
13956 case BO_GE:
13957 return Success(IsEqual || IsGreater, E);
13958 }
13959 };
13960 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13961 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13962 });
13963 }
13964
13965 QualType LHSTy = E->getLHS()->getType();
13966 QualType RHSTy = E->getRHS()->getType();
13967
13968 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13969 E->getOpcode() == BO_Sub) {
13970 LValue LHSValue, RHSValue;
13971
13972 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13973 if (!LHSOK && !Info.noteFailure())
13974 return false;
13975
13976 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13977 return false;
13978
13979 // Reject differing bases from the normal codepath; we special-case
13980 // comparisons to null.
13981 if (!HasSameBase(LHSValue, RHSValue)) {
13982 // Handle &&A - &&B.
13983 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13984 return Error(E);
13985 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13986 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13987 if (!LHSExpr || !RHSExpr)
13988 return Error(E);
13989 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13990 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13991 if (!LHSAddrExpr || !RHSAddrExpr)
13992 return Error(E);
13993 // Make sure both labels come from the same function.
13994 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13995 RHSAddrExpr->getLabel()->getDeclContext())
13996 return Error(E);
13997 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13998 }
13999 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14000 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14001
14002 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14003 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14004
14005 // C++11 [expr.add]p6:
14006 // Unless both pointers point to elements of the same array object, or
14007 // one past the last element of the array object, the behavior is
14008 // undefined.
14009 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14010 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
14011 RHSDesignator))
14012 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
14013
14014 QualType Type = E->getLHS()->getType();
14015 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14016
14017 CharUnits ElementSize;
14018 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14019 return false;
14020
14021 // As an extension, a type may have zero size (empty struct or union in
14022 // C, array of zero length). Pointer subtraction in such cases has
14023 // undefined behavior, so is not constant.
14024 if (ElementSize.isZero()) {
14025 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
14026 << ElementType;
14027 return false;
14028 }
14029
14030 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14031 // and produce incorrect results when it overflows. Such behavior
14032 // appears to be non-conforming, but is common, so perhaps we should
14033 // assume the standard intended for such cases to be undefined behavior
14034 // and check for them.
14035
14036 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14037 // overflow in the final conversion to ptrdiff_t.
14038 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14039 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14040 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14041 false);
14042 APSInt TrueResult = (LHS - RHS) / ElemSize;
14043 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14044
14045 if (Result.extend(65) != TrueResult &&
14046 !HandleOverflow(Info, E, TrueResult, E->getType()))
14047 return false;
14048 return Success(Result, E);
14049 }
14050
14051 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14052}
14053
14054/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14055/// a result as the expression's type.
14056bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14057 const UnaryExprOrTypeTraitExpr *E) {
14058 switch(E->getKind()) {
14059 case UETT_PreferredAlignOf:
14060 case UETT_AlignOf: {
14061 if (E->isArgumentType())
14062 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
14063 E);
14064 else
14065 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
14066 E);
14067 }
14068
14069 case UETT_PtrAuthTypeDiscriminator: {
14070 if (E->getArgumentType()->isDependentType())
14071 return false;
14072 return Success(
14073 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14074 }
14075 case UETT_VecStep: {
14076 QualType Ty = E->getTypeOfArgument();
14077
14078 if (Ty->isVectorType()) {
14079 unsigned n = Ty->castAs<VectorType>()->getNumElements();
14080
14081 // The vec_step built-in functions that take a 3-component
14082 // vector return 4. (OpenCL 1.1 spec 6.11.12)
14083 if (n == 3)
14084 n = 4;
14085
14086 return Success(n, E);
14087 } else
14088 return Success(1, E);
14089 }
14090
14091 case UETT_DataSizeOf:
14092 case UETT_SizeOf: {
14093 QualType SrcTy = E->getTypeOfArgument();
14094 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14095 // the result is the size of the referenced type."
14096 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14097 SrcTy = Ref->getPointeeType();
14098
14099 CharUnits Sizeof;
14100 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14101 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14102 : SizeOfType::SizeOf)) {
14103 return false;
14104 }
14105 return Success(Sizeof, E);
14106 }
14107 case UETT_OpenMPRequiredSimdAlign:
14108 assert(E->isArgumentType());
14109 return Success(
14110 Info.Ctx.toCharUnitsFromBits(
14111 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14112 .getQuantity(),
14113 E);
14114 case UETT_VectorElements: {
14115 QualType Ty = E->getTypeOfArgument();
14116 // If the vector has a fixed size, we can determine the number of elements
14117 // at compile time.
14118 if (const auto *VT = Ty->getAs<VectorType>())
14119 return Success(VT->getNumElements(), E);
14120
14121 assert(Ty->isSizelessVectorType());
14122 if (Info.InConstantContext)
14123 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14124 << E->getSourceRange();
14125
14126 return false;
14127 }
14128 }
14129
14130 llvm_unreachable("unknown expr/type trait");
14131}
14132
14133bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14134 CharUnits Result;
14135 unsigned n = OOE->getNumComponents();
14136 if (n == 0)
14137 return Error(OOE);
14138 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14139 for (unsigned i = 0; i != n; ++i) {
14140 OffsetOfNode ON = OOE->getComponent(i);
14141 switch (ON.getKind()) {
14142 case OffsetOfNode::Array: {
14143 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14144 APSInt IdxResult;
14145 if (!EvaluateInteger(Idx, IdxResult, Info))
14146 return false;
14147 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
14148 if (!AT)
14149 return Error(OOE);
14150 CurrentType = AT->getElementType();
14151 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
14152 Result += IdxResult.getSExtValue() * ElementSize;
14153 break;
14154 }
14155
14156 case OffsetOfNode::Field: {
14157 FieldDecl *MemberDecl = ON.getField();
14158 const RecordType *RT = CurrentType->getAs<RecordType>();
14159 if (!RT)
14160 return Error(OOE);
14161 RecordDecl *RD = RT->getDecl();
14162 if (RD->isInvalidDecl()) return false;
14163 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14164 unsigned i = MemberDecl->getFieldIndex();
14165 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14166 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
14167 CurrentType = MemberDecl->getType().getNonReferenceType();
14168 break;
14169 }
14170
14172 llvm_unreachable("dependent __builtin_offsetof");
14173
14174 case OffsetOfNode::Base: {
14175 CXXBaseSpecifier *BaseSpec = ON.getBase();
14176 if (BaseSpec->isVirtual())
14177 return Error(OOE);
14178
14179 // Find the layout of the class whose base we are looking into.
14180 const RecordType *RT = CurrentType->getAs<RecordType>();
14181 if (!RT)
14182 return Error(OOE);
14183 RecordDecl *RD = RT->getDecl();
14184 if (RD->isInvalidDecl()) return false;
14185 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14186
14187 // Find the base class itself.
14188 CurrentType = BaseSpec->getType();
14189 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14190 if (!BaseRT)
14191 return Error(OOE);
14192
14193 // Add the offset to the base.
14194 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14195 break;
14196 }
14197 }
14198 }
14199 return Success(Result, OOE);
14200}
14201
14202bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14203 switch (E->getOpcode()) {
14204 default:
14205 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14206 // See C99 6.6p3.
14207 return Error(E);
14208 case UO_Extension:
14209 // FIXME: Should extension allow i-c-e extension expressions in its scope?
14210 // If so, we could clear the diagnostic ID.
14211 return Visit(E->getSubExpr());
14212 case UO_Plus:
14213 // The result is just the value.
14214 return Visit(E->getSubExpr());
14215 case UO_Minus: {
14216 if (!Visit(E->getSubExpr()))
14217 return false;
14218 if (!Result.isInt()) return Error(E);
14219 const APSInt &Value = Result.getInt();
14220 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14221 if (Info.checkingForUndefinedBehavior())
14222 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14223 diag::warn_integer_constant_overflow)
14224 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
14225 /*UpperCase=*/true, /*InsertSeparators=*/true)
14226 << E->getType() << E->getSourceRange();
14227
14228 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14229 E->getType()))
14230 return false;
14231 }
14232 return Success(-Value, E);
14233 }
14234 case UO_Not: {
14235 if (!Visit(E->getSubExpr()))
14236 return false;
14237 if (!Result.isInt()) return Error(E);
14238 return Success(~Result.getInt(), E);
14239 }
14240 case UO_LNot: {
14241 bool bres;
14242 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14243 return false;
14244 return Success(!bres, E);
14245 }
14246 }
14247}
14248
14249/// HandleCast - This is used to evaluate implicit or explicit casts where the
14250/// result type is integer.
14251bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14252 const Expr *SubExpr = E->getSubExpr();
14253 QualType DestType = E->getType();
14254 QualType SrcType = SubExpr->getType();
14255
14256 switch (E->getCastKind()) {
14257 case CK_BaseToDerived:
14258 case CK_DerivedToBase:
14259 case CK_UncheckedDerivedToBase:
14260 case CK_Dynamic:
14261 case CK_ToUnion:
14262 case CK_ArrayToPointerDecay:
14263 case CK_FunctionToPointerDecay:
14264 case CK_NullToPointer:
14265 case CK_NullToMemberPointer:
14266 case CK_BaseToDerivedMemberPointer:
14267 case CK_DerivedToBaseMemberPointer:
14268 case CK_ReinterpretMemberPointer:
14269 case CK_ConstructorConversion:
14270 case CK_IntegralToPointer:
14271 case CK_ToVoid:
14272 case CK_VectorSplat:
14273 case CK_IntegralToFloating:
14274 case CK_FloatingCast:
14275 case CK_CPointerToObjCPointerCast:
14276 case CK_BlockPointerToObjCPointerCast:
14277 case CK_AnyPointerToBlockPointerCast:
14278 case CK_ObjCObjectLValueCast:
14279 case CK_FloatingRealToComplex:
14280 case CK_FloatingComplexToReal:
14281 case CK_FloatingComplexCast:
14282 case CK_FloatingComplexToIntegralComplex:
14283 case CK_IntegralRealToComplex:
14284 case CK_IntegralComplexCast:
14285 case CK_IntegralComplexToFloatingComplex:
14286 case CK_BuiltinFnToFnPtr:
14287 case CK_ZeroToOCLOpaqueType:
14288 case CK_NonAtomicToAtomic:
14289 case CK_AddressSpaceConversion:
14290 case CK_IntToOCLSampler:
14291 case CK_FloatingToFixedPoint:
14292 case CK_FixedPointToFloating:
14293 case CK_FixedPointCast:
14294 case CK_IntegralToFixedPoint:
14295 case CK_MatrixCast:
14296 case CK_HLSLVectorTruncation:
14297 llvm_unreachable("invalid cast kind for integral value");
14298
14299 case CK_BitCast:
14300 case CK_Dependent:
14301 case CK_LValueBitCast:
14302 case CK_ARCProduceObject:
14303 case CK_ARCConsumeObject:
14304 case CK_ARCReclaimReturnedObject:
14305 case CK_ARCExtendBlockObject:
14306 case CK_CopyAndAutoreleaseBlockObject:
14307 return Error(E);
14308
14309 case CK_UserDefinedConversion:
14310 case CK_LValueToRValue:
14311 case CK_AtomicToNonAtomic:
14312 case CK_NoOp:
14313 case CK_LValueToRValueBitCast:
14314 case CK_HLSLArrayRValue:
14315 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14316
14317 case CK_MemberPointerToBoolean:
14318 case CK_PointerToBoolean:
14319 case CK_IntegralToBoolean:
14320 case CK_FloatingToBoolean:
14321 case CK_BooleanToSignedIntegral:
14322 case CK_FloatingComplexToBoolean:
14323 case CK_IntegralComplexToBoolean: {
14324 bool BoolResult;
14325 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
14326 return false;
14327 uint64_t IntResult = BoolResult;
14328 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
14329 IntResult = (uint64_t)-1;
14330 return Success(IntResult, E);
14331 }
14332
14333 case CK_FixedPointToIntegral: {
14334 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
14335 if (!EvaluateFixedPoint(SubExpr, Src, Info))
14336 return false;
14337 bool Overflowed;
14338 llvm::APSInt Result = Src.convertToInt(
14339 Info.Ctx.getIntWidth(DestType),
14340 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
14341 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
14342 return false;
14343 return Success(Result, E);
14344 }
14345
14346 case CK_FixedPointToBoolean: {
14347 // Unsigned padding does not affect this.
14348 APValue Val;
14349 if (!Evaluate(Val, Info, SubExpr))
14350 return false;
14351 return Success(Val.getFixedPoint().getBoolValue(), E);
14352 }
14353
14354 case CK_IntegralCast: {
14355 if (!Visit(SubExpr))
14356 return false;
14357
14358 if (!Result.isInt()) {
14359 // Allow casts of address-of-label differences if they are no-ops
14360 // or narrowing. (The narrowing case isn't actually guaranteed to
14361 // be constant-evaluatable except in some narrow cases which are hard
14362 // to detect here. We let it through on the assumption the user knows
14363 // what they are doing.)
14364 if (Result.isAddrLabelDiff())
14365 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
14366 // Only allow casts of lvalues if they are lossless.
14367 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
14368 }
14369
14370 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
14371 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
14372 DestType->isEnumeralType()) {
14373
14374 bool ConstexprVar = true;
14375
14376 // We know if we are here that we are in a context that we might require
14377 // a constant expression or a context that requires a constant
14378 // value. But if we are initializing a value we don't know if it is a
14379 // constexpr variable or not. We can check the EvaluatingDecl to determine
14380 // if it constexpr or not. If not then we don't want to emit a diagnostic.
14381 if (const auto *VD = dyn_cast_or_null<VarDecl>(
14382 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
14383 ConstexprVar = VD->isConstexpr();
14384
14385 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
14386 const EnumDecl *ED = ET->getDecl();
14387 // Check that the value is within the range of the enumeration values.
14388 //
14389 // This corressponds to [expr.static.cast]p10 which says:
14390 // A value of integral or enumeration type can be explicitly converted
14391 // to a complete enumeration type ... If the enumeration type does not
14392 // have a fixed underlying type, the value is unchanged if the original
14393 // value is within the range of the enumeration values ([dcl.enum]), and
14394 // otherwise, the behavior is undefined.
14395 //
14396 // This was resolved as part of DR2338 which has CD5 status.
14397 if (!ED->isFixed()) {
14398 llvm::APInt Min;
14399 llvm::APInt Max;
14400
14401 ED->getValueRange(Max, Min);
14402 --Max;
14403
14404 if (ED->getNumNegativeBits() && ConstexprVar &&
14405 (Max.slt(Result.getInt().getSExtValue()) ||
14406 Min.sgt(Result.getInt().getSExtValue())))
14407 Info.Ctx.getDiagnostics().Report(
14408 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14409 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
14410 << Max.getSExtValue() << ED;
14411 else if (!ED->getNumNegativeBits() && ConstexprVar &&
14412 Max.ult(Result.getInt().getZExtValue()))
14413 Info.Ctx.getDiagnostics().Report(
14414 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14415 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
14416 << Max.getZExtValue() << ED;
14417 }
14418 }
14419
14420 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
14421 Result.getInt()), E);
14422 }
14423
14424 case CK_PointerToIntegral: {
14425 CCEDiag(E, diag::note_constexpr_invalid_cast)
14426 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14427
14428 LValue LV;
14429 if (!EvaluatePointer(SubExpr, LV, Info))
14430 return false;
14431
14432 if (LV.getLValueBase()) {
14433 // Only allow based lvalue casts if they are lossless.
14434 // FIXME: Allow a larger integer size than the pointer size, and allow
14435 // narrowing back down to pointer width in subsequent integral casts.
14436 // FIXME: Check integer type's active bits, not its type size.
14437 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
14438 return Error(E);
14439
14440 LV.Designator.setInvalid();
14441 LV.moveInto(Result);
14442 return true;
14443 }
14444
14445 APSInt AsInt;
14446 APValue V;
14447 LV.moveInto(V);
14448 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
14449 llvm_unreachable("Can't cast this!");
14450
14451 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
14452 }
14453
14454 case CK_IntegralComplexToReal: {
14455 ComplexValue C;
14456 if (!EvaluateComplex(SubExpr, C, Info))
14457 return false;
14458 return Success(C.getComplexIntReal(), E);
14459 }
14460
14461 case CK_FloatingToIntegral: {
14462 APFloat F(0.0);
14463 if (!EvaluateFloat(SubExpr, F, Info))
14464 return false;
14465
14466 APSInt Value;
14467 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
14468 return false;
14469 return Success(Value, E);
14470 }
14471 }
14472
14473 llvm_unreachable("unknown cast resulting in integral value");
14474}
14475
14476bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14477 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14478 ComplexValue LV;
14479 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14480 return false;
14481 if (!LV.isComplexInt())
14482 return Error(E);
14483 return Success(LV.getComplexIntReal(), E);
14484 }
14485
14486 return Visit(E->getSubExpr());
14487}
14488
14489bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14490 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
14491 ComplexValue LV;
14492 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14493 return false;
14494 if (!LV.isComplexInt())
14495 return Error(E);
14496 return Success(LV.getComplexIntImag(), E);
14497 }
14498
14499 VisitIgnoredValue(E->getSubExpr());
14500 return Success(0, E);
14501}
14502
14503bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
14504 return Success(E->getPackLength(), E);
14505}
14506
14507bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
14508 return Success(E->getValue(), E);
14509}
14510
14511bool IntExprEvaluator::VisitConceptSpecializationExpr(
14513 return Success(E->isSatisfied(), E);
14514}
14515
14516bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
14517 return Success(E->isSatisfied(), E);
14518}
14519
14520bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14521 switch (E->getOpcode()) {
14522 default:
14523 // Invalid unary operators
14524 return Error(E);
14525 case UO_Plus:
14526 // The result is just the value.
14527 return Visit(E->getSubExpr());
14528 case UO_Minus: {
14529 if (!Visit(E->getSubExpr())) return false;
14530 if (!Result.isFixedPoint())
14531 return Error(E);
14532 bool Overflowed;
14533 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
14534 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
14535 return false;
14536 return Success(Negated, E);
14537 }
14538 case UO_LNot: {
14539 bool bres;
14540 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14541 return false;
14542 return Success(!bres, E);
14543 }
14544 }
14545}
14546
14547bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
14548 const Expr *SubExpr = E->getSubExpr();
14549 QualType DestType = E->getType();
14550 assert(DestType->isFixedPointType() &&
14551 "Expected destination type to be a fixed point type");
14552 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
14553
14554 switch (E->getCastKind()) {
14555 case CK_FixedPointCast: {
14556 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14557 if (!EvaluateFixedPoint(SubExpr, Src, Info))
14558 return false;
14559 bool Overflowed;
14560 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
14561 if (Overflowed) {
14562 if (Info.checkingForUndefinedBehavior())
14563 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14564 diag::warn_fixedpoint_constant_overflow)
14565 << Result.toString() << E->getType();
14566 if (!HandleOverflow(Info, E, Result, E->getType()))
14567 return false;
14568 }
14569 return Success(Result, E);
14570 }
14571 case CK_IntegralToFixedPoint: {
14572 APSInt Src;
14573 if (!EvaluateInteger(SubExpr, Src, Info))
14574 return false;
14575
14576 bool Overflowed;
14577 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
14578 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14579
14580 if (Overflowed) {
14581 if (Info.checkingForUndefinedBehavior())
14582 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14583 diag::warn_fixedpoint_constant_overflow)
14584 << IntResult.toString() << E->getType();
14585 if (!HandleOverflow(Info, E, IntResult, E->getType()))
14586 return false;
14587 }
14588
14589 return Success(IntResult, E);
14590 }
14591 case CK_FloatingToFixedPoint: {
14592 APFloat Src(0.0);
14593 if (!EvaluateFloat(SubExpr, Src, Info))
14594 return false;
14595
14596 bool Overflowed;
14597 APFixedPoint Result = APFixedPoint::getFromFloatValue(
14598 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14599
14600 if (Overflowed) {
14601 if (Info.checkingForUndefinedBehavior())
14602 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14603 diag::warn_fixedpoint_constant_overflow)
14604 << Result.toString() << E->getType();
14605 if (!HandleOverflow(Info, E, Result, E->getType()))
14606 return false;
14607 }
14608
14609 return Success(Result, E);
14610 }
14611 case CK_NoOp:
14612 case CK_LValueToRValue:
14613 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14614 default:
14615 return Error(E);
14616 }
14617}
14618
14619bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14620 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14621 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14622
14623 const Expr *LHS = E->getLHS();
14624 const Expr *RHS = E->getRHS();
14625 FixedPointSemantics ResultFXSema =
14626 Info.Ctx.getFixedPointSemantics(E->getType());
14627
14628 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
14629 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
14630 return false;
14631 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
14632 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
14633 return false;
14634
14635 bool OpOverflow = false, ConversionOverflow = false;
14636 APFixedPoint Result(LHSFX.getSemantics());
14637 switch (E->getOpcode()) {
14638 case BO_Add: {
14639 Result = LHSFX.add(RHSFX, &OpOverflow)
14640 .convert(ResultFXSema, &ConversionOverflow);
14641 break;
14642 }
14643 case BO_Sub: {
14644 Result = LHSFX.sub(RHSFX, &OpOverflow)
14645 .convert(ResultFXSema, &ConversionOverflow);
14646 break;
14647 }
14648 case BO_Mul: {
14649 Result = LHSFX.mul(RHSFX, &OpOverflow)
14650 .convert(ResultFXSema, &ConversionOverflow);
14651 break;
14652 }
14653 case BO_Div: {
14654 if (RHSFX.getValue() == 0) {
14655 Info.FFDiag(E, diag::note_expr_divide_by_zero);
14656 return false;
14657 }
14658 Result = LHSFX.div(RHSFX, &OpOverflow)
14659 .convert(ResultFXSema, &ConversionOverflow);
14660 break;
14661 }
14662 case BO_Shl:
14663 case BO_Shr: {
14664 FixedPointSemantics LHSSema = LHSFX.getSemantics();
14665 llvm::APSInt RHSVal = RHSFX.getValue();
14666
14667 unsigned ShiftBW =
14668 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14669 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
14670 // Embedded-C 4.1.6.2.2:
14671 // The right operand must be nonnegative and less than the total number
14672 // of (nonpadding) bits of the fixed-point operand ...
14673 if (RHSVal.isNegative())
14674 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
14675 else if (Amt != RHSVal)
14676 Info.CCEDiag(E, diag::note_constexpr_large_shift)
14677 << RHSVal << E->getType() << ShiftBW;
14678
14679 if (E->getOpcode() == BO_Shl)
14680 Result = LHSFX.shl(Amt, &OpOverflow);
14681 else
14682 Result = LHSFX.shr(Amt, &OpOverflow);
14683 break;
14684 }
14685 default:
14686 return false;
14687 }
14688 if (OpOverflow || ConversionOverflow) {
14689 if (Info.checkingForUndefinedBehavior())
14690 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14691 diag::warn_fixedpoint_constant_overflow)
14692 << Result.toString() << E->getType();
14693 if (!HandleOverflow(Info, E, Result, E->getType()))
14694 return false;
14695 }
14696 return Success(Result, E);
14697}
14698
14699//===----------------------------------------------------------------------===//
14700// Float Evaluation
14701//===----------------------------------------------------------------------===//
14702
14703namespace {
14704class FloatExprEvaluator
14705 : public ExprEvaluatorBase<FloatExprEvaluator> {
14706 APFloat &Result;
14707public:
14708 FloatExprEvaluator(EvalInfo &info, APFloat &result)
14709 : ExprEvaluatorBaseTy(info), Result(result) {}
14710
14711 bool Success(const APValue &V, const Expr *e) {
14712 Result = V.getFloat();
14713 return true;
14714 }
14715
14716 bool ZeroInitialization(const Expr *E) {
14717 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14718 return true;
14719 }
14720
14721 bool VisitCallExpr(const CallExpr *E);
14722
14723 bool VisitUnaryOperator(const UnaryOperator *E);
14724 bool VisitBinaryOperator(const BinaryOperator *E);
14725 bool VisitFloatingLiteral(const FloatingLiteral *E);
14726 bool VisitCastExpr(const CastExpr *E);
14727
14728 bool VisitUnaryReal(const UnaryOperator *E);
14729 bool VisitUnaryImag(const UnaryOperator *E);
14730
14731 // FIXME: Missing: array subscript of vector, member of vector
14732};
14733} // end anonymous namespace
14734
14735static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14736 assert(!E->isValueDependent());
14737 assert(E->isPRValue() && E->getType()->isRealFloatingType());
14738 return FloatExprEvaluator(Info, Result).Visit(E);
14739}
14740
14741static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14742 QualType ResultTy,
14743 const Expr *Arg,
14744 bool SNaN,
14745 llvm::APFloat &Result) {
14746 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14747 if (!S) return false;
14748
14749 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14750
14751 llvm::APInt fill;
14752
14753 // Treat empty strings as if they were zero.
14754 if (S->getString().empty())
14755 fill = llvm::APInt(32, 0);
14756 else if (S->getString().getAsInteger(0, fill))
14757 return false;
14758
14759 if (Context.getTargetInfo().isNan2008()) {
14760 if (SNaN)
14761 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14762 else
14763 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14764 } else {
14765 // Prior to IEEE 754-2008, architectures were allowed to choose whether
14766 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14767 // a different encoding to what became a standard in 2008, and for pre-
14768 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14769 // sNaN. This is now known as "legacy NaN" encoding.
14770 if (SNaN)
14771 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14772 else
14773 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14774 }
14775
14776 return true;
14777}
14778
14779bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14780 if (!IsConstantEvaluatedBuiltinCall(E))
14781 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14782
14783 switch (E->getBuiltinCallee()) {
14784 default:
14785 return false;
14786
14787 case Builtin::BI__builtin_huge_val:
14788 case Builtin::BI__builtin_huge_valf:
14789 case Builtin::BI__builtin_huge_vall:
14790 case Builtin::BI__builtin_huge_valf16:
14791 case Builtin::BI__builtin_huge_valf128:
14792 case Builtin::BI__builtin_inf:
14793 case Builtin::BI__builtin_inff:
14794 case Builtin::BI__builtin_infl:
14795 case Builtin::BI__builtin_inff16:
14796 case Builtin::BI__builtin_inff128: {
14797 const llvm::fltSemantics &Sem =
14798 Info.Ctx.getFloatTypeSemantics(E->getType());
14799 Result = llvm::APFloat::getInf(Sem);
14800 return true;
14801 }
14802
14803 case Builtin::BI__builtin_nans:
14804 case Builtin::BI__builtin_nansf:
14805 case Builtin::BI__builtin_nansl:
14806 case Builtin::BI__builtin_nansf16:
14807 case Builtin::BI__builtin_nansf128:
14808 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14809 true, Result))
14810 return Error(E);
14811 return true;
14812
14813 case Builtin::BI__builtin_nan:
14814 case Builtin::BI__builtin_nanf:
14815 case Builtin::BI__builtin_nanl:
14816 case Builtin::BI__builtin_nanf16:
14817 case Builtin::BI__builtin_nanf128:
14818 // If this is __builtin_nan() turn this into a nan, otherwise we
14819 // can't constant fold it.
14820 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14821 false, Result))
14822 return Error(E);
14823 return true;
14824
14825 case Builtin::BI__builtin_fabs:
14826 case Builtin::BI__builtin_fabsf:
14827 case Builtin::BI__builtin_fabsl:
14828 case Builtin::BI__builtin_fabsf128:
14829 // The C standard says "fabs raises no floating-point exceptions,
14830 // even if x is a signaling NaN. The returned value is independent of
14831 // the current rounding direction mode." Therefore constant folding can
14832 // proceed without regard to the floating point settings.
14833 // Reference, WG14 N2478 F.10.4.3
14834 if (!EvaluateFloat(E->getArg(0), Result, Info))
14835 return false;
14836
14837 if (Result.isNegative())
14838 Result.changeSign();
14839 return true;
14840
14841 case Builtin::BI__arithmetic_fence:
14842 return EvaluateFloat(E->getArg(0), Result, Info);
14843
14844 // FIXME: Builtin::BI__builtin_powi
14845 // FIXME: Builtin::BI__builtin_powif
14846 // FIXME: Builtin::BI__builtin_powil
14847
14848 case Builtin::BI__builtin_copysign:
14849 case Builtin::BI__builtin_copysignf:
14850 case Builtin::BI__builtin_copysignl:
14851 case Builtin::BI__builtin_copysignf128: {
14852 APFloat RHS(0.);
14853 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14854 !EvaluateFloat(E->getArg(1), RHS, Info))
14855 return false;
14856 Result.copySign(RHS);
14857 return true;
14858 }
14859
14860 case Builtin::BI__builtin_fmax:
14861 case Builtin::BI__builtin_fmaxf:
14862 case Builtin::BI__builtin_fmaxl:
14863 case Builtin::BI__builtin_fmaxf16:
14864 case Builtin::BI__builtin_fmaxf128: {
14865 // TODO: Handle sNaN.
14866 APFloat RHS(0.);
14867 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14868 !EvaluateFloat(E->getArg(1), RHS, Info))
14869 return false;
14870 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14871 if (Result.isZero() && RHS.isZero() && Result.isNegative())
14872 Result = RHS;
14873 else if (Result.isNaN() || RHS > Result)
14874 Result = RHS;
14875 return true;
14876 }
14877
14878 case Builtin::BI__builtin_fmin:
14879 case Builtin::BI__builtin_fminf:
14880 case Builtin::BI__builtin_fminl:
14881 case Builtin::BI__builtin_fminf16:
14882 case Builtin::BI__builtin_fminf128: {
14883 // TODO: Handle sNaN.
14884 APFloat RHS(0.);
14885 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14886 !EvaluateFloat(E->getArg(1), RHS, Info))
14887 return false;
14888 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14889 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14890 Result = RHS;
14891 else if (Result.isNaN() || RHS < Result)
14892 Result = RHS;
14893 return true;
14894 }
14895 }
14896}
14897
14898bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14899 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14900 ComplexValue CV;
14901 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14902 return false;
14903 Result = CV.FloatReal;
14904 return true;
14905 }
14906
14907 return Visit(E->getSubExpr());
14908}
14909
14910bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14911 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14912 ComplexValue CV;
14913 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14914 return false;
14915 Result = CV.FloatImag;
14916 return true;
14917 }
14918
14919 VisitIgnoredValue(E->getSubExpr());
14920 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14921 Result = llvm::APFloat::getZero(Sem);
14922 return true;
14923}
14924
14925bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14926 switch (E->getOpcode()) {
14927 default: return Error(E);
14928 case UO_Plus:
14929 return EvaluateFloat(E->getSubExpr(), Result, Info);
14930 case UO_Minus:
14931 // In C standard, WG14 N2478 F.3 p4
14932 // "the unary - raises no floating point exceptions,
14933 // even if the operand is signalling."
14934 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14935 return false;
14936 Result.changeSign();
14937 return true;
14938 }
14939}
14940
14941bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14942 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14943 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14944
14945 APFloat RHS(0.0);
14946 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14947 if (!LHSOK && !Info.noteFailure())
14948 return false;
14949 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14950 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14951}
14952
14953bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14954 Result = E->getValue();
14955 return true;
14956}
14957
14958bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14959 const Expr* SubExpr = E->getSubExpr();
14960
14961 switch (E->getCastKind()) {
14962 default:
14963 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14964
14965 case CK_IntegralToFloating: {
14966 APSInt IntResult;
14967 const FPOptions FPO = E->getFPFeaturesInEffect(
14968 Info.Ctx.getLangOpts());
14969 return EvaluateInteger(SubExpr, IntResult, Info) &&
14970 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14971 IntResult, E->getType(), Result);
14972 }
14973
14974 case CK_FixedPointToFloating: {
14975 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14976 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14977 return false;
14978 Result =
14979 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14980 return true;
14981 }
14982
14983 case CK_FloatingCast: {
14984 if (!Visit(SubExpr))
14985 return false;
14986 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14987 Result);
14988 }
14989
14990 case CK_FloatingComplexToReal: {
14991 ComplexValue V;
14992 if (!EvaluateComplex(SubExpr, V, Info))
14993 return false;
14994 Result = V.getComplexFloatReal();
14995 return true;
14996 }
14997 }
14998}
14999
15000//===----------------------------------------------------------------------===//
15001// Complex Evaluation (for float and integer)
15002//===----------------------------------------------------------------------===//
15003
15004namespace {
15005class ComplexExprEvaluator
15006 : public ExprEvaluatorBase<ComplexExprEvaluator> {
15007 ComplexValue &Result;
15008
15009public:
15010 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15011 : ExprEvaluatorBaseTy(info), Result(Result) {}
15012
15013 bool Success(const APValue &V, const Expr *e) {
15014 Result.setFrom(V);
15015 return true;
15016 }
15017
15018 bool ZeroInitialization(const Expr *E);
15019
15020 //===--------------------------------------------------------------------===//
15021 // Visitor Methods
15022 //===--------------------------------------------------------------------===//
15023
15024 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15025 bool VisitCastExpr(const CastExpr *E);
15026 bool VisitBinaryOperator(const BinaryOperator *E);
15027 bool VisitUnaryOperator(const UnaryOperator *E);
15028 bool VisitInitListExpr(const InitListExpr *E);
15029 bool VisitCallExpr(const CallExpr *E);
15030};
15031} // end anonymous namespace
15032
15033static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15034 EvalInfo &Info) {
15035 assert(!E->isValueDependent());
15036 assert(E->isPRValue() && E->getType()->isAnyComplexType());
15037 return ComplexExprEvaluator(Info, Result).Visit(E);
15038}
15039
15040bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15041 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15042 if (ElemTy->isRealFloatingType()) {
15043 Result.makeComplexFloat();
15044 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
15045 Result.FloatReal = Zero;
15046 Result.FloatImag = Zero;
15047 } else {
15048 Result.makeComplexInt();
15049 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
15050 Result.IntReal = Zero;
15051 Result.IntImag = Zero;
15052 }
15053 return true;
15054}
15055
15056bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15057 const Expr* SubExpr = E->getSubExpr();
15058
15059 if (SubExpr->getType()->isRealFloatingType()) {
15060 Result.makeComplexFloat();
15061 APFloat &Imag = Result.FloatImag;
15062 if (!EvaluateFloat(SubExpr, Imag, Info))
15063 return false;
15064
15065 Result.FloatReal = APFloat(Imag.getSemantics());
15066 return true;
15067 } else {
15068 assert(SubExpr->getType()->isIntegerType() &&
15069 "Unexpected imaginary literal.");
15070
15071 Result.makeComplexInt();
15072 APSInt &Imag = Result.IntImag;
15073 if (!EvaluateInteger(SubExpr, Imag, Info))
15074 return false;
15075
15076 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15077 return true;
15078 }
15079}
15080
15081bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15082
15083 switch (E->getCastKind()) {
15084 case CK_BitCast:
15085 case CK_BaseToDerived:
15086 case CK_DerivedToBase:
15087 case CK_UncheckedDerivedToBase:
15088 case CK_Dynamic:
15089 case CK_ToUnion:
15090 case CK_ArrayToPointerDecay:
15091 case CK_FunctionToPointerDecay:
15092 case CK_NullToPointer:
15093 case CK_NullToMemberPointer:
15094 case CK_BaseToDerivedMemberPointer:
15095 case CK_DerivedToBaseMemberPointer:
15096 case CK_MemberPointerToBoolean:
15097 case CK_ReinterpretMemberPointer:
15098 case CK_ConstructorConversion:
15099 case CK_IntegralToPointer:
15100 case CK_PointerToIntegral:
15101 case CK_PointerToBoolean:
15102 case CK_ToVoid:
15103 case CK_VectorSplat:
15104 case CK_IntegralCast:
15105 case CK_BooleanToSignedIntegral:
15106 case CK_IntegralToBoolean:
15107 case CK_IntegralToFloating:
15108 case CK_FloatingToIntegral:
15109 case CK_FloatingToBoolean:
15110 case CK_FloatingCast:
15111 case CK_CPointerToObjCPointerCast:
15112 case CK_BlockPointerToObjCPointerCast:
15113 case CK_AnyPointerToBlockPointerCast:
15114 case CK_ObjCObjectLValueCast:
15115 case CK_FloatingComplexToReal:
15116 case CK_FloatingComplexToBoolean:
15117 case CK_IntegralComplexToReal:
15118 case CK_IntegralComplexToBoolean:
15119 case CK_ARCProduceObject:
15120 case CK_ARCConsumeObject:
15121 case CK_ARCReclaimReturnedObject:
15122 case CK_ARCExtendBlockObject:
15123 case CK_CopyAndAutoreleaseBlockObject:
15124 case CK_BuiltinFnToFnPtr:
15125 case CK_ZeroToOCLOpaqueType:
15126 case CK_NonAtomicToAtomic:
15127 case CK_AddressSpaceConversion:
15128 case CK_IntToOCLSampler:
15129 case CK_FloatingToFixedPoint:
15130 case CK_FixedPointToFloating:
15131 case CK_FixedPointCast:
15132 case CK_FixedPointToBoolean:
15133 case CK_FixedPointToIntegral:
15134 case CK_IntegralToFixedPoint:
15135 case CK_MatrixCast:
15136 case CK_HLSLVectorTruncation:
15137 llvm_unreachable("invalid cast kind for complex value");
15138
15139 case CK_LValueToRValue:
15140 case CK_AtomicToNonAtomic:
15141 case CK_NoOp:
15142 case CK_LValueToRValueBitCast:
15143 case CK_HLSLArrayRValue:
15144 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15145
15146 case CK_Dependent:
15147 case CK_LValueBitCast:
15148 case CK_UserDefinedConversion:
15149 return Error(E);
15150
15151 case CK_FloatingRealToComplex: {
15152 APFloat &Real = Result.FloatReal;
15153 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15154 return false;
15155
15156 Result.makeComplexFloat();
15157 Result.FloatImag = APFloat(Real.getSemantics());
15158 return true;
15159 }
15160
15161 case CK_FloatingComplexCast: {
15162 if (!Visit(E->getSubExpr()))
15163 return false;
15164
15165 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15166 QualType From
15167 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15168
15169 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
15170 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
15171 }
15172
15173 case CK_FloatingComplexToIntegralComplex: {
15174 if (!Visit(E->getSubExpr()))
15175 return false;
15176
15177 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15178 QualType From
15179 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15180 Result.makeComplexInt();
15181 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
15182 To, Result.IntReal) &&
15183 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
15184 To, Result.IntImag);
15185 }
15186
15187 case CK_IntegralRealToComplex: {
15188 APSInt &Real = Result.IntReal;
15189 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15190 return false;
15191
15192 Result.makeComplexInt();
15193 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15194 return true;
15195 }
15196
15197 case CK_IntegralComplexCast: {
15198 if (!Visit(E->getSubExpr()))
15199 return false;
15200
15201 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15202 QualType From
15203 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15204
15205 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
15206 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
15207 return true;
15208 }
15209
15210 case CK_IntegralComplexToFloatingComplex: {
15211 if (!Visit(E->getSubExpr()))
15212 return false;
15213
15214 const FPOptions FPO = E->getFPFeaturesInEffect(
15215 Info.Ctx.getLangOpts());
15216 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15217 QualType From
15218 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15219 Result.makeComplexFloat();
15220 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
15221 To, Result.FloatReal) &&
15222 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
15223 To, Result.FloatImag);
15224 }
15225 }
15226
15227 llvm_unreachable("unknown cast resulting in complex value");
15228}
15229
15230void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
15231 APFloat &ResR, APFloat &ResI) {
15232 // This is an implementation of complex multiplication according to the
15233 // constraints laid out in C11 Annex G. The implementation uses the
15234 // following naming scheme:
15235 // (a + ib) * (c + id)
15236
15237 APFloat AC = A * C;
15238 APFloat BD = B * D;
15239 APFloat AD = A * D;
15240 APFloat BC = B * C;
15241 ResR = AC - BD;
15242 ResI = AD + BC;
15243 if (ResR.isNaN() && ResI.isNaN()) {
15244 bool Recalc = false;
15245 if (A.isInfinity() || B.isInfinity()) {
15246 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15247 A);
15248 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15249 B);
15250 if (C.isNaN())
15251 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15252 if (D.isNaN())
15253 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15254 Recalc = true;
15255 }
15256 if (C.isInfinity() || D.isInfinity()) {
15257 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15258 C);
15259 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15260 D);
15261 if (A.isNaN())
15262 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15263 if (B.isNaN())
15264 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15265 Recalc = true;
15266 }
15267 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
15268 BC.isInfinity())) {
15269 if (A.isNaN())
15270 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15271 if (B.isNaN())
15272 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15273 if (C.isNaN())
15274 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15275 if (D.isNaN())
15276 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15277 Recalc = true;
15278 }
15279 if (Recalc) {
15280 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
15281 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
15282 }
15283 }
15284}
15285
15286void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
15287 APFloat &ResR, APFloat &ResI) {
15288 // This is an implementation of complex division according to the
15289 // constraints laid out in C11 Annex G. The implementation uses the
15290 // following naming scheme:
15291 // (a + ib) / (c + id)
15292
15293 int DenomLogB = 0;
15294 APFloat MaxCD = maxnum(abs(C), abs(D));
15295 if (MaxCD.isFinite()) {
15296 DenomLogB = ilogb(MaxCD);
15297 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15298 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15299 }
15300 APFloat Denom = C * C + D * D;
15301 ResR =
15302 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15303 ResI =
15304 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15305 if (ResR.isNaN() && ResI.isNaN()) {
15306 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15307 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15308 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15309 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15310 D.isFinite()) {
15311 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15312 A);
15313 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15314 B);
15315 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15316 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15317 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15318 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15319 C);
15320 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15321 D);
15322 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15323 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15324 }
15325 }
15326}
15327
15328bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15329 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15330 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15331
15332 // Track whether the LHS or RHS is real at the type system level. When this is
15333 // the case we can simplify our evaluation strategy.
15334 bool LHSReal = false, RHSReal = false;
15335
15336 bool LHSOK;
15337 if (E->getLHS()->getType()->isRealFloatingType()) {
15338 LHSReal = true;
15339 APFloat &Real = Result.FloatReal;
15340 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
15341 if (LHSOK) {
15342 Result.makeComplexFloat();
15343 Result.FloatImag = APFloat(Real.getSemantics());
15344 }
15345 } else {
15346 LHSOK = Visit(E->getLHS());
15347 }
15348 if (!LHSOK && !Info.noteFailure())
15349 return false;
15350
15351 ComplexValue RHS;
15352 if (E->getRHS()->getType()->isRealFloatingType()) {
15353 RHSReal = true;
15354 APFloat &Real = RHS.FloatReal;
15355 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
15356 return false;
15357 RHS.makeComplexFloat();
15358 RHS.FloatImag = APFloat(Real.getSemantics());
15359 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15360 return false;
15361
15362 assert(!(LHSReal && RHSReal) &&
15363 "Cannot have both operands of a complex operation be real.");
15364 switch (E->getOpcode()) {
15365 default: return Error(E);
15366 case BO_Add:
15367 if (Result.isComplexFloat()) {
15368 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
15369 APFloat::rmNearestTiesToEven);
15370 if (LHSReal)
15371 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15372 else if (!RHSReal)
15373 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
15374 APFloat::rmNearestTiesToEven);
15375 } else {
15376 Result.getComplexIntReal() += RHS.getComplexIntReal();
15377 Result.getComplexIntImag() += RHS.getComplexIntImag();
15378 }
15379 break;
15380 case BO_Sub:
15381 if (Result.isComplexFloat()) {
15382 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
15383 APFloat::rmNearestTiesToEven);
15384 if (LHSReal) {
15385 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15386 Result.getComplexFloatImag().changeSign();
15387 } else if (!RHSReal) {
15388 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
15389 APFloat::rmNearestTiesToEven);
15390 }
15391 } else {
15392 Result.getComplexIntReal() -= RHS.getComplexIntReal();
15393 Result.getComplexIntImag() -= RHS.getComplexIntImag();
15394 }
15395 break;
15396 case BO_Mul:
15397 if (Result.isComplexFloat()) {
15398 // This is an implementation of complex multiplication according to the
15399 // constraints laid out in C11 Annex G. The implementation uses the
15400 // following naming scheme:
15401 // (a + ib) * (c + id)
15402 ComplexValue LHS = Result;
15403 APFloat &A = LHS.getComplexFloatReal();
15404 APFloat &B = LHS.getComplexFloatImag();
15405 APFloat &C = RHS.getComplexFloatReal();
15406 APFloat &D = RHS.getComplexFloatImag();
15407 APFloat &ResR = Result.getComplexFloatReal();
15408 APFloat &ResI = Result.getComplexFloatImag();
15409 if (LHSReal) {
15410 assert(!RHSReal && "Cannot have two real operands for a complex op!");
15411 ResR = A;
15412 ResI = A;
15413 // ResR = A * C;
15414 // ResI = A * D;
15415 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
15416 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
15417 return false;
15418 } else if (RHSReal) {
15419 // ResR = C * A;
15420 // ResI = C * B;
15421 ResR = C;
15422 ResI = C;
15423 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
15424 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
15425 return false;
15426 } else {
15427 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
15428 }
15429 } else {
15430 ComplexValue LHS = Result;
15431 Result.getComplexIntReal() =
15432 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
15433 LHS.getComplexIntImag() * RHS.getComplexIntImag());
15434 Result.getComplexIntImag() =
15435 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
15436 LHS.getComplexIntImag() * RHS.getComplexIntReal());
15437 }
15438 break;
15439 case BO_Div:
15440 if (Result.isComplexFloat()) {
15441 // This is an implementation of complex division according to the
15442 // constraints laid out in C11 Annex G. The implementation uses the
15443 // following naming scheme:
15444 // (a + ib) / (c + id)
15445 ComplexValue LHS = Result;
15446 APFloat &A = LHS.getComplexFloatReal();
15447 APFloat &B = LHS.getComplexFloatImag();
15448 APFloat &C = RHS.getComplexFloatReal();
15449 APFloat &D = RHS.getComplexFloatImag();
15450 APFloat &ResR = Result.getComplexFloatReal();
15451 APFloat &ResI = Result.getComplexFloatImag();
15452 if (RHSReal) {
15453 ResR = A;
15454 ResI = B;
15455 // ResR = A / C;
15456 // ResI = B / C;
15457 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
15458 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
15459 return false;
15460 } else {
15461 if (LHSReal) {
15462 // No real optimizations we can do here, stub out with zero.
15463 B = APFloat::getZero(A.getSemantics());
15464 }
15465 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
15466 }
15467 } else {
15468 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
15469 return Error(E, diag::note_expr_divide_by_zero);
15470
15471 ComplexValue LHS = Result;
15472 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
15473 RHS.getComplexIntImag() * RHS.getComplexIntImag();
15474 Result.getComplexIntReal() =
15475 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
15476 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
15477 Result.getComplexIntImag() =
15478 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
15479 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
15480 }
15481 break;
15482 }
15483
15484 return true;
15485}
15486
15487bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15488 // Get the operand value into 'Result'.
15489 if (!Visit(E->getSubExpr()))
15490 return false;
15491
15492 switch (E->getOpcode()) {
15493 default:
15494 return Error(E);
15495 case UO_Extension:
15496 return true;
15497 case UO_Plus:
15498 // The result is always just the subexpr.
15499 return true;
15500 case UO_Minus:
15501 if (Result.isComplexFloat()) {
15502 Result.getComplexFloatReal().changeSign();
15503 Result.getComplexFloatImag().changeSign();
15504 }
15505 else {
15506 Result.getComplexIntReal() = -Result.getComplexIntReal();
15507 Result.getComplexIntImag() = -Result.getComplexIntImag();
15508 }
15509 return true;
15510 case UO_Not:
15511 if (Result.isComplexFloat())
15512 Result.getComplexFloatImag().changeSign();
15513 else
15514 Result.getComplexIntImag() = -Result.getComplexIntImag();
15515 return true;
15516 }
15517}
15518
15519bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15520 if (E->getNumInits() == 2) {
15521 if (E->getType()->isComplexType()) {
15522 Result.makeComplexFloat();
15523 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
15524 return false;
15525 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
15526 return false;
15527 } else {
15528 Result.makeComplexInt();
15529 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
15530 return false;
15531 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
15532 return false;
15533 }
15534 return true;
15535 }
15536 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
15537}
15538
15539bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
15540 if (!IsConstantEvaluatedBuiltinCall(E))
15541 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15542
15543 switch (E->getBuiltinCallee()) {
15544 case Builtin::BI__builtin_complex:
15545 Result.makeComplexFloat();
15546 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
15547 return false;
15548 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
15549 return false;
15550 return true;
15551
15552 default:
15553 return false;
15554 }
15555}
15556
15557//===----------------------------------------------------------------------===//
15558// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
15559// implicit conversion.
15560//===----------------------------------------------------------------------===//
15561
15562namespace {
15563class AtomicExprEvaluator :
15564 public ExprEvaluatorBase<AtomicExprEvaluator> {
15565 const LValue *This;
15566 APValue &Result;
15567public:
15568 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
15569 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15570
15571 bool Success(const APValue &V, const Expr *E) {
15572 Result = V;
15573 return true;
15574 }
15575
15576 bool ZeroInitialization(const Expr *E) {
15579 // For atomic-qualified class (and array) types in C++, initialize the
15580 // _Atomic-wrapped subobject directly, in-place.
15581 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
15582 : Evaluate(Result, Info, &VIE);
15583 }
15584
15585 bool VisitCastExpr(const CastExpr *E) {
15586 switch (E->getCastKind()) {
15587 default:
15588 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15589 case CK_NullToPointer:
15590 VisitIgnoredValue(E->getSubExpr());
15591 return ZeroInitialization(E);
15592 case CK_NonAtomicToAtomic:
15593 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
15594 : Evaluate(Result, Info, E->getSubExpr());
15595 }
15596 }
15597};
15598} // end anonymous namespace
15599
15600static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
15601 EvalInfo &Info) {
15602 assert(!E->isValueDependent());
15603 assert(E->isPRValue() && E->getType()->isAtomicType());
15604 return AtomicExprEvaluator(Info, This, Result).Visit(E);
15605}
15606
15607//===----------------------------------------------------------------------===//
15608// Void expression evaluation, primarily for a cast to void on the LHS of a
15609// comma operator
15610//===----------------------------------------------------------------------===//
15611
15612namespace {
15613class VoidExprEvaluator
15614 : public ExprEvaluatorBase<VoidExprEvaluator> {
15615public:
15616 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
15617
15618 bool Success(const APValue &V, const Expr *e) { return true; }
15619
15620 bool ZeroInitialization(const Expr *E) { return true; }
15621
15622 bool VisitCastExpr(const CastExpr *E) {
15623 switch (E->getCastKind()) {
15624 default:
15625 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15626 case CK_ToVoid:
15627 VisitIgnoredValue(E->getSubExpr());
15628 return true;
15629 }
15630 }
15631
15632 bool VisitCallExpr(const CallExpr *E) {
15633 if (!IsConstantEvaluatedBuiltinCall(E))
15634 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15635
15636 switch (E->getBuiltinCallee()) {
15637 case Builtin::BI__assume:
15638 case Builtin::BI__builtin_assume:
15639 // The argument is not evaluated!
15640 return true;
15641
15642 case Builtin::BI__builtin_operator_delete:
15643 return HandleOperatorDeleteCall(Info, E);
15644
15645 default:
15646 return false;
15647 }
15648 }
15649
15650 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
15651};
15652} // end anonymous namespace
15653
15654bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
15655 // We cannot speculatively evaluate a delete expression.
15656 if (Info.SpeculativeEvaluationDepth)
15657 return false;
15658
15659 FunctionDecl *OperatorDelete = E->getOperatorDelete();
15660 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
15661 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15662 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
15663 return false;
15664 }
15665
15666 const Expr *Arg = E->getArgument();
15667
15668 LValue Pointer;
15669 if (!EvaluatePointer(Arg, Pointer, Info))
15670 return false;
15671 if (Pointer.Designator.Invalid)
15672 return false;
15673
15674 // Deleting a null pointer has no effect.
15675 if (Pointer.isNullPointer()) {
15676 // This is the only case where we need to produce an extension warning:
15677 // the only other way we can succeed is if we find a dynamic allocation,
15678 // and we will have warned when we allocated it in that case.
15679 if (!Info.getLangOpts().CPlusPlus20)
15680 Info.CCEDiag(E, diag::note_constexpr_new);
15681 return true;
15682 }
15683
15684 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
15685 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
15686 if (!Alloc)
15687 return false;
15688 QualType AllocType = Pointer.Base.getDynamicAllocType();
15689
15690 // For the non-array case, the designator must be empty if the static type
15691 // does not have a virtual destructor.
15692 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
15694 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
15695 << Arg->getType()->getPointeeType() << AllocType;
15696 return false;
15697 }
15698
15699 // For a class type with a virtual destructor, the selected operator delete
15700 // is the one looked up when building the destructor.
15701 if (!E->isArrayForm() && !E->isGlobalDelete()) {
15702 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
15703 if (VirtualDelete &&
15704 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
15705 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15706 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
15707 return false;
15708 }
15709 }
15710
15711 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
15712 (*Alloc)->Value, AllocType))
15713 return false;
15714
15715 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
15716 // The element was already erased. This means the destructor call also
15717 // deleted the object.
15718 // FIXME: This probably results in undefined behavior before we get this
15719 // far, and should be diagnosed elsewhere first.
15720 Info.FFDiag(E, diag::note_constexpr_double_delete);
15721 return false;
15722 }
15723
15724 return true;
15725}
15726
15727static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
15728 assert(!E->isValueDependent());
15729 assert(E->isPRValue() && E->getType()->isVoidType());
15730 return VoidExprEvaluator(Info).Visit(E);
15731}
15732
15733//===----------------------------------------------------------------------===//
15734// Top level Expr::EvaluateAsRValue method.
15735//===----------------------------------------------------------------------===//
15736
15737static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
15738 assert(!E->isValueDependent());
15739 // In C, function designators are not lvalues, but we evaluate them as if they
15740 // are.
15741 QualType T = E->getType();
15742 if (E->isGLValue() || T->isFunctionType()) {
15743 LValue LV;
15744 if (!EvaluateLValue(E, LV, Info))
15745 return false;
15746 LV.moveInto(Result);
15747 } else if (T->isVectorType()) {
15748 if (!EvaluateVector(E, Result, Info))
15749 return false;
15750 } else if (T->isIntegralOrEnumerationType()) {
15751 if (!IntExprEvaluator(Info, Result).Visit(E))
15752 return false;
15753 } else if (T->hasPointerRepresentation()) {
15754 LValue LV;
15755 if (!EvaluatePointer(E, LV, Info))
15756 return false;
15757 LV.moveInto(Result);
15758 } else if (T->isRealFloatingType()) {
15759 llvm::APFloat F(0.0);
15760 if (!EvaluateFloat(E, F, Info))
15761 return false;
15762 Result = APValue(F);
15763 } else if (T->isAnyComplexType()) {
15764 ComplexValue C;
15765 if (!EvaluateComplex(E, C, Info))
15766 return false;
15767 C.moveInto(Result);
15768 } else if (T->isFixedPointType()) {
15769 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15770 } else if (T->isMemberPointerType()) {
15771 MemberPtr P;
15772 if (!EvaluateMemberPointer(E, P, Info))
15773 return false;
15774 P.moveInto(Result);
15775 return true;
15776 } else if (T->isArrayType()) {
15777 LValue LV;
15778 APValue &Value =
15779 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15780 if (!EvaluateArray(E, LV, Value, Info))
15781 return false;
15782 Result = Value;
15783 } else if (T->isRecordType()) {
15784 LValue LV;
15785 APValue &Value =
15786 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15787 if (!EvaluateRecord(E, LV, Value, Info))
15788 return false;
15789 Result = Value;
15790 } else if (T->isVoidType()) {
15791 if (!Info.getLangOpts().CPlusPlus11)
15792 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15793 << E->getType();
15794 if (!EvaluateVoid(E, Info))
15795 return false;
15796 } else if (T->isAtomicType()) {
15797 QualType Unqual = T.getAtomicUnqualifiedType();
15798 if (Unqual->isArrayType() || Unqual->isRecordType()) {
15799 LValue LV;
15800 APValue &Value = Info.CurrentCall->createTemporary(
15801 E, Unqual, ScopeKind::FullExpression, LV);
15802 if (!EvaluateAtomic(E, &LV, Value, Info))
15803 return false;
15804 Result = Value;
15805 } else {
15806 if (!EvaluateAtomic(E, nullptr, Result, Info))
15807 return false;
15808 }
15809 } else if (Info.getLangOpts().CPlusPlus11) {
15810 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15811 return false;
15812 } else {
15813 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15814 return false;
15815 }
15816
15817 return true;
15818}
15819
15820/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15821/// cases, the in-place evaluation is essential, since later initializers for
15822/// an object can indirectly refer to subobjects which were initialized earlier.
15823static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15824 const Expr *E, bool AllowNonLiteralTypes) {
15825 assert(!E->isValueDependent());
15826
15827 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15828 return false;
15829
15830 if (E->isPRValue()) {
15831 // Evaluate arrays and record types in-place, so that later initializers can
15832 // refer to earlier-initialized members of the object.
15833 QualType T = E->getType();
15834 if (T->isArrayType())
15835 return EvaluateArray(E, This, Result, Info);
15836 else if (T->isRecordType())
15837 return EvaluateRecord(E, This, Result, Info);
15838 else if (T->isAtomicType()) {
15839 QualType Unqual = T.getAtomicUnqualifiedType();
15840 if (Unqual->isArrayType() || Unqual->isRecordType())
15841 return EvaluateAtomic(E, &This, Result, Info);
15842 }
15843 }
15844
15845 // For any other type, in-place evaluation is unimportant.
15846 return Evaluate(Result, Info, E);
15847}
15848
15849/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15850/// lvalue-to-rvalue cast if it is an lvalue.
15851static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15852 assert(!E->isValueDependent());
15853
15854 if (E->getType().isNull())
15855 return false;
15856
15857 if (!CheckLiteralType(Info, E))
15858 return false;
15859
15860 if (Info.EnableNewConstInterp) {
15861 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15862 return false;
15863 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15864 ConstantExprKind::Normal);
15865 }
15866
15867 if (!::Evaluate(Result, Info, E))
15868 return false;
15869
15870 // Implicit lvalue-to-rvalue cast.
15871 if (E->isGLValue()) {
15872 LValue LV;
15873 LV.setFrom(Info.Ctx, Result);
15874 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15875 return false;
15876 }
15877
15878 // Check this core constant expression is a constant expression.
15879 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15880 ConstantExprKind::Normal) &&
15881 CheckMemoryLeaks(Info);
15882}
15883
15884static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15885 const ASTContext &Ctx, bool &IsConst) {
15886 // Fast-path evaluations of integer literals, since we sometimes see files
15887 // containing vast quantities of these.
15888 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15889 Result.Val = APValue(APSInt(L->getValue(),
15890 L->getType()->isUnsignedIntegerType()));
15891 IsConst = true;
15892 return true;
15893 }
15894
15895 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15896 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15897 IsConst = true;
15898 return true;
15899 }
15900
15901 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
15902 if (CE->hasAPValueResult()) {
15903 APValue APV = CE->getAPValueResult();
15904 if (!APV.isLValue()) {
15905 Result.Val = std::move(APV);
15906 IsConst = true;
15907 return true;
15908 }
15909 }
15910
15911 // The SubExpr is usually just an IntegerLiteral.
15912 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
15913 }
15914
15915 // This case should be rare, but we need to check it before we check on
15916 // the type below.
15917 if (Exp->getType().isNull()) {
15918 IsConst = false;
15919 return true;
15920 }
15921
15922 return false;
15923}
15924
15927 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15928 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15929}
15930
15931static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15932 const ASTContext &Ctx, EvalInfo &Info) {
15933 assert(!E->isValueDependent());
15934 bool IsConst;
15935 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15936 return IsConst;
15937
15938 return EvaluateAsRValue(Info, E, Result.Val);
15939}
15940
15942 const ASTContext &Ctx,
15943 Expr::SideEffectsKind AllowSideEffects,
15944 EvalInfo &Info) {
15945 assert(!E->isValueDependent());
15947 return false;
15948
15949 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15950 !ExprResult.Val.isInt() ||
15951 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15952 return false;
15953
15954 return true;
15955}
15956
15958 const ASTContext &Ctx,
15959 Expr::SideEffectsKind AllowSideEffects,
15960 EvalInfo &Info) {
15961 assert(!E->isValueDependent());
15962 if (!E->getType()->isFixedPointType())
15963 return false;
15964
15965 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15966 return false;
15967
15968 if (!ExprResult.Val.isFixedPoint() ||
15969 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15970 return false;
15971
15972 return true;
15973}
15974
15975/// EvaluateAsRValue - Return true if this is a constant which we can fold using
15976/// any crazy technique (that has nothing to do with language standards) that
15977/// we want to. If this function returns true, it returns the folded constant
15978/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15979/// will be applied to the result.
15981 bool InConstantContext) const {
15982 assert(!isValueDependent() &&
15983 "Expression evaluator can't be called on a dependent expression.");
15984 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15985 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15986 Info.InConstantContext = InConstantContext;
15987 return ::EvaluateAsRValue(this, Result, Ctx, Info);
15988}
15989
15990bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15991 bool InConstantContext) const {
15992 assert(!isValueDependent() &&
15993 "Expression evaluator can't be called on a dependent expression.");
15994 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15995 EvalResult Scratch;
15996 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15997 HandleConversionToBool(Scratch.Val, Result);
15998}
15999
16001 SideEffectsKind AllowSideEffects,
16002 bool InConstantContext) const {
16003 assert(!isValueDependent() &&
16004 "Expression evaluator can't be called on a dependent expression.");
16005 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16006 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16007 Info.InConstantContext = InConstantContext;
16008 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
16009}
16010
16012 SideEffectsKind AllowSideEffects,
16013 bool InConstantContext) const {
16014 assert(!isValueDependent() &&
16015 "Expression evaluator can't be called on a dependent expression.");
16016 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16017 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16018 Info.InConstantContext = InConstantContext;
16019 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
16020}
16021
16022bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16023 SideEffectsKind AllowSideEffects,
16024 bool InConstantContext) const {
16025 assert(!isValueDependent() &&
16026 "Expression evaluator can't be called on a dependent expression.");
16027
16028 if (!getType()->isRealFloatingType())
16029 return false;
16030
16031 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16033 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
16034 !ExprResult.Val.isFloat() ||
16035 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16036 return false;
16037
16038 Result = ExprResult.Val.getFloat();
16039 return true;
16040}
16041
16043 bool InConstantContext) const {
16044 assert(!isValueDependent() &&
16045 "Expression evaluator can't be called on a dependent expression.");
16046
16047 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16048 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16049 Info.InConstantContext = InConstantContext;
16050 LValue LV;
16051 CheckedTemporaries CheckedTemps;
16052 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
16053 Result.HasSideEffects ||
16054 !CheckLValueConstantExpression(Info, getExprLoc(),
16055 Ctx.getLValueReferenceType(getType()), LV,
16056 ConstantExprKind::Normal, CheckedTemps))
16057 return false;
16058
16059 LV.moveInto(Result.Val);
16060 return true;
16061}
16062
16064 APValue DestroyedValue, QualType Type,
16066 bool IsConstantDestruction) {
16067 EvalInfo Info(Ctx, EStatus,
16068 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16069 : EvalInfo::EM_ConstantFold);
16070 Info.setEvaluatingDecl(Base, DestroyedValue,
16071 EvalInfo::EvaluatingDeclKind::Dtor);
16072 Info.InConstantContext = IsConstantDestruction;
16073
16074 LValue LVal;
16075 LVal.set(Base);
16076
16077 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
16078 EStatus.HasSideEffects)
16079 return false;
16080
16081 if (!Info.discardCleanups())
16082 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16083
16084 return true;
16085}
16086
16088 ConstantExprKind Kind) const {
16089 assert(!isValueDependent() &&
16090 "Expression evaluator can't be called on a dependent expression.");
16091 bool IsConst;
16092 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
16093 return true;
16094
16095 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
16096 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
16097 EvalInfo Info(Ctx, Result, EM);
16098 Info.InConstantContext = true;
16099
16100 if (Info.EnableNewConstInterp) {
16101 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val))
16102 return false;
16103 return CheckConstantExpression(Info, getExprLoc(),
16104 getStorageType(Ctx, this), Result.Val, Kind);
16105 }
16106
16107 // The type of the object we're initializing is 'const T' for a class NTTP.
16108 QualType T = getType();
16109 if (Kind == ConstantExprKind::ClassTemplateArgument)
16110 T.addConst();
16111
16112 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
16113 // represent the result of the evaluation. CheckConstantExpression ensures
16114 // this doesn't escape.
16115 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
16116 APValue::LValueBase Base(&BaseMTE);
16117 Info.setEvaluatingDecl(Base, Result.Val);
16118
16119 if (Info.EnableNewConstInterp) {
16120 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
16121 return false;
16122 } else {
16123 LValue LVal;
16124 LVal.set(Base);
16125 // C++23 [intro.execution]/p5
16126 // A full-expression is [...] a constant-expression
16127 // So we need to make sure temporary objects are destroyed after having
16128 // evaluating the expression (per C++23 [class.temporary]/p4).
16129 FullExpressionRAII Scope(Info);
16130 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
16131 Result.HasSideEffects || !Scope.destroy())
16132 return false;
16133
16134 if (!Info.discardCleanups())
16135 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16136 }
16137
16138 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
16139 Result.Val, Kind))
16140 return false;
16141 if (!CheckMemoryLeaks(Info))
16142 return false;
16143
16144 // If this is a class template argument, it's required to have constant
16145 // destruction too.
16146 if (Kind == ConstantExprKind::ClassTemplateArgument &&
16147 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
16148 true) ||
16149 Result.HasSideEffects)) {
16150 // FIXME: Prefix a note to indicate that the problem is lack of constant
16151 // destruction.
16152 return false;
16153 }
16154
16155 return true;
16156}
16157
16159 const VarDecl *VD,
16161 bool IsConstantInitialization) const {
16162 assert(!isValueDependent() &&
16163 "Expression evaluator can't be called on a dependent expression.");
16164
16165 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16166 std::string Name;
16167 llvm::raw_string_ostream OS(Name);
16168 VD->printQualifiedName(OS);
16169 return Name;
16170 });
16171
16172 Expr::EvalStatus EStatus;
16173 EStatus.Diag = &Notes;
16174
16175 EvalInfo Info(Ctx, EStatus,
16176 (IsConstantInitialization &&
16177 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16178 ? EvalInfo::EM_ConstantExpression
16179 : EvalInfo::EM_ConstantFold);
16180 Info.setEvaluatingDecl(VD, Value);
16181 Info.InConstantContext = IsConstantInitialization;
16182
16183 SourceLocation DeclLoc = VD->getLocation();
16184 QualType DeclTy = VD->getType();
16185
16186 if (Info.EnableNewConstInterp) {
16187 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16188 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
16189 return false;
16190
16191 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16192 ConstantExprKind::Normal);
16193 } else {
16194 LValue LVal;
16195 LVal.set(VD);
16196
16197 {
16198 // C++23 [intro.execution]/p5
16199 // A full-expression is ... an init-declarator ([dcl.decl]) or a
16200 // mem-initializer.
16201 // So we need to make sure temporary objects are destroyed after having
16202 // evaluated the expression (per C++23 [class.temporary]/p4).
16203 //
16204 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16205 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16206 // outermost FullExpr, such as ExprWithCleanups.
16207 FullExpressionRAII Scope(Info);
16208 if (!EvaluateInPlace(Value, Info, LVal, this,
16209 /*AllowNonLiteralTypes=*/true) ||
16210 EStatus.HasSideEffects)
16211 return false;
16212 }
16213
16214 // At this point, any lifetime-extended temporaries are completely
16215 // initialized.
16216 Info.performLifetimeExtension();
16217
16218 if (!Info.discardCleanups())
16219 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16220 }
16221
16222 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16223 ConstantExprKind::Normal) &&
16224 CheckMemoryLeaks(Info);
16225}
16226
16229 Expr::EvalStatus EStatus;
16230 EStatus.Diag = &Notes;
16231
16232 // Only treat the destruction as constant destruction if we formally have
16233 // constant initialization (or are usable in a constant expression).
16234 bool IsConstantDestruction = hasConstantInitialization();
16235
16236 // Make a copy of the value for the destructor to mutate, if we know it.
16237 // Otherwise, treat the value as default-initialized; if the destructor works
16238 // anyway, then the destruction is constant (and must be essentially empty).
16239 APValue DestroyedValue;
16240 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
16241 DestroyedValue = *getEvaluatedValue();
16242 else if (!handleDefaultInitValue(getType(), DestroyedValue))
16243 return false;
16244
16245 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
16246 getType(), getLocation(), EStatus,
16247 IsConstantDestruction) ||
16248 EStatus.HasSideEffects)
16249 return false;
16250
16251 ensureEvaluatedStmt()->HasConstantDestruction = true;
16252 return true;
16253}
16254
16255/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
16256/// constant folded, but discard the result.
16258 assert(!isValueDependent() &&
16259 "Expression evaluator can't be called on a dependent expression.");
16260
16261 EvalResult Result;
16262 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
16263 !hasUnacceptableSideEffect(Result, SEK);
16264}
16265
16268 assert(!isValueDependent() &&
16269 "Expression evaluator can't be called on a dependent expression.");
16270
16271 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
16272 EvalResult EVResult;
16273 EVResult.Diag = Diag;
16274 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16275 Info.InConstantContext = true;
16276
16277 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
16278 (void)Result;
16279 assert(Result && "Could not evaluate expression");
16280 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16281
16282 return EVResult.Val.getInt();
16283}
16284
16287 assert(!isValueDependent() &&
16288 "Expression evaluator can't be called on a dependent expression.");
16289
16290 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
16291 EvalResult EVResult;
16292 EVResult.Diag = Diag;
16293 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16294 Info.InConstantContext = true;
16295 Info.CheckingForUndefinedBehavior = true;
16296
16297 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
16298 (void)Result;
16299 assert(Result && "Could not evaluate expression");
16300 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16301
16302 return EVResult.Val.getInt();
16303}
16304
16306 assert(!isValueDependent() &&
16307 "Expression evaluator can't be called on a dependent expression.");
16308
16309 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
16310 bool IsConst;
16311 EvalResult EVResult;
16312 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
16313 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16314 Info.CheckingForUndefinedBehavior = true;
16315 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
16316 }
16317}
16318
16320 assert(Val.isLValue());
16321 return IsGlobalLValue(Val.getLValueBase());
16322}
16323
16324/// isIntegerConstantExpr - this recursive routine will test if an expression is
16325/// an integer constant expression.
16326
16327/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
16328/// comma, etc
16329
16330// CheckICE - This function does the fundamental ICE checking: the returned
16331// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
16332// and a (possibly null) SourceLocation indicating the location of the problem.
16333//
16334// Note that to reduce code duplication, this helper does no evaluation
16335// itself; the caller checks whether the expression is evaluatable, and
16336// in the rare cases where CheckICE actually cares about the evaluated
16337// value, it calls into Evaluate.
16338
16339namespace {
16340
16341enum ICEKind {
16342 /// This expression is an ICE.
16343 IK_ICE,
16344 /// This expression is not an ICE, but if it isn't evaluated, it's
16345 /// a legal subexpression for an ICE. This return value is used to handle
16346 /// the comma operator in C99 mode, and non-constant subexpressions.
16347 IK_ICEIfUnevaluated,
16348 /// This expression is not an ICE, and is not a legal subexpression for one.
16349 IK_NotICE
16350};
16351
16352struct ICEDiag {
16353 ICEKind Kind;
16355
16356 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
16357};
16358
16359}
16360
16361static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
16362
16363static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
16364
16365static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
16366 Expr::EvalResult EVResult;
16367 Expr::EvalStatus Status;
16368 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16369
16370 Info.InConstantContext = true;
16371 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
16372 !EVResult.Val.isInt())
16373 return ICEDiag(IK_NotICE, E->getBeginLoc());
16374
16375 return NoDiag();
16376}
16377
16378static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
16379 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
16381 return ICEDiag(IK_NotICE, E->getBeginLoc());
16382
16383 switch (E->getStmtClass()) {
16384#define ABSTRACT_STMT(Node)
16385#define STMT(Node, Base) case Expr::Node##Class:
16386#define EXPR(Node, Base)
16387#include "clang/AST/StmtNodes.inc"
16388 case Expr::PredefinedExprClass:
16389 case Expr::FloatingLiteralClass:
16390 case Expr::ImaginaryLiteralClass:
16391 case Expr::StringLiteralClass:
16392 case Expr::ArraySubscriptExprClass:
16393 case Expr::MatrixSubscriptExprClass:
16394 case Expr::ArraySectionExprClass:
16395 case Expr::OMPArrayShapingExprClass:
16396 case Expr::OMPIteratorExprClass:
16397 case Expr::MemberExprClass:
16398 case Expr::CompoundAssignOperatorClass:
16399 case Expr::CompoundLiteralExprClass:
16400 case Expr::ExtVectorElementExprClass:
16401 case Expr::DesignatedInitExprClass:
16402 case Expr::ArrayInitLoopExprClass:
16403 case Expr::ArrayInitIndexExprClass:
16404 case Expr::NoInitExprClass:
16405 case Expr::DesignatedInitUpdateExprClass:
16406 case Expr::ImplicitValueInitExprClass:
16407 case Expr::ParenListExprClass:
16408 case Expr::VAArgExprClass:
16409 case Expr::AddrLabelExprClass:
16410 case Expr::StmtExprClass:
16411 case Expr::CXXMemberCallExprClass:
16412 case Expr::CUDAKernelCallExprClass:
16413 case Expr::CXXAddrspaceCastExprClass:
16414 case Expr::CXXDynamicCastExprClass:
16415 case Expr::CXXTypeidExprClass:
16416 case Expr::CXXUuidofExprClass:
16417 case Expr::MSPropertyRefExprClass:
16418 case Expr::MSPropertySubscriptExprClass:
16419 case Expr::CXXNullPtrLiteralExprClass:
16420 case Expr::UserDefinedLiteralClass:
16421 case Expr::CXXThisExprClass:
16422 case Expr::CXXThrowExprClass:
16423 case Expr::CXXNewExprClass:
16424 case Expr::CXXDeleteExprClass:
16425 case Expr::CXXPseudoDestructorExprClass:
16426 case Expr::UnresolvedLookupExprClass:
16427 case Expr::TypoExprClass:
16428 case Expr::RecoveryExprClass:
16429 case Expr::DependentScopeDeclRefExprClass:
16430 case Expr::CXXConstructExprClass:
16431 case Expr::CXXInheritedCtorInitExprClass:
16432 case Expr::CXXStdInitializerListExprClass:
16433 case Expr::CXXBindTemporaryExprClass:
16434 case Expr::ExprWithCleanupsClass:
16435 case Expr::CXXTemporaryObjectExprClass:
16436 case Expr::CXXUnresolvedConstructExprClass:
16437 case Expr::CXXDependentScopeMemberExprClass:
16438 case Expr::UnresolvedMemberExprClass:
16439 case Expr::ObjCStringLiteralClass:
16440 case Expr::ObjCBoxedExprClass:
16441 case Expr::ObjCArrayLiteralClass:
16442 case Expr::ObjCDictionaryLiteralClass:
16443 case Expr::ObjCEncodeExprClass:
16444 case Expr::ObjCMessageExprClass:
16445 case Expr::ObjCSelectorExprClass:
16446 case Expr::ObjCProtocolExprClass:
16447 case Expr::ObjCIvarRefExprClass:
16448 case Expr::ObjCPropertyRefExprClass:
16449 case Expr::ObjCSubscriptRefExprClass:
16450 case Expr::ObjCIsaExprClass:
16451 case Expr::ObjCAvailabilityCheckExprClass:
16452 case Expr::ShuffleVectorExprClass:
16453 case Expr::ConvertVectorExprClass:
16454 case Expr::BlockExprClass:
16455 case Expr::NoStmtClass:
16456 case Expr::OpaqueValueExprClass:
16457 case Expr::PackExpansionExprClass:
16458 case Expr::SubstNonTypeTemplateParmPackExprClass:
16459 case Expr::FunctionParmPackExprClass:
16460 case Expr::AsTypeExprClass:
16461 case Expr::ObjCIndirectCopyRestoreExprClass:
16462 case Expr::MaterializeTemporaryExprClass:
16463 case Expr::PseudoObjectExprClass:
16464 case Expr::AtomicExprClass:
16465 case Expr::LambdaExprClass:
16466 case Expr::CXXFoldExprClass:
16467 case Expr::CoawaitExprClass:
16468 case Expr::DependentCoawaitExprClass:
16469 case Expr::CoyieldExprClass:
16470 case Expr::SYCLUniqueStableNameExprClass:
16471 case Expr::CXXParenListInitExprClass:
16472 return ICEDiag(IK_NotICE, E->getBeginLoc());
16473
16474 case Expr::InitListExprClass: {
16475 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
16476 // form "T x = { a };" is equivalent to "T x = a;".
16477 // Unless we're initializing a reference, T is a scalar as it is known to be
16478 // of integral or enumeration type.
16479 if (E->isPRValue())
16480 if (cast<InitListExpr>(E)->getNumInits() == 1)
16481 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
16482 return ICEDiag(IK_NotICE, E->getBeginLoc());
16483 }
16484
16485 case Expr::SizeOfPackExprClass:
16486 case Expr::GNUNullExprClass:
16487 case Expr::SourceLocExprClass:
16488 case Expr::EmbedExprClass:
16489 return NoDiag();
16490
16491 case Expr::PackIndexingExprClass:
16492 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
16493
16494 case Expr::SubstNonTypeTemplateParmExprClass:
16495 return
16496 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
16497
16498 case Expr::ConstantExprClass:
16499 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
16500
16501 case Expr::ParenExprClass:
16502 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
16503 case Expr::GenericSelectionExprClass:
16504 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
16505 case Expr::IntegerLiteralClass:
16506 case Expr::FixedPointLiteralClass:
16507 case Expr::CharacterLiteralClass:
16508 case Expr::ObjCBoolLiteralExprClass:
16509 case Expr::CXXBoolLiteralExprClass:
16510 case Expr::CXXScalarValueInitExprClass:
16511 case Expr::TypeTraitExprClass:
16512 case Expr::ConceptSpecializationExprClass:
16513 case Expr::RequiresExprClass:
16514 case Expr::ArrayTypeTraitExprClass:
16515 case Expr::ExpressionTraitExprClass:
16516 case Expr::CXXNoexceptExprClass:
16517 return NoDiag();
16518 case Expr::CallExprClass:
16519 case Expr::CXXOperatorCallExprClass: {
16520 // C99 6.6/3 allows function calls within unevaluated subexpressions of
16521 // constant expressions, but they can never be ICEs because an ICE cannot
16522 // contain an operand of (pointer to) function type.
16523 const CallExpr *CE = cast<CallExpr>(E);
16524 if (CE->getBuiltinCallee())
16525 return CheckEvalInICE(E, Ctx);
16526 return ICEDiag(IK_NotICE, E->getBeginLoc());
16527 }
16528 case Expr::CXXRewrittenBinaryOperatorClass:
16529 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
16530 Ctx);
16531 case Expr::DeclRefExprClass: {
16532 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
16533 if (isa<EnumConstantDecl>(D))
16534 return NoDiag();
16535
16536 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16537 // integer variables in constant expressions:
16538 //
16539 // C++ 7.1.5.1p2
16540 // A variable of non-volatile const-qualified integral or enumeration
16541 // type initialized by an ICE can be used in ICEs.
16542 //
16543 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
16544 // that mode, use of reference variables should not be allowed.
16545 const VarDecl *VD = dyn_cast<VarDecl>(D);
16546 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
16547 !VD->getType()->isReferenceType())
16548 return NoDiag();
16549
16550 return ICEDiag(IK_NotICE, E->getBeginLoc());
16551 }
16552 case Expr::UnaryOperatorClass: {
16553 const UnaryOperator *Exp = cast<UnaryOperator>(E);
16554 switch (Exp->getOpcode()) {
16555 case UO_PostInc:
16556 case UO_PostDec:
16557 case UO_PreInc:
16558 case UO_PreDec:
16559 case UO_AddrOf:
16560 case UO_Deref:
16561 case UO_Coawait:
16562 // C99 6.6/3 allows increment and decrement within unevaluated
16563 // subexpressions of constant expressions, but they can never be ICEs
16564 // because an ICE cannot contain an lvalue operand.
16565 return ICEDiag(IK_NotICE, E->getBeginLoc());
16566 case UO_Extension:
16567 case UO_LNot:
16568 case UO_Plus:
16569 case UO_Minus:
16570 case UO_Not:
16571 case UO_Real:
16572 case UO_Imag:
16573 return CheckICE(Exp->getSubExpr(), Ctx);
16574 }
16575 llvm_unreachable("invalid unary operator class");
16576 }
16577 case Expr::OffsetOfExprClass: {
16578 // Note that per C99, offsetof must be an ICE. And AFAIK, using
16579 // EvaluateAsRValue matches the proposed gcc behavior for cases like
16580 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
16581 // compliance: we should warn earlier for offsetof expressions with
16582 // array subscripts that aren't ICEs, and if the array subscripts
16583 // are ICEs, the value of the offsetof must be an integer constant.
16584 return CheckEvalInICE(E, Ctx);
16585 }
16586 case Expr::UnaryExprOrTypeTraitExprClass: {
16587 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
16588 if ((Exp->getKind() == UETT_SizeOf) &&
16590 return ICEDiag(IK_NotICE, E->getBeginLoc());
16591 return NoDiag();
16592 }
16593 case Expr::BinaryOperatorClass: {
16594 const BinaryOperator *Exp = cast<BinaryOperator>(E);
16595 switch (Exp->getOpcode()) {
16596 case BO_PtrMemD:
16597 case BO_PtrMemI:
16598 case BO_Assign:
16599 case BO_MulAssign:
16600 case BO_DivAssign:
16601 case BO_RemAssign:
16602 case BO_AddAssign:
16603 case BO_SubAssign:
16604 case BO_ShlAssign:
16605 case BO_ShrAssign:
16606 case BO_AndAssign:
16607 case BO_XorAssign:
16608 case BO_OrAssign:
16609 // C99 6.6/3 allows assignments within unevaluated subexpressions of
16610 // constant expressions, but they can never be ICEs because an ICE cannot
16611 // contain an lvalue operand.
16612 return ICEDiag(IK_NotICE, E->getBeginLoc());
16613
16614 case BO_Mul:
16615 case BO_Div:
16616 case BO_Rem:
16617 case BO_Add:
16618 case BO_Sub:
16619 case BO_Shl:
16620 case BO_Shr:
16621 case BO_LT:
16622 case BO_GT:
16623 case BO_LE:
16624 case BO_GE:
16625 case BO_EQ:
16626 case BO_NE:
16627 case BO_And:
16628 case BO_Xor:
16629 case BO_Or:
16630 case BO_Comma:
16631 case BO_Cmp: {
16632 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16633 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16634 if (Exp->getOpcode() == BO_Div ||
16635 Exp->getOpcode() == BO_Rem) {
16636 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
16637 // we don't evaluate one.
16638 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
16639 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
16640 if (REval == 0)
16641 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16642 if (REval.isSigned() && REval.isAllOnes()) {
16643 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
16644 if (LEval.isMinSignedValue())
16645 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16646 }
16647 }
16648 }
16649 if (Exp->getOpcode() == BO_Comma) {
16650 if (Ctx.getLangOpts().C99) {
16651 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
16652 // if it isn't evaluated.
16653 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
16654 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16655 } else {
16656 // In both C89 and C++, commas in ICEs are illegal.
16657 return ICEDiag(IK_NotICE, E->getBeginLoc());
16658 }
16659 }
16660 return Worst(LHSResult, RHSResult);
16661 }
16662 case BO_LAnd:
16663 case BO_LOr: {
16664 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16665 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16666 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
16667 // Rare case where the RHS has a comma "side-effect"; we need
16668 // to actually check the condition to see whether the side
16669 // with the comma is evaluated.
16670 if ((Exp->getOpcode() == BO_LAnd) !=
16671 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
16672 return RHSResult;
16673 return NoDiag();
16674 }
16675
16676 return Worst(LHSResult, RHSResult);
16677 }
16678 }
16679 llvm_unreachable("invalid binary operator kind");
16680 }
16681 case Expr::ImplicitCastExprClass:
16682 case Expr::CStyleCastExprClass:
16683 case Expr::CXXFunctionalCastExprClass:
16684 case Expr::CXXStaticCastExprClass:
16685 case Expr::CXXReinterpretCastExprClass:
16686 case Expr::CXXConstCastExprClass:
16687 case Expr::ObjCBridgedCastExprClass: {
16688 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
16689 if (isa<ExplicitCastExpr>(E)) {
16690 if (const FloatingLiteral *FL
16691 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
16692 unsigned DestWidth = Ctx.getIntWidth(E->getType());
16693 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
16694 APSInt IgnoredVal(DestWidth, !DestSigned);
16695 bool Ignored;
16696 // If the value does not fit in the destination type, the behavior is
16697 // undefined, so we are not required to treat it as a constant
16698 // expression.
16699 if (FL->getValue().convertToInteger(IgnoredVal,
16700 llvm::APFloat::rmTowardZero,
16701 &Ignored) & APFloat::opInvalidOp)
16702 return ICEDiag(IK_NotICE, E->getBeginLoc());
16703 return NoDiag();
16704 }
16705 }
16706 switch (cast<CastExpr>(E)->getCastKind()) {
16707 case CK_LValueToRValue:
16708 case CK_AtomicToNonAtomic:
16709 case CK_NonAtomicToAtomic:
16710 case CK_NoOp:
16711 case CK_IntegralToBoolean:
16712 case CK_IntegralCast:
16713 return CheckICE(SubExpr, Ctx);
16714 default:
16715 return ICEDiag(IK_NotICE, E->getBeginLoc());
16716 }
16717 }
16718 case Expr::BinaryConditionalOperatorClass: {
16719 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
16720 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
16721 if (CommonResult.Kind == IK_NotICE) return CommonResult;
16722 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16723 if (FalseResult.Kind == IK_NotICE) return FalseResult;
16724 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
16725 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
16726 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
16727 return FalseResult;
16728 }
16729 case Expr::ConditionalOperatorClass: {
16730 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
16731 // If the condition (ignoring parens) is a __builtin_constant_p call,
16732 // then only the true side is actually considered in an integer constant
16733 // expression, and it is fully evaluated. This is an important GNU
16734 // extension. See GCC PR38377 for discussion.
16735 if (const CallExpr *CallCE
16736 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
16737 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16738 return CheckEvalInICE(E, Ctx);
16739 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
16740 if (CondResult.Kind == IK_NotICE)
16741 return CondResult;
16742
16743 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
16744 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16745
16746 if (TrueResult.Kind == IK_NotICE)
16747 return TrueResult;
16748 if (FalseResult.Kind == IK_NotICE)
16749 return FalseResult;
16750 if (CondResult.Kind == IK_ICEIfUnevaluated)
16751 return CondResult;
16752 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
16753 return NoDiag();
16754 // Rare case where the diagnostics depend on which side is evaluated
16755 // Note that if we get here, CondResult is 0, and at least one of
16756 // TrueResult and FalseResult is non-zero.
16757 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16758 return FalseResult;
16759 return TrueResult;
16760 }
16761 case Expr::CXXDefaultArgExprClass:
16762 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
16763 case Expr::CXXDefaultInitExprClass:
16764 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
16765 case Expr::ChooseExprClass: {
16766 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
16767 }
16768 case Expr::BuiltinBitCastExprClass: {
16769 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
16770 return ICEDiag(IK_NotICE, E->getBeginLoc());
16771 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
16772 }
16773 }
16774
16775 llvm_unreachable("Invalid StmtClass!");
16776}
16777
16778/// Evaluate an expression as a C++11 integral constant expression.
16780 const Expr *E,
16781 llvm::APSInt *Value,
16784 if (Loc) *Loc = E->getExprLoc();
16785 return false;
16786 }
16787
16788 APValue Result;
16789 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16790 return false;
16791
16792 if (!Result.isInt()) {
16793 if (Loc) *Loc = E->getExprLoc();
16794 return false;
16795 }
16796
16797 if (Value) *Value = Result.getInt();
16798 return true;
16799}
16800
16802 SourceLocation *Loc) const {
16803 assert(!isValueDependent() &&
16804 "Expression evaluator can't be called on a dependent expression.");
16805
16806 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16807
16808 if (Ctx.getLangOpts().CPlusPlus11)
16809 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16810
16811 ICEDiag D = CheckICE(this, Ctx);
16812 if (D.Kind != IK_ICE) {
16813 if (Loc) *Loc = D.Loc;
16814 return false;
16815 }
16816 return true;
16817}
16818
16819std::optional<llvm::APSInt>
16821 if (isValueDependent()) {
16822 // Expression evaluator can't succeed on a dependent expression.
16823 return std::nullopt;
16824 }
16825
16826 APSInt Value;
16827
16828 if (Ctx.getLangOpts().CPlusPlus11) {
16830 return Value;
16831 return std::nullopt;
16832 }
16833
16834 if (!isIntegerConstantExpr(Ctx, Loc))
16835 return std::nullopt;
16836
16837 // The only possible side-effects here are due to UB discovered in the
16838 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16839 // required to treat the expression as an ICE, so we produce the folded
16840 // value.
16842 Expr::EvalStatus Status;
16843 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16844 Info.InConstantContext = true;
16845
16846 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16847 llvm_unreachable("ICE cannot be evaluated!");
16848
16849 return ExprResult.Val.getInt();
16850}
16851
16853 assert(!isValueDependent() &&
16854 "Expression evaluator can't be called on a dependent expression.");
16855
16856 return CheckICE(this, Ctx).Kind == IK_ICE;
16857}
16858
16860 SourceLocation *Loc) const {
16861 assert(!isValueDependent() &&
16862 "Expression evaluator can't be called on a dependent expression.");
16863
16864 // We support this checking in C++98 mode in order to diagnose compatibility
16865 // issues.
16866 assert(Ctx.getLangOpts().CPlusPlus);
16867
16868 // Build evaluation settings.
16869 Expr::EvalStatus Status;
16871 Status.Diag = &Diags;
16872 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16873
16874 APValue Scratch;
16875 bool IsConstExpr =
16876 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16877 // FIXME: We don't produce a diagnostic for this, but the callers that
16878 // call us on arbitrary full-expressions should generally not care.
16879 Info.discardCleanups() && !Status.HasSideEffects;
16880
16881 if (!Diags.empty()) {
16882 IsConstExpr = false;
16883 if (Loc) *Loc = Diags[0].first;
16884 } else if (!IsConstExpr) {
16885 // FIXME: This shouldn't happen.
16886 if (Loc) *Loc = getExprLoc();
16887 }
16888
16889 return IsConstExpr;
16890}
16891
16893 const FunctionDecl *Callee,
16895 const Expr *This) const {
16896 assert(!isValueDependent() &&
16897 "Expression evaluator can't be called on a dependent expression.");
16898
16899 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16900 std::string Name;
16901 llvm::raw_string_ostream OS(Name);
16902 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16903 /*Qualified=*/true);
16904 return Name;
16905 });
16906
16907 Expr::EvalStatus Status;
16908 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16909 Info.InConstantContext = true;
16910
16911 LValue ThisVal;
16912 const LValue *ThisPtr = nullptr;
16913 if (This) {
16914#ifndef NDEBUG
16915 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16916 assert(MD && "Don't provide `this` for non-methods.");
16917 assert(MD->isImplicitObjectMemberFunction() &&
16918 "Don't provide `this` for methods without an implicit object.");
16919#endif
16920 if (!This->isValueDependent() &&
16921 EvaluateObjectArgument(Info, This, ThisVal) &&
16922 !Info.EvalStatus.HasSideEffects)
16923 ThisPtr = &ThisVal;
16924
16925 // Ignore any side-effects from a failed evaluation. This is safe because
16926 // they can't interfere with any other argument evaluation.
16927 Info.EvalStatus.HasSideEffects = false;
16928 }
16929
16930 CallRef Call = Info.CurrentCall->createCall(Callee);
16931 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16932 I != E; ++I) {
16933 unsigned Idx = I - Args.begin();
16934 if (Idx >= Callee->getNumParams())
16935 break;
16936 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16937 if ((*I)->isValueDependent() ||
16938 !EvaluateCallArg(PVD, *I, Call, Info) ||
16939 Info.EvalStatus.HasSideEffects) {
16940 // If evaluation fails, throw away the argument entirely.
16941 if (APValue *Slot = Info.getParamSlot(Call, PVD))
16942 *Slot = APValue();
16943 }
16944
16945 // Ignore any side-effects from a failed evaluation. This is safe because
16946 // they can't interfere with any other argument evaluation.
16947 Info.EvalStatus.HasSideEffects = false;
16948 }
16949
16950 // Parameter cleanups happen in the caller and are not part of this
16951 // evaluation.
16952 Info.discardCleanups();
16953 Info.EvalStatus.HasSideEffects = false;
16954
16955 // Build fake call to Callee.
16956 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
16957 Call);
16958 // FIXME: Missing ExprWithCleanups in enable_if conditions?
16959 FullExpressionRAII Scope(Info);
16960 return Evaluate(Value, Info, this) && Scope.destroy() &&
16961 !Info.EvalStatus.HasSideEffects;
16962}
16963
16966 PartialDiagnosticAt> &Diags) {
16967 // FIXME: It would be useful to check constexpr function templates, but at the
16968 // moment the constant expression evaluator cannot cope with the non-rigorous
16969 // ASTs which we build for dependent expressions.
16970 if (FD->isDependentContext())
16971 return true;
16972
16973 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16974 std::string Name;
16975 llvm::raw_string_ostream OS(Name);
16977 /*Qualified=*/true);
16978 return Name;
16979 });
16980
16981 Expr::EvalStatus Status;
16982 Status.Diag = &Diags;
16983
16984 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16985 Info.InConstantContext = true;
16986 Info.CheckingPotentialConstantExpression = true;
16987
16988 // The constexpr VM attempts to compile all methods to bytecode here.
16989 if (Info.EnableNewConstInterp) {
16990 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16991 return Diags.empty();
16992 }
16993
16994 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16995 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16996
16997 // Fabricate an arbitrary expression on the stack and pretend that it
16998 // is a temporary being used as the 'this' pointer.
16999 LValue This;
17000 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
17001 This.set({&VIE, Info.CurrentCall->Index});
17002
17004
17005 APValue Scratch;
17006 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
17007 // Evaluate the call as a constant initializer, to allow the construction
17008 // of objects of non-literal types.
17009 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
17010 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
17011 } else {
17014 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17015 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17016 /*ResultSlot=*/nullptr);
17017 }
17018
17019 return Diags.empty();
17020}
17021
17023 const FunctionDecl *FD,
17025 PartialDiagnosticAt> &Diags) {
17026 assert(!E->isValueDependent() &&
17027 "Expression evaluator can't be called on a dependent expression.");
17028
17029 Expr::EvalStatus Status;
17030 Status.Diag = &Diags;
17031
17032 EvalInfo Info(FD->getASTContext(), Status,
17033 EvalInfo::EM_ConstantExpressionUnevaluated);
17034 Info.InConstantContext = true;
17035 Info.CheckingPotentialConstantExpression = true;
17036
17037 // Fabricate a call stack frame to give the arguments a plausible cover story.
17038 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17039 /*CallExpr=*/nullptr, CallRef());
17040
17041 APValue ResultScratch;
17042 Evaluate(ResultScratch, Info, E);
17043 return Diags.empty();
17044}
17045
17046bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17047 unsigned Type) const {
17048 if (!getType()->isPointerType())
17049 return false;
17050
17051 Expr::EvalStatus Status;
17052 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17053 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
17054}
17055
17056static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17057 EvalInfo &Info, std::string *StringResult) {
17058 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17059 return false;
17060
17061 LValue String;
17062
17063 if (!EvaluatePointer(E, String, Info))
17064 return false;
17065
17066 QualType CharTy = E->getType()->getPointeeType();
17067
17068 // Fast path: if it's a string literal, search the string value.
17069 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17070 String.getLValueBase().dyn_cast<const Expr *>())) {
17071 StringRef Str = S->getBytes();
17072 int64_t Off = String.Offset.getQuantity();
17073 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17074 S->getCharByteWidth() == 1 &&
17075 // FIXME: Add fast-path for wchar_t too.
17076 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
17077 Str = Str.substr(Off);
17078
17079 StringRef::size_type Pos = Str.find(0);
17080 if (Pos != StringRef::npos)
17081 Str = Str.substr(0, Pos);
17082
17083 Result = Str.size();
17084 if (StringResult)
17085 *StringResult = Str;
17086 return true;
17087 }
17088
17089 // Fall through to slow path.
17090 }
17091
17092 // Slow path: scan the bytes of the string looking for the terminating 0.
17093 for (uint64_t Strlen = 0; /**/; ++Strlen) {
17094 APValue Char;
17095 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
17096 !Char.isInt())
17097 return false;
17098 if (!Char.getInt()) {
17099 Result = Strlen;
17100 return true;
17101 } else if (StringResult)
17102 StringResult->push_back(Char.getInt().getExtValue());
17103 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
17104 return false;
17105 }
17106}
17107
17108std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
17109 Expr::EvalStatus Status;
17110 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17111 uint64_t Result;
17112 std::string StringResult;
17113
17114 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
17115 return StringResult;
17116 return {};
17117}
17118
17119bool Expr::EvaluateCharRangeAsString(std::string &Result,
17120 const Expr *SizeExpression,
17121 const Expr *PtrExpression, ASTContext &Ctx,
17122 EvalResult &Status) const {
17123 LValue String;
17124 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17125 Info.InConstantContext = true;
17126
17127 FullExpressionRAII Scope(Info);
17128 APSInt SizeValue;
17129 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
17130 return false;
17131
17132 uint64_t Size = SizeValue.getZExtValue();
17133
17134 if (!::EvaluatePointer(PtrExpression, String, Info))
17135 return false;
17136
17137 QualType CharTy = PtrExpression->getType()->getPointeeType();
17138 for (uint64_t I = 0; I < Size; ++I) {
17139 APValue Char;
17140 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
17141 Char))
17142 return false;
17143
17144 APSInt C = Char.getInt();
17145 Result.push_back(static_cast<char>(C.getExtValue()));
17146 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
17147 return false;
17148 }
17149 if (!Scope.destroy())
17150 return false;
17151
17152 if (!CheckMemoryLeaks(Info))
17153 return false;
17154
17155 return true;
17156}
17157
17158bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17159 Expr::EvalStatus Status;
17160 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17161 return EvaluateBuiltinStrLen(this, Result, Info);
17162}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3338
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1651::IndirectLocalPathEntry::EntryKind Kind
llvm::APSInt APSInt
Definition: Compiler.cpp:22
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1152
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of axcess valid on an indeterminate object value?
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, UnaryExprOrTypeTrait ExprKind)
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize.
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type.
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static bool IsLiteralLValue(const LValue &Value)
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *This, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class.
static bool hasVirtualDestructor(QualType T)
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value)
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid).
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false)
Evaluate the arguments to a function call.
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static bool IsNoOpCall(const CallExpr *E)
Should this call expression be treated as a no-op?
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const CallExpr *Call, llvm::APInt &Result)
Attempts to compute the number of bytes available at the pointer returned by a function with the allo...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, SourceLocation *Loc)
Evaluate an expression as a C++11 integral constant expression.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E.
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout.
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue.
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue.
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned.
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static bool EvaluateDecl(EvalInfo &Info, const Decl *D)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:22
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
SourceLocation Loc
Definition: SemaObjC.cpp:758
bool Indirect
Definition: SemaObjC.cpp:759
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
__DEVICE__ long long abs(long long __n)
__device__ int
do v
Definition: arm_acle.h:91
QualType getType() const
Definition: APValue.cpp:63
QualType getDynamicAllocType() const
Definition: APValue.cpp:122
QualType getTypeInfoType() const
Definition: APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition: APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition: APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition: APValue.h:208
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition: APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool hasArrayFiller() const
Definition: APValue.h:518
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:510
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:468
APSInt & getInt()
Definition: APValue.h:423
APValue & getStructField(unsigned i)
Definition: APValue.h:551
const FieldDecl * getUnionField() const
Definition: APValue.h:563
bool isVector() const
Definition: APValue.h:407
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isAbsent() const
Definition: APValue.h:397
bool isComplexInt() const
Definition: APValue.h:404
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition: APValue.h:205
ValueKind getKind() const
Definition: APValue.h:395
unsigned getArrayInitializedElts() const
Definition: APValue.h:529
static APValue IndeterminateValue()
Definition: APValue.h:366
bool isFloat() const
Definition: APValue.h:402
APFixedPoint & getFixedPoint()
Definition: APValue.h:445
bool hasValue() const
Definition: APValue.h:399
bool hasLValuePath() const
Definition: APValue.cpp:989
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
APValue & getUnionValue()
Definition: APValue.h:567
CharUnits & getLValueOffset()
Definition: APValue.cpp:984
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:693
bool isComplexFloat() const
Definition: APValue.h:405
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
APValue & getArrayFiller()
Definition: APValue.h:521
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition: APValue.cpp:1050
bool isIndeterminate() const
Definition: APValue.h:398
bool isInt() const
Definition: APValue.h:401
unsigned getArraySize() const
Definition: APValue.h:533
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
bool isFixedPoint() const
Definition: APValue.h:403
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
bool isStruct() const
Definition: APValue.h:409
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
APValue & getStructBase(unsigned i)
Definition: APValue.h:546
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
SourceManager & getSourceManager()
Definition: ASTContext.h:720
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getRecordType(const RecordDecl *Decl) const
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:796
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2322
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:712
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2391
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:778
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:196
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4362
LabelDecl * getLabel() const
Definition: Expr.h:4385
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5746
Represents a loop initializing the elements of an array.
Definition: Expr.h:5693
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2674
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2852
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3540
QualType getElementType() const
Definition: Type.h:3552
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7573
Attr - This represents one attribute.
Definition: Attr.h:42
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4265
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition: Expr.h:4319
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:4300
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
Expr * getLHS() const
Definition: Expr.h:3909
bool isComparisonOp() const
Definition: Expr.h:3960
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:4006
bool isLogicalOp() const
Definition: Expr.h:3993
Expr * getRHS() const
Definition: Expr.h:3911
Opcode getOpcode() const
Definition: Expr.h:3904
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6355
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5290
This class is used for builtin types like 'int'.
Definition: Type.h:3000
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1491
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2755
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2620
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2497
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:478
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1737
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2457
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2464
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2567
bool isInstance() const
Definition: DeclCXX.h:2087
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2490
bool isStatic() const
Definition: DeclCXX.cpp:2188
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2468
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition: DeclCXX.cpp:2603
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2240
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4124
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4952
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition: DeclCXX.h:1234
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1567
base_class_iterator bases_end()
Definition: DeclCXX.h:628
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
base_class_range bases()
Definition: DeclCXX.h:619
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1111
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition: DeclCXX.cpp:1644
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
base_class_iterator bases_begin()
Definition: DeclCXX.h:626
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1190
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1978
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1105
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1597
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:634
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:523
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2181
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:797
Represents the this expression in C++.
Definition: ExprCXX.h:1152
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1579
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3000
Decl * getCalleeDecl()
Definition: Expr.h:2994
CaseStmt - Represent a case statement.
Definition: Stmt.h:1806
Expr * getLHS()
Definition: Stmt.h:1893
Expr * getRHS()
Definition: Stmt.h:1905
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3498
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3565
Expr * getSubExpr()
Definition: Expr.h:3548
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition: CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition: CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4582
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3108
QualType getElementType() const
Definition: Type.h:3118
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4112
QualType getComputationLHSType() const
Definition: Expr.h:4146
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3428
bool isFileScope() const
Definition: Expr.h:3455
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
bool body_empty() const
Definition: Stmt.h:1650
Stmt *const * const_body_iterator
Definition: Stmt.h:1678
body_iterator body_end()
Definition: Stmt.h:1671
body_range body()
Definition: Stmt.h:1669
body_iterator body_begin()
Definition: Stmt.h:1670
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4203
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4235
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4226
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4230
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3578
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition: Type.h:3641
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:178
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:218
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition: Type.h:3667
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3648
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3674
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3634
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3654
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4523
Represents the current source location and context used to determine the value of the source location...
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2359
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
decl_range decls()
Definition: Stmt.h:1545
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:425
static void add(Kind k)
Definition: DeclBase.cpp:224
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
A decomposition declaration.
Definition: DeclCXX.h:4166
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2730
Stmt * getBody()
Definition: Stmt.h:2755
Expr * getCond()
Definition: Stmt.h:2748
Symbolic representation of a dynamic allocation.
Definition: APValue.h:65
static unsigned getMaxIndex()
Definition: APValue.h:85
Represents a reference to #emded data.
Definition: Expr.h:4857
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3270
Represents an enum.
Definition: Decl.h:3840
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4037
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4054
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4000
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition: Decl.cpp:4961
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
EnumDecl * getDecl() const
Definition: Type.h:5969
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3750
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3472
This represents one expression.
Definition: Expr.h:110
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition: Expr.cpp:82
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition: Expr.h:280
SideEffectsKind
Definition: Expr.h:667
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:671
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition: Expr.h:669
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3075
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition: Expr.cpp:3864
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3567
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3204
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr, SourceLocation *Loc=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
An expression trait intrinsic.
Definition: ExprCXX.h:2923
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6295
bool isFPConstrained() const
Definition: LangOptions.h:847
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:865
RoundingMode getRoundingMode() const
Definition: LangOptions.h:853
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4632
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4580
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3243
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3254
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2786
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4042
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4030
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4166
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2655
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:3329
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3354
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:3069
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4657
Represents a C11 generic selection.
Definition: Expr.h:5907
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2143
Stmt * getThen()
Definition: Stmt.h:2232
Stmt * getInit()
Definition: Stmt.h:2293
bool isNonNegatedConsteval() const
Definition: Stmt.h:2328
Expr * getCond()
Definition: Stmt.h:2220
Stmt * getElse()
Definition: Stmt.h:2241
bool isConsteval() const
Definition: Stmt.h:2323
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:982
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5782
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3314
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3336
Describes an C or C++ initializer list.
Definition: Expr.h:5029
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
A global _GUID constant.
Definition: DeclCXX.h:4289
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4726
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3482
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1675
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2475
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2536
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2522
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2515
unsigned getNumComponents() const
Definition: Expr.h:2532
Helper class for OffsetOfExpr.
Definition: Expr.h:2369
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2427
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2433
@ Array
An index into an array.
Definition: Expr.h:2374
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2378
@ Field
A field.
Definition: Expr.h:2376
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2381
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2423
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2443
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
A partial diagnostic which we might know in advance that we are not going to emit.
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
Represents a parameter to a function.
Definition: Decl.h:1722
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1782
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3161
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6487
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7827
QualType withConst() const
Definition: Type.h:1166
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1163
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7743
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1101
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7944
QualType getCanonicalType() const
Definition: Type.h:7795
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
void removeLocalVolatile()
Definition: Type.h:7859
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1186
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: Type.h:1171
void removeLocalConst()
Definition: Type.h:7851
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7816
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7789
Represents a struct/union/class.
Definition: Decl.h:4141
bool hasFlexibleArrayMember() const
Definition: Decl.h:4174
field_iterator field_end() const
Definition: Decl.h:4350
field_range fields() const
Definition: Decl.h:4347
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4193
bool field_empty() const
Definition: Decl.h:4355
field_iterator field_begin() const
Definition: Decl.cpp:5057
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3402
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:510
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4455
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4256
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4751
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4407
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1870
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4482
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1779
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2393
Expr * getCond()
Definition: Stmt.h:2456
Stmt * getBody()
Definition: Stmt.h:2468
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:1100
Stmt * getInit()
Definition: Stmt.h:2477
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2530
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4714
bool isUnion() const
Definition: Decl.h:3763
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:1251
A template argument list.
Definition: DeclTemplate.h:244
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
A template parameter object.
Symbolic representation of typeid(T) for some type T.
Definition: APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7725
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2767
The base class of the type hierarchy.
Definition: Type.h:1829
bool isStructureType() const
Definition: Type.cpp:629
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8295
bool isBooleanType() const
Definition: Type.h:8423
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2889
bool isIncompleteArrayType() const
Definition: Type.h:8072
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:677
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8592
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2217
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool isConstantArrayType() const
Definition: Type.h:8068
bool isNothrowT() const
Definition: Type.cpp:3058
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2352
bool isArrayType() const
Definition: Type.h:8064
bool isCharType() const
Definition: Type.cpp:2089
bool isFunctionPointerType() const
Definition: Type.h:8032
bool isPointerType() const
Definition: Type.h:7996
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8335
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
bool isEnumeralType() const
Definition: Type.h:8096
bool isVariableArrayType() const
Definition: Type.h:8076
bool isChar8Type() const
Definition: Type.cpp:2105
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2507
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8410
bool isExtVectorBoolType() const
Definition: Type.h:8112
bool isMemberDataPointerType() const
Definition: Type.h:8057
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8264
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
bool isAnyComplexType() const
Definition: Type.h:8100
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8348
const RecordType * getAsStructureType() const
Definition: Type.cpp:721
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8466
bool isMemberPointerType() const
Definition: Type.h:8046
bool isAtomicType() const
Definition: Type.h:8147
bool isComplexIntegerType() const
Definition: Type.cpp:683
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8569
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7992
bool isVectorType() const
Definition: Type.h:8104
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isFloatingType() const
Definition: Type.cpp:2249
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2196
bool isAnyPointerType() const
Definition: Type.h:8000
TypeClass getTypeClass() const
Definition: Type.h:2316
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isNullPtrType() const
Definition: Type.h:8328
bool isRecordType() const
Definition: Type.h:8092
bool isUnionType() const
Definition: Type.cpp:671
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2476
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8457
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2578
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2647
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2610
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Expr * getSubExpr() const
Definition: Expr.h:2233
Opcode getOpcode() const
Definition: Expr.h:2228
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2274
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4346
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5353
QualType getType() const
Definition: Value.cpp:234
bool hasValue() const
Definition: Value.h:134
Represents a variable declaration or definition.
Definition: Decl.h:879
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1510
bool hasInit() const
Definition: Decl.cpp:2380
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2600
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1519
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2539
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2834
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2612
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2348
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2451
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1156
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1125
const Expr * getInit() const
Definition: Decl.h:1316
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition: Decl.cpp:2592
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2357
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1201
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2493
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1306
Represents a GCC generic vector type.
Definition: Type.h:3991
unsigned getNumElements() const
Definition: Type.h:4006
QualType getElementType() const
Definition: Type.h:4005
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2589
Expr * getCond()
Definition: Stmt.h:2641
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1161
Stmt * getBody()
Definition: Stmt.h:2653
Base class for stack frames, shared between VM and walker.
Definition: Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition: State.h:55
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition: limits.h:71
#define UINT_MAX
Definition: limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition: OSLog.cpp:181
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:3819
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: Integral.h:29
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1095
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2230
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2204
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition: Interp.h:2850
bool ReturnValue(const InterpState &S, const T &V, APValue &R)
Convert a value to an APValue.
Definition: Interp.h:43
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
@ NonNull
Values of this type can never be null.
BinaryOperatorKind
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition: CallGraph.h:207
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
@ TSCS_unspecified
Definition: Specifiers.h:233
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition: State.h:40
@ CSK_ArrayToPointer
Definition: State.h:44
@ CSK_Derived
Definition: State.h:42
@ CSK_Base
Definition: State.h:41
@ CSK_Real
Definition: State.h:46
@ CSK_ArrayIndex
Definition: State.h:45
@ CSK_Imag
Definition: State.h:47
@ CSK_Field
Definition: State.h:43
@ SD_Static
Static storage duration.
Definition: Specifiers.h:328
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:325
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition: State.h:26
@ AK_TypeId
Definition: State.h:34
@ AK_Construct
Definition: State.h:35
@ AK_Increment
Definition: State.h:30
@ AK_DynamicCast
Definition: State.h:33
@ AK_Read
Definition: State.h:27
@ AK_Assign
Definition: State.h:29
@ AK_MemberCall
Definition: State.h:32
@ AK_ReadObjectRepresentation
Definition: State.h:28
@ AK_Destroy
Definition: State.h:36
@ AK_Decrement
Definition: State.h:31
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1264
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Success
Template argument deduction was successful.
@ None
The alignment was not explicit in code.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:121
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition: Expr.h:606
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:614
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition: tgmath.h:851
#define scalbn(__x, __y)
Definition: tgmath.h:1165