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"
40#include "clang/AST/ASTContext.h"
41#include "clang/AST/ASTDiagnostic.h"
42#include "clang/AST/ASTLambda.h"
43#include "clang/AST/Attr.h"
44#include "clang/AST/CXXInheritance.h"
45#include "clang/AST/CharUnits.h"
46#include "clang/AST/CurrentSourceLocExprScope.h"
47#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
49#include "clang/AST/OptionalDiagnostic.h"
50#include "clang/AST/RecordLayout.h"
51#include "clang/AST/StmtVisitor.h"
52#include "clang/AST/TypeLoc.h"
53#include "clang/Basic/Builtins.h"
54#include "clang/Basic/DiagnosticSema.h"
55#include "clang/Basic/TargetInfo.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 =
83 CurrentSourceLocExprScope::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>(Val: 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>(Val: 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(T: 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>(Val: E))
135 E = FE->getSubExpr()->IgnoreParens();
136
137 if (const auto *Cast = dyn_cast<CastExpr>(Val: E))
138 E = Cast->getSubExpr()->IgnoreParens();
139
140 if (const auto *CE = dyn_cast<CallExpr>(Val: 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,
195 ArrayRef<APValue::LValuePathEntry> Path,
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(B: Base);
204
205 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
206 if (Type->isArrayType()) {
207 const ArrayType *AT = Ctx.getAsArrayType(T: Type);
208 Type = AT->getElementType();
209 MostDerivedLength = I + 1;
210 IsArray = true;
211
212 if (auto *CAT = dyn_cast<ConstantArrayType>(Val: 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(E: 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.
278 SmallVector<PathEntry, 8> Entries;
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(I: Entries.end(), From: VEntries.begin(), To: VEntries.end());
297 if (V.getLValueBase()) {
298 bool IsArray = false;
299 bool FirstIsUnsizedArray = false;
300 MostDerivedPathLength = findMostDerivedSubobject(
301 Ctx, Base: V.getLValueBase(), Path: V.getLValuePath(), ArraySize&: MostDerivedArraySize,
302 Type&: MostDerivedType, IsArray, FirstEntryIsUnsizedArray&: 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(N: NewLength);
320
321 bool IsArray = false;
322 bool FirstIsUnsizedArray = false;
323 MostDerivedPathLength = findMostDerivedSubobject(
324 Ctx, Base, Path: Entries, ArraySize&: MostDerivedArraySize, Type&: MostDerivedType, IsArray,
325 FirstEntryIsUnsizedArray&: 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(Decl: getAsBaseClass(E: 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(Elt: PathEntry::ArrayIndex(Index: 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(Elt: PathEntry::ArrayIndex(Index: 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(Elt: 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>(Val: 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(Elt: PathEntry::ArrayIndex(Index: 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(width: 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 Index: 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(width: std::max<unsigned>(a: N.getBitWidth() + 1, b: 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(Index: 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(i: 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(Elt: ++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(x: 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(x: MapKeyTy(Key, UINT_MAX));
612 if (UB != Temporaries.begin() && std::prev(x: UB)->first.first == Key)
613 return &std::prev(x: 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(x: MapKeyTy(Key, UINT_MAX));
620 if (UB != Temporaries.begin() && std::prev(x: UB)->first.first == Key)
621 return std::prev(x: 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(SM: 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,
704 APValue::LValueBase LVBase, APValue &Value,
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;
711 APValue::LValueBase Base;
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) {
726 SourceLocation Loc;
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, LVBase: Base, Value&: *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 {
744 APValue::LValueBase Base;
745 ArrayRef<APValue::LValuePathEntry> Path;
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(args: Obj.Base, args: 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: Base::getEmptyKey(), .Path: {}}; }
769 static ObjectUnderConstruction getTombstoneKey() {
770 return {.Base: Base::getTombstoneKey(), .Path: {}};
771 }
772 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
773 return hash_value(Obj: 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.
786 APValue Value;
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>(Val: 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.
859 llvm::SmallVector<Cleanup, 16> CleanupStack;
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(KV: {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(Val: 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(KV: {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(Val: Object);
931 }
932 };
933
934 ConstructionPhase
935 isEvaluatingCtorDtor(APValue::LValueBase Base,
936 ArrayRef<APValue::LValuePathEntry> Path) {
937 return ObjectsUnderConstruction.lookup(Val: {.Base: Base, .Path: 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, DiagId: diag::note_constexpr_call_limit_exceeded);
1036 return false;
1037 }
1038 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1039 return true;
1040 FFDiag(Loc, DiagId: 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(Context: Ctx) ||
1052 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1053 if (Diag)
1054 FFDiag(Loc, DiagId: 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, DiagId: 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(Loc: S->getBeginLoc(), DiagId: 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(x: 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(CallIndex: Call.CallIndex).first;
1111 return Frame ? Frame->getTemporary(Key: Call.getOrigParam(PVD), Version: 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>(Val: Call->Callee);
1126 if (!MD)
1127 continue;
1128 const IdentifierInfo *FnII = MD->getIdentifier();
1129 if (!FnII || !FnII->isStr(Str: FnName))
1130 continue;
1131
1132 const auto *CTSD =
1133 dyn_cast<ClassTemplateSpecializationDecl>(Val: 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(Str: "allocator") && TAL.size() >= 1 &&
1141 TAL[0].getKind() == TemplateArgument::Type)
1142 return {.FrameIndex: Call->Index, .ElemType: TAL[0].getAsType()};
1143 }
1144
1145 return {};
1146 }
1147
1148 void performLifetimeExtension() {
1149 // Disable the cleanups for lifetime-extended temporaries.
1150 llvm::erase_if(C&: CleanupStack, P: [](Cleanup &C) {
1151 return !C.isDestroyedAtEndOf(K: 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(Other: std::move(Other));
1386 }
1387
1388 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1389 maybeRestoreState();
1390 moveFromAndCancel(Other: 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(RunDestructors: 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(K: 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(K: Kind);
1446 });
1447 Info.CleanupStack.erase(CS: NewEnd, CE: 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, DiagId: 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, DiagId: 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, DiagId: diag::note_constexpr_array_index)
1486 << N << /*array*/ 0
1487 << static_cast<unsigned>(getMostDerivedArraySize());
1488 else
1489 Info.CCEDiag(E, DiagId: 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
1514static bool isModification(AccessKinds AK) {
1515 switch (AK) {
1516 case AK_Read:
1517 case AK_ReadObjectRepresentation:
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?
1537static bool isFormalAccess(AccessKinds AK) {
1538 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1539}
1540
1541/// Is this kind of axcess valid on an indeterminate object value?
1542static bool isValidIndeterminateAccess(AccessKinds AK) {
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
1550 case AK_ReadObjectRepresentation:
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 {
1608 APValue::LValueBase Base;
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(Quantity: 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 =
1662 CharUnits::fromQuantity(Quantity: Ctx.getTargetNullPointerValue(QT: PointerTy));
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, BInvalid: true);
1670 }
1671
1672 std::string toString(ASTContext &Ctx, QualType T) const {
1673 APValue Printable;
1674 moveInto(V&: Printable);
1675 return Printable.getAsString(Ctx, Ty: 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(GenDiag: [&Info, E, CSK] {
1697 Info.CCEDiag(E, DiagId: diag::note_constexpr_null_subobject) << CSK;
1698 });
1699 }
1700
1701 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1702 AccessKinds AK) {
1703 return checkNullPointerDiagnosingWith(GenDiag: [&Info, E, AK] {
1704 Info.FFDiag(E, DiagId: 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, CSK: isa<FieldDecl>(Val: 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, DiagId: diag::note_constexpr_unsupported_unsized_array);
1723 Designator.setInvalid();
1724 return;
1725 }
1726 if (checkSubobject(Info, E, CSK: 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: CSK_ArrayToPointer))
1734 Designator.addArrayUnchecked(CAT);
1735 }
1736 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1737 if (checkSubobject(Info, E, CSK: 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(width: 64).getZExtValue();
1756 Offset = CharUnits::fromQuantity(Quantity: Offset64 + ElemSize64 * Index64);
1757
1758 if (checkNullPointer(Info, E, CSK: CSK_ArrayIndex))
1759 Designator.adjustIndex(Info, E, N: 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 Val: 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(I: Path.end(), From: P.begin(), To: 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).
1807 SmallVector<const CXXRecordDecl*, 4> Path;
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(Elt: Derived);
1836 return true;
1837 }
1838 if (!castBack(Class: 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(Elt: Base);
1852 return true;
1853 }
1854 return castBack(Class: 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(width: 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(B: 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(B: 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, Key: PVD, T: PVD->getType(), Scope: 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(Elt: 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, DiagId: diag::note_constexpr_heap_alloc_limit_exceeded);
1957 return nullptr;
1958 }
1959
1960 DynamicAllocLValue DA(NumHeapAllocs++);
1961 LV.set(B: APValue::LValueBase::getDynamicAlloc(LV: DA, Type: T));
1962 auto Result = HeapAllocs.emplace(args: std::piecewise_construct,
1963 args: std::forward_as_tuple(args&: DA), args: 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>(Val: Callee) && !isa<CXXConstructorDecl>(Val: Callee) &&
1974 cast<CXXMethodDecl>(Val: Callee)->isImplicitObjectMemberFunction();
1975
1976 if (!IsMemberCall)
1977 Callee->getNameForDiagnostic(OS&: Out, Policy: Info.Ctx.getPrintingPolicy(),
1978 /*Qualified=*/false);
1979
1980 if (This && IsMemberCall) {
1981 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(Val: CallExpr)) {
1982 const Expr *Object = MCE->getImplicitObjectArgument();
1983 Object->printPretty(OS&: Out, /*Helper=*/nullptr, Policy: 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>(Val: CallExpr)) {
1991 OCE->getArg(Arg: 0)->printPretty(OS&: Out, /*Helper=*/nullptr,
1992 Policy: Info.Ctx.getPrintingPolicy(),
1993 /*Indentation=*/0);
1994 Out << ".";
1995 } else {
1996 APValue Val;
1997 This->moveInto(V&: Val);
1998 Val.printPretty(
1999 OS&: Out, Ctx: Info.Ctx,
2000 Ty: Info.Ctx.getLValueReferenceType(T: This->Designator.MostDerivedType));
2001 Out << ".";
2002 }
2003 Callee->getNameForDiagnostic(OS&: Out, Policy: 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(Call: Arguments, PVD: Param);
2017 if (V)
2018 V->printPretty(OS&: Out, Ctx: Info.Ctx, Ty: 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(Result&: 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
2050static bool IsGlobalLValue(APValue::LValueBase B) {
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>(Val: D))
2062 return VD->hasGlobalStorage();
2063 if (isa<TemplateParamObjectDecl>(Val: 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>(Val: 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>(Val: 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>(Val: 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>(Val: E)->isExpressibleAsConstantInitializer();
2094 case Expr::CallExprClass:
2095 return IsNoOpCall(E: cast<CallExpr>(Val: 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>(Val: 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>(Val: E);
2127}
2128
2129static bool IsWeakLValue(const LValue &Value) {
2130 const ValueDecl *Decl = GetLValueBaseDecl(LVal: Value);
2131 return Decl && Decl->isWeak();
2132}
2133
2134static bool isZeroSized(const LValue &Value) {
2135 const ValueDecl *Decl = GetLValueBaseDecl(LVal: Value);
2136 if (isa_and_nonnull<VarDecl>(Val: Decl)) {
2137 QualType Ty = Decl->getType();
2138 if (Ty->isArrayType())
2139 return Ty->isIncompleteType() ||
2140 Decl->getASTContext().getTypeSize(T: 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>(Val: 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(i: Idx);
2173 break;
2174 }
2175 }
2176 }
2177
2178 if (VD)
2179 Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
2180 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2181 Info.Note(Loc: E->getExprLoc(), DiagId: 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(Loc: (*Alloc)->AllocExpr->getExprLoc(),
2186 DiagId: diag::note_constexpr_dynamic_alloc_here);
2187 }
2188
2189 // We have no information to show for a typeid(T) object.
2190}
2191
2192enum class CheckEvaluationResultKind {
2193 ConstantExpression,
2194 FullyInitialized,
2195};
2196
2197/// Materialized temporaries that we've already checked to determine if they're
2198/// initializsed by a constant expression.
2199using CheckedTemporaries =
2200 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2201
2202static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
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.
2212static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
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>(Val: BaseE))
2233 InvalidBaseKind = 1;
2234 else if (isa_and_nonnull<MaterializeTemporaryExpr>(Val: BaseE) ||
2235 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(Val: BaseVD))
2236 InvalidBaseKind = 2;
2237 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(Val: BaseE)) {
2238 InvalidBaseKind = 3;
2239 Ident = PE->getIdentKindName();
2240 }
2241
2242 if (InvalidBaseKind != -1) {
2243 Info.FFDiag(Loc, DiagId: 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>(Val: BaseVD);
2251 FD && FD->isImmediateFunction()) {
2252 Info.FFDiag(Loc, DiagId: diag::note_consteval_address_accessible)
2253 << !Type->isAnyPointerType();
2254 Info.Note(Loc: FD->getLocation(), DiagId: 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(B: Base)) {
2262 if (Info.getLangOpts().CPlusPlus11) {
2263 Info.FFDiag(Loc, DiagId: diag::note_constexpr_non_global, ExtraNotes: 1)
2264 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2265 << BaseVD;
2266 auto *VarD = dyn_cast_or_null<VarDecl>(Val: 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(Loc: VarD->getLocation(), DiagId: diag::note_constexpr_not_static)
2274 << VarD
2275 << FixItHint::CreateInsertion(InsertionLoc: VarD->getBeginLoc(), Code: "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, DiagId: 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>(Val: 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>(Val: 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>(Val: BaseE)) {
2340 if (CheckedTemps.insert(Ptr: MTE).second) {
2341 QualType TempType = getType(B: Base);
2342 if (TempType.isDestructedType()) {
2343 Info.FFDiag(Loc: MTE->getExprLoc(),
2344 DiagId: diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2345 << TempType;
2346 return false;
2347 }
2348
2349 APValue *V = MTE->getOrCreateValue(MayCreate: false);
2350 assert(V && "evasluation result refers to uninitialised temporary");
2351 if (!CheckEvaluationResult(CERK: CheckEvaluationResultKind::ConstantExpression,
2352 Info, DiagLoc: MTE->getExprLoc(), Type: TempType, Value: *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, DiagId: diag::note_constexpr_past_end, ExtraNotes: 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,
2383 SourceLocation Loc,
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>(Val: Member);
2389 if (!FD)
2390 return true;
2391 if (FD->isImmediateFunction()) {
2392 Info.FFDiag(Loc, DiagId: diag::note_consteval_address_accessible) << /*pointer*/ 0;
2393 Info.Note(Loc: FD->getLocation(), DiagId: 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 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx: Info.Ctx))
2405 return true;
2406
2407 // C++1y: A constant initializer for an object o [...] may also invoke
2408 // constexpr constructors for o and its subobjects even if those objects
2409 // are of non-literal class types.
2410 //
2411 // C++11 missed this detail for aggregates, so classes like this:
2412 // struct foo_t { union { int i; volatile int j; } u; };
2413 // are not (obviously) initializable like so:
2414 // __attribute__((__require_constant_initialization__))
2415 // static const foo_t x = {{0}};
2416 // because "i" is a subobject with non-literal initialization (due to the
2417 // volatile member of the union). See:
2418 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2419 // Therefore, we use the C++1y behavior.
2420 if (This && Info.EvaluatingDecl == This->getLValueBase())
2421 return true;
2422
2423 // Prvalue constant expressions must be of literal types.
2424 if (Info.getLangOpts().CPlusPlus11)
2425 Info.FFDiag(E, DiagId: diag::note_constexpr_nonliteral)
2426 << E->getType();
2427 else
2428 Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
2429 return false;
2430}
2431
2432static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2433 EvalInfo &Info, SourceLocation DiagLoc,
2434 QualType Type, const APValue &Value,
2435 ConstantExprKind Kind,
2436 const FieldDecl *SubobjectDecl,
2437 CheckedTemporaries &CheckedTemps) {
2438 if (!Value.hasValue()) {
2439 if (SubobjectDecl) {
2440 Info.FFDiag(Loc: DiagLoc, DiagId: diag::note_constexpr_uninitialized)
2441 << /*(name)*/ 1 << SubobjectDecl;
2442 Info.Note(Loc: SubobjectDecl->getLocation(),
2443 DiagId: diag::note_constexpr_subobject_declared_here);
2444 } else {
2445 Info.FFDiag(Loc: DiagLoc, DiagId: diag::note_constexpr_uninitialized)
2446 << /*of type*/ 0 << Type;
2447 }
2448 return false;
2449 }
2450
2451 // We allow _Atomic(T) to be initialized from anything that T can be
2452 // initialized from.
2453 if (const AtomicType *AT = Type->getAs<AtomicType>())
2454 Type = AT->getValueType();
2455
2456 // Core issue 1454: For a literal constant expression of array or class type,
2457 // each subobject of its value shall have been initialized by a constant
2458 // expression.
2459 if (Value.isArray()) {
2460 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2461 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2462 if (!CheckEvaluationResult(CERK, Info, DiagLoc, Type: EltTy,
2463 Value: Value.getArrayInitializedElt(I), Kind,
2464 SubobjectDecl, CheckedTemps))
2465 return false;
2466 }
2467 if (!Value.hasArrayFiller())
2468 return true;
2469 return CheckEvaluationResult(CERK, Info, DiagLoc, Type: EltTy,
2470 Value: Value.getArrayFiller(), Kind, SubobjectDecl,
2471 CheckedTemps);
2472 }
2473 if (Value.isUnion() && Value.getUnionField()) {
2474 return CheckEvaluationResult(
2475 CERK, Info, DiagLoc, Type: Value.getUnionField()->getType(),
2476 Value: Value.getUnionValue(), Kind, SubobjectDecl: Value.getUnionField(), CheckedTemps);
2477 }
2478 if (Value.isStruct()) {
2479 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2480 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(Val: RD)) {
2481 unsigned BaseIndex = 0;
2482 for (const CXXBaseSpecifier &BS : CD->bases()) {
2483 const APValue &BaseValue = Value.getStructBase(i: BaseIndex);
2484 if (!BaseValue.hasValue()) {
2485 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2486 Info.FFDiag(Loc: TypeBeginLoc, DiagId: diag::note_constexpr_uninitialized_base)
2487 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2488 return false;
2489 }
2490 if (!CheckEvaluationResult(CERK, Info, DiagLoc, Type: BS.getType(), Value: BaseValue,
2491 Kind, /*SubobjectDecl=*/nullptr,
2492 CheckedTemps))
2493 return false;
2494 ++BaseIndex;
2495 }
2496 }
2497 for (const auto *I : RD->fields()) {
2498 if (I->isUnnamedBitField())
2499 continue;
2500
2501 if (!CheckEvaluationResult(CERK, Info, DiagLoc, Type: I->getType(),
2502 Value: Value.getStructField(i: I->getFieldIndex()), Kind,
2503 SubobjectDecl: I, CheckedTemps))
2504 return false;
2505 }
2506 }
2507
2508 if (Value.isLValue() &&
2509 CERK == CheckEvaluationResultKind::ConstantExpression) {
2510 LValue LVal;
2511 LVal.setFrom(Ctx&: Info.Ctx, V: Value);
2512 return CheckLValueConstantExpression(Info, Loc: DiagLoc, Type, LVal, Kind,
2513 CheckedTemps);
2514 }
2515
2516 if (Value.isMemberPointer() &&
2517 CERK == CheckEvaluationResultKind::ConstantExpression)
2518 return CheckMemberPointerConstantExpression(Info, Loc: DiagLoc, Type, Value, Kind);
2519
2520 // Everything else is fine.
2521 return true;
2522}
2523
2524/// Check that this core constant expression value is a valid value for a
2525/// constant expression. If not, report an appropriate diagnostic. Does not
2526/// check that the expression is of literal type.
2527static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2528 QualType Type, const APValue &Value,
2529 ConstantExprKind Kind) {
2530 // Nothing to check for a constant expression of type 'cv void'.
2531 if (Type->isVoidType())
2532 return true;
2533
2534 CheckedTemporaries CheckedTemps;
2535 return CheckEvaluationResult(CERK: CheckEvaluationResultKind::ConstantExpression,
2536 Info, DiagLoc, Type, Value, Kind,
2537 /*SubobjectDecl=*/nullptr, CheckedTemps);
2538}
2539
2540/// Check that this evaluated value is fully-initialized and can be loaded by
2541/// an lvalue-to-rvalue conversion.
2542static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2543 QualType Type, const APValue &Value) {
2544 CheckedTemporaries CheckedTemps;
2545 return CheckEvaluationResult(
2546 CERK: CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2547 Kind: ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2548}
2549
2550/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2551/// "the allocated storage is deallocated within the evaluation".
2552static bool CheckMemoryLeaks(EvalInfo &Info) {
2553 if (!Info.HeapAllocs.empty()) {
2554 // We can still fold to a constant despite a compile-time memory leak,
2555 // so long as the heap allocation isn't referenced in the result (we check
2556 // that in CheckConstantExpression).
2557 Info.CCEDiag(E: Info.HeapAllocs.begin()->second.AllocExpr,
2558 DiagId: diag::note_constexpr_memory_leak)
2559 << unsigned(Info.HeapAllocs.size() - 1);
2560 }
2561 return true;
2562}
2563
2564static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2565 // A null base expression indicates a null pointer. These are always
2566 // evaluatable, and they are false unless the offset is zero.
2567 if (!Value.getLValueBase()) {
2568 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2569 Result = !Value.getLValueOffset().isZero();
2570 return true;
2571 }
2572
2573 // We have a non-null base. These are generally known to be true, but if it's
2574 // a weak declaration it can be null at runtime.
2575 Result = true;
2576 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2577 return !Decl || !Decl->isWeak();
2578}
2579
2580static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2581 // TODO: This function should produce notes if it fails.
2582 switch (Val.getKind()) {
2583 case APValue::None:
2584 case APValue::Indeterminate:
2585 return false;
2586 case APValue::Int:
2587 Result = Val.getInt().getBoolValue();
2588 return true;
2589 case APValue::FixedPoint:
2590 Result = Val.getFixedPoint().getBoolValue();
2591 return true;
2592 case APValue::Float:
2593 Result = !Val.getFloat().isZero();
2594 return true;
2595 case APValue::ComplexInt:
2596 Result = Val.getComplexIntReal().getBoolValue() ||
2597 Val.getComplexIntImag().getBoolValue();
2598 return true;
2599 case APValue::ComplexFloat:
2600 Result = !Val.getComplexFloatReal().isZero() ||
2601 !Val.getComplexFloatImag().isZero();
2602 return true;
2603 case APValue::LValue:
2604 return EvalPointerValueAsBool(Value: Val, Result);
2605 case APValue::MemberPointer:
2606 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2607 return false;
2608 }
2609 Result = Val.getMemberPointerDecl();
2610 return true;
2611 case APValue::Vector:
2612 case APValue::Array:
2613 case APValue::Struct:
2614 case APValue::Union:
2615 case APValue::AddrLabelDiff:
2616 return false;
2617 }
2618
2619 llvm_unreachable("unknown APValue kind");
2620}
2621
2622static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2623 EvalInfo &Info) {
2624 assert(!E->isValueDependent());
2625 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2626 APValue Val;
2627 if (!Evaluate(Result&: Val, Info, E))
2628 return false;
2629 return HandleConversionToBool(Val, Result);
2630}
2631
2632template<typename T>
2633static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2634 const T &SrcValue, QualType DestType) {
2635 Info.CCEDiag(E, DiagId: diag::note_constexpr_overflow)
2636 << SrcValue << DestType;
2637 return Info.noteUndefinedBehavior();
2638}
2639
2640static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2641 QualType SrcType, const APFloat &Value,
2642 QualType DestType, APSInt &Result) {
2643 unsigned DestWidth = Info.Ctx.getIntWidth(T: DestType);
2644 // Determine whether we are converting to unsigned or signed.
2645 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2646
2647 Result = APSInt(DestWidth, !DestSigned);
2648 bool ignored;
2649 if (Value.convertToInteger(Result, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored)
2650 & APFloat::opInvalidOp)
2651 return HandleOverflow(Info, E, SrcValue: Value, DestType);
2652 return true;
2653}
2654
2655/// Get rounding mode to use in evaluation of the specified expression.
2656///
2657/// If rounding mode is unknown at compile time, still try to evaluate the
2658/// expression. If the result is exact, it does not depend on rounding mode.
2659/// So return "tonearest" mode instead of "dynamic".
2660static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2661 llvm::RoundingMode RM =
2662 E->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts()).getRoundingMode();
2663 if (RM == llvm::RoundingMode::Dynamic)
2664 RM = llvm::RoundingMode::NearestTiesToEven;
2665 return RM;
2666}
2667
2668/// Check if the given evaluation result is allowed for constant evaluation.
2669static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2670 APFloat::opStatus St) {
2671 // In a constant context, assume that any dynamic rounding mode or FP
2672 // exception state matches the default floating-point environment.
2673 if (Info.InConstantContext)
2674 return true;
2675
2676 FPOptions FPO = E->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts());
2677 if ((St & APFloat::opInexact) &&
2678 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2679 // Inexact result means that it depends on rounding mode. If the requested
2680 // mode is dynamic, the evaluation cannot be made in compile time.
2681 Info.FFDiag(E, DiagId: diag::note_constexpr_dynamic_rounding);
2682 return false;
2683 }
2684
2685 if ((St != APFloat::opOK) &&
2686 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2687 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2688 FPO.getAllowFEnvAccess())) {
2689 Info.FFDiag(E, DiagId: diag::note_constexpr_float_arithmetic_strict);
2690 return false;
2691 }
2692
2693 if ((St & APFloat::opStatus::opInvalidOp) &&
2694 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2695 // There is no usefully definable result.
2696 Info.FFDiag(E);
2697 return false;
2698 }
2699
2700 // FIXME: if:
2701 // - evaluation triggered other FP exception, and
2702 // - exception mode is not "ignore", and
2703 // - the expression being evaluated is not a part of global variable
2704 // initializer,
2705 // the evaluation probably need to be rejected.
2706 return true;
2707}
2708
2709static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2710 QualType SrcType, QualType DestType,
2711 APFloat &Result) {
2712 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2713 isa<ConvertVectorExpr>(E)) &&
2714 "HandleFloatToFloatCast has been checked with only CastExpr, "
2715 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2716 "the new expression or address the root cause of this usage.");
2717 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2718 APFloat::opStatus St;
2719 APFloat Value = Result;
2720 bool ignored;
2721 St = Result.convert(ToSemantics: Info.Ctx.getFloatTypeSemantics(T: DestType), RM, losesInfo: &ignored);
2722 return checkFloatingPointResult(Info, E, St);
2723}
2724
2725static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2726 QualType DestType, QualType SrcType,
2727 const APSInt &Value) {
2728 unsigned DestWidth = Info.Ctx.getIntWidth(T: DestType);
2729 // Figure out if this is a truncate, extend or noop cast.
2730 // If the input is signed, do a sign extend, noop, or truncate.
2731 APSInt Result = Value.extOrTrunc(width: DestWidth);
2732 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2733 if (DestType->isBooleanType())
2734 Result = Value.getBoolValue();
2735 return Result;
2736}
2737
2738static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2739 const FPOptions FPO,
2740 QualType SrcType, const APSInt &Value,
2741 QualType DestType, APFloat &Result) {
2742 Result = APFloat(Info.Ctx.getFloatTypeSemantics(T: DestType), 1);
2743 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2744 APFloat::opStatus St = Result.convertFromAPInt(Input: Value, IsSigned: Value.isSigned(), RM);
2745 return checkFloatingPointResult(Info, E, St);
2746}
2747
2748static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2749 APValue &Value, const FieldDecl *FD) {
2750 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2751
2752 if (!Value.isInt()) {
2753 // Trying to store a pointer-cast-to-integer into a bitfield.
2754 // FIXME: In this case, we should provide the diagnostic for casting
2755 // a pointer to an integer.
2756 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2757 Info.FFDiag(E);
2758 return false;
2759 }
2760
2761 APSInt &Int = Value.getInt();
2762 unsigned OldBitWidth = Int.getBitWidth();
2763 unsigned NewBitWidth = FD->getBitWidthValue(Ctx: Info.Ctx);
2764 if (NewBitWidth < OldBitWidth)
2765 Int = Int.trunc(width: NewBitWidth).extend(width: OldBitWidth);
2766 return true;
2767}
2768
2769/// Perform the given integer operation, which is known to need at most BitWidth
2770/// bits, and check for overflow in the original type (if that type was not an
2771/// unsigned type).
2772template<typename Operation>
2773static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2774 const APSInt &LHS, const APSInt &RHS,
2775 unsigned BitWidth, Operation Op,
2776 APSInt &Result) {
2777 if (LHS.isUnsigned()) {
2778 Result = Op(LHS, RHS);
2779 return true;
2780 }
2781
2782 APSInt Value(Op(LHS.extend(width: BitWidth), RHS.extend(width: BitWidth)), false);
2783 Result = Value.trunc(width: LHS.getBitWidth());
2784 if (Result.extend(width: BitWidth) != Value) {
2785 if (Info.checkingForUndefinedBehavior())
2786 Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(),
2787 DiagID: diag::warn_integer_constant_overflow)
2788 << toString(I: Result, Radix: 10, Signed: Result.isSigned(), /*formatAsCLiteral=*/false,
2789 /*UpperCase=*/true, /*InsertSeparators=*/true)
2790 << E->getType() << E->getSourceRange();
2791 return HandleOverflow(Info, E, SrcValue: Value, DestType: E->getType());
2792 }
2793 return true;
2794}
2795
2796/// Perform the given binary integer operation.
2797static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2798 const APSInt &LHS, BinaryOperatorKind Opcode,
2799 APSInt RHS, APSInt &Result) {
2800 bool HandleOverflowResult = true;
2801 switch (Opcode) {
2802 default:
2803 Info.FFDiag(E);
2804 return false;
2805 case BO_Mul:
2806 return CheckedIntArithmetic(Info, E, LHS, RHS, BitWidth: LHS.getBitWidth() * 2,
2807 Op: std::multiplies<APSInt>(), Result);
2808 case BO_Add:
2809 return CheckedIntArithmetic(Info, E, LHS, RHS, BitWidth: LHS.getBitWidth() + 1,
2810 Op: std::plus<APSInt>(), Result);
2811 case BO_Sub:
2812 return CheckedIntArithmetic(Info, E, LHS, RHS, BitWidth: LHS.getBitWidth() + 1,
2813 Op: std::minus<APSInt>(), Result);
2814 case BO_And: Result = LHS & RHS; return true;
2815 case BO_Xor: Result = LHS ^ RHS; return true;
2816 case BO_Or: Result = LHS | RHS; return true;
2817 case BO_Div:
2818 case BO_Rem:
2819 if (RHS == 0) {
2820 Info.FFDiag(E, DiagId: diag::note_expr_divide_by_zero)
2821 << E->getRHS()->getSourceRange();
2822 return false;
2823 }
2824 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2825 // this operation and gives the two's complement result.
2826 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2827 LHS.isMinSignedValue())
2828 HandleOverflowResult = HandleOverflow(
2829 Info, E, SrcValue: -LHS.extend(width: LHS.getBitWidth() + 1), DestType: E->getType());
2830 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2831 return HandleOverflowResult;
2832 case BO_Shl: {
2833 if (Info.getLangOpts().OpenCL)
2834 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2835 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2836 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2837 RHS.isUnsigned());
2838 else if (RHS.isSigned() && RHS.isNegative()) {
2839 // During constant-folding, a negative shift is an opposite shift. Such
2840 // a shift is not a constant expression.
2841 Info.CCEDiag(E, DiagId: diag::note_constexpr_negative_shift) << RHS;
2842 if (!Info.noteUndefinedBehavior())
2843 return false;
2844 RHS = -RHS;
2845 goto shift_right;
2846 }
2847 shift_left:
2848 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2849 // the shifted type.
2850 unsigned SA = (unsigned) RHS.getLimitedValue(Limit: LHS.getBitWidth()-1);
2851 if (SA != RHS) {
2852 Info.CCEDiag(E, DiagId: diag::note_constexpr_large_shift)
2853 << RHS << E->getType() << LHS.getBitWidth();
2854 if (!Info.noteUndefinedBehavior())
2855 return false;
2856 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2857 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2858 // operand, and must not overflow the corresponding unsigned type.
2859 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2860 // E1 x 2^E2 module 2^N.
2861 if (LHS.isNegative()) {
2862 Info.CCEDiag(E, DiagId: diag::note_constexpr_lshift_of_negative) << LHS;
2863 if (!Info.noteUndefinedBehavior())
2864 return false;
2865 } else if (LHS.countl_zero() < SA) {
2866 Info.CCEDiag(E, DiagId: diag::note_constexpr_lshift_discards);
2867 if (!Info.noteUndefinedBehavior())
2868 return false;
2869 }
2870 }
2871 Result = LHS << SA;
2872 return true;
2873 }
2874 case BO_Shr: {
2875 if (Info.getLangOpts().OpenCL)
2876 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2877 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2878 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2879 RHS.isUnsigned());
2880 else if (RHS.isSigned() && RHS.isNegative()) {
2881 // During constant-folding, a negative shift is an opposite shift. Such a
2882 // shift is not a constant expression.
2883 Info.CCEDiag(E, DiagId: diag::note_constexpr_negative_shift) << RHS;
2884 if (!Info.noteUndefinedBehavior())
2885 return false;
2886 RHS = -RHS;
2887 goto shift_left;
2888 }
2889 shift_right:
2890 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2891 // shifted type.
2892 unsigned SA = (unsigned) RHS.getLimitedValue(Limit: LHS.getBitWidth()-1);
2893 if (SA != RHS) {
2894 Info.CCEDiag(E, DiagId: diag::note_constexpr_large_shift)
2895 << RHS << E->getType() << LHS.getBitWidth();
2896 if (!Info.noteUndefinedBehavior())
2897 return false;
2898 }
2899
2900 Result = LHS >> SA;
2901 return true;
2902 }
2903
2904 case BO_LT: Result = LHS < RHS; return true;
2905 case BO_GT: Result = LHS > RHS; return true;
2906 case BO_LE: Result = LHS <= RHS; return true;
2907 case BO_GE: Result = LHS >= RHS; return true;
2908 case BO_EQ: Result = LHS == RHS; return true;
2909 case BO_NE: Result = LHS != RHS; return true;
2910 case BO_Cmp:
2911 llvm_unreachable("BO_Cmp should be handled elsewhere");
2912 }
2913}
2914
2915/// Perform the given binary floating-point operation, in-place, on LHS.
2916static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2917 APFloat &LHS, BinaryOperatorKind Opcode,
2918 const APFloat &RHS) {
2919 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2920 APFloat::opStatus St;
2921 switch (Opcode) {
2922 default:
2923 Info.FFDiag(E);
2924 return false;
2925 case BO_Mul:
2926 St = LHS.multiply(RHS, RM);
2927 break;
2928 case BO_Add:
2929 St = LHS.add(RHS, RM);
2930 break;
2931 case BO_Sub:
2932 St = LHS.subtract(RHS, RM);
2933 break;
2934 case BO_Div:
2935 // [expr.mul]p4:
2936 // If the second operand of / or % is zero the behavior is undefined.
2937 if (RHS.isZero())
2938 Info.CCEDiag(E, DiagId: diag::note_expr_divide_by_zero);
2939 St = LHS.divide(RHS, RM);
2940 break;
2941 }
2942
2943 // [expr.pre]p4:
2944 // If during the evaluation of an expression, the result is not
2945 // mathematically defined [...], the behavior is undefined.
2946 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2947 if (LHS.isNaN()) {
2948 Info.CCEDiag(E, DiagId: diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2949 return Info.noteUndefinedBehavior();
2950 }
2951
2952 return checkFloatingPointResult(Info, E, St);
2953}
2954
2955static bool handleLogicalOpForVector(const APInt &LHSValue,
2956 BinaryOperatorKind Opcode,
2957 const APInt &RHSValue, APInt &Result) {
2958 bool LHS = (LHSValue != 0);
2959 bool RHS = (RHSValue != 0);
2960
2961 if (Opcode == BO_LAnd)
2962 Result = LHS && RHS;
2963 else
2964 Result = LHS || RHS;
2965 return true;
2966}
2967static bool handleLogicalOpForVector(const APFloat &LHSValue,
2968 BinaryOperatorKind Opcode,
2969 const APFloat &RHSValue, APInt &Result) {
2970 bool LHS = !LHSValue.isZero();
2971 bool RHS = !RHSValue.isZero();
2972
2973 if (Opcode == BO_LAnd)
2974 Result = LHS && RHS;
2975 else
2976 Result = LHS || RHS;
2977 return true;
2978}
2979
2980static bool handleLogicalOpForVector(const APValue &LHSValue,
2981 BinaryOperatorKind Opcode,
2982 const APValue &RHSValue, APInt &Result) {
2983 // The result is always an int type, however operands match the first.
2984 if (LHSValue.getKind() == APValue::Int)
2985 return handleLogicalOpForVector(LHSValue: LHSValue.getInt(), Opcode,
2986 RHSValue: RHSValue.getInt(), Result);
2987 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2988 return handleLogicalOpForVector(LHSValue: LHSValue.getFloat(), Opcode,
2989 RHSValue: RHSValue.getFloat(), Result);
2990}
2991
2992template <typename APTy>
2993static bool
2994handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2995 const APTy &RHSValue, APInt &Result) {
2996 switch (Opcode) {
2997 default:
2998 llvm_unreachable("unsupported binary operator");
2999 case BO_EQ:
3000 Result = (LHSValue == RHSValue);
3001 break;
3002 case BO_NE:
3003 Result = (LHSValue != RHSValue);
3004 break;
3005 case BO_LT:
3006 Result = (LHSValue < RHSValue);
3007 break;
3008 case BO_GT:
3009 Result = (LHSValue > RHSValue);
3010 break;
3011 case BO_LE:
3012 Result = (LHSValue <= RHSValue);
3013 break;
3014 case BO_GE:
3015 Result = (LHSValue >= RHSValue);
3016 break;
3017 }
3018
3019 // The boolean operations on these vector types use an instruction that
3020 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3021 // to -1 to make sure that we produce the correct value.
3022 Result.negate();
3023
3024 return true;
3025}
3026
3027static bool handleCompareOpForVector(const APValue &LHSValue,
3028 BinaryOperatorKind Opcode,
3029 const APValue &RHSValue, APInt &Result) {
3030 // The result is always an int type, however operands match the first.
3031 if (LHSValue.getKind() == APValue::Int)
3032 return handleCompareOpForVectorHelper(LHSValue: LHSValue.getInt(), Opcode,
3033 RHSValue: RHSValue.getInt(), Result);
3034 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3035 return handleCompareOpForVectorHelper(LHSValue: LHSValue.getFloat(), Opcode,
3036 RHSValue: RHSValue.getFloat(), Result);
3037}
3038
3039// Perform binary operations for vector types, in place on the LHS.
3040static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3041 BinaryOperatorKind Opcode,
3042 APValue &LHSValue,
3043 const APValue &RHSValue) {
3044 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3045 "Operation not supported on vector types");
3046
3047 const auto *VT = E->getType()->castAs<VectorType>();
3048 unsigned NumElements = VT->getNumElements();
3049 QualType EltTy = VT->getElementType();
3050
3051 // In the cases (typically C as I've observed) where we aren't evaluating
3052 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3053 // just give up.
3054 if (!LHSValue.isVector()) {
3055 assert(LHSValue.isLValue() &&
3056 "A vector result that isn't a vector OR uncalculated LValue");
3057 Info.FFDiag(E);
3058 return false;
3059 }
3060
3061 assert(LHSValue.getVectorLength() == NumElements &&
3062 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3063
3064 SmallVector<APValue, 4> ResultElements;
3065
3066 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3067 APValue LHSElt = LHSValue.getVectorElt(I: EltNum);
3068 APValue RHSElt = RHSValue.getVectorElt(I: EltNum);
3069
3070 if (EltTy->isIntegerType()) {
3071 APSInt EltResult{Info.Ctx.getIntWidth(T: EltTy),
3072 EltTy->isUnsignedIntegerType()};
3073 bool Success = true;
3074
3075 if (BinaryOperator::isLogicalOp(Opc: Opcode))
3076 Success = handleLogicalOpForVector(LHSValue: LHSElt, Opcode, RHSValue: RHSElt, Result&: EltResult);
3077 else if (BinaryOperator::isComparisonOp(Opc: Opcode))
3078 Success = handleCompareOpForVector(LHSValue: LHSElt, Opcode, RHSValue: RHSElt, Result&: EltResult);
3079 else
3080 Success = handleIntIntBinOp(Info, E, LHS: LHSElt.getInt(), Opcode,
3081 RHS: RHSElt.getInt(), Result&: EltResult);
3082
3083 if (!Success) {
3084 Info.FFDiag(E);
3085 return false;
3086 }
3087 ResultElements.emplace_back(Args&: EltResult);
3088
3089 } else if (EltTy->isFloatingType()) {
3090 assert(LHSElt.getKind() == APValue::Float &&
3091 RHSElt.getKind() == APValue::Float &&
3092 "Mismatched LHS/RHS/Result Type");
3093 APFloat LHSFloat = LHSElt.getFloat();
3094
3095 if (!handleFloatFloatBinOp(Info, E, LHS&: LHSFloat, Opcode,
3096 RHS: RHSElt.getFloat())) {
3097 Info.FFDiag(E);
3098 return false;
3099 }
3100
3101 ResultElements.emplace_back(Args&: LHSFloat);
3102 }
3103 }
3104
3105 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3106 return true;
3107}
3108
3109/// Cast an lvalue referring to a base subobject to a derived class, by
3110/// truncating the lvalue's path to the given length.
3111static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3112 const RecordDecl *TruncatedType,
3113 unsigned TruncatedElements) {
3114 SubobjectDesignator &D = Result.Designator;
3115
3116 // Check we actually point to a derived class object.
3117 if (TruncatedElements == D.Entries.size())
3118 return true;
3119 assert(TruncatedElements >= D.MostDerivedPathLength &&
3120 "not casting to a derived class");
3121 if (!Result.checkSubobject(Info, E, CSK: CSK_Derived))
3122 return false;
3123
3124 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3125 const RecordDecl *RD = TruncatedType;
3126 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3127 if (RD->isInvalidDecl()) return false;
3128 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD);
3129 const CXXRecordDecl *Base = getAsBaseClass(E: D.Entries[I]);
3130 if (isVirtualBaseClass(E: D.Entries[I]))
3131 Result.Offset -= Layout.getVBaseClassOffset(VBase: Base);
3132 else
3133 Result.Offset -= Layout.getBaseClassOffset(Base);
3134 RD = Base;
3135 }
3136 D.Entries.resize(N: TruncatedElements);
3137 return true;
3138}
3139
3140static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3141 const CXXRecordDecl *Derived,
3142 const CXXRecordDecl *Base,
3143 const ASTRecordLayout *RL = nullptr) {
3144 if (!RL) {
3145 if (Derived->isInvalidDecl()) return false;
3146 RL = &Info.Ctx.getASTRecordLayout(D: Derived);
3147 }
3148
3149 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3150 Obj.addDecl(Info, E, D: Base, /*Virtual*/ false);
3151 return true;
3152}
3153
3154static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3155 const CXXRecordDecl *DerivedDecl,
3156 const CXXBaseSpecifier *Base) {
3157 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3158
3159 if (!Base->isVirtual())
3160 return HandleLValueDirectBase(Info, E, Obj, Derived: DerivedDecl, Base: BaseDecl);
3161
3162 SubobjectDesignator &D = Obj.Designator;
3163 if (D.Invalid)
3164 return false;
3165
3166 // Extract most-derived object and corresponding type.
3167 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3168 if (!CastToDerivedClass(Info, E, Result&: Obj, TruncatedType: DerivedDecl, TruncatedElements: D.MostDerivedPathLength))
3169 return false;
3170
3171 // Find the virtual base class.
3172 if (DerivedDecl->isInvalidDecl()) return false;
3173 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: DerivedDecl);
3174 Obj.getLValueOffset() += Layout.getVBaseClassOffset(VBase: BaseDecl);
3175 Obj.addDecl(Info, E, D: BaseDecl, /*Virtual*/ true);
3176 return true;
3177}
3178
3179static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3180 QualType Type, LValue &Result) {
3181 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3182 PathE = E->path_end();
3183 PathI != PathE; ++PathI) {
3184 if (!HandleLValueBase(Info, E, Obj&: Result, DerivedDecl: Type->getAsCXXRecordDecl(),
3185 Base: *PathI))
3186 return false;
3187 Type = (*PathI)->getType();
3188 }
3189 return true;
3190}
3191
3192/// Cast an lvalue referring to a derived class to a known base subobject.
3193static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3194 const CXXRecordDecl *DerivedRD,
3195 const CXXRecordDecl *BaseRD) {
3196 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3197 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3198 if (!DerivedRD->isDerivedFrom(Base: BaseRD, Paths))
3199 llvm_unreachable("Class must be derived from the passed in base class!");
3200
3201 for (CXXBasePathElement &Elem : Paths.front())
3202 if (!HandleLValueBase(Info, E, Obj&: Result, DerivedDecl: Elem.Class, Base: Elem.Base))
3203 return false;
3204 return true;
3205}
3206
3207/// Update LVal to refer to the given field, which must be a member of the type
3208/// currently described by LVal.
3209static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3210 const FieldDecl *FD,
3211 const ASTRecordLayout *RL = nullptr) {
3212 if (!RL) {
3213 if (FD->getParent()->isInvalidDecl()) return false;
3214 RL = &Info.Ctx.getASTRecordLayout(D: FD->getParent());
3215 }
3216
3217 unsigned I = FD->getFieldIndex();
3218 LVal.adjustOffset(N: Info.Ctx.toCharUnitsFromBits(BitSize: RL->getFieldOffset(FieldNo: I)));
3219 LVal.addDecl(Info, E, D: FD);
3220 return true;
3221}
3222
3223/// Update LVal to refer to the given indirect field.
3224static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3225 LValue &LVal,
3226 const IndirectFieldDecl *IFD) {
3227 for (const auto *C : IFD->chain())
3228 if (!HandleLValueMember(Info, E, LVal, FD: cast<FieldDecl>(Val: C)))
3229 return false;
3230 return true;
3231}
3232
3233enum class SizeOfType {
3234 SizeOf,
3235 DataSizeOf,
3236};
3237
3238/// Get the size of the given type in char units.
3239static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3240 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3241 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3242 // extension.
3243 if (Type->isVoidType() || Type->isFunctionType()) {
3244 Size = CharUnits::One();
3245 return true;
3246 }
3247
3248 if (Type->isDependentType()) {
3249 Info.FFDiag(Loc);
3250 return false;
3251 }
3252
3253 if (!Type->isConstantSizeType()) {
3254 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3255 // FIXME: Better diagnostic.
3256 Info.FFDiag(Loc);
3257 return false;
3258 }
3259
3260 if (SOT == SizeOfType::SizeOf)
3261 Size = Info.Ctx.getTypeSizeInChars(T: Type);
3262 else
3263 Size = Info.Ctx.getTypeInfoDataSizeInChars(T: Type).Width;
3264 return true;
3265}
3266
3267/// Update a pointer value to model pointer arithmetic.
3268/// \param Info - Information about the ongoing evaluation.
3269/// \param E - The expression being evaluated, for diagnostic purposes.
3270/// \param LVal - The pointer value to be updated.
3271/// \param EltTy - The pointee type represented by LVal.
3272/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3273static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3274 LValue &LVal, QualType EltTy,
3275 APSInt Adjustment) {
3276 CharUnits SizeOfPointee;
3277 if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: EltTy, Size&: SizeOfPointee))
3278 return false;
3279
3280 LVal.adjustOffsetAndIndex(Info, E, Index: Adjustment, ElementSize: SizeOfPointee);
3281 return true;
3282}
3283
3284static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3285 LValue &LVal, QualType EltTy,
3286 int64_t Adjustment) {
3287 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3288 Adjustment: APSInt::get(X: Adjustment));
3289}
3290
3291/// Update an lvalue to refer to a component of a complex number.
3292/// \param Info - Information about the ongoing evaluation.
3293/// \param LVal - The lvalue to be updated.
3294/// \param EltTy - The complex number's component type.
3295/// \param Imag - False for the real component, true for the imaginary.
3296static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3297 LValue &LVal, QualType EltTy,
3298 bool Imag) {
3299 if (Imag) {
3300 CharUnits SizeOfComponent;
3301 if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: EltTy, Size&: SizeOfComponent))
3302 return false;
3303 LVal.Offset += SizeOfComponent;
3304 }
3305 LVal.addComplex(Info, E, EltTy, Imag);
3306 return true;
3307}
3308
3309/// Try to evaluate the initializer for a variable declaration.
3310///
3311/// \param Info Information about the ongoing evaluation.
3312/// \param E An expression to be used when printing diagnostics.
3313/// \param VD The variable whose initializer should be obtained.
3314/// \param Version The version of the variable within the frame.
3315/// \param Frame The frame in which the variable was created. Must be null
3316/// if this variable is not local to the evaluation.
3317/// \param Result Filled in with a pointer to the value of the variable.
3318static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3319 const VarDecl *VD, CallStackFrame *Frame,
3320 unsigned Version, APValue *&Result) {
3321 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3322
3323 // If this is a local variable, dig out its value.
3324 if (Frame) {
3325 Result = Frame->getTemporary(Key: VD, Version);
3326 if (Result)
3327 return true;
3328
3329 if (!isa<ParmVarDecl>(Val: VD)) {
3330 // Assume variables referenced within a lambda's call operator that were
3331 // not declared within the call operator are captures and during checking
3332 // of a potential constant expression, assume they are unknown constant
3333 // expressions.
3334 assert(isLambdaCallOperator(Frame->Callee) &&
3335 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3336 "missing value for local variable");
3337 if (Info.checkingPotentialConstantExpression())
3338 return false;
3339 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3340 // still reachable at all?
3341 Info.FFDiag(Loc: E->getBeginLoc(),
3342 DiagId: diag::note_unimplemented_constexpr_lambda_feature_ast)
3343 << "captures not currently allowed";
3344 return false;
3345 }
3346 }
3347
3348 // If we're currently evaluating the initializer of this declaration, use that
3349 // in-flight value.
3350 if (Info.EvaluatingDecl == Base) {
3351 Result = Info.EvaluatingDeclValue;
3352 return true;
3353 }
3354
3355 if (isa<ParmVarDecl>(Val: VD)) {
3356 // Assume parameters of a potential constant expression are usable in
3357 // constant expressions.
3358 if (!Info.checkingPotentialConstantExpression() ||
3359 !Info.CurrentCall->Callee ||
3360 !Info.CurrentCall->Callee->Equals(DC: VD->getDeclContext())) {
3361 if (Info.getLangOpts().CPlusPlus11) {
3362 Info.FFDiag(E, DiagId: diag::note_constexpr_function_param_value_unknown)
3363 << VD;
3364 NoteLValueLocation(Info, Base);
3365 } else {
3366 Info.FFDiag(E);
3367 }
3368 }
3369 return false;
3370 }
3371
3372 if (E->isValueDependent())
3373 return false;
3374
3375 // Dig out the initializer, and use the declaration which it's attached to.
3376 // FIXME: We should eventually check whether the variable has a reachable
3377 // initializing declaration.
3378 const Expr *Init = VD->getAnyInitializer(D&: VD);
3379 if (!Init) {
3380 // Don't diagnose during potential constant expression checking; an
3381 // initializer might be added later.
3382 if (!Info.checkingPotentialConstantExpression()) {
3383 Info.FFDiag(E, DiagId: diag::note_constexpr_var_init_unknown, ExtraNotes: 1)
3384 << VD;
3385 NoteLValueLocation(Info, Base);
3386 }
3387 return false;
3388 }
3389
3390 if (Init->isValueDependent()) {
3391 // The DeclRefExpr is not value-dependent, but the variable it refers to
3392 // has a value-dependent initializer. This should only happen in
3393 // constant-folding cases, where the variable is not actually of a suitable
3394 // type for use in a constant expression (otherwise the DeclRefExpr would
3395 // have been value-dependent too), so diagnose that.
3396 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3397 if (!Info.checkingPotentialConstantExpression()) {
3398 Info.FFDiag(E, DiagId: Info.getLangOpts().CPlusPlus11
3399 ? diag::note_constexpr_ltor_non_constexpr
3400 : diag::note_constexpr_ltor_non_integral, ExtraNotes: 1)
3401 << VD << VD->getType();
3402 NoteLValueLocation(Info, Base);
3403 }
3404 return false;
3405 }
3406
3407 // Check that we can fold the initializer. In C++, we will have already done
3408 // this in the cases where it matters for conformance.
3409 if (!VD->evaluateValue()) {
3410 Info.FFDiag(E, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1) << VD;
3411 NoteLValueLocation(Info, Base);
3412 return false;
3413 }
3414
3415 // Check that the variable is actually usable in constant expressions. For a
3416 // const integral variable or a reference, we might have a non-constant
3417 // initializer that we can nonetheless evaluate the initializer for. Such
3418 // variables are not usable in constant expressions. In C++98, the
3419 // initializer also syntactically needs to be an ICE.
3420 //
3421 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3422 // expressions here; doing so would regress diagnostics for things like
3423 // reading from a volatile constexpr variable.
3424 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3425 VD->mightBeUsableInConstantExpressions(C: Info.Ctx)) ||
3426 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3427 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Context: Info.Ctx))) {
3428 Info.CCEDiag(E, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1) << VD;
3429 NoteLValueLocation(Info, Base);
3430 }
3431
3432 // Never use the initializer of a weak variable, not even for constant
3433 // folding. We can't be sure that this is the definition that will be used.
3434 if (VD->isWeak()) {
3435 Info.FFDiag(E, DiagId: diag::note_constexpr_var_init_weak) << VD;
3436 NoteLValueLocation(Info, Base);
3437 return false;
3438 }
3439
3440 Result = VD->getEvaluatedValue();
3441 return true;
3442}
3443
3444/// Get the base index of the given base class within an APValue representing
3445/// the given derived class.
3446static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3447 const CXXRecordDecl *Base) {
3448 Base = Base->getCanonicalDecl();
3449 unsigned Index = 0;
3450 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3451 E = Derived->bases_end(); I != E; ++I, ++Index) {
3452 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3453 return Index;
3454 }
3455
3456 llvm_unreachable("base class missing from derived class's bases list");
3457}
3458
3459/// Extract the value of a character from a string literal.
3460static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3461 uint64_t Index) {
3462 assert(!isa<SourceLocExpr>(Lit) &&
3463 "SourceLocExpr should have already been converted to a StringLiteral");
3464
3465 // FIXME: Support MakeStringConstant
3466 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Val: Lit)) {
3467 std::string Str;
3468 Info.Ctx.getObjCEncodingForType(T: ObjCEnc->getEncodedType(), S&: Str);
3469 assert(Index <= Str.size() && "Index too large");
3470 return APSInt::getUnsigned(X: Str.c_str()[Index]);
3471 }
3472
3473 if (auto PE = dyn_cast<PredefinedExpr>(Val: Lit))
3474 Lit = PE->getFunctionName();
3475 const StringLiteral *S = cast<StringLiteral>(Val: Lit);
3476 const ConstantArrayType *CAT =
3477 Info.Ctx.getAsConstantArrayType(T: S->getType());
3478 assert(CAT && "string literal isn't an array");
3479 QualType CharType = CAT->getElementType();
3480 assert(CharType->isIntegerType() && "unexpected character type");
3481 APSInt Value(Info.Ctx.getTypeSize(T: CharType),
3482 CharType->isUnsignedIntegerType());
3483 if (Index < S->getLength())
3484 Value = S->getCodeUnit(i: Index);
3485 return Value;
3486}
3487
3488// Expand a string literal into an array of characters.
3489//
3490// FIXME: This is inefficient; we should probably introduce something similar
3491// to the LLVM ConstantDataArray to make this cheaper.
3492static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3493 APValue &Result,
3494 QualType AllocType = QualType()) {
3495 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3496 T: AllocType.isNull() ? S->getType() : AllocType);
3497 assert(CAT && "string literal isn't an array");
3498 QualType CharType = CAT->getElementType();
3499 assert(CharType->isIntegerType() && "unexpected character type");
3500
3501 unsigned Elts = CAT->getZExtSize();
3502 Result = APValue(APValue::UninitArray(),
3503 std::min(a: S->getLength(), b: Elts), Elts);
3504 APSInt Value(Info.Ctx.getTypeSize(T: CharType),
3505 CharType->isUnsignedIntegerType());
3506 if (Result.hasArrayFiller())
3507 Result.getArrayFiller() = APValue(Value);
3508 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3509 Value = S->getCodeUnit(i: I);
3510 Result.getArrayInitializedElt(I) = APValue(Value);
3511 }
3512}
3513
3514// Expand an array so that it has more than Index filled elements.
3515static void expandArray(APValue &Array, unsigned Index) {
3516 unsigned Size = Array.getArraySize();
3517 assert(Index < Size);
3518
3519 // Always at least double the number of elements for which we store a value.
3520 unsigned OldElts = Array.getArrayInitializedElts();
3521 unsigned NewElts = std::max(a: Index+1, b: OldElts * 2);
3522 NewElts = std::min(a: Size, b: std::max(a: NewElts, b: 8u));
3523
3524 // Copy the data across.
3525 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3526 for (unsigned I = 0; I != OldElts; ++I)
3527 NewValue.getArrayInitializedElt(I).swap(RHS&: Array.getArrayInitializedElt(I));
3528 for (unsigned I = OldElts; I != NewElts; ++I)
3529 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3530 if (NewValue.hasArrayFiller())
3531 NewValue.getArrayFiller() = Array.getArrayFiller();
3532 Array.swap(RHS&: NewValue);
3533}
3534
3535/// Determine whether a type would actually be read by an lvalue-to-rvalue
3536/// conversion. If it's of class type, we may assume that the copy operation
3537/// is trivial. Note that this is never true for a union type with fields
3538/// (because the copy always "reads" the active member) and always true for
3539/// a non-class type.
3540static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3541static bool isReadByLvalueToRvalueConversion(QualType T) {
3542 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3543 return !RD || isReadByLvalueToRvalueConversion(RD);
3544}
3545static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3546 // FIXME: A trivial copy of a union copies the object representation, even if
3547 // the union is empty.
3548 if (RD->isUnion())
3549 return !RD->field_empty();
3550 if (RD->isEmpty())
3551 return false;
3552
3553 for (auto *Field : RD->fields())
3554 if (!Field->isUnnamedBitField() &&
3555 isReadByLvalueToRvalueConversion(T: Field->getType()))
3556 return true;
3557
3558 for (auto &BaseSpec : RD->bases())
3559 if (isReadByLvalueToRvalueConversion(T: BaseSpec.getType()))
3560 return true;
3561
3562 return false;
3563}
3564
3565/// Diagnose an attempt to read from any unreadable field within the specified
3566/// type, which might be a class type.
3567static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3568 QualType T) {
3569 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3570 if (!RD)
3571 return false;
3572
3573 if (!RD->hasMutableFields())
3574 return false;
3575
3576 for (auto *Field : RD->fields()) {
3577 // If we're actually going to read this field in some way, then it can't
3578 // be mutable. If we're in a union, then assigning to a mutable field
3579 // (even an empty one) can change the active member, so that's not OK.
3580 // FIXME: Add core issue number for the union case.
3581 if (Field->isMutable() &&
3582 (RD->isUnion() || isReadByLvalueToRvalueConversion(T: Field->getType()))) {
3583 Info.FFDiag(E, DiagId: diag::note_constexpr_access_mutable, ExtraNotes: 1) << AK << Field;
3584 Info.Note(Loc: Field->getLocation(), DiagId: diag::note_declared_at);
3585 return true;
3586 }
3587
3588 if (diagnoseMutableFields(Info, E, AK, T: Field->getType()))
3589 return true;
3590 }
3591
3592 for (auto &BaseSpec : RD->bases())
3593 if (diagnoseMutableFields(Info, E, AK, T: BaseSpec.getType()))
3594 return true;
3595
3596 // All mutable fields were empty, and thus not actually read.
3597 return false;
3598}
3599
3600static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3601 APValue::LValueBase Base,
3602 bool MutableSubobject = false) {
3603 // A temporary or transient heap allocation we created.
3604 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3605 return true;
3606
3607 switch (Info.IsEvaluatingDecl) {
3608 case EvalInfo::EvaluatingDeclKind::None:
3609 return false;
3610
3611 case EvalInfo::EvaluatingDeclKind::Ctor:
3612 // The variable whose initializer we're evaluating.
3613 if (Info.EvaluatingDecl == Base)
3614 return true;
3615
3616 // A temporary lifetime-extended by the variable whose initializer we're
3617 // evaluating.
3618 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3619 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(Val: BaseE))
3620 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3621 return false;
3622
3623 case EvalInfo::EvaluatingDeclKind::Dtor:
3624 // C++2a [expr.const]p6:
3625 // [during constant destruction] the lifetime of a and its non-mutable
3626 // subobjects (but not its mutable subobjects) [are] considered to start
3627 // within e.
3628 if (MutableSubobject || Base != Info.EvaluatingDecl)
3629 return false;
3630 // FIXME: We can meaningfully extend this to cover non-const objects, but
3631 // we will need special handling: we should be able to access only
3632 // subobjects of such objects that are themselves declared const.
3633 QualType T = getType(B: Base);
3634 return T.isConstQualified() || T->isReferenceType();
3635 }
3636
3637 llvm_unreachable("unknown evaluating decl kind");
3638}
3639
3640static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3641 SourceLocation CallLoc = {}) {
3642 return Info.CheckArraySize(
3643 Loc: CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3644 BitWidth: CAT->getNumAddressingBits(Context: Info.Ctx), ElemCount: CAT->getZExtSize(),
3645 /*Diag=*/true);
3646}
3647
3648namespace {
3649/// A handle to a complete object (an object that is not a subobject of
3650/// another object).
3651struct CompleteObject {
3652 /// The identity of the object.
3653 APValue::LValueBase Base;
3654 /// The value of the complete object.
3655 APValue *Value;
3656 /// The type of the complete object.
3657 QualType Type;
3658
3659 CompleteObject() : Value(nullptr) {}
3660 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3661 : Base(Base), Value(Value), Type(Type) {}
3662
3663 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3664 // If this isn't a "real" access (eg, if it's just accessing the type
3665 // info), allow it. We assume the type doesn't change dynamically for
3666 // subobjects of constexpr objects (even though we'd hit UB here if it
3667 // did). FIXME: Is this right?
3668 if (!isAnyAccess(AK))
3669 return true;
3670
3671 // In C++14 onwards, it is permitted to read a mutable member whose
3672 // lifetime began within the evaluation.
3673 // FIXME: Should we also allow this in C++11?
3674 if (!Info.getLangOpts().CPlusPlus14)
3675 return false;
3676 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3677 }
3678
3679 explicit operator bool() const { return !Type.isNull(); }
3680};
3681} // end anonymous namespace
3682
3683static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3684 bool IsMutable = false) {
3685 // C++ [basic.type.qualifier]p1:
3686 // - A const object is an object of type const T or a non-mutable subobject
3687 // of a const object.
3688 if (ObjType.isConstQualified() && !IsMutable)
3689 SubobjType.addConst();
3690 // - A volatile object is an object of type const T or a subobject of a
3691 // volatile object.
3692 if (ObjType.isVolatileQualified())
3693 SubobjType.addVolatile();
3694 return SubobjType;
3695}
3696
3697/// Find the designated sub-object of an rvalue.
3698template<typename SubobjectHandler>
3699typename SubobjectHandler::result_type
3700findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3701 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3702 if (Sub.Invalid)
3703 // A diagnostic will have already been produced.
3704 return handler.failed();
3705 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3706 if (Info.getLangOpts().CPlusPlus11)
3707 Info.FFDiag(E, DiagId: Sub.isOnePastTheEnd()
3708 ? diag::note_constexpr_access_past_end
3709 : diag::note_constexpr_access_unsized_array)
3710 << handler.AccessKind;
3711 else
3712 Info.FFDiag(E);
3713 return handler.failed();
3714 }
3715
3716 APValue *O = Obj.Value;
3717 QualType ObjType = Obj.Type;
3718 const FieldDecl *LastField = nullptr;
3719 const FieldDecl *VolatileField = nullptr;
3720
3721 // Walk the designator's path to find the subobject.
3722 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3723 // Reading an indeterminate value is undefined, but assigning over one is OK.
3724 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3725 (O->isIndeterminate() &&
3726 !isValidIndeterminateAccess(handler.AccessKind))) {
3727 if (!Info.checkingPotentialConstantExpression())
3728 Info.FFDiag(E, DiagId: diag::note_constexpr_access_uninit)
3729 << handler.AccessKind << O->isIndeterminate()
3730 << E->getSourceRange();
3731 return handler.failed();
3732 }
3733
3734 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3735 // const and volatile semantics are not applied on an object under
3736 // {con,de}struction.
3737 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3738 ObjType->isRecordType() &&
3739 Info.isEvaluatingCtorDtor(
3740 Base: Obj.Base,
3741 Path: llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3742 ConstructionPhase::None) {
3743 ObjType = Info.Ctx.getCanonicalType(T: ObjType);
3744 ObjType.removeLocalConst();
3745 ObjType.removeLocalVolatile();
3746 }
3747
3748 // If this is our last pass, check that the final object type is OK.
3749 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3750 // Accesses to volatile objects are prohibited.
3751 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3752 if (Info.getLangOpts().CPlusPlus) {
3753 int DiagKind;
3754 SourceLocation Loc;
3755 const NamedDecl *Decl = nullptr;
3756 if (VolatileField) {
3757 DiagKind = 2;
3758 Loc = VolatileField->getLocation();
3759 Decl = VolatileField;
3760 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3761 DiagKind = 1;
3762 Loc = VD->getLocation();
3763 Decl = VD;
3764 } else {
3765 DiagKind = 0;
3766 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3767 Loc = E->getExprLoc();
3768 }
3769 Info.FFDiag(E, DiagId: diag::note_constexpr_access_volatile_obj, ExtraNotes: 1)
3770 << handler.AccessKind << DiagKind << Decl;
3771 Info.Note(Loc, DiagId: diag::note_constexpr_volatile_here) << DiagKind;
3772 } else {
3773 Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
3774 }
3775 return handler.failed();
3776 }
3777
3778 // If we are reading an object of class type, there may still be more
3779 // things we need to check: if there are any mutable subobjects, we
3780 // cannot perform this read. (This only happens when performing a trivial
3781 // copy or assignment.)
3782 if (ObjType->isRecordType() &&
3783 !Obj.mayAccessMutableMembers(Info, AK: handler.AccessKind) &&
3784 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3785 return handler.failed();
3786 }
3787
3788 if (I == N) {
3789 if (!handler.found(*O, ObjType))
3790 return false;
3791
3792 // If we modified a bit-field, truncate it to the right width.
3793 if (isModification(handler.AccessKind) &&
3794 LastField && LastField->isBitField() &&
3795 !truncateBitfieldValue(Info, E, Value&: *O, FD: LastField))
3796 return false;
3797
3798 return true;
3799 }
3800
3801 LastField = nullptr;
3802 if (ObjType->isArrayType()) {
3803 // Next subobject is an array element.
3804 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T: ObjType);
3805 assert(CAT && "vla in literal type?");
3806 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3807 if (CAT->getSize().ule(RHS: Index)) {
3808 // Note, it should not be possible to form a pointer with a valid
3809 // designator which points more than one past the end of the array.
3810 if (Info.getLangOpts().CPlusPlus11)
3811 Info.FFDiag(E, DiagId: diag::note_constexpr_access_past_end)
3812 << handler.AccessKind;
3813 else
3814 Info.FFDiag(E);
3815 return handler.failed();
3816 }
3817
3818 ObjType = CAT->getElementType();
3819
3820 if (O->getArrayInitializedElts() > Index)
3821 O = &O->getArrayInitializedElt(I: Index);
3822 else if (!isRead(handler.AccessKind)) {
3823 if (!CheckArraySize(Info, CAT, CallLoc: E->getExprLoc()))
3824 return handler.failed();
3825
3826 expandArray(Array&: *O, Index);
3827 O = &O->getArrayInitializedElt(I: Index);
3828 } else
3829 O = &O->getArrayFiller();
3830 } else if (ObjType->isAnyComplexType()) {
3831 // Next subobject is a complex number.
3832 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3833 if (Index > 1) {
3834 if (Info.getLangOpts().CPlusPlus11)
3835 Info.FFDiag(E, DiagId: diag::note_constexpr_access_past_end)
3836 << handler.AccessKind;
3837 else
3838 Info.FFDiag(E);
3839 return handler.failed();
3840 }
3841
3842 ObjType = getSubobjectType(
3843 ObjType, SubobjType: ObjType->castAs<ComplexType>()->getElementType());
3844
3845 assert(I == N - 1 && "extracting subobject of scalar?");
3846 if (O->isComplexInt()) {
3847 return handler.found(Index ? O->getComplexIntImag()
3848 : O->getComplexIntReal(), ObjType);
3849 } else {
3850 assert(O->isComplexFloat());
3851 return handler.found(Index ? O->getComplexFloatImag()
3852 : O->getComplexFloatReal(), ObjType);
3853 }
3854 } else if (const FieldDecl *Field = getAsField(E: Sub.Entries[I])) {
3855 if (Field->isMutable() &&
3856 !Obj.mayAccessMutableMembers(Info, AK: handler.AccessKind)) {
3857 Info.FFDiag(E, DiagId: diag::note_constexpr_access_mutable, ExtraNotes: 1)
3858 << handler.AccessKind << Field;
3859 Info.Note(Loc: Field->getLocation(), DiagId: diag::note_declared_at);
3860 return handler.failed();
3861 }
3862
3863 // Next subobject is a class, struct or union field.
3864 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3865 if (RD->isUnion()) {
3866 const FieldDecl *UnionField = O->getUnionField();
3867 if (!UnionField ||
3868 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3869 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3870 // Placement new onto an inactive union member makes it active.
3871 O->setUnion(Field, Value: APValue());
3872 } else {
3873 // FIXME: If O->getUnionValue() is absent, report that there's no
3874 // active union member rather than reporting the prior active union
3875 // member. We'll need to fix nullptr_t to not use APValue() as its
3876 // representation first.
3877 Info.FFDiag(E, DiagId: diag::note_constexpr_access_inactive_union_member)
3878 << handler.AccessKind << Field << !UnionField << UnionField;
3879 return handler.failed();
3880 }
3881 }
3882 O = &O->getUnionValue();
3883 } else
3884 O = &O->getStructField(i: Field->getFieldIndex());
3885
3886 ObjType = getSubobjectType(ObjType, SubobjType: Field->getType(), IsMutable: Field->isMutable());
3887 LastField = Field;
3888 if (Field->getType().isVolatileQualified())
3889 VolatileField = Field;
3890 } else {
3891 // Next subobject is a base class.
3892 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3893 const CXXRecordDecl *Base = getAsBaseClass(E: Sub.Entries[I]);
3894 O = &O->getStructBase(i: getBaseIndex(Derived, Base));
3895
3896 ObjType = getSubobjectType(ObjType, SubobjType: Info.Ctx.getRecordType(Decl: Base));
3897 }
3898 }
3899}
3900
3901namespace {
3902struct ExtractSubobjectHandler {
3903 EvalInfo &Info;
3904 const Expr *E;
3905 APValue &Result;
3906 const AccessKinds AccessKind;
3907
3908 typedef bool result_type;
3909 bool failed() { return false; }
3910 bool found(APValue &Subobj, QualType SubobjType) {
3911 Result = Subobj;
3912 if (AccessKind == AK_ReadObjectRepresentation)
3913 return true;
3914 return CheckFullyInitialized(Info, DiagLoc: E->getExprLoc(), Type: SubobjType, Value: Result);
3915 }
3916 bool found(APSInt &Value, QualType SubobjType) {
3917 Result = APValue(Value);
3918 return true;
3919 }
3920 bool found(APFloat &Value, QualType SubobjType) {
3921 Result = APValue(Value);
3922 return true;
3923 }
3924};
3925} // end anonymous namespace
3926
3927/// Extract the designated sub-object of an rvalue.
3928static bool extractSubobject(EvalInfo &Info, const Expr *E,
3929 const CompleteObject &Obj,
3930 const SubobjectDesignator &Sub, APValue &Result,
3931 AccessKinds AK = AK_Read) {
3932 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3933 ExtractSubobjectHandler Handler = {.Info: Info, .E: E, .Result: Result, .AccessKind: AK};
3934 return findSubobject(Info, E, Obj, Sub, handler&: Handler);
3935}
3936
3937namespace {
3938struct ModifySubobjectHandler {
3939 EvalInfo &Info;
3940 APValue &NewVal;
3941 const Expr *E;
3942
3943 typedef bool result_type;
3944 static const AccessKinds AccessKind = AK_Assign;
3945
3946 bool checkConst(QualType QT) {
3947 // Assigning to a const object has undefined behavior.
3948 if (QT.isConstQualified()) {
3949 Info.FFDiag(E, DiagId: diag::note_constexpr_modify_const_type) << QT;
3950 return false;
3951 }
3952 return true;
3953 }
3954
3955 bool failed() { return false; }
3956 bool found(APValue &Subobj, QualType SubobjType) {
3957 if (!checkConst(QT: SubobjType))
3958 return false;
3959 // We've been given ownership of NewVal, so just swap it in.
3960 Subobj.swap(RHS&: NewVal);
3961 return true;
3962 }
3963 bool found(APSInt &Value, QualType SubobjType) {
3964 if (!checkConst(QT: SubobjType))
3965 return false;
3966 if (!NewVal.isInt()) {
3967 // Maybe trying to write a cast pointer value into a complex?
3968 Info.FFDiag(E);
3969 return false;
3970 }
3971 Value = NewVal.getInt();
3972 return true;
3973 }
3974 bool found(APFloat &Value, QualType SubobjType) {
3975 if (!checkConst(QT: SubobjType))
3976 return false;
3977 Value = NewVal.getFloat();
3978 return true;
3979 }
3980};
3981} // end anonymous namespace
3982
3983const AccessKinds ModifySubobjectHandler::AccessKind;
3984
3985/// Update the designated sub-object of an rvalue to the given value.
3986static bool modifySubobject(EvalInfo &Info, const Expr *E,
3987 const CompleteObject &Obj,
3988 const SubobjectDesignator &Sub,
3989 APValue &NewVal) {
3990 ModifySubobjectHandler Handler = { .Info: Info, .NewVal: NewVal, .E: E };
3991 return findSubobject(Info, E, Obj, Sub, handler&: Handler);
3992}
3993
3994/// Find the position where two subobject designators diverge, or equivalently
3995/// the length of the common initial subsequence.
3996static unsigned FindDesignatorMismatch(QualType ObjType,
3997 const SubobjectDesignator &A,
3998 const SubobjectDesignator &B,
3999 bool &WasArrayIndex) {
4000 unsigned I = 0, N = std::min(a: A.Entries.size(), b: B.Entries.size());
4001 for (/**/; I != N; ++I) {
4002 if (!ObjType.isNull() &&
4003 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4004 // Next subobject is an array element.
4005 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4006 WasArrayIndex = true;
4007 return I;
4008 }
4009 if (ObjType->isAnyComplexType())
4010 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4011 else
4012 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4013 } else {
4014 if (A.Entries[I].getAsBaseOrMember() !=
4015 B.Entries[I].getAsBaseOrMember()) {
4016 WasArrayIndex = false;
4017 return I;
4018 }
4019 if (const FieldDecl *FD = getAsField(E: A.Entries[I]))
4020 // Next subobject is a field.
4021 ObjType = FD->getType();
4022 else
4023 // Next subobject is a base class.
4024 ObjType = QualType();
4025 }
4026 }
4027 WasArrayIndex = false;
4028 return I;
4029}
4030
4031/// Determine whether the given subobject designators refer to elements of the
4032/// same array object.
4033static bool AreElementsOfSameArray(QualType ObjType,
4034 const SubobjectDesignator &A,
4035 const SubobjectDesignator &B) {
4036 if (A.Entries.size() != B.Entries.size())
4037 return false;
4038
4039 bool IsArray = A.MostDerivedIsArrayElement;
4040 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4041 // A is a subobject of the array element.
4042 return false;
4043
4044 // If A (and B) designates an array element, the last entry will be the array
4045 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4046 // of length 1' case, and the entire path must match.
4047 bool WasArrayIndex;
4048 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4049 return CommonLength >= A.Entries.size() - IsArray;
4050}
4051
4052/// Find the complete object to which an LValue refers.
4053static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4054 AccessKinds AK, const LValue &LVal,
4055 QualType LValType) {
4056 if (LVal.InvalidBase) {
4057 Info.FFDiag(E);
4058 return CompleteObject();
4059 }
4060
4061 if (!LVal.Base) {
4062 Info.FFDiag(E, DiagId: diag::note_constexpr_access_null) << AK;
4063 return CompleteObject();
4064 }
4065
4066 CallStackFrame *Frame = nullptr;
4067 unsigned Depth = 0;
4068 if (LVal.getLValueCallIndex()) {
4069 std::tie(args&: Frame, args&: Depth) =
4070 Info.getCallFrameAndDepth(CallIndex: LVal.getLValueCallIndex());
4071 if (!Frame) {
4072 Info.FFDiag(E, DiagId: diag::note_constexpr_lifetime_ended, ExtraNotes: 1)
4073 << AK << LVal.Base.is<const ValueDecl*>();
4074 NoteLValueLocation(Info, Base: LVal.Base);
4075 return CompleteObject();
4076 }
4077 }
4078
4079 bool IsAccess = isAnyAccess(AK);
4080
4081 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4082 // is not a constant expression (even if the object is non-volatile). We also
4083 // apply this rule to C++98, in order to conform to the expected 'volatile'
4084 // semantics.
4085 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4086 if (Info.getLangOpts().CPlusPlus)
4087 Info.FFDiag(E, DiagId: diag::note_constexpr_access_volatile_type)
4088 << AK << LValType;
4089 else
4090 Info.FFDiag(E);
4091 return CompleteObject();
4092 }
4093
4094 // Compute value storage location and type of base object.
4095 APValue *BaseVal = nullptr;
4096 QualType BaseType = getType(B: LVal.Base);
4097
4098 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4099 lifetimeStartedInEvaluation(Info, Base: LVal.Base)) {
4100 // This is the object whose initializer we're evaluating, so its lifetime
4101 // started in the current evaluation.
4102 BaseVal = Info.EvaluatingDeclValue;
4103 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4104 // Allow reading from a GUID declaration.
4105 if (auto *GD = dyn_cast<MSGuidDecl>(Val: D)) {
4106 if (isModification(AK)) {
4107 // All the remaining cases do not permit modification of the object.
4108 Info.FFDiag(E, DiagId: diag::note_constexpr_modify_global);
4109 return CompleteObject();
4110 }
4111 APValue &V = GD->getAsAPValue();
4112 if (V.isAbsent()) {
4113 Info.FFDiag(E, DiagId: diag::note_constexpr_unsupported_layout)
4114 << GD->getType();
4115 return CompleteObject();
4116 }
4117 return CompleteObject(LVal.Base, &V, GD->getType());
4118 }
4119
4120 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4121 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(Val: D)) {
4122 if (isModification(AK)) {
4123 Info.FFDiag(E, DiagId: diag::note_constexpr_modify_global);
4124 return CompleteObject();
4125 }
4126 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4127 GCD->getType());
4128 }
4129
4130 // Allow reading from template parameter objects.
4131 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: D)) {
4132 if (isModification(AK)) {
4133 Info.FFDiag(E, DiagId: diag::note_constexpr_modify_global);
4134 return CompleteObject();
4135 }
4136 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4137 TPO->getType());
4138 }
4139
4140 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4141 // In C++11, constexpr, non-volatile variables initialized with constant
4142 // expressions are constant expressions too. Inside constexpr functions,
4143 // parameters are constant expressions even if they're non-const.
4144 // In C++1y, objects local to a constant expression (those with a Frame) are
4145 // both readable and writable inside constant expressions.
4146 // In C, such things can also be folded, although they are not ICEs.
4147 const VarDecl *VD = dyn_cast<VarDecl>(Val: D);
4148 if (VD) {
4149 if (const VarDecl *VDef = VD->getDefinition(C&: Info.Ctx))
4150 VD = VDef;
4151 }
4152 if (!VD || VD->isInvalidDecl()) {
4153 Info.FFDiag(E);
4154 return CompleteObject();
4155 }
4156
4157 bool IsConstant = BaseType.isConstant(Ctx: Info.Ctx);
4158 bool ConstexprVar = false;
4159 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4160 Val: Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4161 ConstexprVar = VD->isConstexpr();
4162
4163 // Unless we're looking at a local variable or argument in a constexpr call,
4164 // the variable we're reading must be const.
4165 if (!Frame) {
4166 if (IsAccess && isa<ParmVarDecl>(Val: VD)) {
4167 // Access of a parameter that's not associated with a frame isn't going
4168 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4169 // suitable diagnostic.
4170 } else if (Info.getLangOpts().CPlusPlus14 &&
4171 lifetimeStartedInEvaluation(Info, Base: LVal.Base)) {
4172 // OK, we can read and modify an object if we're in the process of
4173 // evaluating its initializer, because its lifetime began in this
4174 // evaluation.
4175 } else if (isModification(AK)) {
4176 // All the remaining cases do not permit modification of the object.
4177 Info.FFDiag(E, DiagId: diag::note_constexpr_modify_global);
4178 return CompleteObject();
4179 } else if (VD->isConstexpr()) {
4180 // OK, we can read this variable.
4181 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4182 Info.FFDiag(E);
4183 return CompleteObject();
4184 } else if (BaseType->isIntegralOrEnumerationType()) {
4185 if (!IsConstant) {
4186 if (!IsAccess)
4187 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4188 if (Info.getLangOpts().CPlusPlus) {
4189 Info.FFDiag(E, DiagId: diag::note_constexpr_ltor_non_const_int, ExtraNotes: 1) << VD;
4190 Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
4191 } else {
4192 Info.FFDiag(E);
4193 }
4194 return CompleteObject();
4195 }
4196 } else if (!IsAccess) {
4197 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4198 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4199 BaseType->isLiteralType(Ctx: Info.Ctx) && !VD->hasDefinition()) {
4200 // This variable might end up being constexpr. Don't diagnose it yet.
4201 } else if (IsConstant) {
4202 // Keep evaluating to see what we can do. In particular, we support
4203 // folding of const floating-point types, in order to make static const
4204 // data members of such types (supported as an extension) more useful.
4205 if (Info.getLangOpts().CPlusPlus) {
4206 Info.CCEDiag(E, DiagId: Info.getLangOpts().CPlusPlus11
4207 ? diag::note_constexpr_ltor_non_constexpr
4208 : diag::note_constexpr_ltor_non_integral, ExtraNotes: 1)
4209 << VD << BaseType;
4210 Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
4211 } else {
4212 Info.CCEDiag(E);
4213 }
4214 } else {
4215 // Never allow reading a non-const value.
4216 if (Info.getLangOpts().CPlusPlus) {
4217 Info.FFDiag(E, DiagId: Info.getLangOpts().CPlusPlus11
4218 ? diag::note_constexpr_ltor_non_constexpr
4219 : diag::note_constexpr_ltor_non_integral, ExtraNotes: 1)
4220 << VD << BaseType;
4221 Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
4222 } else {
4223 Info.FFDiag(E);
4224 }
4225 return CompleteObject();
4226 }
4227 }
4228
4229 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version: LVal.getLValueVersion(), Result&: BaseVal))
4230 return CompleteObject();
4231 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4232 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4233 if (!Alloc) {
4234 Info.FFDiag(E, DiagId: diag::note_constexpr_access_deleted_object) << AK;
4235 return CompleteObject();
4236 }
4237 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4238 LVal.Base.getDynamicAllocType());
4239 } else {
4240 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4241
4242 if (!Frame) {
4243 if (const MaterializeTemporaryExpr *MTE =
4244 dyn_cast_or_null<MaterializeTemporaryExpr>(Val: Base)) {
4245 assert(MTE->getStorageDuration() == SD_Static &&
4246 "should have a frame for a non-global materialized temporary");
4247
4248 // C++20 [expr.const]p4: [DR2126]
4249 // An object or reference is usable in constant expressions if it is
4250 // - a temporary object of non-volatile const-qualified literal type
4251 // whose lifetime is extended to that of a variable that is usable
4252 // in constant expressions
4253 //
4254 // C++20 [expr.const]p5:
4255 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4256 // - a non-volatile glvalue that refers to an object that is usable
4257 // in constant expressions, or
4258 // - a non-volatile glvalue of literal type that refers to a
4259 // non-volatile object whose lifetime began within the evaluation
4260 // of E;
4261 //
4262 // C++11 misses the 'began within the evaluation of e' check and
4263 // instead allows all temporaries, including things like:
4264 // int &&r = 1;
4265 // int x = ++r;
4266 // constexpr int k = r;
4267 // Therefore we use the C++14-onwards rules in C++11 too.
4268 //
4269 // Note that temporaries whose lifetimes began while evaluating a
4270 // variable's constructor are not usable while evaluating the
4271 // corresponding destructor, not even if they're of const-qualified
4272 // types.
4273 if (!MTE->isUsableInConstantExpressions(Context: Info.Ctx) &&
4274 !lifetimeStartedInEvaluation(Info, Base: LVal.Base)) {
4275 if (!IsAccess)
4276 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4277 Info.FFDiag(E, DiagId: diag::note_constexpr_access_static_temporary, ExtraNotes: 1) << AK;
4278 Info.Note(Loc: MTE->getExprLoc(), DiagId: diag::note_constexpr_temporary_here);
4279 return CompleteObject();
4280 }
4281
4282 BaseVal = MTE->getOrCreateValue(MayCreate: false);
4283 assert(BaseVal && "got reference to unevaluated temporary");
4284 } else {
4285 if (!IsAccess)
4286 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4287 APValue Val;
4288 LVal.moveInto(V&: Val);
4289 Info.FFDiag(E, DiagId: diag::note_constexpr_access_unreadable_object)
4290 << AK
4291 << Val.getAsString(Ctx: Info.Ctx,
4292 Ty: Info.Ctx.getLValueReferenceType(T: LValType));
4293 NoteLValueLocation(Info, Base: LVal.Base);
4294 return CompleteObject();
4295 }
4296 } else {
4297 BaseVal = Frame->getTemporary(Key: Base, Version: LVal.Base.getVersion());
4298 assert(BaseVal && "missing value for temporary");
4299 }
4300 }
4301
4302 // In C++14, we can't safely access any mutable state when we might be
4303 // evaluating after an unmodeled side effect. Parameters are modeled as state
4304 // in the caller, but aren't visible once the call returns, so they can be
4305 // modified in a speculatively-evaluated call.
4306 //
4307 // FIXME: Not all local state is mutable. Allow local constant subobjects
4308 // to be read here (but take care with 'mutable' fields).
4309 unsigned VisibleDepth = Depth;
4310 if (llvm::isa_and_nonnull<ParmVarDecl>(
4311 Val: LVal.Base.dyn_cast<const ValueDecl *>()))
4312 ++VisibleDepth;
4313 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4314 Info.EvalStatus.HasSideEffects) ||
4315 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4316 return CompleteObject();
4317
4318 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4319}
4320
4321/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4322/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4323/// glvalue referred to by an entity of reference type.
4324///
4325/// \param Info - Information about the ongoing evaluation.
4326/// \param Conv - The expression for which we are performing the conversion.
4327/// Used for diagnostics.
4328/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4329/// case of a non-class type).
4330/// \param LVal - The glvalue on which we are attempting to perform this action.
4331/// \param RVal - The produced value will be placed here.
4332/// \param WantObjectRepresentation - If true, we're looking for the object
4333/// representation rather than the value, and in particular,
4334/// there is no requirement that the result be fully initialized.
4335static bool
4336handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4337 const LValue &LVal, APValue &RVal,
4338 bool WantObjectRepresentation = false) {
4339 if (LVal.Designator.Invalid)
4340 return false;
4341
4342 // Check for special cases where there is no existing APValue to look at.
4343 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4344
4345 AccessKinds AK =
4346 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4347
4348 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4349 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Val: Base)) {
4350 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4351 // initializer until now for such expressions. Such an expression can't be
4352 // an ICE in C, so this only matters for fold.
4353 if (Type.isVolatileQualified()) {
4354 Info.FFDiag(E: Conv);
4355 return false;
4356 }
4357
4358 APValue Lit;
4359 if (!Evaluate(Result&: Lit, Info, E: CLE->getInitializer()))
4360 return false;
4361
4362 // According to GCC info page:
4363 //
4364 // 6.28 Compound Literals
4365 //
4366 // As an optimization, G++ sometimes gives array compound literals longer
4367 // lifetimes: when the array either appears outside a function or has a
4368 // const-qualified type. If foo and its initializer had elements of type
4369 // char *const rather than char *, or if foo were a global variable, the
4370 // array would have static storage duration. But it is probably safest
4371 // just to avoid the use of array compound literals in C++ code.
4372 //
4373 // Obey that rule by checking constness for converted array types.
4374
4375 QualType CLETy = CLE->getType();
4376 if (CLETy->isArrayType() && !Type->isArrayType()) {
4377 if (!CLETy.isConstant(Ctx: Info.Ctx)) {
4378 Info.FFDiag(E: Conv);
4379 Info.Note(Loc: CLE->getExprLoc(), DiagId: diag::note_declared_at);
4380 return false;
4381 }
4382 }
4383
4384 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4385 return extractSubobject(Info, E: Conv, Obj: LitObj, Sub: LVal.Designator, Result&: RVal, AK);
4386 } else if (isa<StringLiteral>(Val: Base) || isa<PredefinedExpr>(Val: Base)) {
4387 // Special-case character extraction so we don't have to construct an
4388 // APValue for the whole string.
4389 assert(LVal.Designator.Entries.size() <= 1 &&
4390 "Can only read characters from string literals");
4391 if (LVal.Designator.Entries.empty()) {
4392 // Fail for now for LValue to RValue conversion of an array.
4393 // (This shouldn't show up in C/C++, but it could be triggered by a
4394 // weird EvaluateAsRValue call from a tool.)
4395 Info.FFDiag(E: Conv);
4396 return false;
4397 }
4398 if (LVal.Designator.isOnePastTheEnd()) {
4399 if (Info.getLangOpts().CPlusPlus11)
4400 Info.FFDiag(E: Conv, DiagId: diag::note_constexpr_access_past_end) << AK;
4401 else
4402 Info.FFDiag(E: Conv);
4403 return false;
4404 }
4405 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4406 RVal = APValue(extractStringLiteralCharacter(Info, Lit: Base, Index: CharIndex));
4407 return true;
4408 }
4409 }
4410
4411 CompleteObject Obj = findCompleteObject(Info, E: Conv, AK, LVal, LValType: Type);
4412 return Obj && extractSubobject(Info, E: Conv, Obj, Sub: LVal.Designator, Result&: RVal, AK);
4413}
4414
4415/// Perform an assignment of Val to LVal. Takes ownership of Val.
4416static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4417 QualType LValType, APValue &Val) {
4418 if (LVal.Designator.Invalid)
4419 return false;
4420
4421 if (!Info.getLangOpts().CPlusPlus14) {
4422 Info.FFDiag(E);
4423 return false;
4424 }
4425
4426 CompleteObject Obj = findCompleteObject(Info, E, AK: AK_Assign, LVal, LValType);
4427 return Obj && modifySubobject(Info, E, Obj, Sub: LVal.Designator, NewVal&: Val);
4428}
4429
4430namespace {
4431struct CompoundAssignSubobjectHandler {
4432 EvalInfo &Info;
4433 const CompoundAssignOperator *E;
4434 QualType PromotedLHSType;
4435 BinaryOperatorKind Opcode;
4436 const APValue &RHS;
4437
4438 static const AccessKinds AccessKind = AK_Assign;
4439
4440 typedef bool result_type;
4441
4442 bool checkConst(QualType QT) {
4443 // Assigning to a const object has undefined behavior.
4444 if (QT.isConstQualified()) {
4445 Info.FFDiag(E, DiagId: diag::note_constexpr_modify_const_type) << QT;
4446 return false;
4447 }
4448 return true;
4449 }
4450
4451 bool failed() { return false; }
4452 bool found(APValue &Subobj, QualType SubobjType) {
4453 switch (Subobj.getKind()) {
4454 case APValue::Int:
4455 return found(Value&: Subobj.getInt(), SubobjType);
4456 case APValue::Float:
4457 return found(Value&: Subobj.getFloat(), SubobjType);
4458 case APValue::ComplexInt:
4459 case APValue::ComplexFloat:
4460 // FIXME: Implement complex compound assignment.
4461 Info.FFDiag(E);
4462 return false;
4463 case APValue::LValue:
4464 return foundPointer(Subobj, SubobjType);
4465 case APValue::Vector:
4466 return foundVector(Value&: Subobj, SubobjType);
4467 case APValue::Indeterminate:
4468 Info.FFDiag(E, DiagId: diag::note_constexpr_access_uninit)
4469 << /*read of=*/0 << /*uninitialized object=*/1
4470 << E->getLHS()->getSourceRange();
4471 return false;
4472 default:
4473 // FIXME: can this happen?
4474 Info.FFDiag(E);
4475 return false;
4476 }
4477 }
4478
4479 bool foundVector(APValue &Value, QualType SubobjType) {
4480 if (!checkConst(QT: SubobjType))
4481 return false;
4482
4483 if (!SubobjType->isVectorType()) {
4484 Info.FFDiag(E);
4485 return false;
4486 }
4487 return handleVectorVectorBinOp(Info, E, Opcode, LHSValue&: Value, RHSValue: RHS);
4488 }
4489
4490 bool found(APSInt &Value, QualType SubobjType) {
4491 if (!checkConst(QT: SubobjType))
4492 return false;
4493
4494 if (!SubobjType->isIntegerType()) {
4495 // We don't support compound assignment on integer-cast-to-pointer
4496 // values.
4497 Info.FFDiag(E);
4498 return false;
4499 }
4500
4501 if (RHS.isInt()) {
4502 APSInt LHS =
4503 HandleIntToIntCast(Info, E, DestType: PromotedLHSType, SrcType: SubobjType, Value);
4504 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS: RHS.getInt(), Result&: LHS))
4505 return false;
4506 Value = HandleIntToIntCast(Info, E, DestType: SubobjType, SrcType: PromotedLHSType, Value: LHS);
4507 return true;
4508 } else if (RHS.isFloat()) {
4509 const FPOptions FPO = E->getFPFeaturesInEffect(
4510 LO: Info.Ctx.getLangOpts());
4511 APFloat FValue(0.0);
4512 return HandleIntToFloatCast(Info, E, FPO, SrcType: SubobjType, Value,
4513 DestType: PromotedLHSType, Result&: FValue) &&
4514 handleFloatFloatBinOp(Info, E, LHS&: FValue, Opcode, RHS: RHS.getFloat()) &&
4515 HandleFloatToIntCast(Info, E, SrcType: PromotedLHSType, Value: FValue, DestType: SubobjType,
4516 Result&: Value);
4517 }
4518
4519 Info.FFDiag(E);
4520 return false;
4521 }
4522 bool found(APFloat &Value, QualType SubobjType) {
4523 return checkConst(QT: SubobjType) &&
4524 HandleFloatToFloatCast(Info, E, SrcType: SubobjType, DestType: PromotedLHSType,
4525 Result&: Value) &&
4526 handleFloatFloatBinOp(Info, E, LHS&: Value, Opcode, RHS: RHS.getFloat()) &&
4527 HandleFloatToFloatCast(Info, E, SrcType: PromotedLHSType, DestType: SubobjType, Result&: Value);
4528 }
4529 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4530 if (!checkConst(QT: SubobjType))
4531 return false;
4532
4533 QualType PointeeType;
4534 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4535 PointeeType = PT->getPointeeType();
4536
4537 if (PointeeType.isNull() || !RHS.isInt() ||
4538 (Opcode != BO_Add && Opcode != BO_Sub)) {
4539 Info.FFDiag(E);
4540 return false;
4541 }
4542
4543 APSInt Offset = RHS.getInt();
4544 if (Opcode == BO_Sub)
4545 negateAsSigned(Int&: Offset);
4546
4547 LValue LVal;
4548 LVal.setFrom(Ctx&: Info.Ctx, V: Subobj);
4549 if (!HandleLValueArrayAdjustment(Info, E, LVal, EltTy: PointeeType, Adjustment: Offset))
4550 return false;
4551 LVal.moveInto(V&: Subobj);
4552 return true;
4553 }
4554};
4555} // end anonymous namespace
4556
4557const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4558
4559/// Perform a compound assignment of LVal <op>= RVal.
4560static bool handleCompoundAssignment(EvalInfo &Info,
4561 const CompoundAssignOperator *E,
4562 const LValue &LVal, QualType LValType,
4563 QualType PromotedLValType,
4564 BinaryOperatorKind Opcode,
4565 const APValue &RVal) {
4566 if (LVal.Designator.Invalid)
4567 return false;
4568
4569 if (!Info.getLangOpts().CPlusPlus14) {
4570 Info.FFDiag(E);
4571 return false;
4572 }
4573
4574 CompleteObject Obj = findCompleteObject(Info, E, AK: AK_Assign, LVal, LValType);
4575 CompoundAssignSubobjectHandler Handler = { .Info: Info, .E: E, .PromotedLHSType: PromotedLValType, .Opcode: Opcode,
4576 .RHS: RVal };
4577 return Obj && findSubobject(Info, E, Obj, Sub: LVal.Designator, handler&: Handler);
4578}
4579
4580namespace {
4581struct IncDecSubobjectHandler {
4582 EvalInfo &Info;
4583 const UnaryOperator *E;
4584 AccessKinds AccessKind;
4585 APValue *Old;
4586
4587 typedef bool result_type;
4588
4589 bool checkConst(QualType QT) {
4590 // Assigning to a const object has undefined behavior.
4591 if (QT.isConstQualified()) {
4592 Info.FFDiag(E, DiagId: diag::note_constexpr_modify_const_type) << QT;
4593 return false;
4594 }
4595 return true;
4596 }
4597
4598 bool failed() { return false; }
4599 bool found(APValue &Subobj, QualType SubobjType) {
4600 // Stash the old value. Also clear Old, so we don't clobber it later
4601 // if we're post-incrementing a complex.
4602 if (Old) {
4603 *Old = Subobj;
4604 Old = nullptr;
4605 }
4606
4607 switch (Subobj.getKind()) {
4608 case APValue::Int:
4609 return found(Value&: Subobj.getInt(), SubobjType);
4610 case APValue::Float:
4611 return found(Value&: Subobj.getFloat(), SubobjType);
4612 case APValue::ComplexInt:
4613 return found(Value&: Subobj.getComplexIntReal(),
4614 SubobjType: SubobjType->castAs<ComplexType>()->getElementType()
4615 .withCVRQualifiers(CVR: SubobjType.getCVRQualifiers()));
4616 case APValue::ComplexFloat:
4617 return found(Value&: Subobj.getComplexFloatReal(),
4618 SubobjType: SubobjType->castAs<ComplexType>()->getElementType()
4619 .withCVRQualifiers(CVR: SubobjType.getCVRQualifiers()));
4620 case APValue::LValue:
4621 return foundPointer(Subobj, SubobjType);
4622 default:
4623 // FIXME: can this happen?
4624 Info.FFDiag(E);
4625 return false;
4626 }
4627 }
4628 bool found(APSInt &Value, QualType SubobjType) {
4629 if (!checkConst(QT: SubobjType))
4630 return false;
4631
4632 if (!SubobjType->isIntegerType()) {
4633 // We don't support increment / decrement on integer-cast-to-pointer
4634 // values.
4635 Info.FFDiag(E);
4636 return false;
4637 }
4638
4639 if (Old) *Old = APValue(Value);
4640
4641 // bool arithmetic promotes to int, and the conversion back to bool
4642 // doesn't reduce mod 2^n, so special-case it.
4643 if (SubobjType->isBooleanType()) {
4644 if (AccessKind == AK_Increment)
4645 Value = 1;
4646 else
4647 Value = !Value;
4648 return true;
4649 }
4650
4651 bool WasNegative = Value.isNegative();
4652 if (AccessKind == AK_Increment) {
4653 ++Value;
4654
4655 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4656 APSInt ActualValue(Value, /*IsUnsigned*/true);
4657 return HandleOverflow(Info, E, SrcValue: ActualValue, DestType: SubobjType);
4658 }
4659 } else {
4660 --Value;
4661
4662 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4663 unsigned BitWidth = Value.getBitWidth();
4664 APSInt ActualValue(Value.sext(width: BitWidth + 1), /*IsUnsigned*/false);
4665 ActualValue.setBit(BitWidth);
4666 return HandleOverflow(Info, E, SrcValue: ActualValue, DestType: SubobjType);
4667 }
4668 }
4669 return true;
4670 }
4671 bool found(APFloat &Value, QualType SubobjType) {
4672 if (!checkConst(QT: SubobjType))
4673 return false;
4674
4675 if (Old) *Old = APValue(Value);
4676
4677 APFloat One(Value.getSemantics(), 1);
4678 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4679 APFloat::opStatus St;
4680 if (AccessKind == AK_Increment)
4681 St = Value.add(RHS: One, RM);
4682 else
4683 St = Value.subtract(RHS: One, RM);
4684 return checkFloatingPointResult(Info, E, St);
4685 }
4686 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4687 if (!checkConst(QT: SubobjType))
4688 return false;
4689
4690 QualType PointeeType;
4691 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4692 PointeeType = PT->getPointeeType();
4693 else {
4694 Info.FFDiag(E);
4695 return false;
4696 }
4697
4698 LValue LVal;
4699 LVal.setFrom(Ctx&: Info.Ctx, V: Subobj);
4700 if (!HandleLValueArrayAdjustment(Info, E, LVal, EltTy: PointeeType,
4701 Adjustment: AccessKind == AK_Increment ? 1 : -1))
4702 return false;
4703 LVal.moveInto(V&: Subobj);
4704 return true;
4705 }
4706};
4707} // end anonymous namespace
4708
4709/// Perform an increment or decrement on LVal.
4710static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4711 QualType LValType, bool IsIncrement, APValue *Old) {
4712 if (LVal.Designator.Invalid)
4713 return false;
4714
4715 if (!Info.getLangOpts().CPlusPlus14) {
4716 Info.FFDiag(E);
4717 return false;
4718 }
4719
4720 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4721 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4722 IncDecSubobjectHandler Handler = {.Info: Info, .E: cast<UnaryOperator>(Val: E), .AccessKind: AK, .Old: Old};
4723 return Obj && findSubobject(Info, E, Obj, Sub: LVal.Designator, handler&: Handler);
4724}
4725
4726/// Build an lvalue for the object argument of a member function call.
4727static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4728 LValue &This) {
4729 if (Object->getType()->isPointerType() && Object->isPRValue())
4730 return EvaluatePointer(E: Object, Result&: This, Info);
4731
4732 if (Object->isGLValue())
4733 return EvaluateLValue(E: Object, Result&: This, Info);
4734
4735 if (Object->getType()->isLiteralType(Ctx: Info.Ctx))
4736 return EvaluateTemporary(E: Object, Result&: This, Info);
4737
4738 if (Object->getType()->isRecordType() && Object->isPRValue())
4739 return EvaluateTemporary(E: Object, Result&: This, Info);
4740
4741 Info.FFDiag(E: Object, DiagId: diag::note_constexpr_nonliteral) << Object->getType();
4742 return false;
4743}
4744
4745/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4746/// lvalue referring to the result.
4747///
4748/// \param Info - Information about the ongoing evaluation.
4749/// \param LV - An lvalue referring to the base of the member pointer.
4750/// \param RHS - The member pointer expression.
4751/// \param IncludeMember - Specifies whether the member itself is included in
4752/// the resulting LValue subobject designator. This is not possible when
4753/// creating a bound member function.
4754/// \return The field or method declaration to which the member pointer refers,
4755/// or 0 if evaluation fails.
4756static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4757 QualType LVType,
4758 LValue &LV,
4759 const Expr *RHS,
4760 bool IncludeMember = true) {
4761 MemberPtr MemPtr;
4762 if (!EvaluateMemberPointer(E: RHS, Result&: MemPtr, Info))
4763 return nullptr;
4764
4765 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4766 // member value, the behavior is undefined.
4767 if (!MemPtr.getDecl()) {
4768 // FIXME: Specific diagnostic.
4769 Info.FFDiag(E: RHS);
4770 return nullptr;
4771 }
4772
4773 if (MemPtr.isDerivedMember()) {
4774 // This is a member of some derived class. Truncate LV appropriately.
4775 // The end of the derived-to-base path for the base object must match the
4776 // derived-to-base path for the member pointer.
4777 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4778 LV.Designator.Entries.size()) {
4779 Info.FFDiag(E: RHS);
4780 return nullptr;
4781 }
4782 unsigned PathLengthToMember =
4783 LV.Designator.Entries.size() - MemPtr.Path.size();
4784 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4785 const CXXRecordDecl *LVDecl = getAsBaseClass(
4786 E: LV.Designator.Entries[PathLengthToMember + I]);
4787 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4788 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4789 Info.FFDiag(E: RHS);
4790 return nullptr;
4791 }
4792 }
4793
4794 // Truncate the lvalue to the appropriate derived class.
4795 if (!CastToDerivedClass(Info, E: RHS, Result&: LV, TruncatedType: MemPtr.getContainingRecord(),
4796 TruncatedElements: PathLengthToMember))
4797 return nullptr;
4798 } else if (!MemPtr.Path.empty()) {
4799 // Extend the LValue path with the member pointer's path.
4800 LV.Designator.Entries.reserve(N: LV.Designator.Entries.size() +
4801 MemPtr.Path.size() + IncludeMember);
4802
4803 // Walk down to the appropriate base class.
4804 if (const PointerType *PT = LVType->getAs<PointerType>())
4805 LVType = PT->getPointeeType();
4806 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4807 assert(RD && "member pointer access on non-class-type expression");
4808 // The first class in the path is that of the lvalue.
4809 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4810 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4811 if (!HandleLValueDirectBase(Info, E: RHS, Obj&: LV, Derived: RD, Base))
4812 return nullptr;
4813 RD = Base;
4814 }
4815 // Finally cast to the class containing the member.
4816 if (!HandleLValueDirectBase(Info, E: RHS, Obj&: LV, Derived: RD,
4817 Base: MemPtr.getContainingRecord()))
4818 return nullptr;
4819 }
4820
4821 // Add the member. Note that we cannot build bound member functions here.
4822 if (IncludeMember) {
4823 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: MemPtr.getDecl())) {
4824 if (!HandleLValueMember(Info, E: RHS, LVal&: LV, FD))
4825 return nullptr;
4826 } else if (const IndirectFieldDecl *IFD =
4827 dyn_cast<IndirectFieldDecl>(Val: MemPtr.getDecl())) {
4828 if (!HandleLValueIndirectMember(Info, E: RHS, LVal&: LV, IFD))
4829 return nullptr;
4830 } else {
4831 llvm_unreachable("can't construct reference to bound member function");
4832 }
4833 }
4834
4835 return MemPtr.getDecl();
4836}
4837
4838static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4839 const BinaryOperator *BO,
4840 LValue &LV,
4841 bool IncludeMember = true) {
4842 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4843
4844 if (!EvaluateObjectArgument(Info, Object: BO->getLHS(), This&: LV)) {
4845 if (Info.noteFailure()) {
4846 MemberPtr MemPtr;
4847 EvaluateMemberPointer(E: BO->getRHS(), Result&: MemPtr, Info);
4848 }
4849 return nullptr;
4850 }
4851
4852 return HandleMemberPointerAccess(Info, LVType: BO->getLHS()->getType(), LV,
4853 RHS: BO->getRHS(), IncludeMember);
4854}
4855
4856/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4857/// the provided lvalue, which currently refers to the base object.
4858static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4859 LValue &Result) {
4860 SubobjectDesignator &D = Result.Designator;
4861 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK: CSK_Derived))
4862 return false;
4863
4864 QualType TargetQT = E->getType();
4865 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4866 TargetQT = PT->getPointeeType();
4867
4868 // Check this cast lands within the final derived-to-base subobject path.
4869 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4870 Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_downcast)
4871 << D.MostDerivedType << TargetQT;
4872 return false;
4873 }
4874
4875 // Check the type of the final cast. We don't need to check the path,
4876 // since a cast can only be formed if the path is unique.
4877 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4878 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4879 const CXXRecordDecl *FinalType;
4880 if (NewEntriesSize == D.MostDerivedPathLength)
4881 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4882 else
4883 FinalType = getAsBaseClass(E: D.Entries[NewEntriesSize - 1]);
4884 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4885 Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_downcast)
4886 << D.MostDerivedType << TargetQT;
4887 return false;
4888 }
4889
4890 // Truncate the lvalue to the appropriate derived class.
4891 return CastToDerivedClass(Info, E, Result, TruncatedType: TargetType, TruncatedElements: NewEntriesSize);
4892}
4893
4894/// Get the value to use for a default-initialized object of type T.
4895/// Return false if it encounters something invalid.
4896static bool handleDefaultInitValue(QualType T, APValue &Result) {
4897 bool Success = true;
4898
4899 // If there is already a value present don't overwrite it.
4900 if (!Result.isAbsent())
4901 return true;
4902
4903 if (auto *RD = T->getAsCXXRecordDecl()) {
4904 if (RD->isInvalidDecl()) {
4905 Result = APValue();
4906 return false;
4907 }
4908 if (RD->isUnion()) {
4909 Result = APValue((const FieldDecl *)nullptr);
4910 return true;
4911 }
4912 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4913 std::distance(first: RD->field_begin(), last: RD->field_end()));
4914
4915 unsigned Index = 0;
4916 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4917 End = RD->bases_end();
4918 I != End; ++I, ++Index)
4919 Success &=
4920 handleDefaultInitValue(T: I->getType(), Result&: Result.getStructBase(i: Index));
4921
4922 for (const auto *I : RD->fields()) {
4923 if (I->isUnnamedBitField())
4924 continue;
4925 Success &= handleDefaultInitValue(
4926 T: I->getType(), Result&: Result.getStructField(i: I->getFieldIndex()));
4927 }
4928 return Success;
4929 }
4930
4931 if (auto *AT =
4932 dyn_cast_or_null<ConstantArrayType>(Val: T->getAsArrayTypeUnsafe())) {
4933 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
4934 if (Result.hasArrayFiller())
4935 Success &=
4936 handleDefaultInitValue(T: AT->getElementType(), Result&: Result.getArrayFiller());
4937
4938 return Success;
4939 }
4940
4941 Result = APValue::IndeterminateValue();
4942 return true;
4943}
4944
4945namespace {
4946enum EvalStmtResult {
4947 /// Evaluation failed.
4948 ESR_Failed,
4949 /// Hit a 'return' statement.
4950 ESR_Returned,
4951 /// Evaluation succeeded.
4952 ESR_Succeeded,
4953 /// Hit a 'continue' statement.
4954 ESR_Continue,
4955 /// Hit a 'break' statement.
4956 ESR_Break,
4957 /// Still scanning for 'case' or 'default' statement.
4958 ESR_CaseNotFound
4959};
4960}
4961
4962static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4963 if (VD->isInvalidDecl())
4964 return false;
4965 // We don't need to evaluate the initializer for a static local.
4966 if (!VD->hasLocalStorage())
4967 return true;
4968
4969 LValue Result;
4970 APValue &Val = Info.CurrentCall->createTemporary(Key: VD, T: VD->getType(),
4971 Scope: ScopeKind::Block, LV&: Result);
4972
4973 const Expr *InitE = VD->getInit();
4974 if (!InitE) {
4975 if (VD->getType()->isDependentType())
4976 return Info.noteSideEffect();
4977 return handleDefaultInitValue(T: VD->getType(), Result&: Val);
4978 }
4979 if (InitE->isValueDependent())
4980 return false;
4981
4982 if (!EvaluateInPlace(Result&: Val, Info, This: Result, E: InitE)) {
4983 // Wipe out any partially-computed value, to allow tracking that this
4984 // evaluation failed.
4985 Val = APValue();
4986 return false;
4987 }
4988
4989 return true;
4990}
4991
4992static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4993 bool OK = true;
4994
4995 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D))
4996 OK &= EvaluateVarDecl(Info, VD);
4997
4998 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(Val: D))
4999 for (auto *BD : DD->bindings())
5000 if (auto *VD = BD->getHoldingVar())
5001 OK &= EvaluateDecl(Info, D: VD);
5002
5003 return OK;
5004}
5005
5006static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5007 assert(E->isValueDependent());
5008 if (Info.noteSideEffect())
5009 return true;
5010 assert(E->containsErrors() && "valid value-dependent expression should never "
5011 "reach invalid code path.");
5012 return false;
5013}
5014
5015/// Evaluate a condition (either a variable declaration or an expression).
5016static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5017 const Expr *Cond, bool &Result) {
5018 if (Cond->isValueDependent())
5019 return false;
5020 FullExpressionRAII Scope(Info);
5021 if (CondDecl && !EvaluateDecl(Info, D: CondDecl))
5022 return false;
5023 if (!EvaluateAsBooleanCondition(E: Cond, Result, Info))
5024 return false;
5025 return Scope.destroy();
5026}
5027
5028namespace {
5029/// A location where the result (returned value) of evaluating a
5030/// statement should be stored.
5031struct StmtResult {
5032 /// The APValue that should be filled in with the returned value.
5033 APValue &Value;
5034 /// The location containing the result, if any (used to support RVO).
5035 const LValue *Slot;
5036};
5037
5038struct TempVersionRAII {
5039 CallStackFrame &Frame;
5040
5041 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5042 Frame.pushTempVersion();
5043 }
5044
5045 ~TempVersionRAII() {
5046 Frame.popTempVersion();
5047 }
5048};
5049
5050}
5051
5052static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5053 const Stmt *S,
5054 const SwitchCase *SC = nullptr);
5055
5056/// Evaluate the body of a loop, and translate the result as appropriate.
5057static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5058 const Stmt *Body,
5059 const SwitchCase *Case = nullptr) {
5060 BlockScopeRAII Scope(Info);
5061
5062 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Body, SC: Case);
5063 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5064 ESR = ESR_Failed;
5065
5066 switch (ESR) {
5067 case ESR_Break:
5068 return ESR_Succeeded;
5069 case ESR_Succeeded:
5070 case ESR_Continue:
5071 return ESR_Continue;
5072 case ESR_Failed:
5073 case ESR_Returned:
5074 case ESR_CaseNotFound:
5075 return ESR;
5076 }
5077 llvm_unreachable("Invalid EvalStmtResult!");
5078}
5079
5080/// Evaluate a switch statement.
5081static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5082 const SwitchStmt *SS) {
5083 BlockScopeRAII Scope(Info);
5084
5085 // Evaluate the switch condition.
5086 APSInt Value;
5087 {
5088 if (const Stmt *Init = SS->getInit()) {
5089 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Init);
5090 if (ESR != ESR_Succeeded) {
5091 if (ESR != ESR_Failed && !Scope.destroy())
5092 ESR = ESR_Failed;
5093 return ESR;
5094 }
5095 }
5096
5097 FullExpressionRAII CondScope(Info);
5098 if (SS->getConditionVariable() &&
5099 !EvaluateDecl(Info, D: SS->getConditionVariable()))
5100 return ESR_Failed;
5101 if (SS->getCond()->isValueDependent()) {
5102 // We don't know what the value is, and which branch should jump to.
5103 EvaluateDependentExpr(E: SS->getCond(), Info);
5104 return ESR_Failed;
5105 }
5106 if (!EvaluateInteger(E: SS->getCond(), Result&: Value, Info))
5107 return ESR_Failed;
5108
5109 if (!CondScope.destroy())
5110 return ESR_Failed;
5111 }
5112
5113 // Find the switch case corresponding to the value of the condition.
5114 // FIXME: Cache this lookup.
5115 const SwitchCase *Found = nullptr;
5116 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5117 SC = SC->getNextSwitchCase()) {
5118 if (isa<DefaultStmt>(Val: SC)) {
5119 Found = SC;
5120 continue;
5121 }
5122
5123 const CaseStmt *CS = cast<CaseStmt>(Val: SC);
5124 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Ctx: Info.Ctx);
5125 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Ctx: Info.Ctx)
5126 : LHS;
5127 if (LHS <= Value && Value <= RHS) {
5128 Found = SC;
5129 break;
5130 }
5131 }
5132
5133 if (!Found)
5134 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5135
5136 // Search the switch body for the switch case and evaluate it from there.
5137 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: SS->getBody(), SC: Found);
5138 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5139 return ESR_Failed;
5140
5141 switch (ESR) {
5142 case ESR_Break:
5143 return ESR_Succeeded;
5144 case ESR_Succeeded:
5145 case ESR_Continue:
5146 case ESR_Failed:
5147 case ESR_Returned:
5148 return ESR;
5149 case ESR_CaseNotFound:
5150 // This can only happen if the switch case is nested within a statement
5151 // expression. We have no intention of supporting that.
5152 Info.FFDiag(Loc: Found->getBeginLoc(),
5153 DiagId: diag::note_constexpr_stmt_expr_unsupported);
5154 return ESR_Failed;
5155 }
5156 llvm_unreachable("Invalid EvalStmtResult!");
5157}
5158
5159static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5160 // An expression E is a core constant expression unless the evaluation of E
5161 // would evaluate one of the following: [C++23] - a control flow that passes
5162 // through a declaration of a variable with static or thread storage duration
5163 // unless that variable is usable in constant expressions.
5164 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5165 !VD->isUsableInConstantExpressions(C: Info.Ctx)) {
5166 Info.CCEDiag(Loc: VD->getLocation(), DiagId: diag::note_constexpr_static_local)
5167 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5168 return false;
5169 }
5170 return true;
5171}
5172
5173// Evaluate a statement.
5174static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5175 const Stmt *S, const SwitchCase *Case) {
5176 if (!Info.nextStep(S))
5177 return ESR_Failed;
5178
5179 // If we're hunting down a 'case' or 'default' label, recurse through
5180 // substatements until we hit the label.
5181 if (Case) {
5182 switch (S->getStmtClass()) {
5183 case Stmt::CompoundStmtClass:
5184 // FIXME: Precompute which substatement of a compound statement we
5185 // would jump to, and go straight there rather than performing a
5186 // linear scan each time.
5187 case Stmt::LabelStmtClass:
5188 case Stmt::AttributedStmtClass:
5189 case Stmt::DoStmtClass:
5190 break;
5191
5192 case Stmt::CaseStmtClass:
5193 case Stmt::DefaultStmtClass:
5194 if (Case == S)
5195 Case = nullptr;
5196 break;
5197
5198 case Stmt::IfStmtClass: {
5199 // FIXME: Precompute which side of an 'if' we would jump to, and go
5200 // straight there rather than scanning both sides.
5201 const IfStmt *IS = cast<IfStmt>(Val: S);
5202
5203 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5204 // preceded by our switch label.
5205 BlockScopeRAII Scope(Info);
5206
5207 // Step into the init statement in case it brings an (uninitialized)
5208 // variable into scope.
5209 if (const Stmt *Init = IS->getInit()) {
5210 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Init, Case);
5211 if (ESR != ESR_CaseNotFound) {
5212 assert(ESR != ESR_Succeeded);
5213 return ESR;
5214 }
5215 }
5216
5217 // Condition variable must be initialized if it exists.
5218 // FIXME: We can skip evaluating the body if there's a condition
5219 // variable, as there can't be any case labels within it.
5220 // (The same is true for 'for' statements.)
5221
5222 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: IS->getThen(), Case);
5223 if (ESR == ESR_Failed)
5224 return ESR;
5225 if (ESR != ESR_CaseNotFound)
5226 return Scope.destroy() ? ESR : ESR_Failed;
5227 if (!IS->getElse())
5228 return ESR_CaseNotFound;
5229
5230 ESR = EvaluateStmt(Result, Info, S: IS->getElse(), Case);
5231 if (ESR == ESR_Failed)
5232 return ESR;
5233 if (ESR != ESR_CaseNotFound)
5234 return Scope.destroy() ? ESR : ESR_Failed;
5235 return ESR_CaseNotFound;
5236 }
5237
5238 case Stmt::WhileStmtClass: {
5239 EvalStmtResult ESR =
5240 EvaluateLoopBody(Result, Info, Body: cast<WhileStmt>(Val: S)->getBody(), Case);
5241 if (ESR != ESR_Continue)
5242 return ESR;
5243 break;
5244 }
5245
5246 case Stmt::ForStmtClass: {
5247 const ForStmt *FS = cast<ForStmt>(Val: S);
5248 BlockScopeRAII Scope(Info);
5249
5250 // Step into the init statement in case it brings an (uninitialized)
5251 // variable into scope.
5252 if (const Stmt *Init = FS->getInit()) {
5253 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Init, Case);
5254 if (ESR != ESR_CaseNotFound) {
5255 assert(ESR != ESR_Succeeded);
5256 return ESR;
5257 }
5258 }
5259
5260 EvalStmtResult ESR =
5261 EvaluateLoopBody(Result, Info, Body: FS->getBody(), Case);
5262 if (ESR != ESR_Continue)
5263 return ESR;
5264 if (const auto *Inc = FS->getInc()) {
5265 if (Inc->isValueDependent()) {
5266 if (!EvaluateDependentExpr(E: Inc, Info))
5267 return ESR_Failed;
5268 } else {
5269 FullExpressionRAII IncScope(Info);
5270 if (!EvaluateIgnoredValue(Info, E: Inc) || !IncScope.destroy())
5271 return ESR_Failed;
5272 }
5273 }
5274 break;
5275 }
5276
5277 case Stmt::DeclStmtClass: {
5278 // Start the lifetime of any uninitialized variables we encounter. They
5279 // might be used by the selected branch of the switch.
5280 const DeclStmt *DS = cast<DeclStmt>(Val: S);
5281 for (const auto *D : DS->decls()) {
5282 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
5283 if (!CheckLocalVariableDeclaration(Info, VD))
5284 return ESR_Failed;
5285 if (VD->hasLocalStorage() && !VD->getInit())
5286 if (!EvaluateVarDecl(Info, VD))
5287 return ESR_Failed;
5288 // FIXME: If the variable has initialization that can't be jumped
5289 // over, bail out of any immediately-surrounding compound-statement
5290 // too. There can't be any case labels here.
5291 }
5292 }
5293 return ESR_CaseNotFound;
5294 }
5295
5296 default:
5297 return ESR_CaseNotFound;
5298 }
5299 }
5300
5301 switch (S->getStmtClass()) {
5302 default:
5303 if (const Expr *E = dyn_cast<Expr>(Val: S)) {
5304 if (E->isValueDependent()) {
5305 if (!EvaluateDependentExpr(E, Info))
5306 return ESR_Failed;
5307 } else {
5308 // Don't bother evaluating beyond an expression-statement which couldn't
5309 // be evaluated.
5310 // FIXME: Do we need the FullExpressionRAII object here?
5311 // VisitExprWithCleanups should create one when necessary.
5312 FullExpressionRAII Scope(Info);
5313 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5314 return ESR_Failed;
5315 }
5316 return ESR_Succeeded;
5317 }
5318
5319 Info.FFDiag(Loc: S->getBeginLoc()) << S->getSourceRange();
5320 return ESR_Failed;
5321
5322 case Stmt::NullStmtClass:
5323 return ESR_Succeeded;
5324
5325 case Stmt::DeclStmtClass: {
5326 const DeclStmt *DS = cast<DeclStmt>(Val: S);
5327 for (const auto *D : DS->decls()) {
5328 const VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: D);
5329 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5330 return ESR_Failed;
5331 // Each declaration initialization is its own full-expression.
5332 FullExpressionRAII Scope(Info);
5333 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5334 return ESR_Failed;
5335 if (!Scope.destroy())
5336 return ESR_Failed;
5337 }
5338 return ESR_Succeeded;
5339 }
5340
5341 case Stmt::ReturnStmtClass: {
5342 const Expr *RetExpr = cast<ReturnStmt>(Val: S)->getRetValue();
5343 FullExpressionRAII Scope(Info);
5344 if (RetExpr && RetExpr->isValueDependent()) {
5345 EvaluateDependentExpr(E: RetExpr, Info);
5346 // We know we returned, but we don't know what the value is.
5347 return ESR_Failed;
5348 }
5349 if (RetExpr &&
5350 !(Result.Slot
5351 ? EvaluateInPlace(Result&: Result.Value, Info, This: *Result.Slot, E: RetExpr)
5352 : Evaluate(Result&: Result.Value, Info, E: RetExpr)))
5353 return ESR_Failed;
5354 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5355 }
5356
5357 case Stmt::CompoundStmtClass: {
5358 BlockScopeRAII Scope(Info);
5359
5360 const CompoundStmt *CS = cast<CompoundStmt>(Val: S);
5361 for (const auto *BI : CS->body()) {
5362 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: BI, Case);
5363 if (ESR == ESR_Succeeded)
5364 Case = nullptr;
5365 else if (ESR != ESR_CaseNotFound) {
5366 if (ESR != ESR_Failed && !Scope.destroy())
5367 return ESR_Failed;
5368 return ESR;
5369 }
5370 }
5371 if (Case)
5372 return ESR_CaseNotFound;
5373 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5374 }
5375
5376 case Stmt::IfStmtClass: {
5377 const IfStmt *IS = cast<IfStmt>(Val: S);
5378
5379 // Evaluate the condition, as either a var decl or as an expression.
5380 BlockScopeRAII Scope(Info);
5381 if (const Stmt *Init = IS->getInit()) {
5382 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: Init);
5383 if (ESR != ESR_Succeeded) {
5384 if (ESR != ESR_Failed && !Scope.destroy())
5385 return ESR_Failed;
5386 return ESR;
5387 }
5388 }
5389 bool Cond;
5390 if (IS->isConsteval()) {
5391 Cond = IS->isNonNegatedConsteval();
5392 // If we are not in a constant context, if consteval should not evaluate
5393 // to true.
5394 if (!Info.InConstantContext)
5395 Cond = !Cond;
5396 } else if (!EvaluateCond(Info, CondDecl: IS->getConditionVariable(), Cond: IS->getCond(),
5397 Result&: Cond))
5398 return ESR_Failed;
5399
5400 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5401 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: SubStmt);
5402 if (ESR != ESR_Succeeded) {
5403 if (ESR != ESR_Failed && !Scope.destroy())
5404 return ESR_Failed;
5405 return ESR;
5406 }
5407 }
5408 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5409 }
5410
5411 case Stmt::WhileStmtClass: {
5412 const WhileStmt *WS = cast<WhileStmt>(Val: S);
5413 while (true) {
5414 BlockScopeRAII Scope(Info);
5415 bool Continue;
5416 if (!EvaluateCond(Info, CondDecl: WS->getConditionVariable(), Cond: WS->getCond(),
5417 Result&: Continue))
5418 return ESR_Failed;
5419 if (!Continue)
5420 break;
5421
5422 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, Body: WS->getBody());
5423 if (ESR != ESR_Continue) {
5424 if (ESR != ESR_Failed && !Scope.destroy())
5425 return ESR_Failed;
5426 return ESR;
5427 }
5428 if (!Scope.destroy())
5429 return ESR_Failed;
5430 }
5431 return ESR_Succeeded;
5432 }
5433
5434 case Stmt::DoStmtClass: {
5435 const DoStmt *DS = cast<DoStmt>(Val: S);
5436 bool Continue;
5437 do {
5438 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, Body: DS->getBody(), Case);
5439 if (ESR != ESR_Continue)
5440 return ESR;
5441 Case = nullptr;
5442
5443 if (DS->getCond()->isValueDependent()) {
5444 EvaluateDependentExpr(E: DS->getCond(), Info);
5445 // Bailout as we don't know whether to keep going or terminate the loop.
5446 return ESR_Failed;
5447 }
5448 FullExpressionRAII CondScope(Info);
5449 if (!EvaluateAsBooleanCondition(E: DS->getCond(), Result&: Continue, Info) ||
5450 !CondScope.destroy())
5451 return ESR_Failed;
5452 } while (Continue);
5453 return ESR_Succeeded;
5454 }
5455
5456 case Stmt::ForStmtClass: {
5457 const ForStmt *FS = cast<ForStmt>(Val: S);
5458 BlockScopeRAII ForScope(Info);
5459 if (FS->getInit()) {
5460 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: FS->getInit());
5461 if (ESR != ESR_Succeeded) {
5462 if (ESR != ESR_Failed && !ForScope.destroy())
5463 return ESR_Failed;
5464 return ESR;
5465 }
5466 }
5467 while (true) {
5468 BlockScopeRAII IterScope(Info);
5469 bool Continue = true;
5470 if (FS->getCond() && !EvaluateCond(Info, CondDecl: FS->getConditionVariable(),
5471 Cond: FS->getCond(), Result&: Continue))
5472 return ESR_Failed;
5473 if (!Continue)
5474 break;
5475
5476 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, Body: FS->getBody());
5477 if (ESR != ESR_Continue) {
5478 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5479 return ESR_Failed;
5480 return ESR;
5481 }
5482
5483 if (const auto *Inc = FS->getInc()) {
5484 if (Inc->isValueDependent()) {
5485 if (!EvaluateDependentExpr(E: Inc, Info))
5486 return ESR_Failed;
5487 } else {
5488 FullExpressionRAII IncScope(Info);
5489 if (!EvaluateIgnoredValue(Info, E: Inc) || !IncScope.destroy())
5490 return ESR_Failed;
5491 }
5492 }
5493
5494 if (!IterScope.destroy())
5495 return ESR_Failed;
5496 }
5497 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5498 }
5499
5500 case Stmt::CXXForRangeStmtClass: {
5501 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(Val: S);
5502 BlockScopeRAII Scope(Info);
5503
5504 // Evaluate the init-statement if present.
5505 if (FS->getInit()) {
5506 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: FS->getInit());
5507 if (ESR != ESR_Succeeded) {
5508 if (ESR != ESR_Failed && !Scope.destroy())
5509 return ESR_Failed;
5510 return ESR;
5511 }
5512 }
5513
5514 // Initialize the __range variable.
5515 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: FS->getRangeStmt());
5516 if (ESR != ESR_Succeeded) {
5517 if (ESR != ESR_Failed && !Scope.destroy())
5518 return ESR_Failed;
5519 return ESR;
5520 }
5521
5522 // In error-recovery cases it's possible to get here even if we failed to
5523 // synthesize the __begin and __end variables.
5524 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5525 return ESR_Failed;
5526
5527 // Create the __begin and __end iterators.
5528 ESR = EvaluateStmt(Result, Info, S: FS->getBeginStmt());
5529 if (ESR != ESR_Succeeded) {
5530 if (ESR != ESR_Failed && !Scope.destroy())
5531 return ESR_Failed;
5532 return ESR;
5533 }
5534 ESR = EvaluateStmt(Result, Info, S: FS->getEndStmt());
5535 if (ESR != ESR_Succeeded) {
5536 if (ESR != ESR_Failed && !Scope.destroy())
5537 return ESR_Failed;
5538 return ESR;
5539 }
5540
5541 while (true) {
5542 // Condition: __begin != __end.
5543 {
5544 if (FS->getCond()->isValueDependent()) {
5545 EvaluateDependentExpr(E: FS->getCond(), Info);
5546 // We don't know whether to keep going or terminate the loop.
5547 return ESR_Failed;
5548 }
5549 bool Continue = true;
5550 FullExpressionRAII CondExpr(Info);
5551 if (!EvaluateAsBooleanCondition(E: FS->getCond(), Result&: Continue, Info))
5552 return ESR_Failed;
5553 if (!Continue)
5554 break;
5555 }
5556
5557 // User's variable declaration, initialized by *__begin.
5558 BlockScopeRAII InnerScope(Info);
5559 ESR = EvaluateStmt(Result, Info, S: FS->getLoopVarStmt());
5560 if (ESR != ESR_Succeeded) {
5561 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5562 return ESR_Failed;
5563 return ESR;
5564 }
5565
5566 // Loop body.
5567 ESR = EvaluateLoopBody(Result, Info, Body: FS->getBody());
5568 if (ESR != ESR_Continue) {
5569 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5570 return ESR_Failed;
5571 return ESR;
5572 }
5573 if (FS->getInc()->isValueDependent()) {
5574 if (!EvaluateDependentExpr(E: FS->getInc(), Info))
5575 return ESR_Failed;
5576 } else {
5577 // Increment: ++__begin
5578 if (!EvaluateIgnoredValue(Info, E: FS->getInc()))
5579 return ESR_Failed;
5580 }
5581
5582 if (!InnerScope.destroy())
5583 return ESR_Failed;
5584 }
5585
5586 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5587 }
5588
5589 case Stmt::SwitchStmtClass:
5590 return EvaluateSwitch(Result, Info, SS: cast<SwitchStmt>(Val: S));
5591
5592 case Stmt::ContinueStmtClass:
5593 return ESR_Continue;
5594
5595 case Stmt::BreakStmtClass:
5596 return ESR_Break;
5597
5598 case Stmt::LabelStmtClass:
5599 return EvaluateStmt(Result, Info, S: cast<LabelStmt>(Val: S)->getSubStmt(), Case);
5600
5601 case Stmt::AttributedStmtClass: {
5602 const auto *AS = cast<AttributedStmt>(Val: S);
5603 const auto *SS = AS->getSubStmt();
5604 MSConstexprContextRAII ConstexprContext(
5605 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(container: AS->getAttrs()) &&
5606 isa<ReturnStmt>(Val: SS));
5607
5608 auto LO = Info.getCtx().getLangOpts();
5609 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5610 for (auto *Attr : AS->getAttrs()) {
5611 auto *AA = dyn_cast<CXXAssumeAttr>(Val: Attr);
5612 if (!AA)
5613 continue;
5614
5615 auto *Assumption = AA->getAssumption();
5616 if (Assumption->isValueDependent())
5617 return ESR_Failed;
5618
5619 if (Assumption->HasSideEffects(Ctx: Info.getCtx()))
5620 continue;
5621
5622 bool Value;
5623 if (!EvaluateAsBooleanCondition(E: Assumption, Result&: Value, Info))
5624 return ESR_Failed;
5625 if (!Value) {
5626 Info.CCEDiag(Loc: Assumption->getExprLoc(),
5627 DiagId: diag::note_constexpr_assumption_failed);
5628 return ESR_Failed;
5629 }
5630 }
5631 }
5632
5633 return EvaluateStmt(Result, Info, S: SS, Case);
5634 }
5635
5636 case Stmt::CaseStmtClass:
5637 case Stmt::DefaultStmtClass:
5638 return EvaluateStmt(Result, Info, S: cast<SwitchCase>(Val: S)->getSubStmt(), Case);
5639 case Stmt::CXXTryStmtClass:
5640 // Evaluate try blocks by evaluating all sub statements.
5641 return EvaluateStmt(Result, Info, S: cast<CXXTryStmt>(Val: S)->getTryBlock(), Case);
5642 }
5643}
5644
5645/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5646/// default constructor. If so, we'll fold it whether or not it's marked as
5647/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5648/// so we need special handling.
5649static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5650 const CXXConstructorDecl *CD,
5651 bool IsValueInitialization) {
5652 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5653 return false;
5654
5655 // Value-initialization does not call a trivial default constructor, so such a
5656 // call is a core constant expression whether or not the constructor is
5657 // constexpr.
5658 if (!CD->isConstexpr() && !IsValueInitialization) {
5659 if (Info.getLangOpts().CPlusPlus11) {
5660 // FIXME: If DiagDecl is an implicitly-declared special member function,
5661 // we should be much more explicit about why it's not constexpr.
5662 Info.CCEDiag(Loc, DiagId: diag::note_constexpr_invalid_function, ExtraNotes: 1)
5663 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5664 Info.Note(Loc: CD->getLocation(), DiagId: diag::note_declared_at);
5665 } else {
5666 Info.CCEDiag(Loc, DiagId: diag::note_invalid_subexpr_in_const_expr);
5667 }
5668 }
5669 return true;
5670}
5671
5672/// CheckConstexprFunction - Check that a function can be called in a constant
5673/// expression.
5674static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5675 const FunctionDecl *Declaration,
5676 const FunctionDecl *Definition,
5677 const Stmt *Body) {
5678 // Potential constant expressions can contain calls to declared, but not yet
5679 // defined, constexpr functions.
5680 if (Info.checkingPotentialConstantExpression() && !Definition &&
5681 Declaration->isConstexpr())
5682 return false;
5683
5684 // Bail out if the function declaration itself is invalid. We will
5685 // have produced a relevant diagnostic while parsing it, so just
5686 // note the problematic sub-expression.
5687 if (Declaration->isInvalidDecl()) {
5688 Info.FFDiag(Loc: CallLoc, DiagId: diag::note_invalid_subexpr_in_const_expr);
5689 return false;
5690 }
5691
5692 // DR1872: An instantiated virtual constexpr function can't be called in a
5693 // constant expression (prior to C++20). We can still constant-fold such a
5694 // call.
5695 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Val: Declaration) &&
5696 cast<CXXMethodDecl>(Val: Declaration)->isVirtual())
5697 Info.CCEDiag(Loc: CallLoc, DiagId: diag::note_constexpr_virtual_call);
5698
5699 if (Definition && Definition->isInvalidDecl()) {
5700 Info.FFDiag(Loc: CallLoc, DiagId: diag::note_invalid_subexpr_in_const_expr);
5701 return false;
5702 }
5703
5704 // Can we evaluate this function call?
5705 if (Definition && Body &&
5706 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5707 Definition->hasAttr<MSConstexprAttr>())))
5708 return true;
5709
5710 if (Info.getLangOpts().CPlusPlus11) {
5711 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5712
5713 // If this function is not constexpr because it is an inherited
5714 // non-constexpr constructor, diagnose that directly.
5715 auto *CD = dyn_cast<CXXConstructorDecl>(Val: DiagDecl);
5716 if (CD && CD->isInheritingConstructor()) {
5717 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5718 if (!Inherited->isConstexpr())
5719 DiagDecl = CD = Inherited;
5720 }
5721
5722 // FIXME: If DiagDecl is an implicitly-declared special member function
5723 // or an inheriting constructor, we should be much more explicit about why
5724 // it's not constexpr.
5725 if (CD && CD->isInheritingConstructor())
5726 Info.FFDiag(Loc: CallLoc, DiagId: diag::note_constexpr_invalid_inhctor, ExtraNotes: 1)
5727 << CD->getInheritedConstructor().getConstructor()->getParent();
5728 else
5729 Info.FFDiag(Loc: CallLoc, DiagId: diag::note_constexpr_invalid_function, ExtraNotes: 1)
5730 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5731 Info.Note(Loc: DiagDecl->getLocation(), DiagId: diag::note_declared_at);
5732 } else {
5733 Info.FFDiag(Loc: CallLoc, DiagId: diag::note_invalid_subexpr_in_const_expr);
5734 }
5735 return false;
5736}
5737
5738namespace {
5739struct CheckDynamicTypeHandler {
5740 AccessKinds AccessKind;
5741 typedef bool result_type;
5742 bool failed() { return false; }
5743 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5744 bool found(APSInt &Value, QualType SubobjType) { return true; }
5745 bool found(APFloat &Value, QualType SubobjType) { return true; }
5746};
5747} // end anonymous namespace
5748
5749/// Check that we can access the notional vptr of an object / determine its
5750/// dynamic type.
5751static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5752 AccessKinds AK, bool Polymorphic) {
5753 if (This.Designator.Invalid)
5754 return false;
5755
5756 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal: This, LValType: QualType());
5757
5758 if (!Obj)
5759 return false;
5760
5761 if (!Obj.Value) {
5762 // The object is not usable in constant expressions, so we can't inspect
5763 // its value to see if it's in-lifetime or what the active union members
5764 // are. We can still check for a one-past-the-end lvalue.
5765 if (This.Designator.isOnePastTheEnd() ||
5766 This.Designator.isMostDerivedAnUnsizedArray()) {
5767 Info.FFDiag(E, DiagId: This.Designator.isOnePastTheEnd()
5768 ? diag::note_constexpr_access_past_end
5769 : diag::note_constexpr_access_unsized_array)
5770 << AK;
5771 return false;
5772 } else if (Polymorphic) {
5773 // Conservatively refuse to perform a polymorphic operation if we would
5774 // not be able to read a notional 'vptr' value.
5775 APValue Val;
5776 This.moveInto(V&: Val);
5777 QualType StarThisType =
5778 Info.Ctx.getLValueReferenceType(T: This.Designator.getType(Ctx&: Info.Ctx));
5779 Info.FFDiag(E, DiagId: diag::note_constexpr_polymorphic_unknown_dynamic_type)
5780 << AK << Val.getAsString(Ctx: Info.Ctx, Ty: StarThisType);
5781 return false;
5782 }
5783 return true;
5784 }
5785
5786 CheckDynamicTypeHandler Handler{.AccessKind: AK};
5787 return Obj && findSubobject(Info, E, Obj, Sub: This.Designator, handler&: Handler);
5788}
5789
5790/// Check that the pointee of the 'this' pointer in a member function call is
5791/// either within its lifetime or in its period of construction or destruction.
5792static bool
5793checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5794 const LValue &This,
5795 const CXXMethodDecl *NamedMember) {
5796 return checkDynamicType(
5797 Info, E, This,
5798 AK: isa<CXXDestructorDecl>(Val: NamedMember) ? AK_Destroy : AK_MemberCall, Polymorphic: false);
5799}
5800
5801struct DynamicType {
5802 /// The dynamic class type of the object.
5803 const CXXRecordDecl *Type;
5804 /// The corresponding path length in the lvalue.
5805 unsigned PathLength;
5806};
5807
5808static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5809 unsigned PathLength) {
5810 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5811 Designator.Entries.size() && "invalid path length");
5812 return (PathLength == Designator.MostDerivedPathLength)
5813 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5814 : getAsBaseClass(E: Designator.Entries[PathLength - 1]);
5815}
5816
5817/// Determine the dynamic type of an object.
5818static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5819 const Expr *E,
5820 LValue &This,
5821 AccessKinds AK) {
5822 // If we don't have an lvalue denoting an object of class type, there is no
5823 // meaningful dynamic type. (We consider objects of non-class type to have no
5824 // dynamic type.)
5825 if (!checkDynamicType(Info, E, This, AK, Polymorphic: true))
5826 return std::nullopt;
5827
5828 // Refuse to compute a dynamic type in the presence of virtual bases. This
5829 // shouldn't happen other than in constant-folding situations, since literal
5830 // types can't have virtual bases.
5831 //
5832 // Note that consumers of DynamicType assume that the type has no virtual
5833 // bases, and will need modifications if this restriction is relaxed.
5834 const CXXRecordDecl *Class =
5835 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5836 if (!Class || Class->getNumVBases()) {
5837 Info.FFDiag(E);
5838 return std::nullopt;
5839 }
5840
5841 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5842 // binary search here instead. But the overwhelmingly common case is that
5843 // we're not in the middle of a constructor, so it probably doesn't matter
5844 // in practice.
5845 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5846 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5847 PathLength <= Path.size(); ++PathLength) {
5848 switch (Info.isEvaluatingCtorDtor(Base: This.getLValueBase(),
5849 Path: Path.slice(N: 0, M: PathLength))) {
5850 case ConstructionPhase::Bases:
5851 case ConstructionPhase::DestroyingBases:
5852 // We're constructing or destroying a base class. This is not the dynamic
5853 // type.
5854 break;
5855
5856 case ConstructionPhase::None:
5857 case ConstructionPhase::AfterBases:
5858 case ConstructionPhase::AfterFields:
5859 case ConstructionPhase::Destroying:
5860 // We've finished constructing the base classes and not yet started
5861 // destroying them again, so this is the dynamic type.
5862 return DynamicType{.Type: getBaseClassType(Designator&: This.Designator, PathLength),
5863 .PathLength: PathLength};
5864 }
5865 }
5866
5867 // CWG issue 1517: we're constructing a base class of the object described by
5868 // 'This', so that object has not yet begun its period of construction and
5869 // any polymorphic operation on it results in undefined behavior.
5870 Info.FFDiag(E);
5871 return std::nullopt;
5872}
5873
5874/// Perform virtual dispatch.
5875static const CXXMethodDecl *HandleVirtualDispatch(
5876 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5877 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5878 std::optional<DynamicType> DynType = ComputeDynamicType(
5879 Info, E, This,
5880 AK: isa<CXXDestructorDecl>(Val: Found) ? AK_Destroy : AK_MemberCall);
5881 if (!DynType)
5882 return nullptr;
5883
5884 // Find the final overrider. It must be declared in one of the classes on the
5885 // path from the dynamic type to the static type.
5886 // FIXME: If we ever allow literal types to have virtual base classes, that
5887 // won't be true.
5888 const CXXMethodDecl *Callee = Found;
5889 unsigned PathLength = DynType->PathLength;
5890 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5891 const CXXRecordDecl *Class = getBaseClassType(Designator&: This.Designator, PathLength);
5892 const CXXMethodDecl *Overrider =
5893 Found->getCorrespondingMethodDeclaredInClass(RD: Class, MayBeBase: false);
5894 if (Overrider) {
5895 Callee = Overrider;
5896 break;
5897 }
5898 }
5899
5900 // C++2a [class.abstract]p6:
5901 // the effect of making a virtual call to a pure virtual function [...] is
5902 // undefined
5903 if (Callee->isPureVirtual()) {
5904 Info.FFDiag(E, DiagId: diag::note_constexpr_pure_virtual_call, ExtraNotes: 1) << Callee;
5905 Info.Note(Loc: Callee->getLocation(), DiagId: diag::note_declared_at);
5906 return nullptr;
5907 }
5908
5909 // If necessary, walk the rest of the path to determine the sequence of
5910 // covariant adjustment steps to apply.
5911 if (!Info.Ctx.hasSameUnqualifiedType(T1: Callee->getReturnType(),
5912 T2: Found->getReturnType())) {
5913 CovariantAdjustmentPath.push_back(Elt: Callee->getReturnType());
5914 for (unsigned CovariantPathLength = PathLength + 1;
5915 CovariantPathLength != This.Designator.Entries.size();
5916 ++CovariantPathLength) {
5917 const CXXRecordDecl *NextClass =
5918 getBaseClassType(Designator&: This.Designator, PathLength: CovariantPathLength);
5919 const CXXMethodDecl *Next =
5920 Found->getCorrespondingMethodDeclaredInClass(RD: NextClass, MayBeBase: false);
5921 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5922 T1: Next->getReturnType(), T2: CovariantAdjustmentPath.back()))
5923 CovariantAdjustmentPath.push_back(Elt: Next->getReturnType());
5924 }
5925 if (!Info.Ctx.hasSameUnqualifiedType(T1: Found->getReturnType(),
5926 T2: CovariantAdjustmentPath.back()))
5927 CovariantAdjustmentPath.push_back(Elt: Found->getReturnType());
5928 }
5929
5930 // Perform 'this' adjustment.
5931 if (!CastToDerivedClass(Info, E, Result&: This, TruncatedType: Callee->getParent(), TruncatedElements: PathLength))
5932 return nullptr;
5933
5934 return Callee;
5935}
5936
5937/// Perform the adjustment from a value returned by a virtual function to
5938/// a value of the statically expected type, which may be a pointer or
5939/// reference to a base class of the returned type.
5940static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5941 APValue &Result,
5942 ArrayRef<QualType> Path) {
5943 assert(Result.isLValue() &&
5944 "unexpected kind of APValue for covariant return");
5945 if (Result.isNullPointer())
5946 return true;
5947
5948 LValue LVal;
5949 LVal.setFrom(Ctx&: Info.Ctx, V: Result);
5950
5951 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5952 for (unsigned I = 1; I != Path.size(); ++I) {
5953 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5954 assert(OldClass && NewClass && "unexpected kind of covariant return");
5955 if (OldClass != NewClass &&
5956 !CastToBaseClass(Info, E, Result&: LVal, DerivedRD: OldClass, BaseRD: NewClass))
5957 return false;
5958 OldClass = NewClass;
5959 }
5960
5961 LVal.moveInto(V&: Result);
5962 return true;
5963}
5964
5965/// Determine whether \p Base, which is known to be a direct base class of
5966/// \p Derived, is a public base class.
5967static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5968 const CXXRecordDecl *Base) {
5969 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5970 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5971 if (BaseClass && declaresSameEntity(D1: BaseClass, D2: Base))
5972 return BaseSpec.getAccessSpecifier() == AS_public;
5973 }
5974 llvm_unreachable("Base is not a direct base of Derived");
5975}
5976
5977/// Apply the given dynamic cast operation on the provided lvalue.
5978///
5979/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5980/// to find a suitable target subobject.
5981static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5982 LValue &Ptr) {
5983 // We can't do anything with a non-symbolic pointer value.
5984 SubobjectDesignator &D = Ptr.Designator;
5985 if (D.Invalid)
5986 return false;
5987
5988 // C++ [expr.dynamic.cast]p6:
5989 // If v is a null pointer value, the result is a null pointer value.
5990 if (Ptr.isNullPointer() && !E->isGLValue())
5991 return true;
5992
5993 // For all the other cases, we need the pointer to point to an object within
5994 // its lifetime / period of construction / destruction, and we need to know
5995 // its dynamic type.
5996 std::optional<DynamicType> DynType =
5997 ComputeDynamicType(Info, E, This&: Ptr, AK: AK_DynamicCast);
5998 if (!DynType)
5999 return false;
6000
6001 // C++ [expr.dynamic.cast]p7:
6002 // If T is "pointer to cv void", then the result is a pointer to the most
6003 // derived object
6004 if (E->getType()->isVoidPointerType())
6005 return CastToDerivedClass(Info, E, Result&: Ptr, TruncatedType: DynType->Type, TruncatedElements: DynType->PathLength);
6006
6007 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6008 assert(C && "dynamic_cast target is not void pointer nor class");
6009 CanQualType CQT = Info.Ctx.getCanonicalType(T: Info.Ctx.getRecordType(Decl: C));
6010
6011 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6012 // C++ [expr.dynamic.cast]p9:
6013 if (!E->isGLValue()) {
6014 // The value of a failed cast to pointer type is the null pointer value
6015 // of the required result type.
6016 Ptr.setNull(Ctx&: Info.Ctx, PointerTy: E->getType());
6017 return true;
6018 }
6019
6020 // A failed cast to reference type throws [...] std::bad_cast.
6021 unsigned DiagKind;
6022 if (!Paths && (declaresSameEntity(D1: DynType->Type, D2: C) ||
6023 DynType->Type->isDerivedFrom(Base: C)))
6024 DiagKind = 0;
6025 else if (!Paths || Paths->begin() == Paths->end())
6026 DiagKind = 1;
6027 else if (Paths->isAmbiguous(BaseType: CQT))
6028 DiagKind = 2;
6029 else {
6030 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6031 DiagKind = 3;
6032 }
6033 Info.FFDiag(E, DiagId: diag::note_constexpr_dynamic_cast_to_reference_failed)
6034 << DiagKind << Ptr.Designator.getType(Ctx&: Info.Ctx)
6035 << Info.Ctx.getRecordType(Decl: DynType->Type)
6036 << E->getType().getUnqualifiedType();
6037 return false;
6038 };
6039
6040 // Runtime check, phase 1:
6041 // Walk from the base subobject towards the derived object looking for the
6042 // target type.
6043 for (int PathLength = Ptr.Designator.Entries.size();
6044 PathLength >= (int)DynType->PathLength; --PathLength) {
6045 const CXXRecordDecl *Class = getBaseClassType(Designator&: Ptr.Designator, PathLength);
6046 if (declaresSameEntity(D1: Class, D2: C))
6047 return CastToDerivedClass(Info, E, Result&: Ptr, TruncatedType: Class, TruncatedElements: PathLength);
6048 // We can only walk across public inheritance edges.
6049 if (PathLength > (int)DynType->PathLength &&
6050 !isBaseClassPublic(Derived: getBaseClassType(Designator&: Ptr.Designator, PathLength: PathLength - 1),
6051 Base: Class))
6052 return RuntimeCheckFailed(nullptr);
6053 }
6054
6055 // Runtime check, phase 2:
6056 // Search the dynamic type for an unambiguous public base of type C.
6057 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6058 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6059 if (DynType->Type->isDerivedFrom(Base: C, Paths) && !Paths.isAmbiguous(BaseType: CQT) &&
6060 Paths.front().Access == AS_public) {
6061 // Downcast to the dynamic type...
6062 if (!CastToDerivedClass(Info, E, Result&: Ptr, TruncatedType: DynType->Type, TruncatedElements: DynType->PathLength))
6063 return false;
6064 // ... then upcast to the chosen base class subobject.
6065 for (CXXBasePathElement &Elem : Paths.front())
6066 if (!HandleLValueBase(Info, E, Obj&: Ptr, DerivedDecl: Elem.Class, Base: Elem.Base))
6067 return false;
6068 return true;
6069 }
6070
6071 // Otherwise, the runtime check fails.
6072 return RuntimeCheckFailed(&Paths);
6073}
6074
6075namespace {
6076struct StartLifetimeOfUnionMemberHandler {
6077 EvalInfo &Info;
6078 const Expr *LHSExpr;
6079 const FieldDecl *Field;
6080 bool DuringInit;
6081 bool Failed = false;
6082 static const AccessKinds AccessKind = AK_Assign;
6083
6084 typedef bool result_type;
6085 bool failed() { return Failed; }
6086 bool found(APValue &Subobj, QualType SubobjType) {
6087 // We are supposed to perform no initialization but begin the lifetime of
6088 // the object. We interpret that as meaning to do what default
6089 // initialization of the object would do if all constructors involved were
6090 // trivial:
6091 // * All base, non-variant member, and array element subobjects' lifetimes
6092 // begin
6093 // * No variant members' lifetimes begin
6094 // * All scalar subobjects whose lifetimes begin have indeterminate values
6095 assert(SubobjType->isUnionType());
6096 if (declaresSameEntity(D1: Subobj.getUnionField(), D2: Field)) {
6097 // This union member is already active. If it's also in-lifetime, there's
6098 // nothing to do.
6099 if (Subobj.getUnionValue().hasValue())
6100 return true;
6101 } else if (DuringInit) {
6102 // We're currently in the process of initializing a different union
6103 // member. If we carried on, that initialization would attempt to
6104 // store to an inactive union member, resulting in undefined behavior.
6105 Info.FFDiag(E: LHSExpr,
6106 DiagId: diag::note_constexpr_union_member_change_during_init);
6107 return false;
6108 }
6109 APValue Result;
6110 Failed = !handleDefaultInitValue(T: Field->getType(), Result);
6111 Subobj.setUnion(Field, Value: Result);
6112 return true;
6113 }
6114 bool found(APSInt &Value, QualType SubobjType) {
6115 llvm_unreachable("wrong value kind for union object");
6116 }
6117 bool found(APFloat &Value, QualType SubobjType) {
6118 llvm_unreachable("wrong value kind for union object");
6119 }
6120};
6121} // end anonymous namespace
6122
6123const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6124
6125/// Handle a builtin simple-assignment or a call to a trivial assignment
6126/// operator whose left-hand side might involve a union member access. If it
6127/// does, implicitly start the lifetime of any accessed union elements per
6128/// C++20 [class.union]5.
6129static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6130 const Expr *LHSExpr,
6131 const LValue &LHS) {
6132 if (LHS.InvalidBase || LHS.Designator.Invalid)
6133 return false;
6134
6135 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6136 // C++ [class.union]p5:
6137 // define the set S(E) of subexpressions of E as follows:
6138 unsigned PathLength = LHS.Designator.Entries.size();
6139 for (const Expr *E = LHSExpr; E != nullptr;) {
6140 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6141 if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
6142 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
6143 // Note that we can't implicitly start the lifetime of a reference,
6144 // so we don't need to proceed any further if we reach one.
6145 if (!FD || FD->getType()->isReferenceType())
6146 break;
6147
6148 // ... and also contains A.B if B names a union member ...
6149 if (FD->getParent()->isUnion()) {
6150 // ... of a non-class, non-array type, or of a class type with a
6151 // trivial default constructor that is not deleted, or an array of
6152 // such types.
6153 auto *RD =
6154 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6155 if (!RD || RD->hasTrivialDefaultConstructor())
6156 UnionPathLengths.push_back(Elt: {PathLength - 1, FD});
6157 }
6158
6159 E = ME->getBase();
6160 --PathLength;
6161 assert(declaresSameEntity(FD,
6162 LHS.Designator.Entries[PathLength]
6163 .getAsBaseOrMember().getPointer()));
6164
6165 // -- If E is of the form A[B] and is interpreted as a built-in array
6166 // subscripting operator, S(E) is [S(the array operand, if any)].
6167 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: E)) {
6168 // Step over an ArrayToPointerDecay implicit cast.
6169 auto *Base = ASE->getBase()->IgnoreImplicit();
6170 if (!Base->getType()->isArrayType())
6171 break;
6172
6173 E = Base;
6174 --PathLength;
6175
6176 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
6177 // Step over a derived-to-base conversion.
6178 E = ICE->getSubExpr();
6179 if (ICE->getCastKind() == CK_NoOp)
6180 continue;
6181 if (ICE->getCastKind() != CK_DerivedToBase &&
6182 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6183 break;
6184 // Walk path backwards as we walk up from the base to the derived class.
6185 for (const CXXBaseSpecifier *Elt : llvm::reverse(C: ICE->path())) {
6186 if (Elt->isVirtual()) {
6187 // A class with virtual base classes never has a trivial default
6188 // constructor, so S(E) is empty in this case.
6189 E = nullptr;
6190 break;
6191 }
6192
6193 --PathLength;
6194 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6195 LHS.Designator.Entries[PathLength]
6196 .getAsBaseOrMember().getPointer()));
6197 }
6198
6199 // -- Otherwise, S(E) is empty.
6200 } else {
6201 break;
6202 }
6203 }
6204
6205 // Common case: no unions' lifetimes are started.
6206 if (UnionPathLengths.empty())
6207 return true;
6208
6209 // if modification of X [would access an inactive union member], an object
6210 // of the type of X is implicitly created
6211 CompleteObject Obj =
6212 findCompleteObject(Info, E: LHSExpr, AK: AK_Assign, LVal: LHS, LValType: LHSExpr->getType());
6213 if (!Obj)
6214 return false;
6215 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6216 llvm::reverse(C&: UnionPathLengths)) {
6217 // Form a designator for the union object.
6218 SubobjectDesignator D = LHS.Designator;
6219 D.truncate(Ctx&: Info.Ctx, Base: LHS.Base, NewLength: LengthAndField.first);
6220
6221 bool DuringInit = Info.isEvaluatingCtorDtor(Base: LHS.Base, Path: D.Entries) ==
6222 ConstructionPhase::AfterBases;
6223 StartLifetimeOfUnionMemberHandler StartLifetime{
6224 .Info: Info, .LHSExpr: LHSExpr, .Field: LengthAndField.second, .DuringInit: DuringInit};
6225 if (!findSubobject(Info, E: LHSExpr, Obj, Sub: D, handler&: StartLifetime))
6226 return false;
6227 }
6228
6229 return true;
6230}
6231
6232static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6233 CallRef Call, EvalInfo &Info,
6234 bool NonNull = false) {
6235 LValue LV;
6236 // Create the parameter slot and register its destruction. For a vararg
6237 // argument, create a temporary.
6238 // FIXME: For calling conventions that destroy parameters in the callee,
6239 // should we consider performing destruction when the function returns
6240 // instead?
6241 APValue &V = PVD ? Info.CurrentCall->createParam(Args: Call, PVD, LV)
6242 : Info.CurrentCall->createTemporary(Key: Arg, T: Arg->getType(),
6243 Scope: ScopeKind::Call, LV);
6244 if (!EvaluateInPlace(Result&: V, Info, This: LV, E: Arg))
6245 return false;
6246
6247 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6248 // undefined behavior, so is non-constant.
6249 if (NonNull && V.isLValue() && V.isNullPointer()) {
6250 Info.CCEDiag(E: Arg, DiagId: diag::note_non_null_attribute_failed);
6251 return false;
6252 }
6253
6254 return true;
6255}
6256
6257/// Evaluate the arguments to a function call.
6258static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6259 EvalInfo &Info, const FunctionDecl *Callee,
6260 bool RightToLeft = false) {
6261 bool Success = true;
6262 llvm::SmallBitVector ForbiddenNullArgs;
6263 if (Callee->hasAttr<NonNullAttr>()) {
6264 ForbiddenNullArgs.resize(N: Args.size());
6265 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6266 if (!Attr->args_size()) {
6267 ForbiddenNullArgs.set();
6268 break;
6269 } else
6270 for (auto Idx : Attr->args()) {
6271 unsigned ASTIdx = Idx.getASTIndex();
6272 if (ASTIdx >= Args.size())
6273 continue;
6274 ForbiddenNullArgs[ASTIdx] = true;
6275 }
6276 }
6277 }
6278 for (unsigned I = 0; I < Args.size(); I++) {
6279 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6280 const ParmVarDecl *PVD =
6281 Idx < Callee->getNumParams() ? Callee->getParamDecl(i: Idx) : nullptr;
6282 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6283 if (!EvaluateCallArg(PVD, Arg: Args[Idx], Call, Info, NonNull)) {
6284 // If we're checking for a potential constant expression, evaluate all
6285 // initializers even if some of them fail.
6286 if (!Info.noteFailure())
6287 return false;
6288 Success = false;
6289 }
6290 }
6291 return Success;
6292}
6293
6294/// Perform a trivial copy from Param, which is the parameter of a copy or move
6295/// constructor or assignment operator.
6296static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6297 const Expr *E, APValue &Result,
6298 bool CopyObjectRepresentation) {
6299 // Find the reference argument.
6300 CallStackFrame *Frame = Info.CurrentCall;
6301 APValue *RefValue = Info.getParamSlot(Call: Frame->Arguments, PVD: Param);
6302 if (!RefValue) {
6303 Info.FFDiag(E);
6304 return false;
6305 }
6306
6307 // Copy out the contents of the RHS object.
6308 LValue RefLValue;
6309 RefLValue.setFrom(Ctx&: Info.Ctx, V: *RefValue);
6310 return handleLValueToRValueConversion(
6311 Info, Conv: E, Type: Param->getType().getNonReferenceType(), LVal: RefLValue, RVal&: Result,
6312 WantObjectRepresentation: CopyObjectRepresentation);
6313}
6314
6315/// Evaluate a function call.
6316static bool HandleFunctionCall(SourceLocation CallLoc,
6317 const FunctionDecl *Callee, const LValue *This,
6318 const Expr *E, ArrayRef<const Expr *> Args,
6319 CallRef Call, const Stmt *Body, EvalInfo &Info,
6320 APValue &Result, const LValue *ResultSlot) {
6321 if (!Info.CheckCallLimit(Loc: CallLoc))
6322 return false;
6323
6324 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6325
6326 // For a trivial copy or move assignment, perform an APValue copy. This is
6327 // essential for unions, where the operations performed by the assignment
6328 // operator cannot be represented as statements.
6329 //
6330 // Skip this for non-union classes with no fields; in that case, the defaulted
6331 // copy/move does not actually read the object.
6332 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Callee);
6333 if (MD && MD->isDefaulted() &&
6334 (MD->getParent()->isUnion() ||
6335 (MD->isTrivial() &&
6336 isReadByLvalueToRvalueConversion(RD: MD->getParent())))) {
6337 assert(This &&
6338 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6339 APValue RHSValue;
6340 if (!handleTrivialCopy(Info, Param: MD->getParamDecl(i: 0), E: Args[0], Result&: RHSValue,
6341 CopyObjectRepresentation: MD->getParent()->isUnion()))
6342 return false;
6343 if (!handleAssignment(Info, E: Args[0], LVal: *This, LValType: MD->getThisType(),
6344 Val&: RHSValue))
6345 return false;
6346 This->moveInto(V&: Result);
6347 return true;
6348 } else if (MD && isLambdaCallOperator(MD)) {
6349 // We're in a lambda; determine the lambda capture field maps unless we're
6350 // just constexpr checking a lambda's call operator. constexpr checking is
6351 // done before the captures have been added to the closure object (unless
6352 // we're inferring constexpr-ness), so we don't have access to them in this
6353 // case. But since we don't need the captures to constexpr check, we can
6354 // just ignore them.
6355 if (!Info.checkingPotentialConstantExpression())
6356 MD->getParent()->getCaptureFields(Captures&: Frame.LambdaCaptureFields,
6357 ThisCapture&: Frame.LambdaThisCaptureField);
6358 }
6359
6360 StmtResult Ret = {.Value: Result, .Slot: ResultSlot};
6361 EvalStmtResult ESR = EvaluateStmt(Result&: Ret, Info, S: Body);
6362 if (ESR == ESR_Succeeded) {
6363 if (Callee->getReturnType()->isVoidType())
6364 return true;
6365 Info.FFDiag(Loc: Callee->getEndLoc(), DiagId: diag::note_constexpr_no_return);
6366 }
6367 return ESR == ESR_Returned;
6368}
6369
6370/// Evaluate a constructor call.
6371static bool HandleConstructorCall(const Expr *E, const LValue &This,
6372 CallRef Call,
6373 const CXXConstructorDecl *Definition,
6374 EvalInfo &Info, APValue &Result) {
6375 SourceLocation CallLoc = E->getExprLoc();
6376 if (!Info.CheckCallLimit(Loc: CallLoc))
6377 return false;
6378
6379 const CXXRecordDecl *RD = Definition->getParent();
6380 if (RD->getNumVBases()) {
6381 Info.FFDiag(Loc: CallLoc, DiagId: diag::note_constexpr_virtual_base) << RD;
6382 return false;
6383 }
6384
6385 EvalInfo::EvaluatingConstructorRAII EvalObj(
6386 Info,
6387 ObjectUnderConstruction{.Base: This.getLValueBase(), .Path: This.Designator.Entries},
6388 RD->getNumBases());
6389 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6390
6391 // FIXME: Creating an APValue just to hold a nonexistent return value is
6392 // wasteful.
6393 APValue RetVal;
6394 StmtResult Ret = {.Value: RetVal, .Slot: nullptr};
6395
6396 // If it's a delegating constructor, delegate.
6397 if (Definition->isDelegatingConstructor()) {
6398 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6399 if ((*I)->getInit()->isValueDependent()) {
6400 if (!EvaluateDependentExpr(E: (*I)->getInit(), Info))
6401 return false;
6402 } else {
6403 FullExpressionRAII InitScope(Info);
6404 if (!EvaluateInPlace(Result, Info, This, E: (*I)->getInit()) ||
6405 !InitScope.destroy())
6406 return false;
6407 }
6408 return EvaluateStmt(Result&: Ret, Info, S: Definition->getBody()) != ESR_Failed;
6409 }
6410
6411 // For a trivial copy or move constructor, perform an APValue copy. This is
6412 // essential for unions (or classes with anonymous union members), where the
6413 // operations performed by the constructor cannot be represented by
6414 // ctor-initializers.
6415 //
6416 // Skip this for empty non-union classes; we should not perform an
6417 // lvalue-to-rvalue conversion on them because their copy constructor does not
6418 // actually read them.
6419 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6420 (Definition->getParent()->isUnion() ||
6421 (Definition->isTrivial() &&
6422 isReadByLvalueToRvalueConversion(RD: Definition->getParent())))) {
6423 return handleTrivialCopy(Info, Param: Definition->getParamDecl(i: 0), E, Result,
6424 CopyObjectRepresentation: Definition->getParent()->isUnion());
6425 }
6426
6427 // Reserve space for the struct members.
6428 if (!Result.hasValue()) {
6429 if (!RD->isUnion())
6430 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6431 std::distance(first: RD->field_begin(), last: RD->field_end()));
6432 else
6433 // A union starts with no active member.
6434 Result = APValue((const FieldDecl*)nullptr);
6435 }
6436
6437 if (RD->isInvalidDecl()) return false;
6438 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD);
6439
6440 // A scope for temporaries lifetime-extended by reference members.
6441 BlockScopeRAII LifetimeExtendedScope(Info);
6442
6443 bool Success = true;
6444 unsigned BasesSeen = 0;
6445#ifndef NDEBUG
6446 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6447#endif
6448 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6449 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6450 // We might be initializing the same field again if this is an indirect
6451 // field initialization.
6452 if (FieldIt == RD->field_end() ||
6453 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6454 assert(Indirect && "fields out of order?");
6455 return;
6456 }
6457
6458 // Default-initialize any fields with no explicit initializer.
6459 for (; !declaresSameEntity(D1: *FieldIt, D2: FD); ++FieldIt) {
6460 assert(FieldIt != RD->field_end() && "missing field?");
6461 if (!FieldIt->isUnnamedBitField())
6462 Success &= handleDefaultInitValue(
6463 T: FieldIt->getType(),
6464 Result&: Result.getStructField(i: FieldIt->getFieldIndex()));
6465 }
6466 ++FieldIt;
6467 };
6468 for (const auto *I : Definition->inits()) {
6469 LValue Subobject = This;
6470 LValue SubobjectParent = This;
6471 APValue *Value = &Result;
6472
6473 // Determine the subobject to initialize.
6474 FieldDecl *FD = nullptr;
6475 if (I->isBaseInitializer()) {
6476 QualType BaseType(I->getBaseClass(), 0);
6477#ifndef NDEBUG
6478 // Non-virtual base classes are initialized in the order in the class
6479 // definition. We have already checked for virtual base classes.
6480 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6481 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6482 "base class initializers not in expected order");
6483 ++BaseIt;
6484#endif
6485 if (!HandleLValueDirectBase(Info, E: I->getInit(), Obj&: Subobject, Derived: RD,
6486 Base: BaseType->getAsCXXRecordDecl(), RL: &Layout))
6487 return false;
6488 Value = &Result.getStructBase(i: BasesSeen++);
6489 } else if ((FD = I->getMember())) {
6490 if (!HandleLValueMember(Info, E: I->getInit(), LVal&: Subobject, FD, RL: &Layout))
6491 return false;
6492 if (RD->isUnion()) {
6493 Result = APValue(FD);
6494 Value = &Result.getUnionValue();
6495 } else {
6496 SkipToField(FD, false);
6497 Value = &Result.getStructField(i: FD->getFieldIndex());
6498 }
6499 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6500 // Walk the indirect field decl's chain to find the object to initialize,
6501 // and make sure we've initialized every step along it.
6502 auto IndirectFieldChain = IFD->chain();
6503 for (auto *C : IndirectFieldChain) {
6504 FD = cast<FieldDecl>(Val: C);
6505 CXXRecordDecl *CD = cast<CXXRecordDecl>(Val: FD->getParent());
6506 // Switch the union field if it differs. This happens if we had
6507 // preceding zero-initialization, and we're now initializing a union
6508 // subobject other than the first.
6509 // FIXME: In this case, the values of the other subobjects are
6510 // specified, since zero-initialization sets all padding bits to zero.
6511 if (!Value->hasValue() ||
6512 (Value->isUnion() && Value->getUnionField() != FD)) {
6513 if (CD->isUnion())
6514 *Value = APValue(FD);
6515 else
6516 // FIXME: This immediately starts the lifetime of all members of
6517 // an anonymous struct. It would be preferable to strictly start
6518 // member lifetime in initialization order.
6519 Success &=
6520 handleDefaultInitValue(T: Info.Ctx.getRecordType(Decl: CD), Result&: *Value);
6521 }
6522 // Store Subobject as its parent before updating it for the last element
6523 // in the chain.
6524 if (C == IndirectFieldChain.back())
6525 SubobjectParent = Subobject;
6526 if (!HandleLValueMember(Info, E: I->getInit(), LVal&: Subobject, FD))
6527 return false;
6528 if (CD->isUnion())
6529 Value = &Value->getUnionValue();
6530 else {
6531 if (C == IndirectFieldChain.front() && !RD->isUnion())
6532 SkipToField(FD, true);
6533 Value = &Value->getStructField(i: FD->getFieldIndex());
6534 }
6535 }
6536 } else {
6537 llvm_unreachable("unknown base initializer kind");
6538 }
6539
6540 // Need to override This for implicit field initializers as in this case
6541 // This refers to innermost anonymous struct/union containing initializer,
6542 // not to currently constructed class.
6543 const Expr *Init = I->getInit();
6544 if (Init->isValueDependent()) {
6545 if (!EvaluateDependentExpr(E: Init, Info))
6546 return false;
6547 } else {
6548 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6549 isa<CXXDefaultInitExpr>(Val: Init));
6550 FullExpressionRAII InitScope(Info);
6551 if (!EvaluateInPlace(Result&: *Value, Info, This: Subobject, E: Init) ||
6552 (FD && FD->isBitField() &&
6553 !truncateBitfieldValue(Info, E: Init, Value&: *Value, FD))) {
6554 // If we're checking for a potential constant expression, evaluate all
6555 // initializers even if some of them fail.
6556 if (!Info.noteFailure())
6557 return false;
6558 Success = false;
6559 }
6560 }
6561
6562 // This is the point at which the dynamic type of the object becomes this
6563 // class type.
6564 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6565 EvalObj.finishedConstructingBases();
6566 }
6567
6568 // Default-initialize any remaining fields.
6569 if (!RD->isUnion()) {
6570 for (; FieldIt != RD->field_end(); ++FieldIt) {
6571 if (!FieldIt->isUnnamedBitField())
6572 Success &= handleDefaultInitValue(
6573 T: FieldIt->getType(),
6574 Result&: Result.getStructField(i: FieldIt->getFieldIndex()));
6575 }
6576 }
6577
6578 EvalObj.finishedConstructingFields();
6579
6580 return Success &&
6581 EvaluateStmt(Result&: Ret, Info, S: Definition->getBody()) != ESR_Failed &&
6582 LifetimeExtendedScope.destroy();
6583}
6584
6585static bool HandleConstructorCall(const Expr *E, const LValue &This,
6586 ArrayRef<const Expr*> Args,
6587 const CXXConstructorDecl *Definition,
6588 EvalInfo &Info, APValue &Result) {
6589 CallScopeRAII CallScope(Info);
6590 CallRef Call = Info.CurrentCall->createCall(Callee: Definition);
6591 if (!EvaluateArgs(Args, Call, Info, Callee: Definition))
6592 return false;
6593
6594 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6595 CallScope.destroy();
6596}
6597
6598static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6599 const LValue &This, APValue &Value,
6600 QualType T) {
6601 // Objects can only be destroyed while they're within their lifetimes.
6602 // FIXME: We have no representation for whether an object of type nullptr_t
6603 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6604 // as indeterminate instead?
6605 if (Value.isAbsent() && !T->isNullPtrType()) {
6606 APValue Printable;
6607 This.moveInto(V&: Printable);
6608 Info.FFDiag(Loc: CallRange.getBegin(),
6609 DiagId: diag::note_constexpr_destroy_out_of_lifetime)
6610 << Printable.getAsString(Ctx: Info.Ctx, Ty: Info.Ctx.getLValueReferenceType(T));
6611 return false;
6612 }
6613
6614 // Invent an expression for location purposes.
6615 // FIXME: We shouldn't need to do this.
6616 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6617
6618 // For arrays, destroy elements right-to-left.
6619 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6620 uint64_t Size = CAT->getZExtSize();
6621 QualType ElemT = CAT->getElementType();
6622
6623 if (!CheckArraySize(Info, CAT, CallLoc: CallRange.getBegin()))
6624 return false;
6625
6626 LValue ElemLV = This;
6627 ElemLV.addArray(Info, E: &LocE, CAT);
6628 if (!HandleLValueArrayAdjustment(Info, E: &LocE, LVal&: ElemLV, EltTy: ElemT, Adjustment: Size))
6629 return false;
6630
6631 // Ensure that we have actual array elements available to destroy; the
6632 // destructors might mutate the value, so we can't run them on the array
6633 // filler.
6634 if (Size && Size > Value.getArrayInitializedElts())
6635 expandArray(Array&: Value, Index: Value.getArraySize() - 1);
6636
6637 for (; Size != 0; --Size) {
6638 APValue &Elem = Value.getArrayInitializedElt(I: Size - 1);
6639 if (!HandleLValueArrayAdjustment(Info, E: &LocE, LVal&: ElemLV, EltTy: ElemT, Adjustment: -1) ||
6640 !HandleDestructionImpl(Info, CallRange, This: ElemLV, Value&: Elem, T: ElemT))
6641 return false;
6642 }
6643
6644 // End the lifetime of this array now.
6645 Value = APValue();
6646 return true;
6647 }
6648
6649 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6650 if (!RD) {
6651 if (T.isDestructedType()) {
6652 Info.FFDiag(Loc: CallRange.getBegin(),
6653 DiagId: diag::note_constexpr_unsupported_destruction)
6654 << T;
6655 return false;
6656 }
6657
6658 Value = APValue();
6659 return true;
6660 }
6661
6662 if (RD->getNumVBases()) {
6663 Info.FFDiag(Loc: CallRange.getBegin(), DiagId: diag::note_constexpr_virtual_base) << RD;
6664 return false;
6665 }
6666
6667 const CXXDestructorDecl *DD = RD->getDestructor();
6668 if (!DD && !RD->hasTrivialDestructor()) {
6669 Info.FFDiag(Loc: CallRange.getBegin());
6670 return false;
6671 }
6672
6673 if (!DD || DD->isTrivial() ||
6674 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6675 // A trivial destructor just ends the lifetime of the object. Check for
6676 // this case before checking for a body, because we might not bother
6677 // building a body for a trivial destructor. Note that it doesn't matter
6678 // whether the destructor is constexpr in this case; all trivial
6679 // destructors are constexpr.
6680 //
6681 // If an anonymous union would be destroyed, some enclosing destructor must
6682 // have been explicitly defined, and the anonymous union destruction should
6683 // have no effect.
6684 Value = APValue();
6685 return true;
6686 }
6687
6688 if (!Info.CheckCallLimit(Loc: CallRange.getBegin()))
6689 return false;
6690
6691 const FunctionDecl *Definition = nullptr;
6692 const Stmt *Body = DD->getBody(Definition);
6693
6694 if (!CheckConstexprFunction(Info, CallLoc: CallRange.getBegin(), Declaration: DD, Definition, Body))
6695 return false;
6696
6697 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6698 CallRef());
6699
6700 // We're now in the period of destruction of this object.
6701 unsigned BasesLeft = RD->getNumBases();
6702 EvalInfo::EvaluatingDestructorRAII EvalObj(
6703 Info,
6704 ObjectUnderConstruction{.Base: This.getLValueBase(), .Path: This.Designator.Entries});
6705 if (!EvalObj.DidInsert) {
6706 // C++2a [class.dtor]p19:
6707 // the behavior is undefined if the destructor is invoked for an object
6708 // whose lifetime has ended
6709 // (Note that formally the lifetime ends when the period of destruction
6710 // begins, even though certain uses of the object remain valid until the
6711 // period of destruction ends.)
6712 Info.FFDiag(Loc: CallRange.getBegin(), DiagId: diag::note_constexpr_double_destroy);
6713 return false;
6714 }
6715
6716 // FIXME: Creating an APValue just to hold a nonexistent return value is
6717 // wasteful.
6718 APValue RetVal;
6719 StmtResult Ret = {.Value: RetVal, .Slot: nullptr};
6720 if (EvaluateStmt(Result&: Ret, Info, S: Definition->getBody()) == ESR_Failed)
6721 return false;
6722
6723 // A union destructor does not implicitly destroy its members.
6724 if (RD->isUnion())
6725 return true;
6726
6727 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD);
6728
6729 // We don't have a good way to iterate fields in reverse, so collect all the
6730 // fields first and then walk them backwards.
6731 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6732 for (const FieldDecl *FD : llvm::reverse(C&: Fields)) {
6733 if (FD->isUnnamedBitField())
6734 continue;
6735
6736 LValue Subobject = This;
6737 if (!HandleLValueMember(Info, E: &LocE, LVal&: Subobject, FD, RL: &Layout))
6738 return false;
6739
6740 APValue *SubobjectValue = &Value.getStructField(i: FD->getFieldIndex());
6741 if (!HandleDestructionImpl(Info, CallRange, This: Subobject, Value&: *SubobjectValue,
6742 T: FD->getType()))
6743 return false;
6744 }
6745
6746 if (BasesLeft != 0)
6747 EvalObj.startedDestroyingBases();
6748
6749 // Destroy base classes in reverse order.
6750 for (const CXXBaseSpecifier &Base : llvm::reverse(C: RD->bases())) {
6751 --BasesLeft;
6752
6753 QualType BaseType = Base.getType();
6754 LValue Subobject = This;
6755 if (!HandleLValueDirectBase(Info, E: &LocE, Obj&: Subobject, Derived: RD,
6756 Base: BaseType->getAsCXXRecordDecl(), RL: &Layout))
6757 return false;
6758
6759 APValue *SubobjectValue = &Value.getStructBase(i: BasesLeft);
6760 if (!HandleDestructionImpl(Info, CallRange, This: Subobject, Value&: *SubobjectValue,
6761 T: BaseType))
6762 return false;
6763 }
6764 assert(BasesLeft == 0 && "NumBases was wrong?");
6765
6766 // The period of destruction ends now. The object is gone.
6767 Value = APValue();
6768 return true;
6769}
6770
6771namespace {
6772struct DestroyObjectHandler {
6773 EvalInfo &Info;
6774 const Expr *E;
6775 const LValue &This;
6776 const AccessKinds AccessKind;
6777
6778 typedef bool result_type;
6779 bool failed() { return false; }
6780 bool found(APValue &Subobj, QualType SubobjType) {
6781 return HandleDestructionImpl(Info, CallRange: E->getSourceRange(), This, Value&: Subobj,
6782 T: SubobjType);
6783 }
6784 bool found(APSInt &Value, QualType SubobjType) {
6785 Info.FFDiag(E, DiagId: diag::note_constexpr_destroy_complex_elem);
6786 return false;
6787 }
6788 bool found(APFloat &Value, QualType SubobjType) {
6789 Info.FFDiag(E, DiagId: diag::note_constexpr_destroy_complex_elem);
6790 return false;
6791 }
6792};
6793}
6794
6795/// Perform a destructor or pseudo-destructor call on the given object, which
6796/// might in general not be a complete object.
6797static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6798 const LValue &This, QualType ThisType) {
6799 CompleteObject Obj = findCompleteObject(Info, E, AK: AK_Destroy, LVal: This, LValType: ThisType);
6800 DestroyObjectHandler Handler = {.Info: Info, .E: E, .This: This, .AccessKind: AK_Destroy};
6801 return Obj && findSubobject(Info, E, Obj, Sub: This.Designator, handler&: Handler);
6802}
6803
6804/// Destroy and end the lifetime of the given complete object.
6805static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6806 APValue::LValueBase LVBase, APValue &Value,
6807 QualType T) {
6808 // If we've had an unmodeled side-effect, we can't rely on mutable state
6809 // (such as the object we're about to destroy) being correct.
6810 if (Info.EvalStatus.HasSideEffects)
6811 return false;
6812
6813 LValue LV;
6814 LV.set(B: {LVBase});
6815 return HandleDestructionImpl(Info, CallRange: Loc, This: LV, Value, T);
6816}
6817
6818/// Perform a call to 'operator new' or to `__builtin_operator_new'.
6819static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6820 LValue &Result) {
6821 if (Info.checkingPotentialConstantExpression() ||
6822 Info.SpeculativeEvaluationDepth)
6823 return false;
6824
6825 // This is permitted only within a call to std::allocator<T>::allocate.
6826 auto Caller = Info.getStdAllocatorCaller(FnName: "allocate");
6827 if (!Caller) {
6828 Info.FFDiag(Loc: E->getExprLoc(), DiagId: Info.getLangOpts().CPlusPlus20
6829 ? diag::note_constexpr_new_untyped
6830 : diag::note_constexpr_new);
6831 return false;
6832 }
6833
6834 QualType ElemType = Caller.ElemType;
6835 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6836 Info.FFDiag(Loc: E->getExprLoc(),
6837 DiagId: diag::note_constexpr_new_not_complete_object_type)
6838 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6839 return false;
6840 }
6841
6842 APSInt ByteSize;
6843 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: ByteSize, Info))
6844 return false;
6845 bool IsNothrow = false;
6846 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6847 EvaluateIgnoredValue(Info, E: E->getArg(Arg: I));
6848 IsNothrow |= E->getType()->isNothrowT();
6849 }
6850
6851 CharUnits ElemSize;
6852 if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: ElemType, Size&: ElemSize))
6853 return false;
6854 APInt Size, Remainder;
6855 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6856 APInt::udivrem(LHS: ByteSize, RHS: ElemSizeAP, Quotient&: Size, Remainder);
6857 if (Remainder != 0) {
6858 // This likely indicates a bug in the implementation of 'std::allocator'.
6859 Info.FFDiag(Loc: E->getExprLoc(), DiagId: diag::note_constexpr_operator_new_bad_size)
6860 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6861 return false;
6862 }
6863
6864 if (!Info.CheckArraySize(Loc: E->getBeginLoc(), BitWidth: ByteSize.getActiveBits(),
6865 ElemCount: Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
6866 if (IsNothrow) {
6867 Result.setNull(Ctx&: Info.Ctx, PointerTy: E->getType());
6868 return true;
6869 }
6870 return false;
6871 }
6872
6873 QualType AllocType = Info.Ctx.getConstantArrayType(
6874 EltTy: ElemType, ArySize: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6875 APValue *Val = Info.createHeapAlloc(E, T: AllocType, LV&: Result);
6876 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6877 Result.addArray(Info, E, CAT: cast<ConstantArrayType>(Val&: AllocType));
6878 return true;
6879}
6880
6881static bool hasVirtualDestructor(QualType T) {
6882 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6883 if (CXXDestructorDecl *DD = RD->getDestructor())
6884 return DD->isVirtual();
6885 return false;
6886}
6887
6888static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6889 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6890 if (CXXDestructorDecl *DD = RD->getDestructor())
6891 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6892 return nullptr;
6893}
6894
6895/// Check that the given object is a suitable pointer to a heap allocation that
6896/// still exists and is of the right kind for the purpose of a deletion.
6897///
6898/// On success, returns the heap allocation to deallocate. On failure, produces
6899/// a diagnostic and returns std::nullopt.
6900static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6901 const LValue &Pointer,
6902 DynAlloc::Kind DeallocKind) {
6903 auto PointerAsString = [&] {
6904 return Pointer.toString(Ctx&: Info.Ctx, T: Info.Ctx.VoidPtrTy);
6905 };
6906
6907 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6908 if (!DA) {
6909 Info.FFDiag(E, DiagId: diag::note_constexpr_delete_not_heap_alloc)
6910 << PointerAsString();
6911 if (Pointer.Base)
6912 NoteLValueLocation(Info, Base: Pointer.Base);
6913 return std::nullopt;
6914 }
6915
6916 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6917 if (!Alloc) {
6918 Info.FFDiag(E, DiagId: diag::note_constexpr_double_delete);
6919 return std::nullopt;
6920 }
6921
6922 if (DeallocKind != (*Alloc)->getKind()) {
6923 QualType AllocType = Pointer.Base.getDynamicAllocType();
6924 Info.FFDiag(E, DiagId: diag::note_constexpr_new_delete_mismatch)
6925 << DeallocKind << (*Alloc)->getKind() << AllocType;
6926 NoteLValueLocation(Info, Base: Pointer.Base);
6927 return std::nullopt;
6928 }
6929
6930 bool Subobject = false;
6931 if (DeallocKind == DynAlloc::New) {
6932 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6933 Pointer.Designator.isOnePastTheEnd();
6934 } else {
6935 Subobject = Pointer.Designator.Entries.size() != 1 ||
6936 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6937 }
6938 if (Subobject) {
6939 Info.FFDiag(E, DiagId: diag::note_constexpr_delete_subobject)
6940 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6941 return std::nullopt;
6942 }
6943
6944 return Alloc;
6945}
6946
6947// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6948bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6949 if (Info.checkingPotentialConstantExpression() ||
6950 Info.SpeculativeEvaluationDepth)
6951 return false;
6952
6953 // This is permitted only within a call to std::allocator<T>::deallocate.
6954 if (!Info.getStdAllocatorCaller(FnName: "deallocate")) {
6955 Info.FFDiag(Loc: E->getExprLoc());
6956 return true;
6957 }
6958
6959 LValue Pointer;
6960 if (!EvaluatePointer(E: E->getArg(Arg: 0), Result&: Pointer, Info))
6961 return false;
6962 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6963 EvaluateIgnoredValue(Info, E: E->getArg(Arg: I));
6964
6965 if (Pointer.Designator.Invalid)
6966 return false;
6967
6968 // Deleting a null pointer would have no effect, but it's not permitted by
6969 // std::allocator<T>::deallocate's contract.
6970 if (Pointer.isNullPointer()) {
6971 Info.CCEDiag(Loc: E->getExprLoc(), DiagId: diag::note_constexpr_deallocate_null);
6972 return true;
6973 }
6974
6975 if (!CheckDeleteKind(Info, E, Pointer, DeallocKind: DynAlloc::StdAllocator))
6976 return false;
6977
6978 Info.HeapAllocs.erase(x: Pointer.Base.get<DynamicAllocLValue>());
6979 return true;
6980}
6981
6982//===----------------------------------------------------------------------===//
6983// Generic Evaluation
6984//===----------------------------------------------------------------------===//
6985namespace {
6986
6987class BitCastBuffer {
6988 // FIXME: We're going to need bit-level granularity when we support
6989 // bit-fields.
6990 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6991 // we don't support a host or target where that is the case. Still, we should
6992 // use a more generic type in case we ever do.
6993 SmallVector<std::optional<unsigned char>, 32> Bytes;
6994
6995 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6996 "Need at least 8 bit unsigned char");
6997
6998 bool TargetIsLittleEndian;
6999
7000public:
7001 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7002 : Bytes(Width.getQuantity()),
7003 TargetIsLittleEndian(TargetIsLittleEndian) {}
7004
7005 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7006 SmallVectorImpl<unsigned char> &Output) const {
7007 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7008 // If a byte of an integer is uninitialized, then the whole integer is
7009 // uninitialized.
7010 if (!Bytes[I.getQuantity()])
7011 return false;
7012 Output.push_back(Elt: *Bytes[I.getQuantity()]);
7013 }
7014 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7015 std::reverse(first: Output.begin(), last: Output.end());
7016 return true;
7017 }
7018
7019 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7020 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7021 std::reverse(first: Input.begin(), last: Input.end());
7022
7023 size_t Index = 0;
7024 for (unsigned char Byte : Input) {
7025 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7026 Bytes[Offset.getQuantity() + Index] = Byte;
7027 ++Index;
7028 }
7029 }
7030
7031 size_t size() { return Bytes.size(); }
7032};
7033
7034/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7035/// target would represent the value at runtime.
7036class APValueToBufferConverter {
7037 EvalInfo &Info;
7038 BitCastBuffer Buffer;
7039 const CastExpr *BCE;
7040
7041 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7042 const CastExpr *BCE)
7043 : Info(Info),
7044 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7045 BCE(BCE) {}
7046
7047 bool visit(const APValue &Val, QualType Ty) {
7048 return visit(Val, Ty, Offset: CharUnits::fromQuantity(Quantity: 0));
7049 }
7050
7051 // Write out Val with type Ty into Buffer starting at Offset.
7052 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7053 assert((size_t)Offset.getQuantity() <= Buffer.size());
7054
7055 // As a special case, nullptr_t has an indeterminate value.
7056 if (Ty->isNullPtrType())
7057 return true;
7058
7059 // Dig through Src to find the byte at SrcOffset.
7060 switch (Val.getKind()) {
7061 case APValue::Indeterminate:
7062 case APValue::None:
7063 return true;
7064
7065 case APValue::Int:
7066 return visitInt(Val: Val.getInt(), Ty, Offset);
7067 case APValue::Float:
7068 return visitFloat(Val: Val.getFloat(), Ty, Offset);
7069 case APValue::Array:
7070 return visitArray(Val, Ty, Offset);
7071 case APValue::Struct:
7072 return visitRecord(Val, Ty, Offset);
7073 case APValue::Vector:
7074 return visitVector(Val, Ty, Offset);
7075
7076 case APValue::ComplexInt:
7077 case APValue::ComplexFloat:
7078 case APValue::FixedPoint:
7079 // FIXME: We should support these.
7080
7081 case APValue::Union:
7082 case APValue::MemberPointer:
7083 case APValue::AddrLabelDiff: {
7084 Info.FFDiag(Loc: BCE->getBeginLoc(),
7085 DiagId: diag::note_constexpr_bit_cast_unsupported_type)
7086 << Ty;
7087 return false;
7088 }
7089
7090 case APValue::LValue:
7091 llvm_unreachable("LValue subobject in bit_cast?");
7092 }
7093 llvm_unreachable("Unhandled APValue::ValueKind");
7094 }
7095
7096 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7097 const RecordDecl *RD = Ty->getAsRecordDecl();
7098 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD);
7099
7100 // Visit the base classes.
7101 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
7102 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7103 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7104 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7105
7106 if (!visitRecord(Val: Val.getStructBase(i: I), Ty: BS.getType(),
7107 Offset: Layout.getBaseClassOffset(Base: BaseDecl) + Offset))
7108 return false;
7109 }
7110 }
7111
7112 // Visit the fields.
7113 unsigned FieldIdx = 0;
7114 for (FieldDecl *FD : RD->fields()) {
7115 if (FD->isBitField()) {
7116 Info.FFDiag(Loc: BCE->getBeginLoc(),
7117 DiagId: diag::note_constexpr_bit_cast_unsupported_bitfield);
7118 return false;
7119 }
7120
7121 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldNo: FieldIdx);
7122
7123 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7124 "only bit-fields can have sub-char alignment");
7125 CharUnits FieldOffset =
7126 Info.Ctx.toCharUnitsFromBits(BitSize: FieldOffsetBits) + Offset;
7127 QualType FieldTy = FD->getType();
7128 if (!visit(Val: Val.getStructField(i: FieldIdx), Ty: FieldTy, Offset: FieldOffset))
7129 return false;
7130 ++FieldIdx;
7131 }
7132
7133 return true;
7134 }
7135
7136 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7137 const auto *CAT =
7138 dyn_cast_or_null<ConstantArrayType>(Val: Ty->getAsArrayTypeUnsafe());
7139 if (!CAT)
7140 return false;
7141
7142 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(T: CAT->getElementType());
7143 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7144 unsigned ArraySize = Val.getArraySize();
7145 // First, initialize the initialized elements.
7146 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7147 const APValue &SubObj = Val.getArrayInitializedElt(I);
7148 if (!visit(Val: SubObj, Ty: CAT->getElementType(), Offset: Offset + I * ElemWidth))
7149 return false;
7150 }
7151
7152 // Next, initialize the rest of the array using the filler.
7153 if (Val.hasArrayFiller()) {
7154 const APValue &Filler = Val.getArrayFiller();
7155 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7156 if (!visit(Val: Filler, Ty: CAT->getElementType(), Offset: Offset + I * ElemWidth))
7157 return false;
7158 }
7159 }
7160
7161 return true;
7162 }
7163
7164 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7165 const VectorType *VTy = Ty->castAs<VectorType>();
7166 QualType EltTy = VTy->getElementType();
7167 unsigned NElts = VTy->getNumElements();
7168 unsigned EltSize =
7169 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(T: EltTy);
7170
7171 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7172 // The vector's size in bits is not a multiple of the target's byte size,
7173 // so its layout is unspecified. For now, we'll simply treat these cases
7174 // as unsupported (this should only be possible with OpenCL bool vectors
7175 // whose element count isn't a multiple of the byte size).
7176 Info.FFDiag(Loc: BCE->getBeginLoc(),
7177 DiagId: diag::note_constexpr_bit_cast_invalid_vector)
7178 << Ty.getCanonicalType() << EltSize << NElts
7179 << Info.Ctx.getCharWidth();
7180 return false;
7181 }
7182
7183 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(T: EltTy) ==
7184 &APFloat::x87DoubleExtended()) {
7185 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7186 // by both clang and LLVM, so for now we won't allow bit_casts involving
7187 // it in a constexpr context.
7188 Info.FFDiag(Loc: BCE->getBeginLoc(),
7189 DiagId: diag::note_constexpr_bit_cast_unsupported_type)
7190 << EltTy;
7191 return false;
7192 }
7193
7194 if (VTy->isExtVectorBoolType()) {
7195 // Special handling for OpenCL bool vectors:
7196 // Since these vectors are stored as packed bits, but we can't write
7197 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7198 // together into an appropriately sized APInt and write them all out at
7199 // once. Because we don't accept vectors where NElts * EltSize isn't a
7200 // multiple of the char size, there will be no padding space, so we don't
7201 // have to worry about writing data which should have been left
7202 // uninitialized.
7203 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7204
7205 llvm::APInt Res = llvm::APInt::getZero(numBits: NElts);
7206 for (unsigned I = 0; I < NElts; ++I) {
7207 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7208 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7209 "bool vector element must be 1-bit unsigned integer!");
7210
7211 Res.insertBits(SubBits: EltAsInt, bitPosition: BigEndian ? (NElts - I - 1) : I);
7212 }
7213
7214 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7215 llvm::StoreIntToMemory(IntVal: Res, Dst: &*Bytes.begin(), StoreBytes: NElts / 8);
7216 Buffer.writeObject(Offset, Input&: Bytes);
7217 } else {
7218 // Iterate over each of the elements and write them out to the buffer at
7219 // the appropriate offset.
7220 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(T: EltTy);
7221 for (unsigned I = 0; I < NElts; ++I) {
7222 if (!visit(Val: Val.getVectorElt(I), Ty: EltTy, Offset: Offset + I * EltSizeChars))
7223 return false;
7224 }
7225 }
7226
7227 return true;
7228 }
7229
7230 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7231 APSInt AdjustedVal = Val;
7232 unsigned Width = AdjustedVal.getBitWidth();
7233 if (Ty->isBooleanType()) {
7234 Width = Info.Ctx.getTypeSize(T: Ty);
7235 AdjustedVal = AdjustedVal.extend(width: Width);
7236 }
7237
7238 SmallVector<uint8_t, 8> Bytes(Width / 8);
7239 llvm::StoreIntToMemory(IntVal: AdjustedVal, Dst: &*Bytes.begin(), StoreBytes: Width / 8);
7240 Buffer.writeObject(Offset, Input&: Bytes);
7241 return true;
7242 }
7243
7244 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7245 APSInt AsInt(Val.bitcastToAPInt());
7246 return visitInt(Val: AsInt, Ty, Offset);
7247 }
7248
7249public:
7250 static std::optional<BitCastBuffer>
7251 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7252 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(T: BCE->getType());
7253 APValueToBufferConverter Converter(Info, DstSize, BCE);
7254 if (!Converter.visit(Val: Src, Ty: BCE->getSubExpr()->getType()))
7255 return std::nullopt;
7256 return Converter.Buffer;
7257 }
7258};
7259
7260/// Write an BitCastBuffer into an APValue.
7261class BufferToAPValueConverter {
7262 EvalInfo &Info;
7263 const BitCastBuffer &Buffer;
7264 const CastExpr *BCE;
7265
7266 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7267 const CastExpr *BCE)
7268 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7269
7270 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7271 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7272 // Ideally this will be unreachable.
7273 std::nullopt_t unsupportedType(QualType Ty) {
7274 Info.FFDiag(Loc: BCE->getBeginLoc(),
7275 DiagId: diag::note_constexpr_bit_cast_unsupported_type)
7276 << Ty;
7277 return std::nullopt;
7278 }
7279
7280 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7281 Info.FFDiag(Loc: BCE->getBeginLoc(),
7282 DiagId: diag::note_constexpr_bit_cast_unrepresentable_value)
7283 << Ty << toString(I: Val, /*Radix=*/10);
7284 return std::nullopt;
7285 }
7286
7287 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7288 const EnumType *EnumSugar = nullptr) {
7289 if (T->isNullPtrType()) {
7290 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QT: QualType(T, 0));
7291 return APValue((Expr *)nullptr,
7292 /*Offset=*/CharUnits::fromQuantity(Quantity: NullValue),
7293 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7294 }
7295
7296 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7297
7298 // Work around floating point types that contain unused padding bytes. This
7299 // is really just `long double` on x86, which is the only fundamental type
7300 // with padding bytes.
7301 if (T->isRealFloatingType()) {
7302 const llvm::fltSemantics &Semantics =
7303 Info.Ctx.getFloatTypeSemantics(T: QualType(T, 0));
7304 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Sem: Semantics);
7305 assert(NumBits % 8 == 0);
7306 CharUnits NumBytes = CharUnits::fromQuantity(Quantity: NumBits / 8);
7307 if (NumBytes != SizeOf)
7308 SizeOf = NumBytes;
7309 }
7310
7311 SmallVector<uint8_t, 8> Bytes;
7312 if (!Buffer.readObject(Offset, Width: SizeOf, Output&: Bytes)) {
7313 // If this is std::byte or unsigned char, then its okay to store an
7314 // indeterminate value.
7315 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7316 bool IsUChar =
7317 !EnumSugar && (T->isSpecificBuiltinType(K: BuiltinType::UChar) ||
7318 T->isSpecificBuiltinType(K: BuiltinType::Char_U));
7319 if (!IsStdByte && !IsUChar) {
7320 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7321 Info.FFDiag(Loc: BCE->getExprLoc(),
7322 DiagId: diag::note_constexpr_bit_cast_indet_dest)
7323 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7324 return std::nullopt;
7325 }
7326
7327 return APValue::IndeterminateValue();
7328 }
7329
7330 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7331 llvm::LoadIntFromMemory(IntVal&: Val, Src: &*Bytes.begin(), LoadBytes: Bytes.size());
7332
7333 if (T->isIntegralOrEnumerationType()) {
7334 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7335
7336 unsigned IntWidth = Info.Ctx.getIntWidth(T: QualType(T, 0));
7337 if (IntWidth != Val.getBitWidth()) {
7338 APSInt Truncated = Val.trunc(width: IntWidth);
7339 if (Truncated.extend(width: Val.getBitWidth()) != Val)
7340 return unrepresentableValue(Ty: QualType(T, 0), Val);
7341 Val = Truncated;
7342 }
7343
7344 return APValue(Val);
7345 }
7346
7347 if (T->isRealFloatingType()) {
7348 const llvm::fltSemantics &Semantics =
7349 Info.Ctx.getFloatTypeSemantics(T: QualType(T, 0));
7350 return APValue(APFloat(Semantics, Val));
7351 }
7352
7353 return unsupportedType(Ty: QualType(T, 0));
7354 }
7355
7356 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7357 const RecordDecl *RD = RTy->getAsRecordDecl();
7358 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD);
7359
7360 unsigned NumBases = 0;
7361 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
7362 NumBases = CXXRD->getNumBases();
7363
7364 APValue ResultVal(APValue::UninitStruct(), NumBases,
7365 std::distance(first: RD->field_begin(), last: RD->field_end()));
7366
7367 // Visit the base classes.
7368 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
7369 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7370 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7371 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7372
7373 std::optional<APValue> SubObj = visitType(
7374 Ty: BS.getType(), Offset: Layout.getBaseClassOffset(Base: BaseDecl) + Offset);
7375 if (!SubObj)
7376 return std::nullopt;
7377 ResultVal.getStructBase(i: I) = *SubObj;
7378 }
7379 }
7380
7381 // Visit the fields.
7382 unsigned FieldIdx = 0;
7383 for (FieldDecl *FD : RD->fields()) {
7384 // FIXME: We don't currently support bit-fields. A lot of the logic for
7385 // this is in CodeGen, so we need to factor it around.
7386 if (FD->isBitField()) {
7387 Info.FFDiag(Loc: BCE->getBeginLoc(),
7388 DiagId: diag::note_constexpr_bit_cast_unsupported_bitfield);
7389 return std::nullopt;
7390 }
7391
7392 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldNo: FieldIdx);
7393 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7394
7395 CharUnits FieldOffset =
7396 CharUnits::fromQuantity(Quantity: FieldOffsetBits / Info.Ctx.getCharWidth()) +
7397 Offset;
7398 QualType FieldTy = FD->getType();
7399 std::optional<APValue> SubObj = visitType(Ty: FieldTy, Offset: FieldOffset);
7400 if (!SubObj)
7401 return std::nullopt;
7402 ResultVal.getStructField(i: FieldIdx) = *SubObj;
7403 ++FieldIdx;
7404 }
7405
7406 return ResultVal;
7407 }
7408
7409 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7410 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7411 assert(!RepresentationType.isNull() &&
7412 "enum forward decl should be caught by Sema");
7413 const auto *AsBuiltin =
7414 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7415 // Recurse into the underlying type. Treat std::byte transparently as
7416 // unsigned char.
7417 return visit(T: AsBuiltin, Offset, /*EnumTy=*/EnumSugar: Ty);
7418 }
7419
7420 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7421 size_t Size = Ty->getLimitedSize();
7422 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(T: Ty->getElementType());
7423
7424 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7425 for (size_t I = 0; I != Size; ++I) {
7426 std::optional<APValue> ElementValue =
7427 visitType(Ty: Ty->getElementType(), Offset: Offset + I * ElementWidth);
7428 if (!ElementValue)
7429 return std::nullopt;
7430 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7431 }
7432
7433 return ArrayValue;
7434 }
7435
7436 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7437 QualType EltTy = VTy->getElementType();
7438 unsigned NElts = VTy->getNumElements();
7439 unsigned EltSize =
7440 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(T: EltTy);
7441
7442 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7443 // The vector's size in bits is not a multiple of the target's byte size,
7444 // so its layout is unspecified. For now, we'll simply treat these cases
7445 // as unsupported (this should only be possible with OpenCL bool vectors
7446 // whose element count isn't a multiple of the byte size).
7447 Info.FFDiag(Loc: BCE->getBeginLoc(),
7448 DiagId: diag::note_constexpr_bit_cast_invalid_vector)
7449 << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();
7450 return std::nullopt;
7451 }
7452
7453 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(T: EltTy) ==
7454 &APFloat::x87DoubleExtended()) {
7455 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7456 // by both clang and LLVM, so for now we won't allow bit_casts involving
7457 // it in a constexpr context.
7458 Info.FFDiag(Loc: BCE->getBeginLoc(),
7459 DiagId: diag::note_constexpr_bit_cast_unsupported_type)
7460 << EltTy;
7461 return std::nullopt;
7462 }
7463
7464 SmallVector<APValue, 4> Elts;
7465 Elts.reserve(N: NElts);
7466 if (VTy->isExtVectorBoolType()) {
7467 // Special handling for OpenCL bool vectors:
7468 // Since these vectors are stored as packed bits, but we can't read
7469 // individual bits from the BitCastBuffer, we'll buffer all of the
7470 // elements together into an appropriately sized APInt and write them all
7471 // out at once. Because we don't accept vectors where NElts * EltSize
7472 // isn't a multiple of the char size, there will be no padding space, so
7473 // we don't have to worry about reading any padding data which didn't
7474 // actually need to be accessed.
7475 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7476
7477 SmallVector<uint8_t, 8> Bytes;
7478 Bytes.reserve(N: NElts / 8);
7479 if (!Buffer.readObject(Offset, Width: CharUnits::fromQuantity(Quantity: NElts / 8), Output&: Bytes))
7480 return std::nullopt;
7481
7482 APSInt SValInt(NElts, true);
7483 llvm::LoadIntFromMemory(IntVal&: SValInt, Src: &*Bytes.begin(), LoadBytes: Bytes.size());
7484
7485 for (unsigned I = 0; I < NElts; ++I) {
7486 llvm::APInt Elt =
7487 SValInt.extractBits(numBits: 1, bitPosition: (BigEndian ? NElts - I - 1 : I) * EltSize);
7488 Elts.emplace_back(
7489 Args: APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7490 }
7491 } else {
7492 // Iterate over each of the elements and read them from the buffer at
7493 // the appropriate offset.
7494 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(T: EltTy);
7495 for (unsigned I = 0; I < NElts; ++I) {
7496 std::optional<APValue> EltValue =
7497 visitType(Ty: EltTy, Offset: Offset + I * EltSizeChars);
7498 if (!EltValue)
7499 return std::nullopt;
7500 Elts.push_back(Elt: std::move(*EltValue));
7501 }
7502 }
7503
7504 return APValue(Elts.data(), Elts.size());
7505 }
7506
7507 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7508 return unsupportedType(Ty: QualType(Ty, 0));
7509 }
7510
7511 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7512 QualType Can = Ty.getCanonicalType();
7513
7514 switch (Can->getTypeClass()) {
7515#define TYPE(Class, Base) \
7516 case Type::Class: \
7517 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7518#define ABSTRACT_TYPE(Class, Base)
7519#define NON_CANONICAL_TYPE(Class, Base) \
7520 case Type::Class: \
7521 llvm_unreachable("non-canonical type should be impossible!");
7522#define DEPENDENT_TYPE(Class, Base) \
7523 case Type::Class: \
7524 llvm_unreachable( \
7525 "dependent types aren't supported in the constant evaluator!");
7526#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7527 case Type::Class: \
7528 llvm_unreachable("either dependent or not canonical!");
7529#include "clang/AST/TypeNodes.inc"
7530 }
7531 llvm_unreachable("Unhandled Type::TypeClass");
7532 }
7533
7534public:
7535 // Pull out a full value of type DstType.
7536 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7537 const CastExpr *BCE) {
7538 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7539 return Converter.visitType(Ty: BCE->getType(), Offset: CharUnits::fromQuantity(Quantity: 0));
7540 }
7541};
7542
7543static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7544 QualType Ty, EvalInfo *Info,
7545 const ASTContext &Ctx,
7546 bool CheckingDest) {
7547 Ty = Ty.getCanonicalType();
7548
7549 auto diag = [&](int Reason) {
7550 if (Info)
7551 Info->FFDiag(Loc, DiagId: diag::note_constexpr_bit_cast_invalid_type)
7552 << CheckingDest << (Reason == 4) << Reason;
7553 return false;
7554 };
7555 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7556 if (Info)
7557 Info->Note(Loc: NoteLoc, DiagId: diag::note_constexpr_bit_cast_invalid_subtype)
7558 << NoteTy << Construct << Ty;
7559 return false;
7560 };
7561
7562 if (Ty->isUnionType())
7563 return diag(0);
7564 if (Ty->isPointerType())
7565 return diag(1);
7566 if (Ty->isMemberPointerType())
7567 return diag(2);
7568 if (Ty.isVolatileQualified())
7569 return diag(3);
7570
7571 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7572 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: Record)) {
7573 for (CXXBaseSpecifier &BS : CXXRD->bases())
7574 if (!checkBitCastConstexprEligibilityType(Loc, Ty: BS.getType(), Info, Ctx,
7575 CheckingDest))
7576 return note(1, BS.getType(), BS.getBeginLoc());
7577 }
7578 for (FieldDecl *FD : Record->fields()) {
7579 if (FD->getType()->isReferenceType())
7580 return diag(4);
7581 if (!checkBitCastConstexprEligibilityType(Loc, Ty: FD->getType(), Info, Ctx,
7582 CheckingDest))
7583 return note(0, FD->getType(), FD->getBeginLoc());
7584 }
7585 }
7586
7587 if (Ty->isArrayType() &&
7588 !checkBitCastConstexprEligibilityType(Loc, Ty: Ctx.getBaseElementType(QT: Ty),
7589 Info, Ctx, CheckingDest))
7590 return false;
7591
7592 return true;
7593}
7594
7595static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7596 const ASTContext &Ctx,
7597 const CastExpr *BCE) {
7598 bool DestOK = checkBitCastConstexprEligibilityType(
7599 Loc: BCE->getBeginLoc(), Ty: BCE->getType(), Info, Ctx, CheckingDest: true);
7600 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7601 Loc: BCE->getBeginLoc(),
7602 Ty: BCE->getSubExpr()->getType(), Info, Ctx, CheckingDest: false);
7603 return SourceOK;
7604}
7605
7606static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7607 const APValue &SourceRValue,
7608 const CastExpr *BCE) {
7609 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7610 "no host or target supports non 8-bit chars");
7611
7612 if (!checkBitCastConstexprEligibility(Info: &Info, Ctx: Info.Ctx, BCE))
7613 return false;
7614
7615 // Read out SourceValue into a char buffer.
7616 std::optional<BitCastBuffer> Buffer =
7617 APValueToBufferConverter::convert(Info, Src: SourceRValue, BCE);
7618 if (!Buffer)
7619 return false;
7620
7621 // Write out the buffer into a new APValue.
7622 std::optional<APValue> MaybeDestValue =
7623 BufferToAPValueConverter::convert(Info, Buffer&: *Buffer, BCE);
7624 if (!MaybeDestValue)
7625 return false;
7626
7627 DestValue = std::move(*MaybeDestValue);
7628 return true;
7629}
7630
7631static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7632 APValue &SourceValue,
7633 const CastExpr *BCE) {
7634 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7635 "no host or target supports non 8-bit chars");
7636 assert(SourceValue.isLValue() &&
7637 "LValueToRValueBitcast requires an lvalue operand!");
7638
7639 LValue SourceLValue;
7640 APValue SourceRValue;
7641 SourceLValue.setFrom(Ctx&: Info.Ctx, V: SourceValue);
7642 if (!handleLValueToRValueConversion(
7643 Info, Conv: BCE, Type: BCE->getSubExpr()->getType().withConst(), LVal: SourceLValue,
7644 RVal&: SourceRValue, /*WantObjectRepresentation=*/true))
7645 return false;
7646
7647 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7648}
7649
7650template <class Derived>
7651class ExprEvaluatorBase
7652 : public ConstStmtVisitor<Derived, bool> {
7653private:
7654 Derived &getDerived() { return static_cast<Derived&>(*this); }
7655 bool DerivedSuccess(const APValue &V, const Expr *E) {
7656 return getDerived().Success(V, E);
7657 }
7658 bool DerivedZeroInitialization(const Expr *E) {
7659 return getDerived().ZeroInitialization(E);
7660 }
7661
7662 // Check whether a conditional operator with a non-constant condition is a
7663 // potential constant expression. If neither arm is a potential constant
7664 // expression, then the conditional operator is not either.
7665 template<typename ConditionalOperator>
7666 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7667 assert(Info.checkingPotentialConstantExpression());
7668
7669 // Speculatively evaluate both arms.
7670 SmallVector<PartialDiagnosticAt, 8> Diag;
7671 {
7672 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7673 StmtVisitorTy::Visit(E->getFalseExpr());
7674 if (Diag.empty())
7675 return;
7676 }
7677
7678 {
7679 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7680 Diag.clear();
7681 StmtVisitorTy::Visit(E->getTrueExpr());
7682 if (Diag.empty())
7683 return;
7684 }
7685
7686 Error(E, diag::note_constexpr_conditional_never_const);
7687 }
7688
7689
7690 template<typename ConditionalOperator>
7691 bool HandleConditionalOperator(const ConditionalOperator *E) {
7692 bool BoolResult;
7693 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7694 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7695 CheckPotentialConstantConditional(E);
7696 return false;
7697 }
7698 if (Info.noteFailure()) {
7699 StmtVisitorTy::Visit(E->getTrueExpr());
7700 StmtVisitorTy::Visit(E->getFalseExpr());
7701 }
7702 return false;
7703 }
7704
7705 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7706 return StmtVisitorTy::Visit(EvalExpr);
7707 }
7708
7709protected:
7710 EvalInfo &Info;
7711 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7712 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7713
7714 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7715 return Info.CCEDiag(E, DiagId: D);
7716 }
7717
7718 bool ZeroInitialization(const Expr *E) { return Error(E); }
7719
7720 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7721 unsigned BuiltinOp = E->getBuiltinCallee();
7722 return BuiltinOp != 0 &&
7723 Info.Ctx.BuiltinInfo.isConstantEvaluated(ID: BuiltinOp);
7724 }
7725
7726public:
7727 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7728
7729 EvalInfo &getEvalInfo() { return Info; }
7730
7731 /// Report an evaluation error. This should only be called when an error is
7732 /// first discovered. When propagating an error, just return false.
7733 bool Error(const Expr *E, diag::kind D) {
7734 Info.FFDiag(E, DiagId: D) << E->getSourceRange();
7735 return false;
7736 }
7737 bool Error(const Expr *E) {
7738 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7739 }
7740
7741 bool VisitStmt(const Stmt *) {
7742 llvm_unreachable("Expression evaluator should not be called on stmts");
7743 }
7744 bool VisitExpr(const Expr *E) {
7745 return Error(E);
7746 }
7747
7748 bool VisitEmbedExpr(const EmbedExpr *E) {
7749 const auto It = E->begin();
7750 return StmtVisitorTy::Visit(*It);
7751 }
7752
7753 bool VisitPredefinedExpr(const PredefinedExpr *E) {
7754 return StmtVisitorTy::Visit(E->getFunctionName());
7755 }
7756 bool VisitConstantExpr(const ConstantExpr *E) {
7757 if (E->hasAPValueResult())
7758 return DerivedSuccess(V: E->getAPValueResult(), E);
7759
7760 return StmtVisitorTy::Visit(E->getSubExpr());
7761 }
7762
7763 bool VisitParenExpr(const ParenExpr *E)
7764 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7765 bool VisitUnaryExtension(const UnaryOperator *E)
7766 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7767 bool VisitUnaryPlus(const UnaryOperator *E)
7768 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7769 bool VisitChooseExpr(const ChooseExpr *E)
7770 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7771 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7772 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7773 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7774 { return StmtVisitorTy::Visit(E->getReplacement()); }
7775 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7776 TempVersionRAII RAII(*Info.CurrentCall);
7777 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7778 return StmtVisitorTy::Visit(E->getExpr());
7779 }
7780 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7781 TempVersionRAII RAII(*Info.CurrentCall);
7782 // The initializer may not have been parsed yet, or might be erroneous.
7783 if (!E->getExpr())
7784 return Error(E);
7785 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7786 return StmtVisitorTy::Visit(E->getExpr());
7787 }
7788
7789 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7790 FullExpressionRAII Scope(Info);
7791 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7792 }
7793
7794 // Temporaries are registered when created, so we don't care about
7795 // CXXBindTemporaryExpr.
7796 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7797 return StmtVisitorTy::Visit(E->getSubExpr());
7798 }
7799
7800 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7801 CCEDiag(E, D: diag::note_constexpr_invalid_cast) << 0;
7802 return static_cast<Derived*>(this)->VisitCastExpr(E);
7803 }
7804 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7805 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7806 CCEDiag(E, D: diag::note_constexpr_invalid_cast) << 1;
7807 return static_cast<Derived*>(this)->VisitCastExpr(E);
7808 }
7809 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7810 return static_cast<Derived*>(this)->VisitCastExpr(E);
7811 }
7812
7813 bool VisitBinaryOperator(const BinaryOperator *E) {
7814 switch (E->getOpcode()) {
7815 default:
7816 return Error(E);
7817
7818 case BO_Comma:
7819 VisitIgnoredValue(E: E->getLHS());
7820 return StmtVisitorTy::Visit(E->getRHS());
7821
7822 case BO_PtrMemD:
7823 case BO_PtrMemI: {
7824 LValue Obj;
7825 if (!HandleMemberPointerAccess(Info, BO: E, LV&: Obj))
7826 return false;
7827 APValue Result;
7828 if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getType(), LVal: Obj, RVal&: Result))
7829 return false;
7830 return DerivedSuccess(V: Result, E);
7831 }
7832 }
7833 }
7834
7835 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7836 return StmtVisitorTy::Visit(E->getSemanticForm());
7837 }
7838
7839 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7840 // Evaluate and cache the common expression. We treat it as a temporary,
7841 // even though it's not quite the same thing.
7842 LValue CommonLV;
7843 if (!Evaluate(Result&: Info.CurrentCall->createTemporary(
7844 Key: E->getOpaqueValue(),
7845 T: getStorageType(Ctx: Info.Ctx, E: E->getOpaqueValue()),
7846 Scope: ScopeKind::FullExpression, LV&: CommonLV),
7847 Info, E: E->getCommon()))
7848 return false;
7849
7850 return HandleConditionalOperator(E);
7851 }
7852
7853 bool VisitConditionalOperator(const ConditionalOperator *E) {
7854 bool IsBcpCall = false;
7855 // If the condition (ignoring parens) is a __builtin_constant_p call,
7856 // the result is a constant expression if it can be folded without
7857 // side-effects. This is an important GNU extension. See GCC PR38377
7858 // for discussion.
7859 if (const CallExpr *CallCE =
7860 dyn_cast<CallExpr>(Val: E->getCond()->IgnoreParenCasts()))
7861 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7862 IsBcpCall = true;
7863
7864 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7865 // constant expression; we can't check whether it's potentially foldable.
7866 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7867 // it would return 'false' in this mode.
7868 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7869 return false;
7870
7871 FoldConstant Fold(Info, IsBcpCall);
7872 if (!HandleConditionalOperator(E)) {
7873 Fold.keepDiagnostics();
7874 return false;
7875 }
7876
7877 return true;
7878 }
7879
7880 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7881 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(Key: E);
7882 Value && !Value->isAbsent())
7883 return DerivedSuccess(V: *Value, E);
7884
7885 const Expr *Source = E->getSourceExpr();
7886 if (!Source)
7887 return Error(E);
7888 if (Source == E) {
7889 assert(0 && "OpaqueValueExpr recursively refers to itself");
7890 return Error(E);
7891 }
7892 return StmtVisitorTy::Visit(Source);
7893 }
7894
7895 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7896 for (const Expr *SemE : E->semantics()) {
7897 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SemE)) {
7898 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7899 // result expression: there could be two different LValues that would
7900 // refer to the same object in that case, and we can't model that.
7901 if (SemE == E->getResultExpr())
7902 return Error(E);
7903
7904 // Unique OVEs get evaluated if and when we encounter them when
7905 // emitting the rest of the semantic form, rather than eagerly.
7906 if (OVE->isUnique())
7907 continue;
7908
7909 LValue LV;
7910 if (!Evaluate(Result&: Info.CurrentCall->createTemporary(
7911 Key: OVE, T: getStorageType(Ctx: Info.Ctx, E: OVE),
7912 Scope: ScopeKind::FullExpression, LV),
7913 Info, E: OVE->getSourceExpr()))
7914 return false;
7915 } else if (SemE == E->getResultExpr()) {
7916 if (!StmtVisitorTy::Visit(SemE))
7917 return false;
7918 } else {
7919 if (!EvaluateIgnoredValue(Info, E: SemE))
7920 return false;
7921 }
7922 }
7923 return true;
7924 }
7925
7926 bool VisitCallExpr(const CallExpr *E) {
7927 APValue Result;
7928 if (!handleCallExpr(E, Result, ResultSlot: nullptr))
7929 return false;
7930 return DerivedSuccess(V: Result, E);
7931 }
7932
7933 bool handleCallExpr(const CallExpr *E, APValue &Result,
7934 const LValue *ResultSlot) {
7935 CallScopeRAII CallScope(Info);
7936
7937 const Expr *Callee = E->getCallee()->IgnoreParens();
7938 QualType CalleeType = Callee->getType();
7939
7940 const FunctionDecl *FD = nullptr;
7941 LValue *This = nullptr, ThisVal;
7942 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7943 bool HasQualifier = false;
7944
7945 CallRef Call;
7946
7947 // Extract function decl and 'this' pointer from the callee.
7948 if (CalleeType->isSpecificBuiltinType(K: BuiltinType::BoundMember)) {
7949 const CXXMethodDecl *Member = nullptr;
7950 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: Callee)) {
7951 // Explicit bound member calls, such as x.f() or p->g();
7952 if (!EvaluateObjectArgument(Info, Object: ME->getBase(), This&: ThisVal))
7953 return false;
7954 Member = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
7955 if (!Member)
7956 return Error(Callee);
7957 This = &ThisVal;
7958 HasQualifier = ME->hasQualifier();
7959 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: Callee)) {
7960 // Indirect bound member calls ('.*' or '->*').
7961 const ValueDecl *D =
7962 HandleMemberPointerAccess(Info, BO: BE, LV&: ThisVal, IncludeMember: false);
7963 if (!D)
7964 return false;
7965 Member = dyn_cast<CXXMethodDecl>(Val: D);
7966 if (!Member)
7967 return Error(Callee);
7968 This = &ThisVal;
7969 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Val: Callee)) {
7970 if (!Info.getLangOpts().CPlusPlus20)
7971 Info.CCEDiag(E: PDE, DiagId: diag::note_constexpr_pseudo_destructor);
7972 return EvaluateObjectArgument(Info, Object: PDE->getBase(), This&: ThisVal) &&
7973 HandleDestruction(Info, E: PDE, This: ThisVal, ThisType: PDE->getDestroyedType());
7974 } else
7975 return Error(Callee);
7976 FD = Member;
7977 } else if (CalleeType->isFunctionPointerType()) {
7978 LValue CalleeLV;
7979 if (!EvaluatePointer(E: Callee, Result&: CalleeLV, Info))
7980 return false;
7981
7982 if (!CalleeLV.getLValueOffset().isZero())
7983 return Error(Callee);
7984 if (CalleeLV.isNullPointer()) {
7985 Info.FFDiag(E: Callee, DiagId: diag::note_constexpr_null_callee)
7986 << const_cast<Expr *>(Callee);
7987 return false;
7988 }
7989 FD = dyn_cast_or_null<FunctionDecl>(
7990 Val: CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7991 if (!FD)
7992 return Error(Callee);
7993 // Don't call function pointers which have been cast to some other type.
7994 // Per DR (no number yet), the caller and callee can differ in noexcept.
7995 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7996 T: CalleeType->getPointeeType(), U: FD->getType())) {
7997 return Error(E);
7998 }
7999
8000 // For an (overloaded) assignment expression, evaluate the RHS before the
8001 // LHS.
8002 auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: E);
8003 if (OCE && OCE->isAssignmentOp()) {
8004 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8005 Call = Info.CurrentCall->createCall(Callee: FD);
8006 bool HasThis = false;
8007 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
8008 HasThis = MD->isImplicitObjectMemberFunction();
8009 if (!EvaluateArgs(Args: HasThis ? Args.slice(N: 1) : Args, Call, Info, Callee: FD,
8010 /*RightToLeft=*/true))
8011 return false;
8012 }
8013
8014 // Overloaded operator calls to member functions are represented as normal
8015 // calls with '*this' as the first argument.
8016 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8017 if (MD &&
8018 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8019 // FIXME: When selecting an implicit conversion for an overloaded
8020 // operator delete, we sometimes try to evaluate calls to conversion
8021 // operators without a 'this' parameter!
8022 if (Args.empty())
8023 return Error(E);
8024
8025 if (!EvaluateObjectArgument(Info, Object: Args[0], This&: ThisVal))
8026 return false;
8027
8028 // If we are calling a static operator, the 'this' argument needs to be
8029 // ignored after being evaluated.
8030 if (MD->isInstance())
8031 This = &ThisVal;
8032
8033 // If this is syntactically a simple assignment using a trivial
8034 // assignment operator, start the lifetimes of union members as needed,
8035 // per C++20 [class.union]5.
8036 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8037 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8038 !MaybeHandleUnionActiveMemberChange(Info, LHSExpr: Args[0], LHS: ThisVal))
8039 return false;
8040
8041 Args = Args.slice(N: 1);
8042 } else if (MD && MD->isLambdaStaticInvoker()) {
8043 // Map the static invoker for the lambda back to the call operator.
8044 // Conveniently, we don't have to slice out the 'this' argument (as is
8045 // being done for the non-static case), since a static member function
8046 // doesn't have an implicit argument passed in.
8047 const CXXRecordDecl *ClosureClass = MD->getParent();
8048 assert(
8049 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8050 "Number of captures must be zero for conversion to function-ptr");
8051
8052 const CXXMethodDecl *LambdaCallOp =
8053 ClosureClass->getLambdaCallOperator();
8054
8055 // Set 'FD', the function that will be called below, to the call
8056 // operator. If the closure object represents a generic lambda, find
8057 // the corresponding specialization of the call operator.
8058
8059 if (ClosureClass->isGenericLambda()) {
8060 assert(MD->isFunctionTemplateSpecialization() &&
8061 "A generic lambda's static-invoker function must be a "
8062 "template specialization");
8063 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8064 FunctionTemplateDecl *CallOpTemplate =
8065 LambdaCallOp->getDescribedFunctionTemplate();
8066 void *InsertPos = nullptr;
8067 FunctionDecl *CorrespondingCallOpSpecialization =
8068 CallOpTemplate->findSpecialization(Args: TAL->asArray(), InsertPos);
8069 assert(CorrespondingCallOpSpecialization &&
8070 "We must always have a function call operator specialization "
8071 "that corresponds to our static invoker specialization");
8072 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8073 FD = CorrespondingCallOpSpecialization;
8074 } else
8075 FD = LambdaCallOp;
8076 } else if (FD->isReplaceableGlobalAllocationFunction()) {
8077 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8078 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8079 LValue Ptr;
8080 if (!HandleOperatorNewCall(Info, E, Result&: Ptr))
8081 return false;
8082 Ptr.moveInto(V&: Result);
8083 return CallScope.destroy();
8084 } else {
8085 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8086 }
8087 }
8088 } else
8089 return Error(E);
8090
8091 // Evaluate the arguments now if we've not already done so.
8092 if (!Call) {
8093 Call = Info.CurrentCall->createCall(Callee: FD);
8094 if (!EvaluateArgs(Args, Call, Info, Callee: FD))
8095 return false;
8096 }
8097
8098 SmallVector<QualType, 4> CovariantAdjustmentPath;
8099 if (This) {
8100 auto *NamedMember = dyn_cast<CXXMethodDecl>(Val: FD);
8101 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8102 // Perform virtual dispatch, if necessary.
8103 FD = HandleVirtualDispatch(Info, E, This&: *This, Found: NamedMember,
8104 CovariantAdjustmentPath);
8105 if (!FD)
8106 return false;
8107 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8108 // Check that the 'this' pointer points to an object of the right type.
8109 // FIXME: If this is an assignment operator call, we may need to change
8110 // the active union member before we check this.
8111 if (!checkNonVirtualMemberCallThisPointer(Info, E, This: *This, NamedMember))
8112 return false;
8113 }
8114 }
8115
8116 // Destructor calls are different enough that they have their own codepath.
8117 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: FD)) {
8118 assert(This && "no 'this' pointer for destructor call");
8119 return HandleDestruction(Info, E, This: *This,
8120 ThisType: Info.Ctx.getRecordType(Decl: DD->getParent())) &&
8121 CallScope.destroy();
8122 }
8123
8124 const FunctionDecl *Definition = nullptr;
8125 Stmt *Body = FD->getBody(Definition);
8126
8127 if (!CheckConstexprFunction(Info, CallLoc: E->getExprLoc(), Declaration: FD, Definition, Body) ||
8128 !HandleFunctionCall(CallLoc: E->getExprLoc(), Callee: Definition, This, E, Args, Call,
8129 Body, Info, Result, ResultSlot))
8130 return false;
8131
8132 if (!CovariantAdjustmentPath.empty() &&
8133 !HandleCovariantReturnAdjustment(Info, E, Result,
8134 Path: CovariantAdjustmentPath))
8135 return false;
8136
8137 return CallScope.destroy();
8138 }
8139
8140 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8141 return StmtVisitorTy::Visit(E->getInitializer());
8142 }
8143 bool VisitInitListExpr(const InitListExpr *E) {
8144 if (E->getNumInits() == 0)
8145 return DerivedZeroInitialization(E);
8146 if (E->getNumInits() == 1)
8147 return StmtVisitorTy::Visit(E->getInit(Init: 0));
8148 return Error(E);
8149 }
8150 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8151 return DerivedZeroInitialization(E);
8152 }
8153 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8154 return DerivedZeroInitialization(E);
8155 }
8156 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8157 return DerivedZeroInitialization(E);
8158 }
8159
8160 /// A member expression where the object is a prvalue is itself a prvalue.
8161 bool VisitMemberExpr(const MemberExpr *E) {
8162 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8163 "missing temporary materialization conversion");
8164 assert(!E->isArrow() && "missing call to bound member function?");
8165
8166 APValue Val;
8167 if (!Evaluate(Result&: Val, Info, E: E->getBase()))
8168 return false;
8169
8170 QualType BaseTy = E->getBase()->getType();
8171
8172 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: E->getMemberDecl());
8173 if (!FD) return Error(E);
8174 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8175 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8176 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8177
8178 // Note: there is no lvalue base here. But this case should only ever
8179 // happen in C or in C++98, where we cannot be evaluating a constexpr
8180 // constructor, which is the only case the base matters.
8181 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8182 SubobjectDesignator Designator(BaseTy);
8183 Designator.addDeclUnchecked(D: FD);
8184
8185 APValue Result;
8186 return extractSubobject(Info, E, Obj, Sub: Designator, Result) &&
8187 DerivedSuccess(V: Result, E);
8188 }
8189
8190 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8191 APValue Val;
8192 if (!Evaluate(Result&: Val, Info, E: E->getBase()))
8193 return false;
8194
8195 if (Val.isVector()) {
8196 SmallVector<uint32_t, 4> Indices;
8197 E->getEncodedElementAccess(Elts&: Indices);
8198 if (Indices.size() == 1) {
8199 // Return scalar.
8200 return DerivedSuccess(V: Val.getVectorElt(I: Indices[0]), E);
8201 } else {
8202 // Construct new APValue vector.
8203 SmallVector<APValue, 4> Elts;
8204 for (unsigned I = 0; I < Indices.size(); ++I) {
8205 Elts.push_back(Elt: Val.getVectorElt(I: Indices[I]));
8206 }
8207 APValue VecResult(Elts.data(), Indices.size());
8208 return DerivedSuccess(V: VecResult, E);
8209 }
8210 }
8211
8212 return false;
8213 }
8214
8215 bool VisitCastExpr(const CastExpr *E) {
8216 switch (E->getCastKind()) {
8217 default:
8218 break;
8219
8220 case CK_AtomicToNonAtomic: {
8221 APValue AtomicVal;
8222 // This does not need to be done in place even for class/array types:
8223 // atomic-to-non-atomic conversion implies copying the object
8224 // representation.
8225 if (!Evaluate(Result&: AtomicVal, Info, E: E->getSubExpr()))
8226 return false;
8227 return DerivedSuccess(V: AtomicVal, E);
8228 }
8229
8230 case CK_NoOp:
8231 case CK_UserDefinedConversion:
8232 return StmtVisitorTy::Visit(E->getSubExpr());
8233
8234 case CK_LValueToRValue: {
8235 LValue LVal;
8236 if (!EvaluateLValue(E: E->getSubExpr(), Result&: LVal, Info))
8237 return false;
8238 APValue RVal;
8239 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8240 if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getSubExpr()->getType(),
8241 LVal, RVal))
8242 return false;
8243 return DerivedSuccess(V: RVal, E);
8244 }
8245 case CK_LValueToRValueBitCast: {
8246 APValue DestValue, SourceValue;
8247 if (!Evaluate(Result&: SourceValue, Info, E: E->getSubExpr()))
8248 return false;
8249 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, BCE: E))
8250 return false;
8251 return DerivedSuccess(V: DestValue, E);
8252 }
8253
8254 case CK_AddressSpaceConversion: {
8255 APValue Value;
8256 if (!Evaluate(Result&: Value, Info, E: E->getSubExpr()))
8257 return false;
8258 return DerivedSuccess(V: Value, E);
8259 }
8260 }
8261
8262 return Error(E);
8263 }
8264
8265 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8266 return VisitUnaryPostIncDec(UO);
8267 }
8268 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8269 return VisitUnaryPostIncDec(UO);
8270 }
8271 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8272 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8273 return Error(UO);
8274
8275 LValue LVal;
8276 if (!EvaluateLValue(E: UO->getSubExpr(), Result&: LVal, Info))
8277 return false;
8278 APValue RVal;
8279 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8280 UO->isIncrementOp(), &RVal))
8281 return false;
8282 return DerivedSuccess(V: RVal, E: UO);
8283 }
8284
8285 bool VisitStmtExpr(const StmtExpr *E) {
8286 // We will have checked the full-expressions inside the statement expression
8287 // when they were completed, and don't need to check them again now.
8288 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8289 false);
8290
8291 const CompoundStmt *CS = E->getSubStmt();
8292 if (CS->body_empty())
8293 return true;
8294
8295 BlockScopeRAII Scope(Info);
8296 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8297 BE = CS->body_end();
8298 /**/; ++BI) {
8299 if (BI + 1 == BE) {
8300 const Expr *FinalExpr = dyn_cast<Expr>(Val: *BI);
8301 if (!FinalExpr) {
8302 Info.FFDiag(Loc: (*BI)->getBeginLoc(),
8303 DiagId: diag::note_constexpr_stmt_expr_unsupported);
8304 return false;
8305 }
8306 return this->Visit(FinalExpr) && Scope.destroy();
8307 }
8308
8309 APValue ReturnValue;
8310 StmtResult Result = { .Value: ReturnValue, .Slot: nullptr };
8311 EvalStmtResult ESR = EvaluateStmt(Result, Info, S: *BI);
8312 if (ESR != ESR_Succeeded) {
8313 // FIXME: If the statement-expression terminated due to 'return',
8314 // 'break', or 'continue', it would be nice to propagate that to
8315 // the outer statement evaluation rather than bailing out.
8316 if (ESR != ESR_Failed)
8317 Info.FFDiag(Loc: (*BI)->getBeginLoc(),
8318 DiagId: diag::note_constexpr_stmt_expr_unsupported);
8319 return false;
8320 }
8321 }
8322
8323 llvm_unreachable("Return from function from the loop above.");
8324 }
8325
8326 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8327 return StmtVisitorTy::Visit(E->getSelectedExpr());
8328 }
8329
8330 /// Visit a value which is evaluated, but whose value is ignored.
8331 void VisitIgnoredValue(const Expr *E) {
8332 EvaluateIgnoredValue(Info, E);
8333 }
8334
8335 /// Potentially visit a MemberExpr's base expression.
8336 void VisitIgnoredBaseExpression(const Expr *E) {
8337 // While MSVC doesn't evaluate the base expression, it does diagnose the
8338 // presence of side-effecting behavior.
8339 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Ctx: Info.Ctx))
8340 return;
8341 VisitIgnoredValue(E);
8342 }
8343};
8344
8345} // namespace
8346
8347//===----------------------------------------------------------------------===//
8348// Common base class for lvalue and temporary evaluation.
8349//===----------------------------------------------------------------------===//
8350namespace {
8351template<class Derived>
8352class LValueExprEvaluatorBase
8353 : public ExprEvaluatorBase<Derived> {
8354protected:
8355 LValue &Result;
8356 bool InvalidBaseOK;
8357 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8358 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8359
8360 bool Success(APValue::LValueBase B) {
8361 Result.set(B);
8362 return true;
8363 }
8364
8365 bool evaluatePointer(const Expr *E, LValue &Result) {
8366 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8367 }
8368
8369public:
8370 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8371 : ExprEvaluatorBaseTy(Info), Result(Result),
8372 InvalidBaseOK(InvalidBaseOK) {}
8373
8374 bool Success(const APValue &V, const Expr *E) {
8375 Result.setFrom(Ctx&: this->Info.Ctx, V);
8376 return true;
8377 }
8378
8379 bool VisitMemberExpr(const MemberExpr *E) {
8380 // Handle non-static data members.
8381 QualType BaseTy;
8382 bool EvalOK;
8383 if (E->isArrow()) {
8384 EvalOK = evaluatePointer(E: E->getBase(), Result);
8385 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8386 } else if (E->getBase()->isPRValue()) {
8387 assert(E->getBase()->getType()->isRecordType());
8388 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8389 BaseTy = E->getBase()->getType();
8390 } else {
8391 EvalOK = this->Visit(E->getBase());
8392 BaseTy = E->getBase()->getType();
8393 }
8394 if (!EvalOK) {
8395 if (!InvalidBaseOK)
8396 return false;
8397 Result.setInvalid(B: E);
8398 return true;
8399 }
8400
8401 const ValueDecl *MD = E->getMemberDecl();
8402 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: E->getMemberDecl())) {
8403 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8404 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8405 (void)BaseTy;
8406 if (!HandleLValueMember(this->Info, E, Result, FD))
8407 return false;
8408 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(Val: MD)) {
8409 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8410 return false;
8411 } else
8412 return this->Error(E);
8413
8414 if (MD->getType()->isReferenceType()) {
8415 APValue RefValue;
8416 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8417 RefValue))
8418 return false;
8419 return Success(RefValue, E);
8420 }
8421 return true;
8422 }
8423
8424 bool VisitBinaryOperator(const BinaryOperator *E) {
8425 switch (E->getOpcode()) {
8426 default:
8427 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8428
8429 case BO_PtrMemD:
8430 case BO_PtrMemI:
8431 return HandleMemberPointerAccess(this->Info, E, Result);
8432 }
8433 }
8434
8435 bool VisitCastExpr(const CastExpr *E) {
8436 switch (E->getCastKind()) {
8437 default:
8438 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8439
8440 case CK_DerivedToBase:
8441 case CK_UncheckedDerivedToBase:
8442 if (!this->Visit(E->getSubExpr()))
8443 return false;
8444
8445 // Now figure out the necessary offset to add to the base LV to get from
8446 // the derived class to the base class.
8447 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8448 Result);
8449 }
8450 }
8451};
8452}
8453
8454//===----------------------------------------------------------------------===//
8455// LValue Evaluation
8456//
8457// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8458// function designators (in C), decl references to void objects (in C), and
8459// temporaries (if building with -Wno-address-of-temporary).
8460//
8461// LValue evaluation produces values comprising a base expression of one of the
8462// following types:
8463// - Declarations
8464// * VarDecl
8465// * FunctionDecl
8466// - Literals
8467// * CompoundLiteralExpr in C (and in global scope in C++)
8468// * StringLiteral
8469// * PredefinedExpr
8470// * ObjCStringLiteralExpr
8471// * ObjCEncodeExpr
8472// * AddrLabelExpr
8473// * BlockExpr
8474// * CallExpr for a MakeStringConstant builtin
8475// - typeid(T) expressions, as TypeInfoLValues
8476// - Locals and temporaries
8477// * MaterializeTemporaryExpr
8478// * Any Expr, with a CallIndex indicating the function in which the temporary
8479// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8480// from the AST (FIXME).
8481// * A MaterializeTemporaryExpr that has static storage duration, with no
8482// CallIndex, for a lifetime-extended temporary.
8483// * The ConstantExpr that is currently being evaluated during evaluation of an
8484// immediate invocation.
8485// plus an offset in bytes.
8486//===----------------------------------------------------------------------===//
8487namespace {
8488class LValueExprEvaluator
8489 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8490public:
8491 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8492 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8493
8494 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8495 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8496
8497 bool VisitCallExpr(const CallExpr *E);
8498 bool VisitDeclRefExpr(const DeclRefExpr *E);
8499 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(B: E); }
8500 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8501 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8502 bool VisitMemberExpr(const MemberExpr *E);
8503 bool VisitStringLiteral(const StringLiteral *E) { return Success(B: E); }
8504 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(B: E); }
8505 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8506 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8507 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8508 bool VisitUnaryDeref(const UnaryOperator *E);
8509 bool VisitUnaryReal(const UnaryOperator *E);
8510 bool VisitUnaryImag(const UnaryOperator *E);
8511 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8512 return VisitUnaryPreIncDec(UO);
8513 }
8514 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8515 return VisitUnaryPreIncDec(UO);
8516 }
8517 bool VisitBinAssign(const BinaryOperator *BO);
8518 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8519
8520 bool VisitCastExpr(const CastExpr *E) {
8521 switch (E->getCastKind()) {
8522 default:
8523 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8524
8525 case CK_LValueBitCast:
8526 this->CCEDiag(E, D: diag::note_constexpr_invalid_cast)
8527 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8528 if (!Visit(S: E->getSubExpr()))
8529 return false;
8530 Result.Designator.setInvalid();
8531 return true;
8532
8533 case CK_BaseToDerived:
8534 if (!Visit(S: E->getSubExpr()))
8535 return false;
8536 return HandleBaseToDerivedCast(Info, E, Result);
8537
8538 case CK_Dynamic:
8539 if (!Visit(S: E->getSubExpr()))
8540 return false;
8541 return HandleDynamicCast(Info, E: cast<ExplicitCastExpr>(Val: E), Ptr&: Result);
8542 }
8543 }
8544};
8545} // end anonymous namespace
8546
8547/// Get an lvalue to a field of a lambda's closure type.
8548static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8549 const CXXMethodDecl *MD, const FieldDecl *FD,
8550 bool LValueToRValueConversion) {
8551 // Static lambda function call operators can't have captures. We already
8552 // diagnosed this, so bail out here.
8553 if (MD->isStatic()) {
8554 assert(Info.CurrentCall->This == nullptr &&
8555 "This should not be set for a static call operator");
8556 return false;
8557 }
8558
8559 // Start with 'Result' referring to the complete closure object...
8560 if (MD->isExplicitObjectMemberFunction()) {
8561 // Self may be passed by reference or by value.
8562 const ParmVarDecl *Self = MD->getParamDecl(i: 0);
8563 if (Self->getType()->isReferenceType()) {
8564 APValue *RefValue = Info.getParamSlot(Call: Info.CurrentCall->Arguments, PVD: Self);
8565 Result.setFrom(Ctx&: Info.Ctx, V: *RefValue);
8566 } else {
8567 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(PVD: Self);
8568 CallStackFrame *Frame =
8569 Info.getCallFrameAndDepth(CallIndex: Info.CurrentCall->Arguments.CallIndex)
8570 .first;
8571 unsigned Version = Info.CurrentCall->Arguments.Version;
8572 Result.set(B: {VD, Frame->Index, Version});
8573 }
8574 } else
8575 Result = *Info.CurrentCall->This;
8576
8577 // ... then update it to refer to the field of the closure object
8578 // that represents the capture.
8579 if (!HandleLValueMember(Info, E, LVal&: Result, FD))
8580 return false;
8581
8582 // And if the field is of reference type (or if we captured '*this' by
8583 // reference), update 'Result' to refer to what
8584 // the field refers to.
8585 if (LValueToRValueConversion) {
8586 APValue RVal;
8587 if (!handleLValueToRValueConversion(Info, Conv: E, Type: FD->getType(), LVal: Result, RVal))
8588 return false;
8589 Result.setFrom(Ctx&: Info.Ctx, V: RVal);
8590 }
8591 return true;
8592}
8593
8594/// Evaluate an expression as an lvalue. This can be legitimately called on
8595/// expressions which are not glvalues, in three cases:
8596/// * function designators in C, and
8597/// * "extern void" objects
8598/// * @selector() expressions in Objective-C
8599static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8600 bool InvalidBaseOK) {
8601 assert(!E->isValueDependent());
8602 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8603 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8604 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(S: E);
8605}
8606
8607bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8608 const NamedDecl *D = E->getDecl();
8609 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8610 UnnamedGlobalConstantDecl>(Val: D))
8611 return Success(B: cast<ValueDecl>(Val: D));
8612 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D))
8613 return VisitVarDecl(E, VD);
8614 if (const BindingDecl *BD = dyn_cast<BindingDecl>(Val: D))
8615 return Visit(S: BD->getBinding());
8616 return Error(E);
8617}
8618
8619
8620bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8621
8622 // If we are within a lambda's call operator, check whether the 'VD' referred
8623 // to within 'E' actually represents a lambda-capture that maps to a
8624 // data-member/field within the closure object, and if so, evaluate to the
8625 // field or what the field refers to.
8626 if (Info.CurrentCall && isLambdaCallOperator(DC: Info.CurrentCall->Callee) &&
8627 isa<DeclRefExpr>(Val: E) &&
8628 cast<DeclRefExpr>(Val: E)->refersToEnclosingVariableOrCapture()) {
8629 // We don't always have a complete capture-map when checking or inferring if
8630 // the function call operator meets the requirements of a constexpr function
8631 // - but we don't need to evaluate the captures to determine constexprness
8632 // (dcl.constexpr C++17).
8633 if (Info.checkingPotentialConstantExpression())
8634 return false;
8635
8636 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(Val: VD)) {
8637 const auto *MD = cast<CXXMethodDecl>(Val: Info.CurrentCall->Callee);
8638 return HandleLambdaCapture(Info, E, Result, MD, FD,
8639 LValueToRValueConversion: FD->getType()->isReferenceType());
8640 }
8641 }
8642
8643 CallStackFrame *Frame = nullptr;
8644 unsigned Version = 0;
8645 if (VD->hasLocalStorage()) {
8646 // Only if a local variable was declared in the function currently being
8647 // evaluated, do we expect to be able to find its value in the current
8648 // frame. (Otherwise it was likely declared in an enclosing context and
8649 // could either have a valid evaluatable value (for e.g. a constexpr
8650 // variable) or be ill-formed (and trigger an appropriate evaluation
8651 // diagnostic)).
8652 CallStackFrame *CurrFrame = Info.CurrentCall;
8653 if (CurrFrame->Callee && CurrFrame->Callee->Equals(DC: VD->getDeclContext())) {
8654 // Function parameters are stored in some caller's frame. (Usually the
8655 // immediate caller, but for an inherited constructor they may be more
8656 // distant.)
8657 if (auto *PVD = dyn_cast<ParmVarDecl>(Val: VD)) {
8658 if (CurrFrame->Arguments) {
8659 VD = CurrFrame->Arguments.getOrigParam(PVD);
8660 Frame =
8661 Info.getCallFrameAndDepth(CallIndex: CurrFrame->Arguments.CallIndex).first;
8662 Version = CurrFrame->Arguments.Version;
8663 }
8664 } else {
8665 Frame = CurrFrame;
8666 Version = CurrFrame->getCurrentTemporaryVersion(Key: VD);
8667 }
8668 }
8669 }
8670
8671 if (!VD->getType()->isReferenceType()) {
8672 if (Frame) {
8673 Result.set(B: {VD, Frame->Index, Version});
8674 return true;
8675 }
8676 return Success(B: VD);
8677 }
8678
8679 if (!Info.getLangOpts().CPlusPlus11) {
8680 Info.CCEDiag(E, DiagId: diag::note_constexpr_ltor_non_integral, ExtraNotes: 1)
8681 << VD << VD->getType();
8682 Info.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
8683 }
8684
8685 APValue *V;
8686 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, Result&: V))
8687 return false;
8688 if (!V->hasValue()) {
8689 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8690 // adjust the diagnostic to say that.
8691 if (!Info.checkingPotentialConstantExpression())
8692 Info.FFDiag(E, DiagId: diag::note_constexpr_use_uninit_reference);
8693 return false;
8694 }
8695 return Success(V: *V, E);
8696}
8697
8698bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8699 if (!IsConstantEvaluatedBuiltinCall(E))
8700 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8701
8702 switch (E->getBuiltinCallee()) {
8703 default:
8704 return false;
8705 case Builtin::BIas_const:
8706 case Builtin::BIforward:
8707 case Builtin::BIforward_like:
8708 case Builtin::BImove:
8709 case Builtin::BImove_if_noexcept:
8710 if (cast<FunctionDecl>(Val: E->getCalleeDecl())->isConstexpr())
8711 return Visit(S: E->getArg(Arg: 0));
8712 break;
8713 }
8714
8715 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8716}
8717
8718bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8719 const MaterializeTemporaryExpr *E) {
8720 // Walk through the expression to find the materialized temporary itself.
8721 SmallVector<const Expr *, 2> CommaLHSs;
8722 SmallVector<SubobjectAdjustment, 2> Adjustments;
8723 const Expr *Inner =
8724 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHS&: CommaLHSs, Adjustments);
8725
8726 // If we passed any comma operators, evaluate their LHSs.
8727 for (const Expr *E : CommaLHSs)
8728 if (!EvaluateIgnoredValue(Info, E))
8729 return false;
8730
8731 // A materialized temporary with static storage duration can appear within the
8732 // result of a constant expression evaluation, so we need to preserve its
8733 // value for use outside this evaluation.
8734 APValue *Value;
8735 if (E->getStorageDuration() == SD_Static) {
8736 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8737 return false;
8738 // FIXME: What about SD_Thread?
8739 Value = E->getOrCreateValue(MayCreate: true);
8740 *Value = APValue();
8741 Result.set(B: E);
8742 } else {
8743 Value = &Info.CurrentCall->createTemporary(
8744 Key: E, T: Inner->getType(),
8745 Scope: E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8746 : ScopeKind::Block,
8747 LV&: Result);
8748 }
8749
8750 QualType Type = Inner->getType();
8751
8752 // Materialize the temporary itself.
8753 if (!EvaluateInPlace(Result&: *Value, Info, This: Result, E: Inner)) {
8754 *Value = APValue();
8755 return false;
8756 }
8757
8758 // Adjust our lvalue to refer to the desired subobject.
8759 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8760 --I;
8761 switch (Adjustments[I].Kind) {
8762 case SubobjectAdjustment::DerivedToBaseAdjustment:
8763 if (!HandleLValueBasePath(Info, E: Adjustments[I].DerivedToBase.BasePath,
8764 Type, Result))
8765 return false;
8766 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8767 break;
8768
8769 case SubobjectAdjustment::FieldAdjustment:
8770 if (!HandleLValueMember(Info, E, LVal&: Result, FD: Adjustments[I].Field))
8771 return false;
8772 Type = Adjustments[I].Field->getType();
8773 break;
8774
8775 case SubobjectAdjustment::MemberPointerAdjustment:
8776 if (!HandleMemberPointerAccess(Info&: this->Info, LVType: Type, LV&: Result,
8777 RHS: Adjustments[I].Ptr.RHS))
8778 return false;
8779 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8780 break;
8781 }
8782 }
8783
8784 return true;
8785}
8786
8787bool
8788LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8789 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8790 "lvalue compound literal in c++?");
8791 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8792 // only see this when folding in C, so there's no standard to follow here.
8793 return Success(B: E);
8794}
8795
8796bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8797 TypeInfoLValue TypeInfo;
8798
8799 if (!E->isPotentiallyEvaluated()) {
8800 if (E->isTypeOperand())
8801 TypeInfo = TypeInfoLValue(E->getTypeOperand(Context&: Info.Ctx).getTypePtr());
8802 else
8803 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8804 } else {
8805 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8806 Info.CCEDiag(E, DiagId: diag::note_constexpr_typeid_polymorphic)
8807 << E->getExprOperand()->getType()
8808 << E->getExprOperand()->getSourceRange();
8809 }
8810
8811 if (!Visit(S: E->getExprOperand()))
8812 return false;
8813
8814 std::optional<DynamicType> DynType =
8815 ComputeDynamicType(Info, E, This&: Result, AK: AK_TypeId);
8816 if (!DynType)
8817 return false;
8818
8819 TypeInfo =
8820 TypeInfoLValue(Info.Ctx.getRecordType(Decl: DynType->Type).getTypePtr());
8821 }
8822
8823 return Success(B: APValue::LValueBase::getTypeInfo(LV: TypeInfo, TypeInfo: E->getType()));
8824}
8825
8826bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8827 return Success(B: E->getGuidDecl());
8828}
8829
8830bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8831 // Handle static data members.
8832 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: E->getMemberDecl())) {
8833 VisitIgnoredBaseExpression(E: E->getBase());
8834 return VisitVarDecl(E, VD);
8835 }
8836
8837 // Handle static member functions.
8838 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl())) {
8839 if (MD->isStatic()) {
8840 VisitIgnoredBaseExpression(E: E->getBase());
8841 return Success(B: MD);
8842 }
8843 }
8844
8845 // Handle non-static data members.
8846 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8847}
8848
8849bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8850 // FIXME: Deal with vectors as array subscript bases.
8851 if (E->getBase()->getType()->isVectorType() ||
8852 E->getBase()->getType()->isSveVLSBuiltinType())
8853 return Error(E);
8854
8855 APSInt Index;
8856 bool Success = true;
8857
8858 // C++17's rules require us to evaluate the LHS first, regardless of which
8859 // side is the base.
8860 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8861 if (SubExpr == E->getBase() ? !evaluatePointer(E: SubExpr, Result)
8862 : !EvaluateInteger(E: SubExpr, Result&: Index, Info)) {
8863 if (!Info.noteFailure())
8864 return false;
8865 Success = false;
8866 }
8867 }
8868
8869 return Success &&
8870 HandleLValueArrayAdjustment(Info, E, LVal&: Result, EltTy: E->getType(), Adjustment: Index);
8871}
8872
8873bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8874 return evaluatePointer(E: E->getSubExpr(), Result);
8875}
8876
8877bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8878 if (!Visit(S: E->getSubExpr()))
8879 return false;
8880 // __real is a no-op on scalar lvalues.
8881 if (E->getSubExpr()->getType()->isAnyComplexType())
8882 HandleLValueComplexElement(Info, E, LVal&: Result, EltTy: E->getType(), Imag: false);
8883 return true;
8884}
8885
8886bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8887 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8888 "lvalue __imag__ on scalar?");
8889 if (!Visit(S: E->getSubExpr()))
8890 return false;
8891 HandleLValueComplexElement(Info, E, LVal&: Result, EltTy: E->getType(), Imag: true);
8892 return true;
8893}
8894
8895bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8896 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8897 return Error(E: UO);
8898
8899 if (!this->Visit(S: UO->getSubExpr()))
8900 return false;
8901
8902 return handleIncDec(
8903 Info&: this->Info, E: UO, LVal: Result, LValType: UO->getSubExpr()->getType(),
8904 IsIncrement: UO->isIncrementOp(), Old: nullptr);
8905}
8906
8907bool LValueExprEvaluator::VisitCompoundAssignOperator(
8908 const CompoundAssignOperator *CAO) {
8909 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8910 return Error(E: CAO);
8911
8912 bool Success = true;
8913
8914 // C++17 onwards require that we evaluate the RHS first.
8915 APValue RHS;
8916 if (!Evaluate(Result&: RHS, Info&: this->Info, E: CAO->getRHS())) {
8917 if (!Info.noteFailure())
8918 return false;
8919 Success = false;
8920 }
8921
8922 // The overall lvalue result is the result of evaluating the LHS.
8923 if (!this->Visit(S: CAO->getLHS()) || !Success)
8924 return false;
8925
8926 return handleCompoundAssignment(
8927 Info&: this->Info, E: CAO,
8928 LVal: Result, LValType: CAO->getLHS()->getType(), PromotedLValType: CAO->getComputationLHSType(),
8929 Opcode: CAO->getOpForCompoundAssignment(Opc: CAO->getOpcode()), RVal: RHS);
8930}
8931
8932bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8933 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8934 return Error(E);
8935
8936 bool Success = true;
8937
8938 // C++17 onwards require that we evaluate the RHS first.
8939 APValue NewVal;
8940 if (!Evaluate(Result&: NewVal, Info&: this->Info, E: E->getRHS())) {
8941 if (!Info.noteFailure())
8942 return false;
8943 Success = false;
8944 }
8945
8946 if (!this->Visit(S: E->getLHS()) || !Success)
8947 return false;
8948
8949 if (Info.getLangOpts().CPlusPlus20 &&
8950 !MaybeHandleUnionActiveMemberChange(Info, LHSExpr: E->getLHS(), LHS: Result))
8951 return false;
8952
8953 return handleAssignment(Info&: this->Info, E, LVal: Result, LValType: E->getLHS()->getType(),
8954 Val&: NewVal);
8955}
8956
8957//===----------------------------------------------------------------------===//
8958// Pointer Evaluation
8959//===----------------------------------------------------------------------===//
8960
8961/// Attempts to compute the number of bytes available at the pointer
8962/// returned by a function with the alloc_size attribute. Returns true if we
8963/// were successful. Places an unsigned number into `Result`.
8964///
8965/// This expects the given CallExpr to be a call to a function with an
8966/// alloc_size attribute.
8967static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8968 const CallExpr *Call,
8969 llvm::APInt &Result) {
8970 const AllocSizeAttr *AllocSize = getAllocSizeAttr(CE: Call);
8971
8972 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8973 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8974 unsigned BitsInSizeT = Ctx.getTypeSize(T: Ctx.getSizeType());
8975 if (Call->getNumArgs() <= SizeArgNo)
8976 return false;
8977
8978 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8979 Expr::EvalResult ExprResult;
8980 if (!E->EvaluateAsInt(Result&: ExprResult, Ctx, AllowSideEffects: Expr::SE_AllowSideEffects))
8981 return false;
8982 Into = ExprResult.Val.getInt();
8983 if (Into.isNegative() || !Into.isIntN(N: BitsInSizeT))
8984 return false;
8985 Into = Into.zext(width: BitsInSizeT);
8986 return true;
8987 };
8988
8989 APSInt SizeOfElem;
8990 if (!EvaluateAsSizeT(Call->getArg(Arg: SizeArgNo), SizeOfElem))
8991 return false;
8992
8993 if (!AllocSize->getNumElemsParam().isValid()) {
8994 Result = std::move(SizeOfElem);
8995 return true;
8996 }
8997
8998 APSInt NumberOfElems;
8999 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9000 if (!EvaluateAsSizeT(Call->getArg(Arg: NumArgNo), NumberOfElems))
9001 return false;
9002
9003 bool Overflow;
9004 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(RHS: NumberOfElems, Overflow);
9005 if (Overflow)
9006 return false;
9007
9008 Result = std::move(BytesAvailable);
9009 return true;
9010}
9011
9012/// Convenience function. LVal's base must be a call to an alloc_size
9013/// function.
9014static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
9015 const LValue &LVal,
9016 llvm::APInt &Result) {
9017 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9018 "Can't get the size of a non alloc_size function");
9019 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9020 const CallExpr *CE = tryUnwrapAllocSizeCall(E: Base);
9021 return getBytesReturnedByAllocSizeCall(Ctx, Call: CE, Result);
9022}
9023
9024/// Attempts to evaluate the given LValueBase as the result of a call to
9025/// a function with the alloc_size attribute. If it was possible to do so, this
9026/// function will return true, make Result's Base point to said function call,
9027/// and mark Result's Base as invalid.
9028static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
9029 LValue &Result) {
9030 if (Base.isNull())
9031 return false;
9032
9033 // Because we do no form of static analysis, we only support const variables.
9034 //
9035 // Additionally, we can't support parameters, nor can we support static
9036 // variables (in the latter case, use-before-assign isn't UB; in the former,
9037 // we have no clue what they'll be assigned to).
9038 const auto *VD =
9039 dyn_cast_or_null<VarDecl>(Val: Base.dyn_cast<const ValueDecl *>());
9040 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9041 return false;
9042
9043 const Expr *Init = VD->getAnyInitializer();
9044 if (!Init || Init->getType().isNull())
9045 return false;
9046
9047 const Expr *E = Init->IgnoreParens();
9048 if (!tryUnwrapAllocSizeCall(E))
9049 return false;
9050
9051 // Store E instead of E unwrapped so that the type of the LValue's base is
9052 // what the user wanted.
9053 Result.setInvalid(B: E);
9054
9055 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9056 Result.addUnsizedArray(Info, E, ElemTy: Pointee);
9057 return true;
9058}
9059
9060namespace {
9061class PointerExprEvaluator
9062 : public ExprEvaluatorBase<PointerExprEvaluator> {
9063 LValue &Result;
9064 bool InvalidBaseOK;
9065
9066 bool Success(const Expr *E) {
9067 Result.set(B: E);
9068 return true;
9069 }
9070
9071 bool evaluateLValue(const Expr *E, LValue &Result) {
9072 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9073 }
9074
9075 bool evaluatePointer(const Expr *E, LValue &Result) {
9076 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9077 }
9078
9079 bool visitNonBuiltinCallExpr(const CallExpr *E);
9080public:
9081
9082 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9083 : ExprEvaluatorBaseTy(info), Result(Result),
9084 InvalidBaseOK(InvalidBaseOK) {}
9085
9086 bool Success(const APValue &V, const Expr *E) {
9087 Result.setFrom(Ctx&: Info.Ctx, V);
9088 return true;
9089 }
9090 bool ZeroInitialization(const Expr *E) {
9091 Result.setNull(Ctx&: Info.Ctx, PointerTy: E->getType());
9092 return true;
9093 }
9094
9095 bool VisitBinaryOperator(const BinaryOperator *E);
9096 bool VisitCastExpr(const CastExpr* E);
9097 bool VisitUnaryAddrOf(const UnaryOperator *E);
9098 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9099 { return Success(E); }
9100 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9101 if (E->isExpressibleAsConstantInitializer())
9102 return Success(E);
9103 if (Info.noteFailure())
9104 EvaluateIgnoredValue(Info, E: E->getSubExpr());
9105 return Error(E);
9106 }
9107 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9108 { return Success(E); }
9109 bool VisitCallExpr(const CallExpr *E);
9110 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9111 bool VisitBlockExpr(const BlockExpr *E) {
9112 if (!E->getBlockDecl()->hasCaptures())
9113 return Success(E);
9114 return Error(E);
9115 }
9116 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9117 auto DiagnoseInvalidUseOfThis = [&] {
9118 if (Info.getLangOpts().CPlusPlus11)
9119 Info.FFDiag(E, DiagId: diag::note_constexpr_this) << E->isImplicit();
9120 else
9121 Info.FFDiag(E);
9122 };
9123
9124 // Can't look at 'this' when checking a potential constant expression.
9125 if (Info.checkingPotentialConstantExpression())
9126 return false;
9127
9128 bool IsExplicitLambda =
9129 isLambdaCallWithExplicitObjectParameter(DC: Info.CurrentCall->Callee);
9130 if (!IsExplicitLambda) {
9131 if (!Info.CurrentCall->This) {
9132 DiagnoseInvalidUseOfThis();
9133 return false;
9134 }
9135
9136 Result = *Info.CurrentCall->This;
9137 }
9138
9139 if (isLambdaCallOperator(DC: Info.CurrentCall->Callee)) {
9140 // Ensure we actually have captured 'this'. If something was wrong with
9141 // 'this' capture, the error would have been previously reported.
9142 // Otherwise we can be inside of a default initialization of an object
9143 // declared by lambda's body, so no need to return false.
9144 if (!Info.CurrentCall->LambdaThisCaptureField) {
9145 if (IsExplicitLambda && !Info.CurrentCall->This) {
9146 DiagnoseInvalidUseOfThis();
9147 return false;
9148 }
9149
9150 return true;
9151 }
9152
9153 const auto *MD = cast<CXXMethodDecl>(Val: Info.CurrentCall->Callee);
9154 return HandleLambdaCapture(
9155 Info, E, Result, MD, FD: Info.CurrentCall->LambdaThisCaptureField,
9156 LValueToRValueConversion: Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9157 }
9158 return true;
9159 }
9160
9161 bool VisitCXXNewExpr(const CXXNewExpr *E);
9162
9163 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9164 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9165 APValue LValResult = E->EvaluateInContext(
9166 Ctx: Info.Ctx, DefaultExpr: Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9167 Result.setFrom(Ctx&: Info.Ctx, V: LValResult);
9168 return true;
9169 }
9170
9171 bool VisitEmbedExpr(const EmbedExpr *E) {
9172 llvm::report_fatal_error(reason: "Not yet implemented for ExprConstant.cpp");
9173 return true;
9174 }
9175
9176 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9177 std::string ResultStr = E->ComputeName(Context&: Info.Ctx);
9178
9179 QualType CharTy = Info.Ctx.CharTy.withConst();
9180 APInt Size(Info.Ctx.getTypeSize(T: Info.Ctx.getSizeType()),
9181 ResultStr.size() + 1);
9182 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9183 EltTy: CharTy, ArySize: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
9184
9185 StringLiteral *SL =
9186 StringLiteral::Create(Ctx: Info.Ctx, Str: ResultStr, Kind: StringLiteralKind::Ordinary,
9187 /*Pascal*/ false, Ty: ArrayTy, Loc: E->getLocation());
9188
9189 evaluateLValue(E: SL, Result);
9190 Result.addArray(Info, E, CAT: cast<ConstantArrayType>(Val&: ArrayTy));
9191 return true;
9192 }
9193
9194 // FIXME: Missing: @protocol, @selector
9195};
9196} // end anonymous namespace
9197
9198static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9199 bool InvalidBaseOK) {
9200 assert(!E->isValueDependent());
9201 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9202 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(S: E);
9203}
9204
9205bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9206 if (E->getOpcode() != BO_Add &&
9207 E->getOpcode() != BO_Sub)
9208 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9209
9210 const Expr *PExp = E->getLHS();
9211 const Expr *IExp = E->getRHS();
9212 if (IExp->getType()->isPointerType())
9213 std::swap(a&: PExp, b&: IExp);
9214
9215 bool EvalPtrOK = evaluatePointer(E: PExp, Result);
9216 if (!EvalPtrOK && !Info.noteFailure())
9217 return false;
9218
9219 llvm::APSInt Offset;
9220 if (!EvaluateInteger(E: IExp, Result&: Offset, Info) || !EvalPtrOK)
9221 return false;
9222
9223 if (E->getOpcode() == BO_Sub)
9224 negateAsSigned(Int&: Offset);
9225
9226 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9227 return HandleLValueArrayAdjustment(Info, E, LVal&: Result, EltTy: Pointee, Adjustment: Offset);
9228}
9229
9230bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9231 return evaluateLValue(E: E->getSubExpr(), Result);
9232}
9233
9234// Is the provided decl 'std::source_location::current'?
9235static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
9236 if (!FD)
9237 return false;
9238 const IdentifierInfo *FnII = FD->getIdentifier();
9239 if (!FnII || !FnII->isStr(Str: "current"))
9240 return false;
9241
9242 const auto *RD = dyn_cast<RecordDecl>(Val: FD->getParent());
9243 if (!RD)
9244 return false;
9245
9246 const IdentifierInfo *ClassII = RD->getIdentifier();
9247 return RD->isInStdNamespace() && ClassII && ClassII->isStr(Str: "source_location");
9248}
9249
9250bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9251 const Expr *SubExpr = E->getSubExpr();
9252
9253 switch (E->getCastKind()) {
9254 default:
9255 break;
9256 case CK_BitCast:
9257 case CK_CPointerToObjCPointerCast:
9258 case CK_BlockPointerToObjCPointerCast:
9259 case CK_AnyPointerToBlockPointerCast:
9260 case CK_AddressSpaceConversion:
9261 if (!Visit(S: SubExpr))
9262 return false;
9263 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9264 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9265 // also static_casts, but we disallow them as a resolution to DR1312.
9266 if (!E->getType()->isVoidPointerType()) {
9267 // In some circumstances, we permit casting from void* to cv1 T*, when the
9268 // actual pointee object is actually a cv2 T.
9269 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9270 !Result.IsNullPtr;
9271 bool VoidPtrCastMaybeOK =
9272 Result.IsNullPtr ||
9273 (HasValidResult &&
9274 Info.Ctx.hasSimilarType(T1: Result.Designator.getType(Ctx&: Info.Ctx),
9275 T2: E->getType()->getPointeeType()));
9276 // 1. We'll allow it in std::allocator::allocate, and anything which that
9277 // calls.
9278 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9279 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9280 // We'll allow it in the body of std::source_location::current. GCC's
9281 // implementation had a parameter of type `void*`, and casts from
9282 // that back to `const __impl*` in its body.
9283 if (VoidPtrCastMaybeOK &&
9284 (Info.getStdAllocatorCaller(FnName: "allocate") ||
9285 IsDeclSourceLocationCurrent(FD: Info.CurrentCall->Callee) ||
9286 Info.getLangOpts().CPlusPlus26)) {
9287 // Permitted.
9288 } else {
9289 if (SubExpr->getType()->isVoidPointerType() &&
9290 Info.getLangOpts().CPlusPlus) {
9291 if (HasValidResult)
9292 CCEDiag(E, D: diag::note_constexpr_invalid_void_star_cast)
9293 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9294 << Result.Designator.getType(Ctx&: Info.Ctx).getCanonicalType()
9295 << E->getType()->getPointeeType();
9296 else
9297 CCEDiag(E, D: diag::note_constexpr_invalid_cast)
9298 << 3 << SubExpr->getType();
9299 } else
9300 CCEDiag(E, D: diag::note_constexpr_invalid_cast)
9301 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9302 Result.Designator.setInvalid();
9303 }
9304 }
9305 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9306 ZeroInitialization(E);
9307 return true;
9308
9309 case CK_DerivedToBase:
9310 case CK_UncheckedDerivedToBase:
9311 if (!evaluatePointer(E: E->getSubExpr(), Result))
9312 return false;
9313 if (!Result.Base && Result.Offset.isZero())
9314 return true;
9315
9316 // Now figure out the necessary offset to add to the base LV to get from
9317 // the derived class to the base class.
9318 return HandleLValueBasePath(Info, E, Type: E->getSubExpr()->getType()->
9319 castAs<PointerType>()->getPointeeType(),
9320 Result);
9321
9322 case CK_BaseToDerived:
9323 if (!Visit(S: E->getSubExpr()))
9324 return false;
9325 if (!Result.Base && Result.Offset.isZero())
9326 return true;
9327 return HandleBaseToDerivedCast(Info, E, Result);
9328
9329 case CK_Dynamic:
9330 if (!Visit(S: E->getSubExpr()))
9331 return false;
9332 return HandleDynamicCast(Info, E: cast<ExplicitCastExpr>(Val: E), Ptr&: Result);
9333
9334 case CK_NullToPointer:
9335 VisitIgnoredValue(E: E->getSubExpr());
9336 return ZeroInitialization(E);
9337
9338 case CK_IntegralToPointer: {
9339 CCEDiag(E, D: diag::note_constexpr_invalid_cast)
9340 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9341
9342 APValue Value;
9343 if (!EvaluateIntegerOrLValue(E: SubExpr, Result&: Value, Info))
9344 break;
9345
9346 if (Value.isInt()) {
9347 unsigned Size = Info.Ctx.getTypeSize(T: E->getType());
9348 uint64_t N = Value.getInt().extOrTrunc(width: Size).getZExtValue();
9349 Result.Base = (Expr*)nullptr;
9350 Result.InvalidBase = false;
9351 Result.Offset = CharUnits::fromQuantity(Quantity: N);
9352 Result.Designator.setInvalid();
9353 Result.IsNullPtr = false;
9354 return true;
9355 } else {
9356 // In rare instances, the value isn't an lvalue.
9357 // For example, when the value is the difference between the addresses of
9358 // two labels. We reject that as a constant expression because we can't
9359 // compute a valid offset to convert into a pointer.
9360 if (!Value.isLValue())
9361 return false;
9362
9363 // Cast is of an lvalue, no need to change value.
9364 Result.setFrom(Ctx&: Info.Ctx, V: Value);
9365 return true;
9366 }
9367 }
9368
9369 case CK_ArrayToPointerDecay: {
9370 if (SubExpr->isGLValue()) {
9371 if (!evaluateLValue(E: SubExpr, Result))
9372 return false;
9373 } else {
9374 APValue &Value = Info.CurrentCall->createTemporary(
9375 Key: SubExpr, T: SubExpr->getType(), Scope: ScopeKind::FullExpression, LV&: Result);
9376 if (!EvaluateInPlace(Result&: Value, Info, This: Result, E: SubExpr))
9377 return false;
9378 }
9379 // The result is a pointer to the first element of the array.
9380 auto *AT = Info.Ctx.getAsArrayType(T: SubExpr->getType());
9381 if (auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
9382 Result.addArray(Info, E, CAT);
9383 else
9384 Result.addUnsizedArray(Info, E, ElemTy: AT->getElementType());
9385 return true;
9386 }
9387
9388 case CK_FunctionToPointerDecay:
9389 return evaluateLValue(E: SubExpr, Result);
9390
9391 case CK_LValueToRValue: {
9392 LValue LVal;
9393 if (!evaluateLValue(E: E->getSubExpr(), Result&: LVal))
9394 return false;
9395
9396 APValue RVal;
9397 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9398 if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getSubExpr()->getType(),
9399 LVal, RVal))
9400 return InvalidBaseOK &&
9401 evaluateLValueAsAllocSize(Info, Base: LVal.Base, Result);
9402 return Success(V: RVal, E);
9403 }
9404 }
9405
9406 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9407}
9408
9409static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9410 UnaryExprOrTypeTrait ExprKind) {
9411 // C++ [expr.alignof]p3:
9412 // When alignof is applied to a reference type, the result is the
9413 // alignment of the referenced type.
9414 T = T.getNonReferenceType();
9415
9416 if (T.getQualifiers().hasUnaligned())
9417 return CharUnits::One();
9418
9419 const bool AlignOfReturnsPreferred =
9420 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9421
9422 // __alignof is defined to return the preferred alignment.
9423 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9424 // as well.
9425 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9426 return Info.Ctx.toCharUnitsFromBits(
9427 BitSize: Info.Ctx.getPreferredTypeAlign(T: T.getTypePtr()));
9428 // alignof and _Alignof are defined to return the ABI alignment.
9429 else if (ExprKind == UETT_AlignOf)
9430 return Info.Ctx.getTypeAlignInChars(T: T.getTypePtr());
9431 else
9432 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9433}
9434
9435static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9436 UnaryExprOrTypeTrait ExprKind) {
9437 E = E->IgnoreParens();
9438
9439 // The kinds of expressions that we have special-case logic here for
9440 // should be kept up to date with the special checks for those
9441 // expressions in Sema.
9442
9443 // alignof decl is always accepted, even if it doesn't make sense: we default
9444 // to 1 in those cases.
9445 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
9446 return Info.Ctx.getDeclAlign(D: DRE->getDecl(),
9447 /*RefAsPointee*/ForAlignof: true);
9448
9449 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E))
9450 return Info.Ctx.getDeclAlign(D: ME->getMemberDecl(),
9451 /*RefAsPointee*/ForAlignof: true);
9452
9453 return GetAlignOfType(Info, T: E->getType(), ExprKind);
9454}
9455
9456static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9457 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9458 return Info.Ctx.getDeclAlign(D: VD);
9459 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9460 return GetAlignOfExpr(Info, E, ExprKind: UETT_AlignOf);
9461 return GetAlignOfType(Info, T: Value.Base.getTypeInfoType(), ExprKind: UETT_AlignOf);
9462}
9463
9464/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9465/// __builtin_is_aligned and __builtin_assume_aligned.
9466static bool getAlignmentArgument(const Expr *E, QualType ForType,
9467 EvalInfo &Info, APSInt &Alignment) {
9468 if (!EvaluateInteger(E, Result&: Alignment, Info))
9469 return false;
9470 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9471 Info.FFDiag(E, DiagId: diag::note_constexpr_invalid_alignment) << Alignment;
9472 return false;
9473 }
9474 unsigned SrcWidth = Info.Ctx.getIntWidth(T: ForType);
9475 APSInt MaxValue(APInt::getOneBitSet(numBits: SrcWidth, BitNo: SrcWidth - 1));
9476 if (APSInt::compareValues(I1: Alignment, I2: MaxValue) > 0) {
9477 Info.FFDiag(E, DiagId: diag::note_constexpr_alignment_too_big)
9478 << MaxValue << ForType << Alignment;
9479 return false;
9480 }
9481 // Ensure both alignment and source value have the same bit width so that we
9482 // don't assert when computing the resulting value.
9483 APSInt ExtAlignment =
9484 APSInt(Alignment.zextOrTrunc(width: SrcWidth), /*isUnsigned=*/true);
9485 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9486 "Alignment should not be changed by ext/trunc");
9487 Alignment = ExtAlignment;
9488 assert(Alignment.getBitWidth() == SrcWidth);
9489 return true;
9490}
9491
9492// To be clear: this happily visits unsupported builtins. Better name welcomed.
9493bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9494 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9495 return true;
9496
9497 if (!(InvalidBaseOK && getAllocSizeAttr(CE: E)))
9498 return false;
9499
9500 Result.setInvalid(B: E);
9501 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9502 Result.addUnsizedArray(Info, E, ElemTy: PointeeTy);
9503 return true;
9504}
9505
9506bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9507 if (!IsConstantEvaluatedBuiltinCall(E))
9508 return visitNonBuiltinCallExpr(E);
9509 return VisitBuiltinCallExpr(E, BuiltinOp: E->getBuiltinCallee());
9510}
9511
9512// Determine if T is a character type for which we guarantee that
9513// sizeof(T) == 1.
9514static bool isOneByteCharacterType(QualType T) {
9515 return T->isCharType() || T->isChar8Type();
9516}
9517
9518bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9519 unsigned BuiltinOp) {
9520 if (IsNoOpCall(E))
9521 return Success(E);
9522
9523 switch (BuiltinOp) {
9524 case Builtin::BIaddressof:
9525 case Builtin::BI__addressof:
9526 case Builtin::BI__builtin_addressof:
9527 return evaluateLValue(E: E->getArg(Arg: 0), Result);
9528 case Builtin::BI__builtin_assume_aligned: {
9529 // We need to be very careful here because: if the pointer does not have the
9530 // asserted alignment, then the behavior is undefined, and undefined
9531 // behavior is non-constant.
9532 if (!evaluatePointer(E: E->getArg(Arg: 0), Result))
9533 return false;
9534
9535 LValue OffsetResult(Result);
9536 APSInt Alignment;
9537 if (!getAlignmentArgument(E: E->getArg(Arg: 1), ForType: E->getArg(Arg: 0)->getType(), Info,
9538 Alignment))
9539 return false;
9540 CharUnits Align = CharUnits::fromQuantity(Quantity: Alignment.getZExtValue());
9541
9542 if (E->getNumArgs() > 2) {
9543 APSInt Offset;
9544 if (!EvaluateInteger(E: E->getArg(Arg: 2), Result&: Offset, Info))
9545 return false;
9546
9547 int64_t AdditionalOffset = -Offset.getZExtValue();
9548 OffsetResult.Offset += CharUnits::fromQuantity(Quantity: AdditionalOffset);
9549 }
9550
9551 // If there is a base object, then it must have the correct alignment.
9552 if (OffsetResult.Base) {
9553 CharUnits BaseAlignment = getBaseAlignment(Info, Value: OffsetResult);
9554
9555 if (BaseAlignment < Align) {
9556 Result.Designator.setInvalid();
9557 // FIXME: Add support to Diagnostic for long / long long.
9558 CCEDiag(E: E->getArg(Arg: 0),
9559 D: diag::note_constexpr_baa_insufficient_alignment) << 0
9560 << (unsigned)BaseAlignment.getQuantity()
9561 << (unsigned)Align.getQuantity();
9562 return false;
9563 }
9564 }
9565
9566 // The offset must also have the correct alignment.
9567 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9568 Result.Designator.setInvalid();
9569
9570 (OffsetResult.Base
9571 ? CCEDiag(E: E->getArg(Arg: 0),
9572 D: diag::note_constexpr_baa_insufficient_alignment) << 1
9573 : CCEDiag(E: E->getArg(Arg: 0),
9574 D: diag::note_constexpr_baa_value_insufficient_alignment))
9575 << (int)OffsetResult.Offset.getQuantity()
9576 << (unsigned)Align.getQuantity();
9577 return false;
9578 }
9579
9580 return true;
9581 }
9582 case Builtin::BI__builtin_align_up:
9583 case Builtin::BI__builtin_align_down: {
9584 if (!evaluatePointer(E: E->getArg(Arg: 0), Result))
9585 return false;
9586 APSInt Alignment;
9587 if (!getAlignmentArgument(E: E->getArg(Arg: 1), ForType: E->getArg(Arg: 0)->getType(), Info,
9588 Alignment))
9589 return false;
9590 CharUnits BaseAlignment = getBaseAlignment(Info, Value: Result);
9591 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(offset: Result.Offset);
9592 // For align_up/align_down, we can return the same value if the alignment
9593 // is known to be greater or equal to the requested value.
9594 if (PtrAlign.getQuantity() >= Alignment)
9595 return true;
9596
9597 // The alignment could be greater than the minimum at run-time, so we cannot
9598 // infer much about the resulting pointer value. One case is possible:
9599 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9600 // can infer the correct index if the requested alignment is smaller than
9601 // the base alignment so we can perform the computation on the offset.
9602 if (BaseAlignment.getQuantity() >= Alignment) {
9603 assert(Alignment.getBitWidth() <= 64 &&
9604 "Cannot handle > 64-bit address-space");
9605 uint64_t Alignment64 = Alignment.getZExtValue();
9606 CharUnits NewOffset = CharUnits::fromQuantity(
9607 Quantity: BuiltinOp == Builtin::BI__builtin_align_down
9608 ? llvm::alignDown(Value: Result.Offset.getQuantity(), Align: Alignment64)
9609 : llvm::alignTo(Value: Result.Offset.getQuantity(), Align: Alignment64));
9610 Result.adjustOffset(N: NewOffset - Result.Offset);
9611 // TODO: diagnose out-of-bounds values/only allow for arrays?
9612 return true;
9613 }
9614 // Otherwise, we cannot constant-evaluate the result.
9615 Info.FFDiag(E: E->getArg(Arg: 0), DiagId: diag::note_constexpr_alignment_adjust)
9616 << Alignment;
9617 return false;
9618 }
9619 case Builtin::BI__builtin_operator_new:
9620 return HandleOperatorNewCall(Info, E, Result);
9621 case Builtin::BI__builtin_launder:
9622 return evaluatePointer(E: E->getArg(Arg: 0), Result);
9623 case Builtin::BIstrchr:
9624 case Builtin::BIwcschr:
9625 case Builtin::BImemchr:
9626 case Builtin::BIwmemchr:
9627 if (Info.getLangOpts().CPlusPlus11)
9628 Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_function)
9629 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9630 << ("'" + Info.Ctx.BuiltinInfo.getName(ID: BuiltinOp) + "'").str();
9631 else
9632 Info.CCEDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
9633 [[fallthrough]];
9634 case Builtin::BI__builtin_strchr:
9635 case Builtin::BI__builtin_wcschr:
9636 case Builtin::BI__builtin_memchr:
9637 case Builtin::BI__builtin_char_memchr:
9638 case Builtin::BI__builtin_wmemchr: {
9639 if (!Visit(S: E->getArg(Arg: 0)))
9640 return false;
9641 APSInt Desired;
9642 if (!EvaluateInteger(E: E->getArg(Arg: 1), Result&: Desired, Info))
9643 return false;
9644 uint64_t MaxLength = uint64_t(-1);
9645 if (BuiltinOp != Builtin::BIstrchr &&
9646 BuiltinOp != Builtin::BIwcschr &&
9647 BuiltinOp != Builtin::BI__builtin_strchr &&
9648 BuiltinOp != Builtin::BI__builtin_wcschr) {
9649 APSInt N;
9650 if (!EvaluateInteger(E: E->getArg(Arg: 2), Result&: N, Info))
9651 return false;
9652 MaxLength = N.getZExtValue();
9653 }
9654 // We cannot find the value if there are no candidates to match against.
9655 if (MaxLength == 0u)
9656 return ZeroInitialization(E);
9657 if (!Result.checkNullPointerForFoldAccess(Info, E, AK: AK_Read) ||
9658 Result.Designator.Invalid)
9659 return false;
9660 QualType CharTy = Result.Designator.getType(Ctx&: Info.Ctx);
9661 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9662 BuiltinOp == Builtin::BI__builtin_memchr;
9663 assert(IsRawByte ||
9664 Info.Ctx.hasSameUnqualifiedType(
9665 CharTy, E->getArg(0)->getType()->getPointeeType()));
9666 // Pointers to const void may point to objects of incomplete type.
9667 if (IsRawByte && CharTy->isIncompleteType()) {
9668 Info.FFDiag(E, DiagId: diag::note_constexpr_ltor_incomplete_type) << CharTy;
9669 return false;
9670 }
9671 // Give up on byte-oriented matching against multibyte elements.
9672 // FIXME: We can compare the bytes in the correct order.
9673 if (IsRawByte && !isOneByteCharacterType(T: CharTy)) {
9674 Info.FFDiag(E, DiagId: diag::note_constexpr_memchr_unsupported)
9675 << ("'" + Info.Ctx.BuiltinInfo.getName(ID: BuiltinOp) + "'").str()
9676 << CharTy;
9677 return false;
9678 }
9679 // Figure out what value we're actually looking for (after converting to
9680 // the corresponding unsigned type if necessary).
9681 uint64_t DesiredVal;
9682 bool StopAtNull = false;
9683 switch (BuiltinOp) {
9684 case Builtin::BIstrchr:
9685 case Builtin::BI__builtin_strchr:
9686 // strchr compares directly to the passed integer, and therefore
9687 // always fails if given an int that is not a char.
9688 if (!APSInt::isSameValue(I1: HandleIntToIntCast(Info, E, DestType: CharTy,
9689 SrcType: E->getArg(Arg: 1)->getType(),
9690 Value: Desired),
9691 I2: Desired))
9692 return ZeroInitialization(E);
9693 StopAtNull = true;
9694 [[fallthrough]];
9695 case Builtin::BImemchr:
9696 case Builtin::BI__builtin_memchr:
9697 case Builtin::BI__builtin_char_memchr:
9698 // memchr compares by converting both sides to unsigned char. That's also
9699 // correct for strchr if we get this far (to cope with plain char being
9700 // unsigned in the strchr case).
9701 DesiredVal = Desired.trunc(width: Info.Ctx.getCharWidth()).getZExtValue();
9702 break;
9703
9704 case Builtin::BIwcschr:
9705 case Builtin::BI__builtin_wcschr:
9706 StopAtNull = true;
9707 [[fallthrough]];
9708 case Builtin::BIwmemchr:
9709 case Builtin::BI__builtin_wmemchr:
9710 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9711 DesiredVal = Desired.getZExtValue();
9712 break;
9713 }
9714
9715 for (; MaxLength; --MaxLength) {
9716 APValue Char;
9717 if (!handleLValueToRValueConversion(Info, Conv: E, Type: CharTy, LVal: Result, RVal&: Char) ||
9718 !Char.isInt())
9719 return false;
9720 if (Char.getInt().getZExtValue() == DesiredVal)
9721 return true;
9722 if (StopAtNull && !Char.getInt())
9723 break;
9724 if (!HandleLValueArrayAdjustment(Info, E, LVal&: Result, EltTy: CharTy, Adjustment: 1))
9725 return false;
9726 }
9727 // Not found: return nullptr.
9728 return ZeroInitialization(E);
9729 }
9730
9731 case Builtin::BImemcpy:
9732 case Builtin::BImemmove:
9733 case Builtin::BIwmemcpy:
9734 case Builtin::BIwmemmove:
9735 if (Info.getLangOpts().CPlusPlus11)
9736 Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_function)
9737 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9738 << ("'" + Info.Ctx.BuiltinInfo.getName(ID: BuiltinOp) + "'").str();
9739 else
9740 Info.CCEDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
9741 [[fallthrough]];
9742 case Builtin::BI__builtin_memcpy:
9743 case Builtin::BI__builtin_memmove:
9744 case Builtin::BI__builtin_wmemcpy:
9745 case Builtin::BI__builtin_wmemmove: {
9746 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9747 BuiltinOp == Builtin::BIwmemmove ||
9748 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9749 BuiltinOp == Builtin::BI__builtin_wmemmove;
9750 bool Move = BuiltinOp == Builtin::BImemmove ||
9751 BuiltinOp == Builtin::BIwmemmove ||
9752 BuiltinOp == Builtin::BI__builtin_memmove ||
9753 BuiltinOp == Builtin::BI__builtin_wmemmove;
9754
9755 // The result of mem* is the first argument.
9756 if (!Visit(S: E->getArg(Arg: 0)))
9757 return false;
9758 LValue Dest = Result;
9759
9760 LValue Src;
9761 if (!EvaluatePointer(E: E->getArg(Arg: 1), Result&: Src, Info))
9762 return false;
9763
9764 APSInt N;
9765 if (!EvaluateInteger(E: E->getArg(Arg: 2), Result&: N, Info))
9766 return false;
9767 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9768
9769 // If the size is zero, we treat this as always being a valid no-op.
9770 // (Even if one of the src and dest pointers is null.)
9771 if (!N)
9772 return true;
9773
9774 // Otherwise, if either of the operands is null, we can't proceed. Don't
9775 // try to determine the type of the copied objects, because there aren't
9776 // any.
9777 if (!Src.Base || !Dest.Base) {
9778 APValue Val;
9779 (!Src.Base ? Src : Dest).moveInto(V&: Val);
9780 Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_null)
9781 << Move << WChar << !!Src.Base
9782 << Val.getAsString(Ctx: Info.Ctx, Ty: E->getArg(Arg: 0)->getType());
9783 return false;
9784 }
9785 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9786 return false;
9787
9788 // We require that Src and Dest are both pointers to arrays of
9789 // trivially-copyable type. (For the wide version, the designator will be
9790 // invalid if the designated object is not a wchar_t.)
9791 QualType T = Dest.Designator.getType(Ctx&: Info.Ctx);
9792 QualType SrcT = Src.Designator.getType(Ctx&: Info.Ctx);
9793 if (!Info.Ctx.hasSameUnqualifiedType(T1: T, T2: SrcT)) {
9794 // FIXME: Consider using our bit_cast implementation to support this.
9795 Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9796 return false;
9797 }
9798 if (T->isIncompleteType()) {
9799 Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9800 return false;
9801 }
9802 if (!T.isTriviallyCopyableType(Context: Info.Ctx)) {
9803 Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_nontrivial) << Move << T;
9804 return false;
9805 }
9806
9807 // Figure out how many T's we're copying.
9808 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9809 if (TSize == 0)
9810 return false;
9811 if (!WChar) {
9812 uint64_t Remainder;
9813 llvm::APInt OrigN = N;
9814 llvm::APInt::udivrem(LHS: OrigN, RHS: TSize, Quotient&: N, Remainder);
9815 if (Remainder) {
9816 Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_unsupported)
9817 << Move << WChar << 0 << T << toString(I: OrigN, Radix: 10, /*Signed*/false)
9818 << (unsigned)TSize;
9819 return false;
9820 }
9821 }
9822
9823 // Check that the copying will remain within the arrays, just so that we
9824 // can give a more meaningful diagnostic. This implicitly also checks that
9825 // N fits into 64 bits.
9826 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9827 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9828 if (N.ugt(RHS: RemainingSrcSize) || N.ugt(RHS: RemainingDestSize)) {
9829 Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_unsupported)
9830 << Move << WChar << (N.ugt(RHS: RemainingSrcSize) ? 1 : 2) << T
9831 << toString(I: N, Radix: 10, /*Signed*/false);
9832 return false;
9833 }
9834 uint64_t NElems = N.getZExtValue();
9835 uint64_t NBytes = NElems * TSize;
9836
9837 // Check for overlap.
9838 int Direction = 1;
9839 if (HasSameBase(A: Src, B: Dest)) {
9840 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9841 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9842 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9843 // Dest is inside the source region.
9844 if (!Move) {
9845 Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_overlap) << WChar;
9846 return false;
9847 }
9848 // For memmove and friends, copy backwards.
9849 if (!HandleLValueArrayAdjustment(Info, E, LVal&: Src, EltTy: T, Adjustment: NElems - 1) ||
9850 !HandleLValueArrayAdjustment(Info, E, LVal&: Dest, EltTy: T, Adjustment: NElems - 1))
9851 return false;
9852 Direction = -1;
9853 } else if (!Move && SrcOffset >= DestOffset &&
9854 SrcOffset - DestOffset < NBytes) {
9855 // Src is inside the destination region for memcpy: invalid.
9856 Info.FFDiag(E, DiagId: diag::note_constexpr_memcpy_overlap) << WChar;
9857 return false;
9858 }
9859 }
9860
9861 while (true) {
9862 APValue Val;
9863 // FIXME: Set WantObjectRepresentation to true if we're copying a
9864 // char-like type?
9865 if (!handleLValueToRValueConversion(Info, Conv: E, Type: T, LVal: Src, RVal&: Val) ||
9866 !handleAssignment(Info, E, LVal: Dest, LValType: T, Val))
9867 return false;
9868 // Do not iterate past the last element; if we're copying backwards, that
9869 // might take us off the start of the array.
9870 if (--NElems == 0)
9871 return true;
9872 if (!HandleLValueArrayAdjustment(Info, E, LVal&: Src, EltTy: T, Adjustment: Direction) ||
9873 !HandleLValueArrayAdjustment(Info, E, LVal&: Dest, EltTy: T, Adjustment: Direction))
9874 return false;
9875 }
9876 }
9877
9878 default:
9879 return false;
9880 }
9881}
9882
9883static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9884 APValue &Result, const InitListExpr *ILE,
9885 QualType AllocType);
9886static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9887 APValue &Result,
9888 const CXXConstructExpr *CCE,
9889 QualType AllocType);
9890
9891bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9892 if (!Info.getLangOpts().CPlusPlus20)
9893 Info.CCEDiag(E, DiagId: diag::note_constexpr_new);
9894
9895 // We cannot speculatively evaluate a delete expression.
9896 if (Info.SpeculativeEvaluationDepth)
9897 return false;
9898
9899 FunctionDecl *OperatorNew = E->getOperatorNew();
9900
9901 bool IsNothrow = false;
9902 bool IsPlacement = false;
9903 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9904 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9905 // FIXME Support array placement new.
9906 assert(E->getNumPlacementArgs() == 1);
9907 if (!EvaluatePointer(E: E->getPlacementArg(I: 0), Result, Info))
9908 return false;
9909 if (Result.Designator.Invalid)
9910 return false;
9911 IsPlacement = true;
9912 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9913 Info.FFDiag(E, DiagId: diag::note_constexpr_new_non_replaceable)
9914 << isa<CXXMethodDecl>(Val: OperatorNew) << OperatorNew;
9915 return false;
9916 } else if (E->getNumPlacementArgs()) {
9917 // The only new-placement list we support is of the form (std::nothrow).
9918 //
9919 // FIXME: There is no restriction on this, but it's not clear that any
9920 // other form makes any sense. We get here for cases such as:
9921 //
9922 // new (std::align_val_t{N}) X(int)
9923 //
9924 // (which should presumably be valid only if N is a multiple of
9925 // alignof(int), and in any case can't be deallocated unless N is
9926 // alignof(X) and X has new-extended alignment).
9927 if (E->getNumPlacementArgs() != 1 ||
9928 !E->getPlacementArg(I: 0)->getType()->isNothrowT())
9929 return Error(E, D: diag::note_constexpr_new_placement);
9930
9931 LValue Nothrow;
9932 if (!EvaluateLValue(E: E->getPlacementArg(I: 0), Result&: Nothrow, Info))
9933 return false;
9934 IsNothrow = true;
9935 }
9936
9937 const Expr *Init = E->getInitializer();
9938 const InitListExpr *ResizedArrayILE = nullptr;
9939 const CXXConstructExpr *ResizedArrayCCE = nullptr;
9940 bool ValueInit = false;
9941
9942 QualType AllocType = E->getAllocatedType();
9943 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9944 const Expr *Stripped = *ArraySize;
9945 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Stripped);
9946 Stripped = ICE->getSubExpr())
9947 if (ICE->getCastKind() != CK_NoOp &&
9948 ICE->getCastKind() != CK_IntegralCast)
9949 break;
9950
9951 llvm::APSInt ArrayBound;
9952 if (!EvaluateInteger(E: Stripped, Result&: ArrayBound, Info))
9953 return false;
9954
9955 // C++ [expr.new]p9:
9956 // The expression is erroneous if:
9957 // -- [...] its value before converting to size_t [or] applying the
9958 // second standard conversion sequence is less than zero
9959 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9960 if (IsNothrow)
9961 return ZeroInitialization(E);
9962
9963 Info.FFDiag(E: *ArraySize, DiagId: diag::note_constexpr_new_negative)
9964 << ArrayBound << (*ArraySize)->getSourceRange();
9965 return false;
9966 }
9967
9968 // -- its value is such that the size of the allocated object would
9969 // exceed the implementation-defined limit
9970 if (!Info.CheckArraySize(Loc: ArraySize.value()->getExprLoc(),
9971 BitWidth: ConstantArrayType::getNumAddressingBits(
9972 Context: Info.Ctx, ElementType: AllocType, NumElements: ArrayBound),
9973 ElemCount: ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
9974 if (IsNothrow)
9975 return ZeroInitialization(E);
9976 return false;
9977 }
9978
9979 // -- the new-initializer is a braced-init-list and the number of
9980 // array elements for which initializers are provided [...]
9981 // exceeds the number of elements to initialize
9982 if (!Init) {
9983 // No initialization is performed.
9984 } else if (isa<CXXScalarValueInitExpr>(Val: Init) ||
9985 isa<ImplicitValueInitExpr>(Val: Init)) {
9986 ValueInit = true;
9987 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) {
9988 ResizedArrayCCE = CCE;
9989 } else {
9990 auto *CAT = Info.Ctx.getAsConstantArrayType(T: Init->getType());
9991 assert(CAT && "unexpected type for array initializer");
9992
9993 unsigned Bits =
9994 std::max(a: CAT->getSizeBitWidth(), b: ArrayBound.getBitWidth());
9995 llvm::APInt InitBound = CAT->getSize().zext(width: Bits);
9996 llvm::APInt AllocBound = ArrayBound.zext(width: Bits);
9997 if (InitBound.ugt(RHS: AllocBound)) {
9998 if (IsNothrow)
9999 return ZeroInitialization(E);
10000
10001 Info.FFDiag(E: *ArraySize, DiagId: diag::note_constexpr_new_too_small)
10002 << toString(I: AllocBound, Radix: 10, /*Signed=*/false)
10003 << toString(I: InitBound, Radix: 10, /*Signed=*/false)
10004 << (*ArraySize)->getSourceRange();
10005 return false;
10006 }
10007
10008 // If the sizes differ, we must have an initializer list, and we need
10009 // special handling for this case when we initialize.
10010 if (InitBound != AllocBound)
10011 ResizedArrayILE = cast<InitListExpr>(Val: Init);
10012 }
10013
10014 AllocType = Info.Ctx.getConstantArrayType(EltTy: AllocType, ArySize: ArrayBound, SizeExpr: nullptr,
10015 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10016 } else {
10017 assert(!AllocType->isArrayType() &&
10018 "array allocation with non-array new");
10019 }
10020
10021 APValue *Val;
10022 if (IsPlacement) {
10023 AccessKinds AK = AK_Construct;
10024 struct FindObjectHandler {
10025 EvalInfo &Info;
10026 const Expr *E;
10027 QualType AllocType;
10028 const AccessKinds AccessKind;
10029 APValue *Value;
10030
10031 typedef bool result_type;
10032 bool failed() { return false; }
10033 bool found(APValue &Subobj, QualType SubobjType) {
10034 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10035 // old name of the object to be used to name the new object.
10036 if (!Info.Ctx.hasSameUnqualifiedType(T1: SubobjType, T2: AllocType)) {
10037 Info.FFDiag(E, DiagId: diag::note_constexpr_placement_new_wrong_type) <<
10038 SubobjType << AllocType;
10039 return false;
10040 }
10041 Value = &Subobj;
10042 return true;
10043 }
10044 bool found(APSInt &Value, QualType SubobjType) {
10045 Info.FFDiag(E, DiagId: diag::note_constexpr_construct_complex_elem);
10046 return false;
10047 }
10048 bool found(APFloat &Value, QualType SubobjType) {
10049 Info.FFDiag(E, DiagId: diag::note_constexpr_construct_complex_elem);
10050 return false;
10051 }
10052 } Handler = {.Info: Info, .E: E, .AllocType: AllocType, .AccessKind: AK, .Value: nullptr};
10053
10054 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal: Result, LValType: AllocType);
10055 if (!Obj || !findSubobject(Info, E, Obj, Sub: Result.Designator, handler&: Handler))
10056 return false;
10057
10058 Val = Handler.Value;
10059
10060 // [basic.life]p1:
10061 // The lifetime of an object o of type T ends when [...] the storage
10062 // which the object occupies is [...] reused by an object that is not
10063 // nested within o (6.6.2).
10064 *Val = APValue();
10065 } else {
10066 // Perform the allocation and obtain a pointer to the resulting object.
10067 Val = Info.createHeapAlloc(E, T: AllocType, LV&: Result);
10068 if (!Val)
10069 return false;
10070 }
10071
10072 if (ValueInit) {
10073 ImplicitValueInitExpr VIE(AllocType);
10074 if (!EvaluateInPlace(Result&: *Val, Info, This: Result, E: &VIE))
10075 return false;
10076 } else if (ResizedArrayILE) {
10077 if (!EvaluateArrayNewInitList(Info, This&: Result, Result&: *Val, ILE: ResizedArrayILE,
10078 AllocType))
10079 return false;
10080 } else if (ResizedArrayCCE) {
10081 if (!EvaluateArrayNewConstructExpr(Info, This&: Result, Result&: *Val, CCE: ResizedArrayCCE,
10082 AllocType))
10083 return false;
10084 } else if (Init) {
10085 if (!EvaluateInPlace(Result&: *Val, Info, This: Result, E: Init))
10086 return false;
10087 } else if (!handleDefaultInitValue(T: AllocType, Result&: *Val)) {
10088 return false;
10089 }
10090
10091 // Array new returns a pointer to the first element, not a pointer to the
10092 // array.
10093 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10094 Result.addArray(Info, E, CAT: cast<ConstantArrayType>(Val: AT));
10095
10096 return true;
10097}
10098//===----------------------------------------------------------------------===//
10099// Member Pointer Evaluation
10100//===----------------------------------------------------------------------===//
10101
10102namespace {
10103class MemberPointerExprEvaluator
10104 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10105 MemberPtr &Result;
10106
10107 bool Success(const ValueDecl *D) {
10108 Result = MemberPtr(D);
10109 return true;
10110 }
10111public:
10112
10113 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10114 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10115
10116 bool Success(const APValue &V, const Expr *E) {
10117 Result.setFrom(V);
10118 return true;
10119 }
10120 bool ZeroInitialization(const Expr *E) {
10121 return Success(D: (const ValueDecl*)nullptr);
10122 }
10123
10124 bool VisitCastExpr(const CastExpr *E);
10125 bool VisitUnaryAddrOf(const UnaryOperator *E);
10126};
10127} // end anonymous namespace
10128
10129static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10130 EvalInfo &Info) {
10131 assert(!E->isValueDependent());
10132 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10133 return MemberPointerExprEvaluator(Info, Result).Visit(S: E);
10134}
10135
10136bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10137 switch (E->getCastKind()) {
10138 default:
10139 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10140
10141 case CK_NullToMemberPointer:
10142 VisitIgnoredValue(E: E->getSubExpr());
10143 return ZeroInitialization(E);
10144
10145 case CK_BaseToDerivedMemberPointer: {
10146 if (!Visit(S: E->getSubExpr()))
10147 return false;
10148 if (E->path_empty())
10149 return true;
10150 // Base-to-derived member pointer casts store the path in derived-to-base
10151 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10152 // the wrong end of the derived->base arc, so stagger the path by one class.
10153 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10154 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10155 PathI != PathE; ++PathI) {
10156 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10157 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10158 if (!Result.castToDerived(Derived))
10159 return Error(E);
10160 }
10161 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10162 if (!Result.castToDerived(Derived: FinalTy->getAsCXXRecordDecl()))
10163 return Error(E);
10164 return true;
10165 }
10166
10167 case CK_DerivedToBaseMemberPointer:
10168 if (!Visit(S: E->getSubExpr()))
10169 return false;
10170 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10171 PathE = E->path_end(); PathI != PathE; ++PathI) {
10172 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10173 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10174 if (!Result.castToBase(Base))
10175 return Error(E);
10176 }
10177 return true;
10178 }
10179}
10180
10181bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10182 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10183 // member can be formed.
10184 return Success(D: cast<DeclRefExpr>(Val: E->getSubExpr())->getDecl());
10185}
10186
10187//===----------------------------------------------------------------------===//
10188// Record Evaluation
10189//===----------------------------------------------------------------------===//
10190
10191namespace {
10192 class RecordExprEvaluator
10193 : public ExprEvaluatorBase<RecordExprEvaluator> {
10194 const LValue &This;
10195 APValue &Result;
10196 public:
10197
10198 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10199 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10200
10201 bool Success(const APValue &V, const Expr *E) {
10202 Result = V;
10203 return true;
10204 }
10205 bool ZeroInitialization(const Expr *E) {
10206 return ZeroInitialization(E, T: E->getType());
10207 }
10208 bool ZeroInitialization(const Expr *E, QualType T);
10209
10210 bool VisitCallExpr(const CallExpr *E) {
10211 return handleCallExpr(E, Result, ResultSlot: &This);
10212 }
10213 bool VisitCastExpr(const CastExpr *E);
10214 bool VisitInitListExpr(const InitListExpr *E);
10215 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10216 return VisitCXXConstructExpr(E, T: E->getType());
10217 }
10218 bool VisitLambdaExpr(const LambdaExpr *E);
10219 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10220 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10221 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10222 bool VisitBinCmp(const BinaryOperator *E);
10223 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10224 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10225 ArrayRef<Expr *> Args);
10226 };
10227}
10228
10229/// Perform zero-initialization on an object of non-union class type.
10230/// C++11 [dcl.init]p5:
10231/// To zero-initialize an object or reference of type T means:
10232/// [...]
10233/// -- if T is a (possibly cv-qualified) non-union class type,
10234/// each non-static data member and each base-class subobject is
10235/// zero-initialized
10236static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10237 const RecordDecl *RD,
10238 const LValue &This, APValue &Result) {
10239 assert(!RD->isUnion() && "Expected non-union class type");
10240 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(Val: RD);
10241 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10242 std::distance(first: RD->field_begin(), last: RD->field_end()));
10243
10244 if (RD->isInvalidDecl()) return false;
10245 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD);
10246
10247 if (CD) {
10248 unsigned Index = 0;
10249 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
10250 End = CD->bases_end(); I != End; ++I, ++Index) {
10251 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10252 LValue Subobject = This;
10253 if (!HandleLValueDirectBase(Info, E, Obj&: Subobject, Derived: CD, Base, RL: &Layout))
10254 return false;
10255 if (!HandleClassZeroInitialization(Info, E, RD: Base, This: Subobject,
10256 Result&: Result.getStructBase(i: Index)))
10257 return false;
10258 }
10259 }
10260
10261 for (const auto *I : RD->fields()) {
10262 // -- if T is a reference type, no initialization is performed.
10263 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10264 continue;
10265
10266 LValue Subobject = This;
10267 if (!HandleLValueMember(Info, E, LVal&: Subobject, FD: I, RL: &Layout))
10268 return false;
10269
10270 ImplicitValueInitExpr VIE(I->getType());
10271 if (!EvaluateInPlace(
10272 Result&: Result.getStructField(i: I->getFieldIndex()), Info, This: Subobject, E: &VIE))
10273 return false;
10274 }
10275
10276 return true;
10277}
10278
10279bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10280 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10281 if (RD->isInvalidDecl()) return false;
10282 if (RD->isUnion()) {
10283 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10284 // object's first non-static named data member is zero-initialized
10285 RecordDecl::field_iterator I = RD->field_begin();
10286 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10287 ++I;
10288 if (I == RD->field_end()) {
10289 Result = APValue((const FieldDecl*)nullptr);
10290 return true;
10291 }
10292
10293 LValue Subobject = This;
10294 if (!HandleLValueMember(Info, E, LVal&: Subobject, FD: *I))
10295 return false;
10296 Result = APValue(*I);
10297 ImplicitValueInitExpr VIE(I->getType());
10298 return EvaluateInPlace(Result&: Result.getUnionValue(), Info, This: Subobject, E: &VIE);
10299 }
10300
10301 if (isa<CXXRecordDecl>(Val: RD) && cast<CXXRecordDecl>(Val: RD)->getNumVBases()) {
10302 Info.FFDiag(E, DiagId: diag::note_constexpr_virtual_base) << RD;
10303 return false;
10304 }
10305
10306 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10307}
10308
10309bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10310 switch (E->getCastKind()) {
10311 default:
10312 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10313
10314 case CK_ConstructorConversion:
10315 return Visit(S: E->getSubExpr());
10316
10317 case CK_DerivedToBase:
10318 case CK_UncheckedDerivedToBase: {
10319 APValue DerivedObject;
10320 if (!Evaluate(Result&: DerivedObject, Info, E: E->getSubExpr()))
10321 return false;
10322 if (!DerivedObject.isStruct())
10323 return Error(E: E->getSubExpr());
10324
10325 // Derived-to-base rvalue conversion: just slice off the derived part.
10326 APValue *Value = &DerivedObject;
10327 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10328 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10329 PathE = E->path_end(); PathI != PathE; ++PathI) {
10330 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10331 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10332 Value = &Value->getStructBase(i: getBaseIndex(Derived: RD, Base));
10333 RD = Base;
10334 }
10335 Result = *Value;
10336 return true;
10337 }
10338 }
10339}
10340
10341bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10342 if (E->isTransparent())
10343 return Visit(S: E->getInit(Init: 0));
10344 return VisitCXXParenListOrInitListExpr(ExprToVisit: E, Args: E->inits());
10345}
10346
10347bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10348 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10349 const RecordDecl *RD =
10350 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10351 if (RD->isInvalidDecl()) return false;
10352 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: RD);
10353 auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD);
10354
10355 EvalInfo::EvaluatingConstructorRAII EvalObj(
10356 Info,
10357 ObjectUnderConstruction{.Base: This.getLValueBase(), .Path: This.Designator.Entries},
10358 CXXRD && CXXRD->getNumBases());
10359
10360 if (RD->isUnion()) {
10361 const FieldDecl *Field;
10362 if (auto *ILE = dyn_cast<InitListExpr>(Val: ExprToVisit)) {
10363 Field = ILE->getInitializedFieldInUnion();
10364 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(Val: ExprToVisit)) {
10365 Field = PLIE->getInitializedFieldInUnion();
10366 } else {
10367 llvm_unreachable(
10368 "Expression is neither an init list nor a C++ paren list");
10369 }
10370
10371 Result = APValue(Field);
10372 if (!Field)
10373 return true;
10374
10375 // If the initializer list for a union does not contain any elements, the
10376 // first element of the union is value-initialized.
10377 // FIXME: The element should be initialized from an initializer list.
10378 // Is this difference ever observable for initializer lists which
10379 // we don't build?
10380 ImplicitValueInitExpr VIE(Field->getType());
10381 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10382
10383 LValue Subobject = This;
10384 if (!HandleLValueMember(Info, E: InitExpr, LVal&: Subobject, FD: Field, RL: &Layout))
10385 return false;
10386
10387 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10388 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10389 isa<CXXDefaultInitExpr>(Val: InitExpr));
10390
10391 if (EvaluateInPlace(Result&: Result.getUnionValue(), Info, This: Subobject, E: InitExpr)) {
10392 if (Field->isBitField())
10393 return truncateBitfieldValue(Info, E: InitExpr, Value&: Result.getUnionValue(),
10394 FD: Field);
10395 return true;
10396 }
10397
10398 return false;
10399 }
10400
10401 if (!Result.hasValue())
10402 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10403 std::distance(first: RD->field_begin(), last: RD->field_end()));
10404 unsigned ElementNo = 0;
10405 bool Success = true;
10406
10407 // Initialize base classes.
10408 if (CXXRD && CXXRD->getNumBases()) {
10409 for (const auto &Base : CXXRD->bases()) {
10410 assert(ElementNo < Args.size() && "missing init for base class");
10411 const Expr *Init = Args[ElementNo];
10412
10413 LValue Subobject = This;
10414 if (!HandleLValueBase(Info, E: Init, Obj&: Subobject, DerivedDecl: CXXRD, Base: &Base))
10415 return false;
10416
10417 APValue &FieldVal = Result.getStructBase(i: ElementNo);
10418 if (!EvaluateInPlace(Result&: FieldVal, Info, This: Subobject, E: Init)) {
10419 if (!Info.noteFailure())
10420 return false;
10421 Success = false;
10422 }
10423 ++ElementNo;
10424 }
10425
10426 EvalObj.finishedConstructingBases();
10427 }
10428
10429 // Initialize members.
10430 for (const auto *Field : RD->fields()) {
10431 // Anonymous bit-fields are not considered members of the class for
10432 // purposes of aggregate initialization.
10433 if (Field->isUnnamedBitField())
10434 continue;
10435
10436 LValue Subobject = This;
10437
10438 bool HaveInit = ElementNo < Args.size();
10439
10440 // FIXME: Diagnostics here should point to the end of the initializer
10441 // list, not the start.
10442 if (!HandleLValueMember(Info, E: HaveInit ? Args[ElementNo] : ExprToVisit,
10443 LVal&: Subobject, FD: Field, RL: &Layout))
10444 return false;
10445
10446 // Perform an implicit value-initialization for members beyond the end of
10447 // the initializer list.
10448 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10449 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10450
10451 if (Field->getType()->isIncompleteArrayType()) {
10452 if (auto *CAT = Info.Ctx.getAsConstantArrayType(T: Init->getType())) {
10453 if (!CAT->isZeroSize()) {
10454 // Bail out for now. This might sort of "work", but the rest of the
10455 // code isn't really prepared to handle it.
10456 Info.FFDiag(E: Init, DiagId: diag::note_constexpr_unsupported_flexible_array);
10457 return false;
10458 }
10459 }
10460 }
10461
10462 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10463 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10464 isa<CXXDefaultInitExpr>(Val: Init));
10465
10466 APValue &FieldVal = Result.getStructField(i: Field->getFieldIndex());
10467 if (!EvaluateInPlace(Result&: FieldVal, Info, This: Subobject, E: Init) ||
10468 (Field->isBitField() && !truncateBitfieldValue(Info, E: Init,
10469 Value&: FieldVal, FD: Field))) {
10470 if (!Info.noteFailure())
10471 return false;
10472 Success = false;
10473 }
10474 }
10475
10476 EvalObj.finishedConstructingFields();
10477
10478 return Success;
10479}
10480
10481bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10482 QualType T) {
10483 // Note that E's type is not necessarily the type of our class here; we might
10484 // be initializing an array element instead.
10485 const CXXConstructorDecl *FD = E->getConstructor();
10486 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10487
10488 bool ZeroInit = E->requiresZeroInitialization();
10489 if (CheckTrivialDefaultConstructor(Info, Loc: E->getExprLoc(), CD: FD, IsValueInitialization: ZeroInit)) {
10490 // If we've already performed zero-initialization, we're already done.
10491 if (Result.hasValue())
10492 return true;
10493
10494 if (ZeroInit)
10495 return ZeroInitialization(E, T);
10496
10497 return handleDefaultInitValue(T, Result);
10498 }
10499
10500 const FunctionDecl *Definition = nullptr;
10501 auto Body = FD->getBody(Definition);
10502
10503 if (!CheckConstexprFunction(Info, CallLoc: E->getExprLoc(), Declaration: FD, Definition, Body))
10504 return false;
10505
10506 // Avoid materializing a temporary for an elidable copy/move constructor.
10507 if (E->isElidable() && !ZeroInit) {
10508 // FIXME: This only handles the simplest case, where the source object
10509 // is passed directly as the first argument to the constructor.
10510 // This should also handle stepping though implicit casts and
10511 // and conversion sequences which involve two steps, with a
10512 // conversion operator followed by a converting constructor.
10513 const Expr *SrcObj = E->getArg(Arg: 0);
10514 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10515 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10516 if (const MaterializeTemporaryExpr *ME =
10517 dyn_cast<MaterializeTemporaryExpr>(Val: SrcObj))
10518 return Visit(S: ME->getSubExpr());
10519 }
10520
10521 if (ZeroInit && !ZeroInitialization(E, T))
10522 return false;
10523
10524 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10525 return HandleConstructorCall(E, This, Args,
10526 Definition: cast<CXXConstructorDecl>(Val: Definition), Info,
10527 Result);
10528}
10529
10530bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10531 const CXXInheritedCtorInitExpr *E) {
10532 if (!Info.CurrentCall) {
10533 assert(Info.checkingPotentialConstantExpression());
10534 return false;
10535 }
10536
10537 const CXXConstructorDecl *FD = E->getConstructor();
10538 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10539 return false;
10540
10541 const FunctionDecl *Definition = nullptr;
10542 auto Body = FD->getBody(Definition);
10543
10544 if (!CheckConstexprFunction(Info, CallLoc: E->getExprLoc(), Declaration: FD, Definition, Body))
10545 return false;
10546
10547 return HandleConstructorCall(E, This, Call: Info.CurrentCall->Arguments,
10548 Definition: cast<CXXConstructorDecl>(Val: Definition), Info,
10549 Result);
10550}
10551
10552bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10553 const CXXStdInitializerListExpr *E) {
10554 const ConstantArrayType *ArrayType =
10555 Info.Ctx.getAsConstantArrayType(T: E->getSubExpr()->getType());
10556
10557 LValue Array;
10558 if (!EvaluateLValue(E: E->getSubExpr(), Result&: Array, Info))
10559 return false;
10560
10561 assert(ArrayType && "unexpected type for array initializer");
10562
10563 // Get a pointer to the first element of the array.
10564 Array.addArray(Info, E, CAT: ArrayType);
10565
10566 // FIXME: What if the initializer_list type has base classes, etc?
10567 Result = APValue(APValue::UninitStruct(), 0, 2);
10568 Array.moveInto(V&: Result.getStructField(i: 0));
10569
10570 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10571 RecordDecl::field_iterator Field = Record->field_begin();
10572 assert(Field != Record->field_end() &&
10573 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10574 ArrayType->getElementType()) &&
10575 "Expected std::initializer_list first field to be const E *");
10576 ++Field;
10577 assert(Field != Record->field_end() &&
10578 "Expected std::initializer_list to have two fields");
10579
10580 if (Info.Ctx.hasSameType(T1: Field->getType(), T2: Info.Ctx.getSizeType())) {
10581 // Length.
10582 Result.getStructField(i: 1) = APValue(APSInt(ArrayType->getSize()));
10583 } else {
10584 // End pointer.
10585 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10586 ArrayType->getElementType()) &&
10587 "Expected std::initializer_list second field to be const E *");
10588 if (!HandleLValueArrayAdjustment(Info, E, LVal&: Array,
10589 EltTy: ArrayType->getElementType(),
10590 Adjustment: ArrayType->getZExtSize()))
10591 return false;
10592 Array.moveInto(V&: Result.getStructField(i: 1));
10593 }
10594
10595 assert(++Field == Record->field_end() &&
10596 "Expected std::initializer_list to only have two fields");
10597
10598 return true;
10599}
10600
10601bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10602 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10603 if (ClosureClass->isInvalidDecl())
10604 return false;
10605
10606 const size_t NumFields =
10607 std::distance(first: ClosureClass->field_begin(), last: ClosureClass->field_end());
10608
10609 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10610 E->capture_init_end()) &&
10611 "The number of lambda capture initializers should equal the number of "
10612 "fields within the closure type");
10613
10614 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10615 // Iterate through all the lambda's closure object's fields and initialize
10616 // them.
10617 auto *CaptureInitIt = E->capture_init_begin();
10618 bool Success = true;
10619 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(D: ClosureClass);
10620 for (const auto *Field : ClosureClass->fields()) {
10621 assert(CaptureInitIt != E->capture_init_end());
10622 // Get the initializer for this field
10623 Expr *const CurFieldInit = *CaptureInitIt++;
10624
10625 // If there is no initializer, either this is a VLA or an error has
10626 // occurred.
10627 if (!CurFieldInit)
10628 return Error(E);
10629
10630 LValue Subobject = This;
10631
10632 if (!HandleLValueMember(Info, E, LVal&: Subobject, FD: Field, RL: &Layout))
10633 return false;
10634
10635 APValue &FieldVal = Result.getStructField(i: Field->getFieldIndex());
10636 if (!EvaluateInPlace(Result&: FieldVal, Info, This: Subobject, E: CurFieldInit)) {
10637 if (!Info.keepEvaluatingAfterFailure())
10638 return false;
10639 Success = false;
10640 }
10641 }
10642 return Success;
10643}
10644
10645static bool EvaluateRecord(const Expr *E, const LValue &This,
10646 APValue &Result, EvalInfo &Info) {
10647 assert(!E->isValueDependent());
10648 assert(E->isPRValue() && E->getType()->isRecordType() &&
10649 "can't evaluate expression as a record rvalue");
10650 return RecordExprEvaluator(Info, This, Result).Visit(S: E);
10651}
10652
10653//===----------------------------------------------------------------------===//
10654// Temporary Evaluation
10655//
10656// Temporaries are represented in the AST as rvalues, but generally behave like
10657// lvalues. The full-object of which the temporary is a subobject is implicitly
10658// materialized so that a reference can bind to it.
10659//===----------------------------------------------------------------------===//
10660namespace {
10661class TemporaryExprEvaluator
10662 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10663public:
10664 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10665 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10666
10667 /// Visit an expression which constructs the value of this temporary.
10668 bool VisitConstructExpr(const Expr *E) {
10669 APValue &Value = Info.CurrentCall->createTemporary(
10670 Key: E, T: E->getType(), Scope: ScopeKind::FullExpression, LV&: Result);
10671 return EvaluateInPlace(Result&: Value, Info, This: Result, E);
10672 }
10673
10674 bool VisitCastExpr(const CastExpr *E) {
10675 switch (E->getCastKind()) {
10676 default:
10677 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10678
10679 case CK_ConstructorConversion:
10680 return VisitConstructExpr(E: E->getSubExpr());
10681 }
10682 }
10683 bool VisitInitListExpr(const InitListExpr *E) {
10684 return VisitConstructExpr(E);
10685 }
10686 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10687 return VisitConstructExpr(E);
10688 }
10689 bool VisitCallExpr(const CallExpr *E) {
10690 return VisitConstructExpr(E);
10691 }
10692 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10693 return VisitConstructExpr(E);
10694 }
10695 bool VisitLambdaExpr(const LambdaExpr *E) {
10696 return VisitConstructExpr(E);
10697 }
10698};
10699} // end anonymous namespace
10700
10701/// Evaluate an expression of record type as a temporary.
10702static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10703 assert(!E->isValueDependent());
10704 assert(E->isPRValue() && E->getType()->isRecordType());
10705 return TemporaryExprEvaluator(Info, Result).Visit(S: E);
10706}
10707
10708//===----------------------------------------------------------------------===//
10709// Vector Evaluation
10710//===----------------------------------------------------------------------===//
10711
10712namespace {
10713 class VectorExprEvaluator
10714 : public ExprEvaluatorBase<VectorExprEvaluator> {
10715 APValue &Result;
10716 public:
10717
10718 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10719 : ExprEvaluatorBaseTy(info), Result(Result) {}
10720
10721 bool Success(ArrayRef<APValue> V, const Expr *E) {
10722 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10723 // FIXME: remove this APValue copy.
10724 Result = APValue(V.data(), V.size());
10725 return true;
10726 }
10727 bool Success(const APValue &V, const Expr *E) {
10728 assert(V.isVector());
10729 Result = V;
10730 return true;
10731 }
10732 bool ZeroInitialization(const Expr *E);
10733
10734 bool VisitUnaryReal(const UnaryOperator *E)
10735 { return Visit(S: E->getSubExpr()); }
10736 bool VisitCastExpr(const CastExpr* E);
10737 bool VisitInitListExpr(const InitListExpr *E);
10738 bool VisitUnaryImag(const UnaryOperator *E);
10739 bool VisitBinaryOperator(const BinaryOperator *E);
10740 bool VisitUnaryOperator(const UnaryOperator *E);
10741 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
10742 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
10743
10744 // FIXME: Missing: conditional operator (for GNU
10745 // conditional select), ExtVectorElementExpr
10746 };
10747} // end anonymous namespace
10748
10749static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10750 assert(E->isPRValue() && E->getType()->isVectorType() &&
10751 "not a vector prvalue");
10752 return VectorExprEvaluator(Info, Result).Visit(S: E);
10753}
10754
10755bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10756 const VectorType *VTy = E->getType()->castAs<VectorType>();
10757 unsigned NElts = VTy->getNumElements();
10758
10759 const Expr *SE = E->getSubExpr();
10760 QualType SETy = SE->getType();
10761
10762 switch (E->getCastKind()) {
10763 case CK_VectorSplat: {
10764 APValue Val = APValue();
10765 if (SETy->isIntegerType()) {
10766 APSInt IntResult;
10767 if (!EvaluateInteger(E: SE, Result&: IntResult, Info))
10768 return false;
10769 Val = APValue(std::move(IntResult));
10770 } else if (SETy->isRealFloatingType()) {
10771 APFloat FloatResult(0.0);
10772 if (!EvaluateFloat(E: SE, Result&: FloatResult, Info))
10773 return false;
10774 Val = APValue(std::move(FloatResult));
10775 } else {
10776 return Error(E);
10777 }
10778
10779 // Splat and create vector APValue.
10780 SmallVector<APValue, 4> Elts(NElts, Val);
10781 return Success(V: Elts, E);
10782 }
10783 case CK_BitCast: {
10784 APValue SVal;
10785 if (!Evaluate(Result&: SVal, Info, E: SE))
10786 return false;
10787
10788 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
10789 // Give up if the input isn't an int, float, or vector. For example, we
10790 // reject "(v4i16)(intptr_t)&a".
10791 Info.FFDiag(E, DiagId: diag::note_constexpr_invalid_cast)
10792 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
10793 return false;
10794 }
10795
10796 if (!handleRValueToRValueBitCast(Info, DestValue&: Result, SourceRValue: SVal, BCE: E))
10797 return false;
10798
10799 return true;
10800 }
10801 default:
10802 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10803 }
10804}
10805
10806bool
10807VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10808 const VectorType *VT = E->getType()->castAs<VectorType>();
10809 unsigned NumInits = E->getNumInits();
10810 unsigned NumElements = VT->getNumElements();
10811
10812 QualType EltTy = VT->getElementType();
10813 SmallVector<APValue, 4> Elements;
10814
10815 // The number of initializers can be less than the number of
10816 // vector elements. For OpenCL, this can be due to nested vector
10817 // initialization. For GCC compatibility, missing trailing elements
10818 // should be initialized with zeroes.
10819 unsigned CountInits = 0, CountElts = 0;
10820 while (CountElts < NumElements) {
10821 // Handle nested vector initialization.
10822 if (CountInits < NumInits
10823 && E->getInit(Init: CountInits)->getType()->isVectorType()) {
10824 APValue v;
10825 if (!EvaluateVector(E: E->getInit(Init: CountInits), Result&: v, Info))
10826 return Error(E);
10827 unsigned vlen = v.getVectorLength();
10828 for (unsigned j = 0; j < vlen; j++)
10829 Elements.push_back(Elt: v.getVectorElt(I: j));
10830 CountElts += vlen;
10831 } else if (EltTy->isIntegerType()) {
10832 llvm::APSInt sInt(32);
10833 if (CountInits < NumInits) {
10834 if (!EvaluateInteger(E: E->getInit(Init: CountInits), Result&: sInt, Info))
10835 return false;
10836 } else // trailing integer zero.
10837 sInt = Info.Ctx.MakeIntValue(Value: 0, Type: EltTy);
10838 Elements.push_back(Elt: APValue(sInt));
10839 CountElts++;
10840 } else {
10841 llvm::APFloat f(0.0);
10842 if (CountInits < NumInits) {
10843 if (!EvaluateFloat(E: E->getInit(Init: CountInits), Result&: f, Info))
10844 return false;
10845 } else // trailing float zero.
10846 f = APFloat::getZero(Sem: Info.Ctx.getFloatTypeSemantics(T: EltTy));
10847 Elements.push_back(Elt: APValue(f));
10848 CountElts++;
10849 }
10850 CountInits++;
10851 }
10852 return Success(V: Elements, E);
10853}
10854
10855bool
10856VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10857 const auto *VT = E->getType()->castAs<VectorType>();
10858 QualType EltTy = VT->getElementType();
10859 APValue ZeroElement;
10860 if (EltTy->isIntegerType())
10861 ZeroElement = APValue(Info.Ctx.MakeIntValue(Value: 0, Type: EltTy));
10862 else
10863 ZeroElement =
10864 APValue(APFloat::getZero(Sem: Info.Ctx.getFloatTypeSemantics(T: EltTy)));
10865
10866 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10867 return Success(V: Elements, E);
10868}
10869
10870bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10871 VisitIgnoredValue(E: E->getSubExpr());
10872 return ZeroInitialization(E);
10873}
10874
10875bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10876 BinaryOperatorKind Op = E->getOpcode();
10877 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10878 "Operation not supported on vector types");
10879
10880 if (Op == BO_Comma)
10881 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10882
10883 Expr *LHS = E->getLHS();
10884 Expr *RHS = E->getRHS();
10885
10886 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10887 "Must both be vector types");
10888 // Checking JUST the types are the same would be fine, except shifts don't
10889 // need to have their types be the same (since you always shift by an int).
10890 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10891 E->getType()->castAs<VectorType>()->getNumElements() &&
10892 RHS->getType()->castAs<VectorType>()->getNumElements() ==
10893 E->getType()->castAs<VectorType>()->getNumElements() &&
10894 "All operands must be the same size.");
10895
10896 APValue LHSValue;
10897 APValue RHSValue;
10898 bool LHSOK = Evaluate(Result&: LHSValue, Info, E: LHS);
10899 if (!LHSOK && !Info.noteFailure())
10900 return false;
10901 if (!Evaluate(Result&: RHSValue, Info, E: RHS) || !LHSOK)
10902 return false;
10903
10904 if (!handleVectorVectorBinOp(Info, E, Opcode: Op, LHSValue, RHSValue))
10905 return false;
10906
10907 return Success(V: LHSValue, E);
10908}
10909
10910static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10911 QualType ResultTy,
10912 UnaryOperatorKind Op,
10913 APValue Elt) {
10914 switch (Op) {
10915 case UO_Plus:
10916 // Nothing to do here.
10917 return Elt;
10918 case UO_Minus:
10919 if (Elt.getKind() == APValue::Int) {
10920 Elt.getInt().negate();
10921 } else {
10922 assert(Elt.getKind() == APValue::Float &&
10923 "Vector can only be int or float type");
10924 Elt.getFloat().changeSign();
10925 }
10926 return Elt;
10927 case UO_Not:
10928 // This is only valid for integral types anyway, so we don't have to handle
10929 // float here.
10930 assert(Elt.getKind() == APValue::Int &&
10931 "Vector operator ~ can only be int");
10932 Elt.getInt().flipAllBits();
10933 return Elt;
10934 case UO_LNot: {
10935 if (Elt.getKind() == APValue::Int) {
10936 Elt.getInt() = !Elt.getInt();
10937 // operator ! on vectors returns -1 for 'truth', so negate it.
10938 Elt.getInt().negate();
10939 return Elt;
10940 }
10941 assert(Elt.getKind() == APValue::Float &&
10942 "Vector can only be int or float type");
10943 // Float types result in an int of the same size, but -1 for true, or 0 for
10944 // false.
10945 APSInt EltResult{Ctx.getIntWidth(T: ResultTy),
10946 ResultTy->isUnsignedIntegerType()};
10947 if (Elt.getFloat().isZero())
10948 EltResult.setAllBits();
10949 else
10950 EltResult.clearAllBits();
10951
10952 return APValue{EltResult};
10953 }
10954 default:
10955 // FIXME: Implement the rest of the unary operators.
10956 return std::nullopt;
10957 }
10958}
10959
10960bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10961 Expr *SubExpr = E->getSubExpr();
10962 const auto *VD = SubExpr->getType()->castAs<VectorType>();
10963 // This result element type differs in the case of negating a floating point
10964 // vector, since the result type is the a vector of the equivilant sized
10965 // integer.
10966 const QualType ResultEltTy = VD->getElementType();
10967 UnaryOperatorKind Op = E->getOpcode();
10968
10969 APValue SubExprValue;
10970 if (!Evaluate(Result&: SubExprValue, Info, E: SubExpr))
10971 return false;
10972
10973 // FIXME: This vector evaluator someday needs to be changed to be LValue
10974 // aware/keep LValue information around, rather than dealing with just vector
10975 // types directly. Until then, we cannot handle cases where the operand to
10976 // these unary operators is an LValue. The only case I've been able to see
10977 // cause this is operator++ assigning to a member expression (only valid in
10978 // altivec compilations) in C mode, so this shouldn't limit us too much.
10979 if (SubExprValue.isLValue())
10980 return false;
10981
10982 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10983 "Vector length doesn't match type?");
10984
10985 SmallVector<APValue, 4> ResultElements;
10986 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10987 std::optional<APValue> Elt = handleVectorUnaryOperator(
10988 Ctx&: Info.Ctx, ResultTy: ResultEltTy, Op, Elt: SubExprValue.getVectorElt(I: EltNum));
10989 if (!Elt)
10990 return false;
10991 ResultElements.push_back(Elt: *Elt);
10992 }
10993 return Success(V: APValue(ResultElements.data(), ResultElements.size()), E);
10994}
10995
10996static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
10997 const Expr *E, QualType SourceTy,
10998 QualType DestTy, APValue const &Original,
10999 APValue &Result) {
11000 if (SourceTy->isIntegerType()) {
11001 if (DestTy->isRealFloatingType()) {
11002 Result = APValue(APFloat(0.0));
11003 return HandleIntToFloatCast(Info, E, FPO, SrcType: SourceTy, Value: Original.getInt(),
11004 DestType: DestTy, Result&: Result.getFloat());
11005 }
11006 if (DestTy->isIntegerType()) {
11007 Result = APValue(
11008 HandleIntToIntCast(Info, E, DestType: DestTy, SrcType: SourceTy, Value: Original.getInt()));
11009 return true;
11010 }
11011 } else if (SourceTy->isRealFloatingType()) {
11012 if (DestTy->isRealFloatingType()) {
11013 Result = Original;
11014 return HandleFloatToFloatCast(Info, E, SrcType: SourceTy, DestType: DestTy,
11015 Result&: Result.getFloat());
11016 }
11017 if (DestTy->isIntegerType()) {
11018 Result = APValue(APSInt());
11019 return HandleFloatToIntCast(Info, E, SrcType: SourceTy, Value: Original.getFloat(),
11020 DestType: DestTy, Result&: Result.getInt());
11021 }
11022 }
11023
11024 Info.FFDiag(E, DiagId: diag::err_convertvector_constexpr_unsupported_vector_cast)
11025 << SourceTy << DestTy;
11026 return false;
11027}
11028
11029bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11030 APValue Source;
11031 QualType SourceVecType = E->getSrcExpr()->getType();
11032 if (!EvaluateAsRValue(Info, E: E->getSrcExpr(), Result&: Source))
11033 return false;
11034
11035 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11036 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11037
11038 const FPOptions FPO = E->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts());
11039
11040 auto SourceLen = Source.getVectorLength();
11041 SmallVector<APValue, 4> ResultElements;
11042 ResultElements.reserve(N: SourceLen);
11043 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11044 APValue Elt;
11045 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11046 Original: Source.getVectorElt(I: EltNum), Result&: Elt))
11047 return false;
11048 ResultElements.push_back(Elt: std::move(Elt));
11049 }
11050
11051 return Success(V: APValue(ResultElements.data(), ResultElements.size()), E);
11052}
11053
11054static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11055 QualType ElemType, APValue const &VecVal1,
11056 APValue const &VecVal2, unsigned EltNum,
11057 APValue &Result) {
11058 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11059 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11060
11061 APSInt IndexVal = E->getShuffleMaskIdx(Ctx: Info.Ctx, N: EltNum);
11062 int64_t index = IndexVal.getExtValue();
11063 // The spec says that -1 should be treated as undef for optimizations,
11064 // but in constexpr we'd have to produce an APValue::Indeterminate,
11065 // which is prohibited from being a top-level constant value. Emit a
11066 // diagnostic instead.
11067 if (index == -1) {
11068 Info.FFDiag(
11069 E, DiagId: diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11070 << EltNum;
11071 return false;
11072 }
11073
11074 if (index < 0 ||
11075 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11076 llvm_unreachable("Out of bounds shuffle index");
11077
11078 if (index >= TotalElementsInInputVector1)
11079 Result = VecVal2.getVectorElt(I: index - TotalElementsInInputVector1);
11080 else
11081 Result = VecVal1.getVectorElt(I: index);
11082 return true;
11083}
11084
11085bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11086 APValue VecVal1;
11087 const Expr *Vec1 = E->getExpr(Index: 0);
11088 if (!EvaluateAsRValue(Info, E: Vec1, Result&: VecVal1))
11089 return false;
11090 APValue VecVal2;
11091 const Expr *Vec2 = E->getExpr(Index: 1);
11092 if (!EvaluateAsRValue(Info, E: Vec2, Result&: VecVal2))
11093 return false;
11094
11095 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11096 QualType DestElTy = DestVecTy->getElementType();
11097
11098 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11099
11100 SmallVector<APValue, 4> ResultElements;
11101 ResultElements.reserve(N: TotalElementsInOutputVector);
11102 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11103 APValue Elt;
11104 if (!handleVectorShuffle(Info, E, ElemType: DestElTy, VecVal1, VecVal2, EltNum, Result&: Elt))
11105 return false;
11106 ResultElements.push_back(Elt: std::move(Elt));
11107 }
11108
11109 return Success(V: APValue(ResultElements.data(), ResultElements.size()), E);
11110}
11111
11112//===----------------------------------------------------------------------===//
11113// Array Evaluation
11114//===----------------------------------------------------------------------===//
11115
11116namespace {
11117 class ArrayExprEvaluator
11118 : public ExprEvaluatorBase<ArrayExprEvaluator> {
11119 const LValue &This;
11120 APValue &Result;
11121 public:
11122
11123 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11124 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11125
11126 bool Success(const APValue &V, const Expr *E) {
11127 assert(V.isArray() && "expected array");
11128 Result = V;
11129 return true;
11130 }
11131
11132 bool ZeroInitialization(const Expr *E) {
11133 const ConstantArrayType *CAT =
11134 Info.Ctx.getAsConstantArrayType(T: E->getType());
11135 if (!CAT) {
11136 if (E->getType()->isIncompleteArrayType()) {
11137 // We can be asked to zero-initialize a flexible array member; this
11138 // is represented as an ImplicitValueInitExpr of incomplete array
11139 // type. In this case, the array has zero elements.
11140 Result = APValue(APValue::UninitArray(), 0, 0);
11141 return true;
11142 }
11143 // FIXME: We could handle VLAs here.
11144 return Error(E);
11145 }
11146
11147 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11148 if (!Result.hasArrayFiller())
11149 return true;
11150
11151 // Zero-initialize all elements.
11152 LValue Subobject = This;
11153 Subobject.addArray(Info, E, CAT);
11154 ImplicitValueInitExpr VIE(CAT->getElementType());
11155 return EvaluateInPlace(Result&: Result.getArrayFiller(), Info, This: Subobject, E: &VIE);
11156 }
11157
11158 bool VisitCallExpr(const CallExpr *E) {
11159 return handleCallExpr(E, Result, ResultSlot: &This);
11160 }
11161 bool VisitInitListExpr(const InitListExpr *E,
11162 QualType AllocType = QualType());
11163 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11164 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11165 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11166 const LValue &Subobject,
11167 APValue *Value, QualType Type);
11168 bool VisitStringLiteral(const StringLiteral *E,
11169 QualType AllocType = QualType()) {
11170 expandStringLiteral(Info, S: E, Result, AllocType);
11171 return true;
11172 }
11173 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11174 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11175 ArrayRef<Expr *> Args,
11176 const Expr *ArrayFiller,
11177 QualType AllocType = QualType());
11178 };
11179} // end anonymous namespace
11180
11181static bool EvaluateArray(const Expr *E, const LValue &This,
11182 APValue &Result, EvalInfo &Info) {
11183 assert(!E->isValueDependent());
11184 assert(E->isPRValue() && E->getType()->isArrayType() &&
11185 "not an array prvalue");
11186 return ArrayExprEvaluator(Info, This, Result).Visit(S: E);
11187}
11188
11189static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11190 APValue &Result, const InitListExpr *ILE,
11191 QualType AllocType) {
11192 assert(!ILE->isValueDependent());
11193 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11194 "not an array prvalue");
11195 return ArrayExprEvaluator(Info, This, Result)
11196 .VisitInitListExpr(E: ILE, AllocType);
11197}
11198
11199static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11200 APValue &Result,
11201 const CXXConstructExpr *CCE,
11202 QualType AllocType) {
11203 assert(!CCE->isValueDependent());
11204 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11205 "not an array prvalue");
11206 return ArrayExprEvaluator(Info, This, Result)
11207 .VisitCXXConstructExpr(E: CCE, Subobject: This, Value: &Result, Type: AllocType);
11208}
11209
11210// Return true iff the given array filler may depend on the element index.
11211static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11212 // For now, just allow non-class value-initialization and initialization
11213 // lists comprised of them.
11214 if (isa<ImplicitValueInitExpr>(Val: FillerExpr))
11215 return false;
11216 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Val: FillerExpr)) {
11217 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11218 if (MaybeElementDependentArrayFiller(FillerExpr: ILE->getInit(Init: I)))
11219 return true;
11220 }
11221
11222 if (ILE->hasArrayFiller() &&
11223 MaybeElementDependentArrayFiller(FillerExpr: ILE->getArrayFiller()))
11224 return true;
11225
11226 return false;
11227 }
11228 return true;
11229}
11230
11231bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11232 QualType AllocType) {
11233 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11234 T: AllocType.isNull() ? E->getType() : AllocType);
11235 if (!CAT)
11236 return Error(E);
11237
11238 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11239 // an appropriately-typed string literal enclosed in braces.
11240 if (E->isStringLiteralInit()) {
11241 auto *SL = dyn_cast<StringLiteral>(Val: E->getInit(Init: 0)->IgnoreParenImpCasts());
11242 // FIXME: Support ObjCEncodeExpr here once we support it in
11243 // ArrayExprEvaluator generally.
11244 if (!SL)
11245 return Error(E);
11246 return VisitStringLiteral(E: SL, AllocType);
11247 }
11248 // Any other transparent list init will need proper handling of the
11249 // AllocType; we can't just recurse to the inner initializer.
11250 assert(!E->isTransparent() &&
11251 "transparent array list initialization is not string literal init?");
11252
11253 return VisitCXXParenListOrInitListExpr(ExprToVisit: E, Args: E->inits(), ArrayFiller: E->getArrayFiller(),
11254 AllocType);
11255}
11256
11257bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11258 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11259 QualType AllocType) {
11260 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11261 T: AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11262
11263 bool Success = true;
11264
11265 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11266 "zero-initialized array shouldn't have any initialized elts");
11267 APValue Filler;
11268 if (Result.isArray() && Result.hasArrayFiller())
11269 Filler = Result.getArrayFiller();
11270
11271 unsigned NumEltsToInit = Args.size();
11272 unsigned NumElts = CAT->getZExtSize();
11273
11274 // If the initializer might depend on the array index, run it for each
11275 // array element.
11276 if (NumEltsToInit != NumElts &&
11277 MaybeElementDependentArrayFiller(FillerExpr: ArrayFiller)) {
11278 NumEltsToInit = NumElts;
11279 } else {
11280 for (auto *Init : Args) {
11281 if (auto *EmbedS = dyn_cast<EmbedExpr>(Val: Init->IgnoreParenImpCasts()))
11282 NumEltsToInit += EmbedS->getDataElementCount() - 1;
11283 }
11284 if (NumEltsToInit > NumElts)
11285 NumEltsToInit = NumElts;
11286 }
11287
11288 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11289 << NumEltsToInit << ".\n");
11290
11291 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11292
11293 // If the array was previously zero-initialized, preserve the
11294 // zero-initialized values.
11295 if (Filler.hasValue()) {
11296 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11297 Result.getArrayInitializedElt(I) = Filler;
11298 if (Result.hasArrayFiller())
11299 Result.getArrayFiller() = Filler;
11300 }
11301
11302 LValue Subobject = This;
11303 Subobject.addArray(Info, E: ExprToVisit, CAT);
11304 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11305 if (!EvaluateInPlace(Result&: Result.getArrayInitializedElt(I: ArrayIndex), Info,
11306 This: Subobject, E: Init) ||
11307 !HandleLValueArrayAdjustment(Info, E: Init, LVal&: Subobject,
11308 EltTy: CAT->getElementType(), Adjustment: 1)) {
11309 if (!Info.noteFailure())
11310 return false;
11311 Success = false;
11312 }
11313 return true;
11314 };
11315 unsigned ArrayIndex = 0;
11316 QualType DestTy = CAT->getElementType();
11317 APSInt Value(Info.Ctx.getTypeSize(T: DestTy), DestTy->isUnsignedIntegerType());
11318 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11319 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11320 if (ArrayIndex >= NumEltsToInit)
11321 break;
11322 if (auto *EmbedS = dyn_cast<EmbedExpr>(Val: Init->IgnoreParenImpCasts())) {
11323 StringLiteral *SL = EmbedS->getDataStringLiteral();
11324 for (unsigned I = EmbedS->getStartingElementPos(),
11325 N = EmbedS->getDataElementCount();
11326 I != EmbedS->getStartingElementPos() + N; ++I) {
11327 Value = SL->getCodeUnit(i: I);
11328 if (DestTy->isIntegerType()) {
11329 Result.getArrayInitializedElt(I: ArrayIndex) = APValue(Value);
11330 } else {
11331 assert(DestTy->isFloatingType() && "unexpected type");
11332 const FPOptions FPO =
11333 Init->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts());
11334 APFloat FValue(0.0);
11335 if (!HandleIntToFloatCast(Info, E: Init, FPO, SrcType: EmbedS->getType(), Value,
11336 DestType: DestTy, Result&: FValue))
11337 return false;
11338 Result.getArrayInitializedElt(I: ArrayIndex) = APValue(FValue);
11339 }
11340 ArrayIndex++;
11341 }
11342 } else {
11343 if (!Eval(Init, ArrayIndex))
11344 return false;
11345 ++ArrayIndex;
11346 }
11347 }
11348
11349 if (!Result.hasArrayFiller())
11350 return Success;
11351
11352 // If we get here, we have a trivial filler, which we can just evaluate
11353 // once and splat over the rest of the array elements.
11354 assert(ArrayFiller && "no array filler for incomplete init list");
11355 return EvaluateInPlace(Result&: Result.getArrayFiller(), Info, This: Subobject,
11356 E: ArrayFiller) &&
11357 Success;
11358}
11359
11360bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11361 LValue CommonLV;
11362 if (E->getCommonExpr() &&
11363 !Evaluate(Result&: Info.CurrentCall->createTemporary(
11364 Key: E->getCommonExpr(),
11365 T: getStorageType(Ctx: Info.Ctx, E: E->getCommonExpr()),
11366 Scope: ScopeKind::FullExpression, LV&: CommonLV),
11367 Info, E: E->getCommonExpr()->getSourceExpr()))
11368 return false;
11369
11370 auto *CAT = cast<ConstantArrayType>(Val: E->getType()->castAsArrayTypeUnsafe());
11371
11372 uint64_t Elements = CAT->getZExtSize();
11373 Result = APValue(APValue::UninitArray(), Elements, Elements);
11374
11375 LValue Subobject = This;
11376 Subobject.addArray(Info, E, CAT);
11377
11378 bool Success = true;
11379 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11380 // C++ [class.temporary]/5
11381 // There are four contexts in which temporaries are destroyed at a different
11382 // point than the end of the full-expression. [...] The second context is
11383 // when a copy constructor is called to copy an element of an array while
11384 // the entire array is copied [...]. In either case, if the constructor has
11385 // one or more default arguments, the destruction of every temporary created
11386 // in a default argument is sequenced before the construction of the next
11387 // array element, if any.
11388 FullExpressionRAII Scope(Info);
11389
11390 if (!EvaluateInPlace(Result&: Result.getArrayInitializedElt(I: Index),
11391 Info, This: Subobject, E: E->getSubExpr()) ||
11392 !HandleLValueArrayAdjustment(Info, E, LVal&: Subobject,
11393 EltTy: CAT->getElementType(), Adjustment: 1)) {
11394 if (!Info.noteFailure())
11395 return false;
11396 Success = false;
11397 }
11398
11399 // Make sure we run the destructors too.
11400 Scope.destroy();
11401 }
11402
11403 return Success;
11404}
11405
11406bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11407 return VisitCXXConstructExpr(E, Subobject: This, Value: &Result, Type: E->getType());
11408}
11409
11410bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11411 const LValue &Subobject,
11412 APValue *Value,
11413 QualType Type) {
11414 bool HadZeroInit = Value->hasValue();
11415
11416 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T: Type)) {
11417 unsigned FinalSize = CAT->getZExtSize();
11418
11419 // Preserve the array filler if we had prior zero-initialization.
11420 APValue Filler =
11421 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11422 : APValue();
11423
11424 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11425 if (FinalSize == 0)
11426 return true;
11427
11428 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11429 Info, Loc: E->getExprLoc(), CD: E->getConstructor(),
11430 IsValueInitialization: E->requiresZeroInitialization());
11431 LValue ArrayElt = Subobject;
11432 ArrayElt.addArray(Info, E, CAT);
11433 // We do the whole initialization in two passes, first for just one element,
11434 // then for the whole array. It's possible we may find out we can't do const
11435 // init in the first pass, in which case we avoid allocating a potentially
11436 // large array. We don't do more passes because expanding array requires
11437 // copying the data, which is wasteful.
11438 for (const unsigned N : {1u, FinalSize}) {
11439 unsigned OldElts = Value->getArrayInitializedElts();
11440 if (OldElts == N)
11441 break;
11442
11443 // Expand the array to appropriate size.
11444 APValue NewValue(APValue::UninitArray(), N, FinalSize);
11445 for (unsigned I = 0; I < OldElts; ++I)
11446 NewValue.getArrayInitializedElt(I).swap(
11447 RHS&: Value->getArrayInitializedElt(I));
11448 Value->swap(RHS&: NewValue);
11449
11450 if (HadZeroInit)
11451 for (unsigned I = OldElts; I < N; ++I)
11452 Value->getArrayInitializedElt(I) = Filler;
11453
11454 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11455 // If we have a trivial constructor, only evaluate it once and copy
11456 // the result into all the array elements.
11457 APValue &FirstResult = Value->getArrayInitializedElt(I: 0);
11458 for (unsigned I = OldElts; I < FinalSize; ++I)
11459 Value->getArrayInitializedElt(I) = FirstResult;
11460 } else {
11461 for (unsigned I = OldElts; I < N; ++I) {
11462 if (!VisitCXXConstructExpr(E, Subobject: ArrayElt,
11463 Value: &Value->getArrayInitializedElt(I),
11464 Type: CAT->getElementType()) ||
11465 !HandleLValueArrayAdjustment(Info, E, LVal&: ArrayElt,
11466 EltTy: CAT->getElementType(), Adjustment: 1))
11467 return false;
11468 // When checking for const initilization any diagnostic is considered
11469 // an error.
11470 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11471 !Info.keepEvaluatingAfterFailure())
11472 return false;
11473 }
11474 }
11475 }
11476
11477 return true;
11478 }
11479
11480 if (!Type->isRecordType())
11481 return Error(E);
11482
11483 return RecordExprEvaluator(Info, Subobject, *Value)
11484 .VisitCXXConstructExpr(E, T: Type);
11485}
11486
11487bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11488 const CXXParenListInitExpr *E) {
11489 assert(E->getType()->isConstantArrayType() &&
11490 "Expression result is not a constant array type");
11491
11492 return VisitCXXParenListOrInitListExpr(ExprToVisit: E, Args: E->getInitExprs(),
11493 ArrayFiller: E->getArrayFiller());
11494}
11495
11496//===----------------------------------------------------------------------===//
11497// Integer Evaluation
11498//
11499// As a GNU extension, we support casting pointers to sufficiently-wide integer
11500// types and back in constant folding. Integer values are thus represented
11501// either as an integer-valued APValue, or as an lvalue-valued APValue.
11502//===----------------------------------------------------------------------===//
11503
11504namespace {
11505class IntExprEvaluator
11506 : public ExprEvaluatorBase<IntExprEvaluator> {
11507 APValue &Result;
11508public:
11509 IntExprEvaluator(EvalInfo &info, APValue &result)
11510 : ExprEvaluatorBaseTy(info), Result(result) {}
11511
11512 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11513 assert(E->getType()->isIntegralOrEnumerationType() &&
11514 "Invalid evaluation result.");
11515 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11516 "Invalid evaluation result.");
11517 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11518 "Invalid evaluation result.");
11519 Result = APValue(SI);
11520 return true;
11521 }
11522 bool Success(const llvm::APSInt &SI, const Expr *E) {
11523 return Success(SI, E, Result);
11524 }
11525
11526 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11527 assert(E->getType()->isIntegralOrEnumerationType() &&
11528 "Invalid evaluation result.");
11529 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11530 "Invalid evaluation result.");
11531 Result = APValue(APSInt(I));
11532 Result.getInt().setIsUnsigned(
11533 E->getType()->isUnsignedIntegerOrEnumerationType());
11534 return true;
11535 }
11536 bool Success(const llvm::APInt &I, const Expr *E) {
11537 return Success(I, E, Result);
11538 }
11539
11540 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11541 assert(E->getType()->isIntegralOrEnumerationType() &&
11542 "Invalid evaluation result.");
11543 Result = APValue(Info.Ctx.MakeIntValue(Value, Type: E->getType()));
11544 return true;
11545 }
11546 bool Success(uint64_t Value, const Expr *E) {
11547 return Success(Value, E, Result);
11548 }
11549
11550 bool Success(CharUnits Size, const Expr *E) {
11551 return Success(Value: Size.getQuantity(), E);
11552 }
11553
11554 bool Success(const APValue &V, const Expr *E) {
11555 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11556 Result = V;
11557 return true;
11558 }
11559 return Success(SI: V.getInt(), E);
11560 }
11561
11562 bool ZeroInitialization(const Expr *E) { return Success(Value: 0, E); }
11563
11564 //===--------------------------------------------------------------------===//
11565 // Visitor Methods
11566 //===--------------------------------------------------------------------===//
11567
11568 bool VisitIntegerLiteral(const IntegerLiteral *E) {
11569 return Success(I: E->getValue(), E);
11570 }
11571 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11572 return Success(Value: E->getValue(), E);
11573 }
11574
11575 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11576 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11577 if (CheckReferencedDecl(E, D: E->getDecl()))
11578 return true;
11579
11580 return ExprEvaluatorBaseTy::VisitDeclRefExpr(S: E);
11581 }
11582 bool VisitMemberExpr(const MemberExpr *E) {
11583 if (CheckReferencedDecl(E, D: E->getMemberDecl())) {
11584 VisitIgnoredBaseExpression(E: E->getBase());
11585 return true;
11586 }
11587
11588 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11589 }
11590
11591 bool VisitCallExpr(const CallExpr *E);
11592 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11593 bool VisitBinaryOperator(const BinaryOperator *E);
11594 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11595 bool VisitUnaryOperator(const UnaryOperator *E);
11596
11597 bool VisitCastExpr(const CastExpr* E);
11598 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11599
11600 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11601 return Success(Value: E->getValue(), E);
11602 }
11603
11604 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11605 return Success(Value: E->getValue(), E);
11606 }
11607
11608 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11609 if (Info.ArrayInitIndex == uint64_t(-1)) {
11610 // We were asked to evaluate this subexpression independent of the
11611 // enclosing ArrayInitLoopExpr. We can't do that.
11612 Info.FFDiag(E);
11613 return false;
11614 }
11615 return Success(Value: Info.ArrayInitIndex, E);
11616 }
11617
11618 // Note, GNU defines __null as an integer, not a pointer.
11619 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11620 return ZeroInitialization(E);
11621 }
11622
11623 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11624 return Success(Value: E->getValue(), E);
11625 }
11626
11627 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11628 return Success(Value: E->getValue(), E);
11629 }
11630
11631 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11632 return Success(Value: E->getValue(), E);
11633 }
11634
11635 bool VisitUnaryReal(const UnaryOperator *E);
11636 bool VisitUnaryImag(const UnaryOperator *E);
11637
11638 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11639 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11640 bool VisitSourceLocExpr(const SourceLocExpr *E);
11641 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11642 bool VisitRequiresExpr(const RequiresExpr *E);
11643 // FIXME: Missing: array subscript of vector, member of vector
11644};
11645
11646class FixedPointExprEvaluator
11647 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11648 APValue &Result;
11649
11650 public:
11651 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11652 : ExprEvaluatorBaseTy(info), Result(result) {}
11653
11654 bool Success(const llvm::APInt &I, const Expr *E) {
11655 return Success(
11656 V: APFixedPoint(I, Info.Ctx.getFixedPointSemantics(Ty: E->getType())), E);
11657 }
11658
11659 bool Success(uint64_t Value, const Expr *E) {
11660 return Success(
11661 V: APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(Ty: E->getType())), E);
11662 }
11663
11664 bool Success(const APValue &V, const Expr *E) {
11665 return Success(V: V.getFixedPoint(), E);
11666 }
11667
11668 bool Success(const APFixedPoint &V, const Expr *E) {
11669 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11670 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11671 "Invalid evaluation result.");
11672 Result = APValue(V);
11673 return true;
11674 }
11675
11676 bool ZeroInitialization(const Expr *E) {
11677 return Success(Value: 0, E);
11678 }
11679
11680 //===--------------------------------------------------------------------===//
11681 // Visitor Methods
11682 //===--------------------------------------------------------------------===//
11683
11684 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11685 return Success(I: E->getValue(), E);
11686 }
11687
11688 bool VisitCastExpr(const CastExpr *E);
11689 bool VisitUnaryOperator(const UnaryOperator *E);
11690 bool VisitBinaryOperator(const BinaryOperator *E);
11691};
11692} // end anonymous namespace
11693
11694/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11695/// produce either the integer value or a pointer.
11696///
11697/// GCC has a heinous extension which folds casts between pointer types and
11698/// pointer-sized integral types. We support this by allowing the evaluation of
11699/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11700/// Some simple arithmetic on such values is supported (they are treated much
11701/// like char*).
11702static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11703 EvalInfo &Info) {
11704 assert(!E->isValueDependent());
11705 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11706 return IntExprEvaluator(Info, Result).Visit(S: E);
11707}
11708
11709static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11710 assert(!E->isValueDependent());
11711 APValue Val;
11712 if (!EvaluateIntegerOrLValue(E, Result&: Val, Info))
11713 return false;
11714 if (!Val.isInt()) {
11715 // FIXME: It would be better to produce the diagnostic for casting
11716 // a pointer to an integer.
11717 Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
11718 return false;
11719 }
11720 Result = Val.getInt();
11721 return true;
11722}
11723
11724bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11725 APValue Evaluated = E->EvaluateInContext(
11726 Ctx: Info.Ctx, DefaultExpr: Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11727 return Success(V: Evaluated, E);
11728}
11729
11730static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11731 EvalInfo &Info) {
11732 assert(!E->isValueDependent());
11733 if (E->getType()->isFixedPointType()) {
11734 APValue Val;
11735 if (!FixedPointExprEvaluator(Info, Val).Visit(S: E))
11736 return false;
11737 if (!Val.isFixedPoint())
11738 return false;
11739
11740 Result = Val.getFixedPoint();
11741 return true;
11742 }
11743 return false;
11744}
11745
11746static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11747 EvalInfo &Info) {
11748 assert(!E->isValueDependent());
11749 if (E->getType()->isIntegerType()) {
11750 auto FXSema = Info.Ctx.getFixedPointSemantics(Ty: E->getType());
11751 APSInt Val;
11752 if (!EvaluateInteger(E, Result&: Val, Info))
11753 return false;
11754 Result = APFixedPoint(Val, FXSema);
11755 return true;
11756 } else if (E->getType()->isFixedPointType()) {
11757 return EvaluateFixedPoint(E, Result, Info);
11758 }
11759 return false;
11760}
11761
11762/// Check whether the given declaration can be directly converted to an integral
11763/// rvalue. If not, no diagnostic is produced; there are other things we can
11764/// try.
11765bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11766 // Enums are integer constant exprs.
11767 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(Val: D)) {
11768 // Check for signedness/width mismatches between E type and ECD value.
11769 bool SameSign = (ECD->getInitVal().isSigned()
11770 == E->getType()->isSignedIntegerOrEnumerationType());
11771 bool SameWidth = (ECD->getInitVal().getBitWidth()
11772 == Info.Ctx.getIntWidth(T: E->getType()));
11773 if (SameSign && SameWidth)
11774 return Success(SI: ECD->getInitVal(), E);
11775 else {
11776 // Get rid of mismatch (otherwise Success assertions will fail)
11777 // by computing a new value matching the type of E.
11778 llvm::APSInt Val = ECD->getInitVal();
11779 if (!SameSign)
11780 Val.setIsSigned(!ECD->getInitVal().isSigned());
11781 if (!SameWidth)
11782 Val = Val.extOrTrunc(width: Info.Ctx.getIntWidth(T: E->getType()));
11783 return Success(SI: Val, E);
11784 }
11785 }
11786 return false;
11787}
11788
11789/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11790/// as GCC.
11791GCCTypeClass EvaluateBuiltinClassifyType(QualType T,
11792 const LangOptions &LangOpts) {
11793 assert(!T->isDependentType() && "unexpected dependent type");
11794
11795 QualType CanTy = T.getCanonicalType();
11796
11797 switch (CanTy->getTypeClass()) {
11798#define TYPE(ID, BASE)
11799#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11800#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11801#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11802#include "clang/AST/TypeNodes.inc"
11803 case Type::Auto:
11804 case Type::DeducedTemplateSpecialization:
11805 llvm_unreachable("unexpected non-canonical or dependent type");
11806
11807 case Type::Builtin:
11808 switch (cast<BuiltinType>(Val&: CanTy)->getKind()) {
11809#define BUILTIN_TYPE(ID, SINGLETON_ID)
11810#define SIGNED_TYPE(ID, SINGLETON_ID) \
11811 case BuiltinType::ID: return GCCTypeClass::Integer;
11812#define FLOATING_TYPE(ID, SINGLETON_ID) \
11813 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11814#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11815 case BuiltinType::ID: break;
11816#include "clang/AST/BuiltinTypes.def"
11817 case BuiltinType::Void:
11818 return GCCTypeClass::Void;
11819
11820 case BuiltinType::Bool:
11821 return GCCTypeClass::Bool;
11822
11823 case BuiltinType::Char_U:
11824 case BuiltinType::UChar:
11825 case BuiltinType::WChar_U:
11826 case BuiltinType::Char8:
11827 case BuiltinType::Char16:
11828 case BuiltinType::Char32:
11829 case BuiltinType::UShort:
11830 case BuiltinType::UInt:
11831 case BuiltinType::ULong:
11832 case BuiltinType::ULongLong:
11833 case BuiltinType::UInt128:
11834 return GCCTypeClass::Integer;
11835
11836 case BuiltinType::UShortAccum:
11837 case BuiltinType::UAccum:
11838 case BuiltinType::ULongAccum:
11839 case BuiltinType::UShortFract:
11840 case BuiltinType::UFract:
11841 case BuiltinType::ULongFract:
11842 case BuiltinType::SatUShortAccum:
11843 case BuiltinType::SatUAccum:
11844 case BuiltinType::SatULongAccum:
11845 case BuiltinType::SatUShortFract:
11846 case BuiltinType::SatUFract:
11847 case BuiltinType::SatULongFract:
11848 return GCCTypeClass::None;
11849
11850 case BuiltinType::NullPtr:
11851
11852 case BuiltinType::ObjCId:
11853 case BuiltinType::ObjCClass:
11854 case BuiltinType::ObjCSel:
11855#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11856 case BuiltinType::Id:
11857#include "clang/Basic/OpenCLImageTypes.def"
11858#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11859 case BuiltinType::Id:
11860#include "clang/Basic/OpenCLExtensionTypes.def"
11861 case BuiltinType::OCLSampler:
11862 case BuiltinType::OCLEvent:
11863 case BuiltinType::OCLClkEvent:
11864 case BuiltinType::OCLQueue:
11865 case BuiltinType::OCLReserveID:
11866#define SVE_TYPE(Name, Id, SingletonId) \
11867 case BuiltinType::Id:
11868#include "clang/Basic/AArch64SVEACLETypes.def"
11869#define PPC_VECTOR_TYPE(Name, Id, Size) \
11870 case BuiltinType::Id:
11871#include "clang/Basic/PPCTypes.def"
11872#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11873#include "clang/Basic/RISCVVTypes.def"
11874#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11875#include "clang/Basic/WebAssemblyReferenceTypes.def"
11876#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11877#include "clang/Basic/AMDGPUTypes.def"
11878 return GCCTypeClass::None;
11879
11880 case BuiltinType::Dependent:
11881 llvm_unreachable("unexpected dependent type");
11882 };
11883 llvm_unreachable("unexpected placeholder type");
11884
11885 case Type::Enum:
11886 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11887
11888 case Type::Pointer:
11889 case Type::ConstantArray:
11890 case Type::VariableArray:
11891 case Type::IncompleteArray:
11892 case Type::FunctionNoProto:
11893 case Type::FunctionProto:
11894 case Type::ArrayParameter:
11895 return GCCTypeClass::Pointer;
11896
11897 case Type::MemberPointer:
11898 return CanTy->isMemberDataPointerType()
11899 ? GCCTypeClass::PointerToDataMember
11900 : GCCTypeClass::PointerToMemberFunction;
11901
11902 case Type::Complex:
11903 return GCCTypeClass::Complex;
11904
11905 case Type::Record:
11906 return CanTy->isUnionType() ? GCCTypeClass::Union
11907 : GCCTypeClass::ClassOrStruct;
11908
11909 case Type::Atomic:
11910 // GCC classifies _Atomic T the same as T.
11911 return EvaluateBuiltinClassifyType(
11912 T: CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11913
11914 case Type::Vector:
11915 case Type::ExtVector:
11916 return GCCTypeClass::Vector;
11917
11918 case Type::BlockPointer:
11919 case Type::ConstantMatrix:
11920 case Type::ObjCObject:
11921 case Type::ObjCInterface:
11922 case Type::ObjCObjectPointer:
11923 case Type::Pipe:
11924 // Classify all other types that don't fit into the regular
11925 // classification the same way.
11926 return GCCTypeClass::None;
11927
11928 case Type::BitInt:
11929 return GCCTypeClass::BitInt;
11930
11931 case Type::LValueReference:
11932 case Type::RValueReference:
11933 llvm_unreachable("invalid type for expression");
11934 }
11935
11936 llvm_unreachable("unexpected type class");
11937}
11938
11939/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11940/// as GCC.
11941static GCCTypeClass
11942EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11943 // If no argument was supplied, default to None. This isn't
11944 // ideal, however it is what gcc does.
11945 if (E->getNumArgs() == 0)
11946 return GCCTypeClass::None;
11947
11948 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11949 // being an ICE, but still folds it to a constant using the type of the first
11950 // argument.
11951 return EvaluateBuiltinClassifyType(T: E->getArg(Arg: 0)->getType(), LangOpts);
11952}
11953
11954/// EvaluateBuiltinConstantPForLValue - Determine the result of
11955/// __builtin_constant_p when applied to the given pointer.
11956///
11957/// A pointer is only "constant" if it is null (or a pointer cast to integer)
11958/// or it points to the first character of a string literal.
11959static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11960 APValue::LValueBase Base = LV.getLValueBase();
11961 if (Base.isNull()) {
11962 // A null base is acceptable.
11963 return true;
11964 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11965 if (!isa<StringLiteral>(Val: E))
11966 return false;
11967 return LV.getLValueOffset().isZero();
11968 } else if (Base.is<TypeInfoLValue>()) {
11969 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11970 // evaluate to true.
11971 return true;
11972 } else {
11973 // Any other base is not constant enough for GCC.
11974 return false;
11975 }
11976}
11977
11978/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11979/// GCC as we can manage.
11980static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11981 // This evaluation is not permitted to have side-effects, so evaluate it in
11982 // a speculative evaluation context.
11983 SpeculativeEvaluationRAII SpeculativeEval(Info);
11984
11985 // Constant-folding is always enabled for the operand of __builtin_constant_p
11986 // (even when the enclosing evaluation context otherwise requires a strict
11987 // language-specific constant expression).
11988 FoldConstant Fold(Info, true);
11989
11990 QualType ArgType = Arg->getType();
11991
11992 // __builtin_constant_p always has one operand. The rules which gcc follows
11993 // are not precisely documented, but are as follows:
11994 //
11995 // - If the operand is of integral, floating, complex or enumeration type,
11996 // and can be folded to a known value of that type, it returns 1.
11997 // - If the operand can be folded to a pointer to the first character
11998 // of a string literal (or such a pointer cast to an integral type)
11999 // or to a null pointer or an integer cast to a pointer, it returns 1.
12000 //
12001 // Otherwise, it returns 0.
12002 //
12003 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12004 // its support for this did not work prior to GCC 9 and is not yet well
12005 // understood.
12006 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12007 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12008 ArgType->isNullPtrType()) {
12009 APValue V;
12010 if (!::EvaluateAsRValue(Info, E: Arg, Result&: V) || Info.EvalStatus.HasSideEffects) {
12011 Fold.keepDiagnostics();
12012 return false;
12013 }
12014
12015 // For a pointer (possibly cast to integer), there are special rules.
12016 if (V.getKind() == APValue::LValue)
12017 return EvaluateBuiltinConstantPForLValue(LV: V);
12018
12019 // Otherwise, any constant value is good enough.
12020 return V.hasValue();
12021 }
12022
12023 // Anything else isn't considered to be sufficiently constant.
12024 return false;
12025}
12026
12027/// Retrieves the "underlying object type" of the given expression,
12028/// as used by __builtin_object_size.
12029static QualType getObjectType(APValue::LValueBase B) {
12030 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12031 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D))
12032 return VD->getType();
12033 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12034 if (isa<CompoundLiteralExpr>(Val: E))
12035 return E->getType();
12036 } else if (B.is<TypeInfoLValue>()) {
12037 return B.getTypeInfoType();
12038 } else if (B.is<DynamicAllocLValue>()) {
12039 return B.getDynamicAllocType();
12040 }
12041
12042 return QualType();
12043}
12044
12045/// A more selective version of E->IgnoreParenCasts for
12046/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12047/// to change the type of E.
12048/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12049///
12050/// Always returns an RValue with a pointer representation.
12051static const Expr *ignorePointerCastsAndParens(const Expr *E) {
12052 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12053
12054 const Expr *NoParens = E->IgnoreParens();
12055 const auto *Cast = dyn_cast<CastExpr>(Val: NoParens);
12056 if (Cast == nullptr)
12057 return NoParens;
12058
12059 // We only conservatively allow a few kinds of casts, because this code is
12060 // inherently a simple solution that seeks to support the common case.
12061 auto CastKind = Cast->getCastKind();
12062 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12063 CastKind != CK_AddressSpaceConversion)
12064 return NoParens;
12065
12066 const auto *SubExpr = Cast->getSubExpr();
12067 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12068 return NoParens;
12069 return ignorePointerCastsAndParens(E: SubExpr);
12070}
12071
12072/// Checks to see if the given LValue's Designator is at the end of the LValue's
12073/// record layout. e.g.
12074/// struct { struct { int a, b; } fst, snd; } obj;
12075/// obj.fst // no
12076/// obj.snd // yes
12077/// obj.fst.a // no
12078/// obj.fst.b // no
12079/// obj.snd.a // no
12080/// obj.snd.b // yes
12081///
12082/// Please note: this function is specialized for how __builtin_object_size
12083/// views "objects".
12084///
12085/// If this encounters an invalid RecordDecl or otherwise cannot determine the
12086/// correct result, it will always return true.
12087static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12088 assert(!LVal.Designator.Invalid);
12089
12090 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12091 const RecordDecl *Parent = FD->getParent();
12092 Invalid = Parent->isInvalidDecl();
12093 if (Invalid || Parent->isUnion())
12094 return true;
12095 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: Parent);
12096 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12097 };
12098
12099 auto &Base = LVal.getLValueBase();
12100 if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: Base.dyn_cast<const Expr *>())) {
12101 if (auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) {
12102 bool Invalid;
12103 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12104 return Invalid;
12105 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: ME->getMemberDecl())) {
12106 for (auto *FD : IFD->chain()) {
12107 bool Invalid;
12108 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(Val: FD), Invalid))
12109 return Invalid;
12110 }
12111 }
12112 }
12113
12114 unsigned I = 0;
12115 QualType BaseType = getType(B: Base);
12116 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12117 // If we don't know the array bound, conservatively assume we're looking at
12118 // the final array element.
12119 ++I;
12120 if (BaseType->isIncompleteArrayType())
12121 BaseType = Ctx.getAsArrayType(T: BaseType)->getElementType();
12122 else
12123 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12124 }
12125
12126 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12127 const auto &Entry = LVal.Designator.Entries[I];
12128 if (BaseType->isArrayType()) {
12129 // Because __builtin_object_size treats arrays as objects, we can ignore
12130 // the index iff this is the last array in the Designator.
12131 if (I + 1 == E)
12132 return true;
12133 const auto *CAT = cast<ConstantArrayType>(Val: Ctx.getAsArrayType(T: BaseType));
12134 uint64_t Index = Entry.getAsArrayIndex();
12135 if (Index + 1 != CAT->getZExtSize())
12136 return false;
12137 BaseType = CAT->getElementType();
12138 } else if (BaseType->isAnyComplexType()) {
12139 const auto *CT = BaseType->castAs<ComplexType>();
12140 uint64_t Index = Entry.getAsArrayIndex();
12141 if (Index != 1)
12142 return false;
12143 BaseType = CT->getElementType();
12144 } else if (auto *FD = getAsField(E: Entry)) {
12145 bool Invalid;
12146 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12147 return Invalid;
12148 BaseType = FD->getType();
12149 } else {
12150 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12151 return false;
12152 }
12153 }
12154 return true;
12155}
12156
12157/// Tests to see if the LValue has a user-specified designator (that isn't
12158/// necessarily valid). Note that this always returns 'true' if the LValue has
12159/// an unsized array as its first designator entry, because there's currently no
12160/// way to tell if the user typed *foo or foo[0].
12161static bool refersToCompleteObject(const LValue &LVal) {
12162 if (LVal.Designator.Invalid)
12163 return false;
12164
12165 if (!LVal.Designator.Entries.empty())
12166 return LVal.Designator.isMostDerivedAnUnsizedArray();
12167
12168 if (!LVal.InvalidBase)
12169 return true;
12170
12171 // If `E` is a MemberExpr, then the first part of the designator is hiding in
12172 // the LValueBase.
12173 const auto *E = LVal.Base.dyn_cast<const Expr *>();
12174 return !E || !isa<MemberExpr>(Val: E);
12175}
12176
12177/// Attempts to detect a user writing into a piece of memory that's impossible
12178/// to figure out the size of by just using types.
12179static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12180 const SubobjectDesignator &Designator = LVal.Designator;
12181 // Notes:
12182 // - Users can only write off of the end when we have an invalid base. Invalid
12183 // bases imply we don't know where the memory came from.
12184 // - We used to be a bit more aggressive here; we'd only be conservative if
12185 // the array at the end was flexible, or if it had 0 or 1 elements. This
12186 // broke some common standard library extensions (PR30346), but was
12187 // otherwise seemingly fine. It may be useful to reintroduce this behavior
12188 // with some sort of list. OTOH, it seems that GCC is always
12189 // conservative with the last element in structs (if it's an array), so our
12190 // current behavior is more compatible than an explicit list approach would
12191 // be.
12192 auto isFlexibleArrayMember = [&] {
12193 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
12194 FAMKind StrictFlexArraysLevel =
12195 Ctx.getLangOpts().getStrictFlexArraysLevel();
12196
12197 if (Designator.isMostDerivedAnUnsizedArray())
12198 return true;
12199
12200 if (StrictFlexArraysLevel == FAMKind::Default)
12201 return true;
12202
12203 if (Designator.getMostDerivedArraySize() == 0 &&
12204 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12205 return true;
12206
12207 if (Designator.getMostDerivedArraySize() == 1 &&
12208 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12209 return true;
12210
12211 return false;
12212 };
12213
12214 return LVal.InvalidBase &&
12215 Designator.Entries.size() == Designator.MostDerivedPathLength &&
12216 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12217 isDesignatorAtObjectEnd(Ctx, LVal);
12218}
12219
12220/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12221/// Fails if the conversion would cause loss of precision.
12222static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12223 CharUnits &Result) {
12224 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12225 if (Int.ugt(RHS: CharUnitsMax))
12226 return false;
12227 Result = CharUnits::fromQuantity(Quantity: Int.getZExtValue());
12228 return true;
12229}
12230
12231/// If we're evaluating the object size of an instance of a struct that
12232/// contains a flexible array member, add the size of the initializer.
12233static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12234 const LValue &LV, CharUnits &Size) {
12235 if (!T.isNull() && T->isStructureType() &&
12236 T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
12237 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12238 if (const auto *VD = dyn_cast<VarDecl>(Val: V))
12239 if (VD->hasInit())
12240 Size += VD->getFlexibleArrayInitChars(Ctx: Info.Ctx);
12241}
12242
12243/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12244/// determine how many bytes exist from the beginning of the object to either
12245/// the end of the current subobject, or the end of the object itself, depending
12246/// on what the LValue looks like + the value of Type.
12247///
12248/// If this returns false, the value of Result is undefined.
12249static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12250 unsigned Type, const LValue &LVal,
12251 CharUnits &EndOffset) {
12252 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12253
12254 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12255 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12256 return false;
12257 return HandleSizeof(Info, Loc: ExprLoc, Type: Ty, Size&: Result);
12258 };
12259
12260 // We want to evaluate the size of the entire object. This is a valid fallback
12261 // for when Type=1 and the designator is invalid, because we're asked for an
12262 // upper-bound.
12263 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12264 // Type=3 wants a lower bound, so we can't fall back to this.
12265 if (Type == 3 && !DetermineForCompleteObject)
12266 return false;
12267
12268 llvm::APInt APEndOffset;
12269 if (isBaseAnAllocSizeCall(Base: LVal.getLValueBase()) &&
12270 getBytesReturnedByAllocSizeCall(Ctx: Info.Ctx, LVal, Result&: APEndOffset))
12271 return convertUnsignedAPIntToCharUnits(Int: APEndOffset, Result&: EndOffset);
12272
12273 if (LVal.InvalidBase)
12274 return false;
12275
12276 QualType BaseTy = getObjectType(B: LVal.getLValueBase());
12277 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12278 addFlexibleArrayMemberInitSize(Info, T: BaseTy, LV: LVal, Size&: EndOffset);
12279 return Ret;
12280 }
12281
12282 // We want to evaluate the size of a subobject.
12283 const SubobjectDesignator &Designator = LVal.Designator;
12284
12285 // The following is a moderately common idiom in C:
12286 //
12287 // struct Foo { int a; char c[1]; };
12288 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12289 // strcpy(&F->c[0], Bar);
12290 //
12291 // In order to not break too much legacy code, we need to support it.
12292 if (isUserWritingOffTheEnd(Ctx: Info.Ctx, LVal)) {
12293 // If we can resolve this to an alloc_size call, we can hand that back,
12294 // because we know for certain how many bytes there are to write to.
12295 llvm::APInt APEndOffset;
12296 if (isBaseAnAllocSizeCall(Base: LVal.getLValueBase()) &&
12297 getBytesReturnedByAllocSizeCall(Ctx: Info.Ctx, LVal, Result&: APEndOffset))
12298 return convertUnsignedAPIntToCharUnits(Int: APEndOffset, Result&: EndOffset);
12299
12300 // If we cannot determine the size of the initial allocation, then we can't
12301 // given an accurate upper-bound. However, we are still able to give
12302 // conservative lower-bounds for Type=3.
12303 if (Type == 1)
12304 return false;
12305 }
12306
12307 CharUnits BytesPerElem;
12308 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12309 return false;
12310
12311 // According to the GCC documentation, we want the size of the subobject
12312 // denoted by the pointer. But that's not quite right -- what we actually
12313 // want is the size of the immediately-enclosing array, if there is one.
12314 int64_t ElemsRemaining;
12315 if (Designator.MostDerivedIsArrayElement &&
12316 Designator.Entries.size() == Designator.MostDerivedPathLength) {
12317 uint64_t ArraySize = Designator.getMostDerivedArraySize();
12318 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12319 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12320 } else {
12321 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12322 }
12323
12324 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12325 return true;
12326}
12327
12328/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12329/// returns true and stores the result in @p Size.
12330///
12331/// If @p WasError is non-null, this will report whether the failure to evaluate
12332/// is to be treated as an Error in IntExprEvaluator.
12333static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12334 EvalInfo &Info, uint64_t &Size) {
12335 // Determine the denoted object.
12336 LValue LVal;
12337 {
12338 // The operand of __builtin_object_size is never evaluated for side-effects.
12339 // If there are any, but we can determine the pointed-to object anyway, then
12340 // ignore the side-effects.
12341 SpeculativeEvaluationRAII SpeculativeEval(Info);
12342 IgnoreSideEffectsRAII Fold(Info);
12343
12344 if (E->isGLValue()) {
12345 // It's possible for us to be given GLValues if we're called via
12346 // Expr::tryEvaluateObjectSize.
12347 APValue RVal;
12348 if (!EvaluateAsRValue(Info, E, Result&: RVal))
12349 return false;
12350 LVal.setFrom(Ctx&: Info.Ctx, V: RVal);
12351 } else if (!EvaluatePointer(E: ignorePointerCastsAndParens(E), Result&: LVal, Info,
12352 /*InvalidBaseOK=*/true))
12353 return false;
12354 }
12355
12356 // If we point to before the start of the object, there are no accessible
12357 // bytes.
12358 if (LVal.getLValueOffset().isNegative()) {
12359 Size = 0;
12360 return true;
12361 }
12362
12363 CharUnits EndOffset;
12364 if (!determineEndOffset(Info, ExprLoc: E->getExprLoc(), Type, LVal, EndOffset))
12365 return false;
12366
12367 // If we've fallen outside of the end offset, just pretend there's nothing to
12368 // write to/read from.
12369 if (EndOffset <= LVal.getLValueOffset())
12370 Size = 0;
12371 else
12372 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12373 return true;
12374}
12375
12376bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12377 if (!IsConstantEvaluatedBuiltinCall(E))
12378 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12379 return VisitBuiltinCallExpr(E, BuiltinOp: E->getBuiltinCallee());
12380}
12381
12382static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12383 APValue &Val, APSInt &Alignment) {
12384 QualType SrcTy = E->getArg(Arg: 0)->getType();
12385 if (!getAlignmentArgument(E: E->getArg(Arg: 1), ForType: SrcTy, Info, Alignment))
12386 return false;
12387 // Even though we are evaluating integer expressions we could get a pointer
12388 // argument for the __builtin_is_aligned() case.
12389 if (SrcTy->isPointerType()) {
12390 LValue Ptr;
12391 if (!EvaluatePointer(E: E->getArg(Arg: 0), Result&: Ptr, Info))
12392 return false;
12393 Ptr.moveInto(V&: Val);
12394 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12395 Info.FFDiag(E: E->getArg(Arg: 0));
12396 return false;
12397 } else {
12398 APSInt SrcInt;
12399 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: SrcInt, Info))
12400 return false;
12401 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12402 "Bit widths must be the same");
12403 Val = APValue(SrcInt);
12404 }
12405 assert(Val.hasValue());
12406 return true;
12407}
12408
12409bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12410 unsigned BuiltinOp) {
12411 switch (BuiltinOp) {
12412 default:
12413 return false;
12414
12415 case Builtin::BI__builtin_dynamic_object_size:
12416 case Builtin::BI__builtin_object_size: {
12417 // The type was checked when we built the expression.
12418 unsigned Type =
12419 E->getArg(Arg: 1)->EvaluateKnownConstInt(Ctx: Info.Ctx).getZExtValue();
12420 assert(Type <= 3 && "unexpected type");
12421
12422 uint64_t Size;
12423 if (tryEvaluateBuiltinObjectSize(E: E->getArg(Arg: 0), Type, Info, Size))
12424 return Success(Value: Size, E);
12425
12426 if (E->getArg(Arg: 0)->HasSideEffects(Ctx: Info.Ctx))
12427 return Success(Value: (Type & 2) ? 0 : -1, E);
12428
12429 // Expression had no side effects, but we couldn't statically determine the
12430 // size of the referenced object.
12431 switch (Info.EvalMode) {
12432 case EvalInfo::EM_ConstantExpression:
12433 case EvalInfo::EM_ConstantFold:
12434 case EvalInfo::EM_IgnoreSideEffects:
12435 // Leave it to IR generation.
12436 return Error(E);
12437 case EvalInfo::EM_ConstantExpressionUnevaluated:
12438 // Reduce it to a constant now.
12439 return Success(Value: (Type & 2) ? 0 : -1, E);
12440 }
12441
12442 llvm_unreachable("unexpected EvalMode");
12443 }
12444
12445 case Builtin::BI__builtin_os_log_format_buffer_size: {
12446 analyze_os_log::OSLogBufferLayout Layout;
12447 analyze_os_log::computeOSLogBufferLayout(Ctx&: Info.Ctx, E, layout&: Layout);
12448 return Success(Value: Layout.size().getQuantity(), E);
12449 }
12450
12451 case Builtin::BI__builtin_is_aligned: {
12452 APValue Src;
12453 APSInt Alignment;
12454 if (!getBuiltinAlignArguments(E, Info, Val&: Src, Alignment))
12455 return false;
12456 if (Src.isLValue()) {
12457 // If we evaluated a pointer, check the minimum known alignment.
12458 LValue Ptr;
12459 Ptr.setFrom(Ctx&: Info.Ctx, V: Src);
12460 CharUnits BaseAlignment = getBaseAlignment(Info, Value: Ptr);
12461 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(offset: Ptr.Offset);
12462 // We can return true if the known alignment at the computed offset is
12463 // greater than the requested alignment.
12464 assert(PtrAlign.isPowerOfTwo());
12465 assert(Alignment.isPowerOf2());
12466 if (PtrAlign.getQuantity() >= Alignment)
12467 return Success(Value: 1, E);
12468 // If the alignment is not known to be sufficient, some cases could still
12469 // be aligned at run time. However, if the requested alignment is less or
12470 // equal to the base alignment and the offset is not aligned, we know that
12471 // the run-time value can never be aligned.
12472 if (BaseAlignment.getQuantity() >= Alignment &&
12473 PtrAlign.getQuantity() < Alignment)
12474 return Success(Value: 0, E);
12475 // Otherwise we can't infer whether the value is sufficiently aligned.
12476 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12477 // in cases where we can't fully evaluate the pointer.
12478 Info.FFDiag(E: E->getArg(Arg: 0), DiagId: diag::note_constexpr_alignment_compute)
12479 << Alignment;
12480 return false;
12481 }
12482 assert(Src.isInt());
12483 return Success(Value: (Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12484 }
12485 case Builtin::BI__builtin_align_up: {
12486 APValue Src;
12487 APSInt Alignment;
12488 if (!getBuiltinAlignArguments(E, Info, Val&: Src, Alignment))
12489 return false;
12490 if (!Src.isInt())
12491 return Error(E);
12492 APSInt AlignedVal =
12493 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12494 Src.getInt().isUnsigned());
12495 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12496 return Success(SI: AlignedVal, E);
12497 }
12498 case Builtin::BI__builtin_align_down: {
12499 APValue Src;
12500 APSInt Alignment;
12501 if (!getBuiltinAlignArguments(E, Info, Val&: Src, Alignment))
12502 return false;
12503 if (!Src.isInt())
12504 return Error(E);
12505 APSInt AlignedVal =
12506 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12507 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12508 return Success(SI: AlignedVal, E);
12509 }
12510
12511 case Builtin::BI__builtin_bitreverse8:
12512 case Builtin::BI__builtin_bitreverse16:
12513 case Builtin::BI__builtin_bitreverse32:
12514 case Builtin::BI__builtin_bitreverse64: {
12515 APSInt Val;
12516 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info))
12517 return false;
12518
12519 return Success(I: Val.reverseBits(), E);
12520 }
12521
12522 case Builtin::BI__builtin_bswap16:
12523 case Builtin::BI__builtin_bswap32:
12524 case Builtin::BI__builtin_bswap64: {
12525 APSInt Val;
12526 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info))
12527 return false;
12528
12529 return Success(I: Val.byteSwap(), E);
12530 }
12531
12532 case Builtin::BI__builtin_classify_type:
12533 return Success(Value: (int)EvaluateBuiltinClassifyType(E, LangOpts: Info.getLangOpts()), E);
12534
12535 case Builtin::BI__builtin_clrsb:
12536 case Builtin::BI__builtin_clrsbl:
12537 case Builtin::BI__builtin_clrsbll: {
12538 APSInt Val;
12539 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info))
12540 return false;
12541
12542 return Success(Value: Val.getBitWidth() - Val.getSignificantBits(), E);
12543 }
12544
12545 case Builtin::BI__builtin_clz:
12546 case Builtin::BI__builtin_clzl:
12547 case Builtin::BI__builtin_clzll:
12548 case Builtin::BI__builtin_clzs:
12549 case Builtin::BI__builtin_clzg:
12550 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12551 case Builtin::BI__lzcnt:
12552 case Builtin::BI__lzcnt64: {
12553 APSInt Val;
12554 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info))
12555 return false;
12556
12557 std::optional<APSInt> Fallback;
12558 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
12559 APSInt FallbackTemp;
12560 if (!EvaluateInteger(E: E->getArg(Arg: 1), Result&: FallbackTemp, Info))
12561 return false;
12562 Fallback = FallbackTemp;
12563 }
12564
12565 if (!Val) {
12566 if (Fallback)
12567 return Success(SI: *Fallback, E);
12568
12569 // When the argument is 0, the result of GCC builtins is undefined,
12570 // whereas for Microsoft intrinsics, the result is the bit-width of the
12571 // argument.
12572 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12573 BuiltinOp != Builtin::BI__lzcnt &&
12574 BuiltinOp != Builtin::BI__lzcnt64;
12575
12576 if (ZeroIsUndefined)
12577 return Error(E);
12578 }
12579
12580 return Success(Value: Val.countl_zero(), E);
12581 }
12582
12583 case Builtin::BI__builtin_constant_p: {
12584 const Expr *Arg = E->getArg(Arg: 0);
12585 if (EvaluateBuiltinConstantP(Info, Arg))
12586 return Success(Value: true, E);
12587 if (Info.InConstantContext || Arg->HasSideEffects(Ctx: Info.Ctx)) {
12588 // Outside a constant context, eagerly evaluate to false in the presence
12589 // of side-effects in order to avoid -Wunsequenced false-positives in
12590 // a branch on __builtin_constant_p(expr).
12591 return Success(Value: false, E);
12592 }
12593 Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
12594 return false;
12595 }
12596
12597 case Builtin::BI__builtin_is_constant_evaluated: {
12598 const auto *Callee = Info.CurrentCall->getCallee();
12599 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12600 (Info.CallStackDepth == 1 ||
12601 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12602 Callee->getIdentifier() &&
12603 Callee->getIdentifier()->isStr(Str: "is_constant_evaluated")))) {
12604 // FIXME: Find a better way to avoid duplicated diagnostics.
12605 if (Info.EvalStatus.Diag)
12606 Info.report(Loc: (Info.CallStackDepth == 1)
12607 ? E->getExprLoc()
12608 : Info.CurrentCall->getCallRange().getBegin(),
12609 DiagId: diag::warn_is_constant_evaluated_always_true_constexpr)
12610 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12611 : "std::is_constant_evaluated");
12612 }
12613
12614 return Success(Value: Info.InConstantContext, E);
12615 }
12616
12617 case Builtin::BI__builtin_ctz:
12618 case Builtin::BI__builtin_ctzl:
12619 case Builtin::BI__builtin_ctzll:
12620 case Builtin::BI__builtin_ctzs:
12621 case Builtin::BI__builtin_ctzg: {
12622 APSInt Val;
12623 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info))
12624 return false;
12625
12626 std::optional<APSInt> Fallback;
12627 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
12628 APSInt FallbackTemp;
12629 if (!EvaluateInteger(E: E->getArg(Arg: 1), Result&: FallbackTemp, Info))
12630 return false;
12631 Fallback = FallbackTemp;
12632 }
12633
12634 if (!Val) {
12635 if (Fallback)
12636 return Success(SI: *Fallback, E);
12637
12638 return Error(E);
12639 }
12640
12641 return Success(Value: Val.countr_zero(), E);
12642 }
12643
12644 case Builtin::BI__builtin_eh_return_data_regno: {
12645 int Operand = E->getArg(Arg: 0)->EvaluateKnownConstInt(Ctx: Info.Ctx).getZExtValue();
12646 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(RegNo: Operand);
12647 return Success(Value: Operand, E);
12648 }
12649
12650 case Builtin::BI__builtin_expect:
12651 case Builtin::BI__builtin_expect_with_probability:
12652 return Visit(S: E->getArg(Arg: 0));
12653
12654 case Builtin::BI__builtin_ptrauth_string_discriminator: {
12655 const auto *Literal =
12656 cast<StringLiteral>(Val: E->getArg(Arg: 0)->IgnoreParenImpCasts());
12657 uint64_t Result = getPointerAuthStableSipHash(S: Literal->getString());
12658 return Success(Value: Result, E);
12659 }
12660
12661 case Builtin::BI__builtin_ffs:
12662 case Builtin::BI__builtin_ffsl:
12663 case Builtin::BI__builtin_ffsll: {
12664 APSInt Val;
12665 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info))
12666 return false;
12667
12668 unsigned N = Val.countr_zero();
12669 return Success(Value: N == Val.getBitWidth() ? 0 : N + 1, E);
12670 }
12671
12672 case Builtin::BI__builtin_fpclassify: {
12673 APFloat Val(0.0);
12674 if (!EvaluateFloat(E: E->getArg(Arg: 5), Result&: Val, Info))
12675 return false;
12676 unsigned Arg;
12677 switch (Val.getCategory()) {
12678 case APFloat::fcNaN: Arg = 0; break;
12679 case APFloat::fcInfinity: Arg = 1; break;
12680 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12681 case APFloat::fcZero: Arg = 4; break;
12682 }
12683 return Visit(S: E->getArg(Arg));
12684 }
12685
12686 case Builtin::BI__builtin_isinf_sign: {
12687 APFloat Val(0.0);
12688 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12689 Success(Value: Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12690 }
12691
12692 case Builtin::BI__builtin_isinf: {
12693 APFloat Val(0.0);
12694 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12695 Success(Value: Val.isInfinity() ? 1 : 0, E);
12696 }
12697
12698 case Builtin::BI__builtin_isfinite: {
12699 APFloat Val(0.0);
12700 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12701 Success(Value: Val.isFinite() ? 1 : 0, E);
12702 }
12703
12704 case Builtin::BI__builtin_isnan: {
12705 APFloat Val(0.0);
12706 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12707 Success(Value: Val.isNaN() ? 1 : 0, E);
12708 }
12709
12710 case Builtin::BI__builtin_isnormal: {
12711 APFloat Val(0.0);
12712 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12713 Success(Value: Val.isNormal() ? 1 : 0, E);
12714 }
12715
12716 case Builtin::BI__builtin_issubnormal: {
12717 APFloat Val(0.0);
12718 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12719 Success(Value: Val.isDenormal() ? 1 : 0, E);
12720 }
12721
12722 case Builtin::BI__builtin_iszero: {
12723 APFloat Val(0.0);
12724 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12725 Success(Value: Val.isZero() ? 1 : 0, E);
12726 }
12727
12728 case Builtin::BI__builtin_issignaling: {
12729 APFloat Val(0.0);
12730 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12731 Success(Value: Val.isSignaling() ? 1 : 0, E);
12732 }
12733
12734 case Builtin::BI__builtin_isfpclass: {
12735 APSInt MaskVal;
12736 if (!EvaluateInteger(E: E->getArg(Arg: 1), Result&: MaskVal, Info))
12737 return false;
12738 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
12739 APFloat Val(0.0);
12740 return EvaluateFloat(E: E->getArg(Arg: 0), Result&: Val, Info) &&
12741 Success(Value: (Val.classify() & Test) ? 1 : 0, E);
12742 }
12743
12744 case Builtin::BI__builtin_parity:
12745 case Builtin::BI__builtin_parityl:
12746 case Builtin::BI__builtin_parityll: {
12747 APSInt Val;
12748 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info))
12749 return false;
12750
12751 return Success(Value: Val.popcount() % 2, E);
12752 }
12753
12754 case Builtin::BI__builtin_popcount:
12755 case Builtin::BI__builtin_popcountl:
12756 case Builtin::BI__builtin_popcountll:
12757 case Builtin::BI__builtin_popcountg:
12758 case Builtin::BI__popcnt16: // Microsoft variants of popcount
12759 case Builtin::BI__popcnt:
12760 case Builtin::BI__popcnt64: {
12761 APSInt Val;
12762 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info))
12763 return false;
12764
12765 return Success(Value: Val.popcount(), E);
12766 }
12767
12768 case Builtin::BI__builtin_rotateleft8:
12769 case Builtin::BI__builtin_rotateleft16:
12770 case Builtin::BI__builtin_rotateleft32:
12771 case Builtin::BI__builtin_rotateleft64:
12772 case Builtin::BI_rotl8: // Microsoft variants of rotate right
12773 case Builtin::BI_rotl16:
12774 case Builtin::BI_rotl:
12775 case Builtin::BI_lrotl:
12776 case Builtin::BI_rotl64: {
12777 APSInt Val, Amt;
12778 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info) ||
12779 !EvaluateInteger(E: E->getArg(Arg: 1), Result&: Amt, Info))
12780 return false;
12781
12782 return Success(I: Val.rotl(rotateAmt: Amt.urem(RHS: Val.getBitWidth())), E);
12783 }
12784
12785 case Builtin::BI__builtin_rotateright8:
12786 case Builtin::BI__builtin_rotateright16:
12787 case Builtin::BI__builtin_rotateright32:
12788 case Builtin::BI__builtin_rotateright64:
12789 case Builtin::BI_rotr8: // Microsoft variants of rotate right
12790 case Builtin::BI_rotr16:
12791 case Builtin::BI_rotr:
12792 case Builtin::BI_lrotr:
12793 case Builtin::BI_rotr64: {
12794 APSInt Val, Amt;
12795 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: Val, Info) ||
12796 !EvaluateInteger(E: E->getArg(Arg: 1), Result&: Amt, Info))
12797 return false;
12798
12799 return Success(I: Val.rotr(rotateAmt: Amt.urem(RHS: Val.getBitWidth())), E);
12800 }
12801
12802 case Builtin::BIstrlen:
12803 case Builtin::BIwcslen:
12804 // A call to strlen is not a constant expression.
12805 if (Info.getLangOpts().CPlusPlus11)
12806 Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_function)
12807 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12808 << ("'" + Info.Ctx.BuiltinInfo.getName(ID: BuiltinOp) + "'").str();
12809 else
12810 Info.CCEDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
12811 [[fallthrough]];
12812 case Builtin::BI__builtin_strlen:
12813 case Builtin::BI__builtin_wcslen: {
12814 // As an extension, we support __builtin_strlen() as a constant expression,
12815 // and support folding strlen() to a constant.
12816 uint64_t StrLen;
12817 if (EvaluateBuiltinStrLen(E: E->getArg(Arg: 0), Result&: StrLen, Info))
12818 return Success(Value: StrLen, E);
12819 return false;
12820 }
12821
12822 case Builtin::BIstrcmp:
12823 case Builtin::BIwcscmp:
12824 case Builtin::BIstrncmp:
12825 case Builtin::BIwcsncmp:
12826 case Builtin::BImemcmp:
12827 case Builtin::BIbcmp:
12828 case Builtin::BIwmemcmp:
12829 // A call to strlen is not a constant expression.
12830 if (Info.getLangOpts().CPlusPlus11)
12831 Info.CCEDiag(E, DiagId: diag::note_constexpr_invalid_function)
12832 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12833 << ("'" + Info.Ctx.BuiltinInfo.getName(ID: BuiltinOp) + "'").str();
12834 else
12835 Info.CCEDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
12836 [[fallthrough]];
12837 case Builtin::BI__builtin_strcmp:
12838 case Builtin::BI__builtin_wcscmp:
12839 case Builtin::BI__builtin_strncmp:
12840 case Builtin::BI__builtin_wcsncmp:
12841 case Builtin::BI__builtin_memcmp:
12842 case Builtin::BI__builtin_bcmp:
12843 case Builtin::BI__builtin_wmemcmp: {
12844 LValue String1, String2;
12845 if (!EvaluatePointer(E: E->getArg(Arg: 0), Result&: String1, Info) ||
12846 !EvaluatePointer(E: E->getArg(Arg: 1), Result&: String2, Info))
12847 return false;
12848
12849 uint64_t MaxLength = uint64_t(-1);
12850 if (BuiltinOp != Builtin::BIstrcmp &&
12851 BuiltinOp != Builtin::BIwcscmp &&
12852 BuiltinOp != Builtin::BI__builtin_strcmp &&
12853 BuiltinOp != Builtin::BI__builtin_wcscmp) {
12854 APSInt N;
12855 if (!EvaluateInteger(E: E->getArg(Arg: 2), Result&: N, Info))
12856 return false;
12857 MaxLength = N.getZExtValue();
12858 }
12859
12860 // Empty substrings compare equal by definition.
12861 if (MaxLength == 0u)
12862 return Success(Value: 0, E);
12863
12864 if (!String1.checkNullPointerForFoldAccess(Info, E, AK: AK_Read) ||
12865 !String2.checkNullPointerForFoldAccess(Info, E, AK: AK_Read) ||
12866 String1.Designator.Invalid || String2.Designator.Invalid)
12867 return false;
12868
12869 QualType CharTy1 = String1.Designator.getType(Ctx&: Info.Ctx);
12870 QualType CharTy2 = String2.Designator.getType(Ctx&: Info.Ctx);
12871
12872 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12873 BuiltinOp == Builtin::BIbcmp ||
12874 BuiltinOp == Builtin::BI__builtin_memcmp ||
12875 BuiltinOp == Builtin::BI__builtin_bcmp;
12876
12877 assert(IsRawByte ||
12878 (Info.Ctx.hasSameUnqualifiedType(
12879 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12880 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12881
12882 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12883 // 'char8_t', but no other types.
12884 if (IsRawByte &&
12885 !(isOneByteCharacterType(T: CharTy1) && isOneByteCharacterType(T: CharTy2))) {
12886 // FIXME: Consider using our bit_cast implementation to support this.
12887 Info.FFDiag(E, DiagId: diag::note_constexpr_memcmp_unsupported)
12888 << ("'" + Info.Ctx.BuiltinInfo.getName(ID: BuiltinOp) + "'").str()
12889 << CharTy1 << CharTy2;
12890 return false;
12891 }
12892
12893 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12894 return handleLValueToRValueConversion(Info, Conv: E, Type: CharTy1, LVal: String1, RVal&: Char1) &&
12895 handleLValueToRValueConversion(Info, Conv: E, Type: CharTy2, LVal: String2, RVal&: Char2) &&
12896 Char1.isInt() && Char2.isInt();
12897 };
12898 const auto &AdvanceElems = [&] {
12899 return HandleLValueArrayAdjustment(Info, E, LVal&: String1, EltTy: CharTy1, Adjustment: 1) &&
12900 HandleLValueArrayAdjustment(Info, E, LVal&: String2, EltTy: CharTy2, Adjustment: 1);
12901 };
12902
12903 bool StopAtNull =
12904 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12905 BuiltinOp != Builtin::BIwmemcmp &&
12906 BuiltinOp != Builtin::BI__builtin_memcmp &&
12907 BuiltinOp != Builtin::BI__builtin_bcmp &&
12908 BuiltinOp != Builtin::BI__builtin_wmemcmp);
12909 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12910 BuiltinOp == Builtin::BIwcsncmp ||
12911 BuiltinOp == Builtin::BIwmemcmp ||
12912 BuiltinOp == Builtin::BI__builtin_wcscmp ||
12913 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12914 BuiltinOp == Builtin::BI__builtin_wmemcmp;
12915
12916 for (; MaxLength; --MaxLength) {
12917 APValue Char1, Char2;
12918 if (!ReadCurElems(Char1, Char2))
12919 return false;
12920 if (Char1.getInt().ne(RHS: Char2.getInt())) {
12921 if (IsWide) // wmemcmp compares with wchar_t signedness.
12922 return Success(Value: Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12923 // memcmp always compares unsigned chars.
12924 return Success(Value: Char1.getInt().ult(RHS: Char2.getInt()) ? -1 : 1, E);
12925 }
12926 if (StopAtNull && !Char1.getInt())
12927 return Success(Value: 0, E);
12928 assert(!(StopAtNull && !Char2.getInt()));
12929 if (!AdvanceElems())
12930 return false;
12931 }
12932 // We hit the strncmp / memcmp limit.
12933 return Success(Value: 0, E);
12934 }
12935
12936 case Builtin::BI__atomic_always_lock_free:
12937 case Builtin::BI__atomic_is_lock_free:
12938 case Builtin::BI__c11_atomic_is_lock_free: {
12939 APSInt SizeVal;
12940 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: SizeVal, Info))
12941 return false;
12942
12943 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12944 // of two less than or equal to the maximum inline atomic width, we know it
12945 // is lock-free. If the size isn't a power of two, or greater than the
12946 // maximum alignment where we promote atomics, we know it is not lock-free
12947 // (at least not in the sense of atomic_is_lock_free). Otherwise,
12948 // the answer can only be determined at runtime; for example, 16-byte
12949 // atomics have lock-free implementations on some, but not all,
12950 // x86-64 processors.
12951
12952 // Check power-of-two.
12953 CharUnits Size = CharUnits::fromQuantity(Quantity: SizeVal.getZExtValue());
12954 if (Size.isPowerOfTwo()) {
12955 // Check against inlining width.
12956 unsigned InlineWidthBits =
12957 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12958 if (Size <= Info.Ctx.toCharUnitsFromBits(BitSize: InlineWidthBits)) {
12959 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12960 Size == CharUnits::One())
12961 return Success(Value: 1, E);
12962
12963 // If the pointer argument can be evaluated to a compile-time constant
12964 // integer (or nullptr), check if that value is appropriately aligned.
12965 const Expr *PtrArg = E->getArg(Arg: 1);
12966 Expr::EvalResult ExprResult;
12967 APSInt IntResult;
12968 if (PtrArg->EvaluateAsRValue(Result&: ExprResult, Ctx: Info.Ctx) &&
12969 ExprResult.Val.toIntegralConstant(Result&: IntResult, SrcTy: PtrArg->getType(),
12970 Ctx: Info.Ctx) &&
12971 IntResult.isAligned(A: Size.getAsAlign()))
12972 return Success(Value: 1, E);
12973
12974 // Otherwise, check if the type's alignment against Size.
12975 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: PtrArg)) {
12976 // Drop the potential implicit-cast to 'const volatile void*', getting
12977 // the underlying type.
12978 if (ICE->getCastKind() == CK_BitCast)
12979 PtrArg = ICE->getSubExpr();
12980 }
12981
12982 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
12983 QualType PointeeType = PtrTy->getPointeeType();
12984 if (!PointeeType->isIncompleteType() &&
12985 Info.Ctx.getTypeAlignInChars(T: PointeeType) >= Size) {
12986 // OK, we will inline operations on this object.
12987 return Success(Value: 1, E);
12988 }
12989 }
12990 }
12991 }
12992
12993 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12994 Success(Value: 0, E) : Error(E);
12995 }
12996 case Builtin::BI__builtin_addcb:
12997 case Builtin::BI__builtin_addcs:
12998 case Builtin::BI__builtin_addc:
12999 case Builtin::BI__builtin_addcl:
13000 case Builtin::BI__builtin_addcll:
13001 case Builtin::BI__builtin_subcb:
13002 case Builtin::BI__builtin_subcs:
13003 case Builtin::BI__builtin_subc:
13004 case Builtin::BI__builtin_subcl:
13005 case Builtin::BI__builtin_subcll: {
13006 LValue CarryOutLValue;
13007 APSInt LHS, RHS, CarryIn, CarryOut, Result;
13008 QualType ResultType = E->getArg(Arg: 0)->getType();
13009 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: LHS, Info) ||
13010 !EvaluateInteger(E: E->getArg(Arg: 1), Result&: RHS, Info) ||
13011 !EvaluateInteger(E: E->getArg(Arg: 2), Result&: CarryIn, Info) ||
13012 !EvaluatePointer(E: E->getArg(Arg: 3), Result&: CarryOutLValue, Info))
13013 return false;
13014 // Copy the number of bits and sign.
13015 Result = LHS;
13016 CarryOut = LHS;
13017
13018 bool FirstOverflowed = false;
13019 bool SecondOverflowed = false;
13020 switch (BuiltinOp) {
13021 default:
13022 llvm_unreachable("Invalid value for BuiltinOp");
13023 case Builtin::BI__builtin_addcb:
13024 case Builtin::BI__builtin_addcs:
13025 case Builtin::BI__builtin_addc:
13026 case Builtin::BI__builtin_addcl:
13027 case Builtin::BI__builtin_addcll:
13028 Result =
13029 LHS.uadd_ov(RHS, Overflow&: FirstOverflowed).uadd_ov(RHS: CarryIn, Overflow&: SecondOverflowed);
13030 break;
13031 case Builtin::BI__builtin_subcb:
13032 case Builtin::BI__builtin_subcs:
13033 case Builtin::BI__builtin_subc:
13034 case Builtin::BI__builtin_subcl:
13035 case Builtin::BI__builtin_subcll:
13036 Result =
13037 LHS.usub_ov(RHS, Overflow&: FirstOverflowed).usub_ov(RHS: CarryIn, Overflow&: SecondOverflowed);
13038 break;
13039 }
13040
13041 // It is possible for both overflows to happen but CGBuiltin uses an OR so
13042 // this is consistent.
13043 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13044 APValue APV{CarryOut};
13045 if (!handleAssignment(Info, E, LVal: CarryOutLValue, LValType: ResultType, Val&: APV))
13046 return false;
13047 return Success(SI: Result, E);
13048 }
13049 case Builtin::BI__builtin_add_overflow:
13050 case Builtin::BI__builtin_sub_overflow:
13051 case Builtin::BI__builtin_mul_overflow:
13052 case Builtin::BI__builtin_sadd_overflow:
13053 case Builtin::BI__builtin_uadd_overflow:
13054 case Builtin::BI__builtin_uaddl_overflow:
13055 case Builtin::BI__builtin_uaddll_overflow:
13056 case Builtin::BI__builtin_usub_overflow:
13057 case Builtin::BI__builtin_usubl_overflow:
13058 case Builtin::BI__builtin_usubll_overflow:
13059 case Builtin::BI__builtin_umul_overflow:
13060 case Builtin::BI__builtin_umull_overflow:
13061 case Builtin::BI__builtin_umulll_overflow:
13062 case Builtin::BI__builtin_saddl_overflow:
13063 case Builtin::BI__builtin_saddll_overflow:
13064 case Builtin::BI__builtin_ssub_overflow:
13065 case Builtin::BI__builtin_ssubl_overflow:
13066 case Builtin::BI__builtin_ssubll_overflow:
13067 case Builtin::BI__builtin_smul_overflow:
13068 case Builtin::BI__builtin_smull_overflow:
13069 case Builtin::BI__builtin_smulll_overflow: {
13070 LValue ResultLValue;
13071 APSInt LHS, RHS;
13072
13073 QualType ResultType = E->getArg(Arg: 2)->getType()->getPointeeType();
13074 if (!EvaluateInteger(E: E->getArg(Arg: 0), Result&: LHS, Info) ||
13075 !EvaluateInteger(E: E->getArg(Arg: 1), Result&: RHS, Info) ||
13076 !EvaluatePointer(E: E->getArg(Arg: 2), Result&: ResultLValue, Info))
13077 return false;
13078
13079 APSInt Result;
13080 bool DidOverflow = false;
13081
13082 // If the types don't have to match, enlarge all 3 to the largest of them.
13083 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13084 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13085 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13086 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13087 ResultType->isSignedIntegerOrEnumerationType();
13088 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13089 ResultType->isSignedIntegerOrEnumerationType();
13090 uint64_t LHSSize = LHS.getBitWidth();
13091 uint64_t RHSSize = RHS.getBitWidth();
13092 uint64_t ResultSize = Info.Ctx.getTypeSize(T: ResultType);
13093 uint64_t MaxBits = std::max(a: std::max(a: LHSSize, b: RHSSize), b: ResultSize);
13094
13095 // Add an additional bit if the signedness isn't uniformly agreed to. We
13096 // could do this ONLY if there is a signed and an unsigned that both have
13097 // MaxBits, but the code to check that is pretty nasty. The issue will be
13098 // caught in the shrink-to-result later anyway.
13099 if (IsSigned && !AllSigned)
13100 ++MaxBits;
13101
13102 LHS = APSInt(LHS.extOrTrunc(width: MaxBits), !IsSigned);
13103 RHS = APSInt(RHS.extOrTrunc(width: MaxBits), !IsSigned);
13104 Result = APSInt(MaxBits, !IsSigned);
13105 }
13106
13107 // Find largest int.
13108 switch (BuiltinOp) {
13109 default:
13110 llvm_unreachable("Invalid value for BuiltinOp");
13111 case Builtin::BI__builtin_add_overflow:
13112 case Builtin::BI__builtin_sadd_overflow:
13113 case Builtin::BI__builtin_saddl_overflow:
13114 case Builtin::BI__builtin_saddll_overflow:
13115 case Builtin::BI__builtin_uadd_overflow:
13116 case Builtin::BI__builtin_uaddl_overflow:
13117 case Builtin::BI__builtin_uaddll_overflow:
13118 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, Overflow&: DidOverflow)
13119 : LHS.uadd_ov(RHS, Overflow&: DidOverflow);
13120 break;
13121 case Builtin::BI__builtin_sub_overflow:
13122 case Builtin::BI__builtin_ssub_overflow:
13123 case Builtin::BI__builtin_ssubl_overflow:
13124 case Builtin::BI__builtin_ssubll_overflow:
13125 case Builtin::BI__builtin_usub_overflow:
13126 case Builtin::BI__builtin_usubl_overflow:
13127 case Builtin::BI__builtin_usubll_overflow:
13128 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, Overflow&: DidOverflow)
13129 : LHS.usub_ov(RHS, Overflow&: DidOverflow);
13130 break;
13131 case Builtin::BI__builtin_mul_overflow:
13132 case Builtin::BI__builtin_smul_overflow:
13133 case Builtin::BI__builtin_smull_overflow:
13134 case Builtin::BI__builtin_smulll_overflow:
13135 case Builtin::BI__builtin_umul_overflow:
13136 case Builtin::BI__builtin_umull_overflow:
13137 case Builtin::BI__builtin_umulll_overflow:
13138 Result = LHS.isSigned() ? LHS.smul_ov(RHS, Overflow&: DidOverflow)
13139 : LHS.umul_ov(RHS, Overflow&: DidOverflow);
13140 break;
13141 }
13142
13143 // In the case where multiple sizes are allowed, truncate and see if
13144 // the values are the same.
13145 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13146 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13147 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13148 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13149 // since it will give us the behavior of a TruncOrSelf in the case where
13150 // its parameter <= its size. We previously set Result to be at least the
13151 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13152 // will work exactly like TruncOrSelf.
13153 APSInt Temp = Result.extOrTrunc(width: Info.Ctx.getTypeSize(T: ResultType));
13154 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13155
13156 if (!APSInt::isSameValue(I1: Temp, I2: Result))
13157 DidOverflow = true;
13158 Result = Temp;
13159 }
13160
13161 APValue APV{Result};
13162 if (!handleAssignment(Info, E, LVal: ResultLValue, LValType: ResultType, Val&: APV))
13163 return false;
13164 return Success(Value: DidOverflow, E);
13165 }
13166 }
13167}
13168
13169/// Determine whether this is a pointer past the end of the complete
13170/// object referred to by the lvalue.
13171static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
13172 const LValue &LV) {
13173 // A null pointer can be viewed as being "past the end" but we don't
13174 // choose to look at it that way here.
13175 if (!LV.getLValueBase())
13176 return false;
13177
13178 // If the designator is valid and refers to a subobject, we're not pointing
13179 // past the end.
13180 if (!LV.getLValueDesignator().Invalid &&
13181 !LV.getLValueDesignator().isOnePastTheEnd())
13182 return false;
13183
13184 // A pointer to an incomplete type might be past-the-end if the type's size is
13185 // zero. We cannot tell because the type is incomplete.
13186 QualType Ty = getType(B: LV.getLValueBase());
13187 if (Ty->isIncompleteType())
13188 return true;
13189
13190 // Can't be past the end of an invalid object.
13191 if (LV.getLValueDesignator().Invalid)
13192 return false;
13193
13194 // We're a past-the-end pointer if we point to the byte after the object,
13195 // no matter what our type or path is.
13196 auto Size = Ctx.getTypeSizeInChars(T: Ty);
13197 return LV.getLValueOffset() == Size;
13198}
13199
13200namespace {
13201
13202/// Data recursive integer evaluator of certain binary operators.
13203///
13204/// We use a data recursive algorithm for binary operators so that we are able
13205/// to handle extreme cases of chained binary operators without causing stack
13206/// overflow.
13207class DataRecursiveIntBinOpEvaluator {
13208 struct EvalResult {
13209 APValue Val;
13210 bool Failed = false;
13211
13212 EvalResult() = default;
13213
13214 void swap(EvalResult &RHS) {
13215 Val.swap(RHS&: RHS.Val);
13216 Failed = RHS.Failed;
13217 RHS.Failed = false;
13218 }
13219 };
13220
13221 struct Job {
13222 const Expr *E;
13223 EvalResult LHSResult; // meaningful only for binary operator expression.
13224 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13225
13226 Job() = default;
13227 Job(Job &&) = default;
13228
13229 void startSpeculativeEval(EvalInfo &Info) {
13230 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13231 }
13232
13233 private:
13234 SpeculativeEvaluationRAII SpecEvalRAII;
13235 };
13236
13237 SmallVector<Job, 16> Queue;
13238
13239 IntExprEvaluator &IntEval;
13240 EvalInfo &Info;
13241 APValue &FinalResult;
13242
13243public:
13244 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13245 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13246
13247 /// True if \param E is a binary operator that we are going to handle
13248 /// data recursively.
13249 /// We handle binary operators that are comma, logical, or that have operands
13250 /// with integral or enumeration type.
13251 static bool shouldEnqueue(const BinaryOperator *E) {
13252 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13253 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
13254 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13255 E->getRHS()->getType()->isIntegralOrEnumerationType());
13256 }
13257
13258 bool Traverse(const BinaryOperator *E) {
13259 enqueue(E);
13260 EvalResult PrevResult;
13261 while (!Queue.empty())
13262 process(Result&: PrevResult);
13263
13264 if (PrevResult.Failed) return false;
13265
13266 FinalResult.swap(RHS&: PrevResult.Val);
13267 return true;
13268 }
13269
13270private:
13271 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13272 return IntEval.Success(Value, E, Result);
13273 }
13274 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13275 return IntEval.Success(SI: Value, E, Result);
13276 }
13277 bool Error(const Expr *E) {
13278 return IntEval.Error(E);
13279 }
13280 bool Error(const Expr *E, diag::kind D) {
13281 return IntEval.Error(E, D);
13282 }
13283
13284 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
13285 return Info.CCEDiag(E, DiagId: D);
13286 }
13287
13288 // Returns true if visiting the RHS is necessary, false otherwise.
13289 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13290 bool &SuppressRHSDiags);
13291
13292 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13293 const BinaryOperator *E, APValue &Result);
13294
13295 void EvaluateExpr(const Expr *E, EvalResult &Result) {
13296 Result.Failed = !Evaluate(Result&: Result.Val, Info, E);
13297 if (Result.Failed)
13298 Result.Val = APValue();
13299 }
13300
13301 void process(EvalResult &Result);
13302
13303 void enqueue(const Expr *E) {
13304 E = E->IgnoreParens();
13305 Queue.resize(N: Queue.size()+1);
13306 Queue.back().E = E;
13307 Queue.back().Kind = Job::AnyExprKind;
13308 }
13309};
13310
13311}
13312
13313bool DataRecursiveIntBinOpEvaluator::
13314 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13315 bool &SuppressRHSDiags) {
13316 if (E->getOpcode() == BO_Comma) {
13317 // Ignore LHS but note if we could not evaluate it.
13318 if (LHSResult.Failed)
13319 return Info.noteSideEffect();
13320 return true;
13321 }
13322
13323 if (E->isLogicalOp()) {
13324 bool LHSAsBool;
13325 if (!LHSResult.Failed && HandleConversionToBool(Val: LHSResult.Val, Result&: LHSAsBool)) {
13326 // We were able to evaluate the LHS, see if we can get away with not
13327 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
13328 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
13329 Success(Value: LHSAsBool, E, Result&: LHSResult.Val);
13330 return false; // Ignore RHS
13331 }
13332 } else {
13333 LHSResult.Failed = true;
13334
13335 // Since we weren't able to evaluate the left hand side, it
13336 // might have had side effects.
13337 if (!Info.noteSideEffect())
13338 return false;
13339
13340 // We can't evaluate the LHS; however, sometimes the result
13341 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13342 // Don't ignore RHS and suppress diagnostics from this arm.
13343 SuppressRHSDiags = true;
13344 }
13345
13346 return true;
13347 }
13348
13349 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13350 E->getRHS()->getType()->isIntegralOrEnumerationType());
13351
13352 if (LHSResult.Failed && !Info.noteFailure())
13353 return false; // Ignore RHS;
13354
13355 return true;
13356}
13357
13358static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
13359 bool IsSub) {
13360 // Compute the new offset in the appropriate width, wrapping at 64 bits.
13361 // FIXME: When compiling for a 32-bit target, we should use 32-bit
13362 // offsets.
13363 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
13364 CharUnits &Offset = LVal.getLValueOffset();
13365 uint64_t Offset64 = Offset.getQuantity();
13366 uint64_t Index64 = Index.extOrTrunc(width: 64).getZExtValue();
13367 Offset = CharUnits::fromQuantity(Quantity: IsSub ? Offset64 - Index64
13368 : Offset64 + Index64);
13369}
13370
13371bool DataRecursiveIntBinOpEvaluator::
13372 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13373 const BinaryOperator *E, APValue &Result) {
13374 if (E->getOpcode() == BO_Comma) {
13375 if (RHSResult.Failed)
13376 return false;
13377 Result = RHSResult.Val;
13378 return true;
13379 }
13380
13381 if (E->isLogicalOp()) {
13382 bool lhsResult, rhsResult;
13383 bool LHSIsOK = HandleConversionToBool(Val: LHSResult.Val, Result&: lhsResult);
13384 bool RHSIsOK = HandleConversionToBool(Val: RHSResult.Val, Result&: rhsResult);
13385
13386 if (LHSIsOK) {
13387 if (RHSIsOK) {
13388 if (E->getOpcode() == BO_LOr)
13389 return Success(Value: lhsResult || rhsResult, E, Result);
13390 else
13391 return Success(Value: lhsResult && rhsResult, E, Result);
13392 }
13393 } else {
13394 if (RHSIsOK) {
13395 // We can't evaluate the LHS; however, sometimes the result
13396 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13397 if (rhsResult == (E->getOpcode() == BO_LOr))
13398 return Success(Value: rhsResult, E, Result);
13399 }
13400 }
13401
13402 return false;
13403 }
13404
13405 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13406 E->getRHS()->getType()->isIntegralOrEnumerationType());
13407
13408 if (LHSResult.Failed || RHSResult.Failed)
13409 return false;
13410
13411 const APValue &LHSVal = LHSResult.Val;
13412 const APValue &RHSVal = RHSResult.Val;
13413
13414 // Handle cases like (unsigned long)&a + 4.
13415 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
13416 Result = LHSVal;
13417 addOrSubLValueAsInteger(LVal&: Result, Index: RHSVal.getInt(), IsSub: E->getOpcode() == BO_Sub);
13418 return true;
13419 }
13420
13421 // Handle cases like 4 + (unsigned long)&a
13422 if (E->getOpcode() == BO_Add &&
13423 RHSVal.isLValue() && LHSVal.isInt()) {
13424 Result = RHSVal;
13425 addOrSubLValueAsInteger(LVal&: Result, Index: LHSVal.getInt(), /*IsSub*/false);
13426 return true;
13427 }
13428
13429 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
13430 // Handle (intptr_t)&&A - (intptr_t)&&B.
13431 if (!LHSVal.getLValueOffset().isZero() ||
13432 !RHSVal.getLValueOffset().isZero())
13433 return false;
13434 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
13435 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
13436 if (!LHSExpr || !RHSExpr)
13437 return false;
13438 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(Val: LHSExpr);
13439 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(Val: RHSExpr);
13440 if (!LHSAddrExpr || !RHSAddrExpr)
13441 return false;
13442 // Make sure both labels come from the same function.
13443 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13444 RHSAddrExpr->getLabel()->getDeclContext())
13445 return false;
13446 Result = APValue(LHSAddrExpr, RHSAddrExpr);
13447 return true;
13448 }
13449
13450 // All the remaining cases expect both operands to be an integer
13451 if (!LHSVal.isInt() || !RHSVal.isInt())
13452 return Error(E);
13453
13454 // Set up the width and signedness manually, in case it can't be deduced
13455 // from the operation we're performing.
13456 // FIXME: Don't do this in the cases where we can deduce it.
13457 APSInt Value(Info.Ctx.getIntWidth(T: E->getType()),
13458 E->getType()->isUnsignedIntegerOrEnumerationType());
13459 if (!handleIntIntBinOp(Info, E, LHS: LHSVal.getInt(), Opcode: E->getOpcode(),
13460 RHS: RHSVal.getInt(), Result&: Value))
13461 return false;
13462 return Success(Value, E, Result);
13463}
13464
13465void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
13466 Job &job = Queue.back();
13467
13468 switch (job.Kind) {
13469 case Job::AnyExprKind: {
13470 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: job.E)) {
13471 if (shouldEnqueue(E: Bop)) {
13472 job.Kind = Job::BinOpKind;
13473 enqueue(E: Bop->getLHS());
13474 return;
13475 }
13476 }
13477
13478 EvaluateExpr(E: job.E, Result);
13479 Queue.pop_back();
13480 return;
13481 }
13482
13483 case Job::BinOpKind: {
13484 const BinaryOperator *Bop = cast<BinaryOperator>(Val: job.E);
13485 bool SuppressRHSDiags = false;
13486 if (!VisitBinOpLHSOnly(LHSResult&: Result, E: Bop, SuppressRHSDiags)) {
13487 Queue.pop_back();
13488 return;
13489 }
13490 if (SuppressRHSDiags)
13491 job.startSpeculativeEval(Info);
13492 job.LHSResult.swap(RHS&: Result);
13493 job.Kind = Job::BinOpVisitedLHSKind;
13494 enqueue(E: Bop->getRHS());
13495 return;
13496 }
13497
13498 case Job::BinOpVisitedLHSKind: {
13499 const BinaryOperator *Bop = cast<BinaryOperator>(Val: job.E);
13500 EvalResult RHS;
13501 RHS.swap(RHS&: Result);
13502 Result.Failed = !VisitBinOp(LHSResult: job.LHSResult, RHSResult: RHS, E: Bop, Result&: Result.Val);
13503 Queue.pop_back();
13504 return;
13505 }
13506 }
13507
13508 llvm_unreachable("Invalid Job::Kind!");
13509}
13510
13511namespace {
13512enum class CmpResult {
13513 Unequal,
13514 Less,
13515 Equal,
13516 Greater,
13517 Unordered,
13518};
13519}
13520
13521template <class SuccessCB, class AfterCB>
13522static bool
13523EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
13524 SuccessCB &&Success, AfterCB &&DoAfter) {
13525 assert(!E->isValueDependent());
13526 assert(E->isComparisonOp() && "expected comparison operator");
13527 assert((E->getOpcode() == BO_Cmp ||
13528 E->getType()->isIntegralOrEnumerationType()) &&
13529 "unsupported binary expression evaluation");
13530 auto Error = [&](const Expr *E) {
13531 Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
13532 return false;
13533 };
13534
13535 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
13536 bool IsEquality = E->isEqualityOp();
13537
13538 QualType LHSTy = E->getLHS()->getType();
13539 QualType RHSTy = E->getRHS()->getType();
13540
13541 if (LHSTy->isIntegralOrEnumerationType() &&
13542 RHSTy->isIntegralOrEnumerationType()) {
13543 APSInt LHS, RHS;
13544 bool LHSOK = EvaluateInteger(E: E->getLHS(), Result&: LHS, Info);
13545 if (!LHSOK && !Info.noteFailure())
13546 return false;
13547 if (!EvaluateInteger(E: E->getRHS(), Result&: RHS, Info) || !LHSOK)
13548 return false;
13549 if (LHS < RHS)
13550 return Success(CmpResult::Less, E);
13551 if (LHS > RHS)
13552 return Success(CmpResult::Greater, E);
13553 return Success(CmpResult::Equal, E);
13554 }
13555
13556 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
13557 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(Ty: LHSTy));
13558 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(Ty: RHSTy));
13559
13560 bool LHSOK = EvaluateFixedPointOrInteger(E: E->getLHS(), Result&: LHSFX, Info);
13561 if (!LHSOK && !Info.noteFailure())
13562 return false;
13563 if (!EvaluateFixedPointOrInteger(E: E->getRHS(), Result&: RHSFX, Info) || !LHSOK)
13564 return false;
13565 if (LHSFX < RHSFX)
13566 return Success(CmpResult::Less, E);
13567 if (LHSFX > RHSFX)
13568 return Success(CmpResult::Greater, E);
13569 return Success(CmpResult::Equal, E);
13570 }
13571
13572 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
13573 ComplexValue LHS, RHS;
13574 bool LHSOK;
13575 if (E->isAssignmentOp()) {
13576 LValue LV;
13577 EvaluateLValue(E: E->getLHS(), Result&: LV, Info);
13578 LHSOK = false;
13579 } else if (LHSTy->isRealFloatingType()) {
13580 LHSOK = EvaluateFloat(E: E->getLHS(), Result&: LHS.FloatReal, Info);
13581 if (LHSOK) {
13582 LHS.makeComplexFloat();
13583 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13584 }
13585 } else {
13586 LHSOK = EvaluateComplex(E: E->getLHS(), Res&: LHS, Info);
13587 }
13588 if (!LHSOK && !Info.noteFailure())
13589 return false;
13590
13591 if (E->getRHS()->getType()->isRealFloatingType()) {
13592 if (!EvaluateFloat(E: E->getRHS(), Result&: RHS.FloatReal, Info) || !LHSOK)
13593 return false;
13594 RHS.makeComplexFloat();
13595 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13596 } else if (!EvaluateComplex(E: E->getRHS(), Res&: RHS, Info) || !LHSOK)
13597 return false;
13598
13599 if (LHS.isComplexFloat()) {
13600 APFloat::cmpResult CR_r =
13601 LHS.getComplexFloatReal().compare(RHS: RHS.getComplexFloatReal());
13602 APFloat::cmpResult CR_i =
13603 LHS.getComplexFloatImag().compare(RHS: RHS.getComplexFloatImag());
13604 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
13605 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13606 } else {
13607 assert(IsEquality && "invalid complex comparison");
13608 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13609 LHS.getComplexIntImag() == RHS.getComplexIntImag();
13610 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13611 }
13612 }
13613
13614 if (LHSTy->isRealFloatingType() &&
13615 RHSTy->isRealFloatingType()) {
13616 APFloat RHS(0.0), LHS(0.0);
13617
13618 bool LHSOK = EvaluateFloat(E: E->getRHS(), Result&: RHS, Info);
13619 if (!LHSOK && !Info.noteFailure())
13620 return false;
13621
13622 if (!EvaluateFloat(E: E->getLHS(), Result&: LHS, Info) || !LHSOK)
13623 return false;
13624
13625 assert(E->isComparisonOp() && "Invalid binary operator!");
13626 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13627 if (!Info.InConstantContext &&
13628 APFloatCmpResult == APFloat::cmpUnordered &&
13629 E->getFPFeaturesInEffect(LO: Info.Ctx.getLangOpts()).isFPConstrained()) {
13630 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13631 Info.FFDiag(E, DiagId: diag::note_constexpr_float_arithmetic_strict);
13632 return false;
13633 }
13634 auto GetCmpRes = [&]() {
13635 switch (APFloatCmpResult) {
13636 case APFloat::cmpEqual:
13637 return CmpResult::Equal;
13638 case APFloat::cmpLessThan:
13639 return CmpResult::Less;
13640 case APFloat::cmpGreaterThan:
13641 return CmpResult::Greater;
13642 case APFloat::cmpUnordered:
13643 return CmpResult::Unordered;
13644 }
13645 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13646 };
13647 return Success(GetCmpRes(), E);
13648 }
13649
13650 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13651 LValue LHSValue, RHSValue;
13652
13653 bool LHSOK = EvaluatePointer(E: E->getLHS(), Result&: LHSValue, Info);
13654 if (!LHSOK && !Info.noteFailure())
13655 return false;
13656
13657 if (!EvaluatePointer(E: E->getRHS(), Result&: RHSValue, Info) || !LHSOK)
13658 return false;
13659
13660 // Reject differing bases from the normal codepath; we special-case
13661 // comparisons to null.
13662 if (!HasSameBase(A: LHSValue, B: RHSValue)) {
13663 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13664 std::string LHS = LHSValue.toString(Ctx&: Info.Ctx, T: E->getLHS()->getType());
13665 std::string RHS = RHSValue.toString(Ctx&: Info.Ctx, T: E->getRHS()->getType());
13666 Info.FFDiag(E, DiagId: DiagID)
13667 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13668 return false;
13669 };
13670 // Inequalities and subtractions between unrelated pointers have
13671 // unspecified or undefined behavior.
13672 if (!IsEquality)
13673 return DiagComparison(
13674 diag::note_constexpr_pointer_comparison_unspecified);
13675 // A constant address may compare equal to the address of a symbol.
13676 // The one exception is that address of an object cannot compare equal
13677 // to a null pointer constant.
13678 // TODO: Should we restrict this to actual null pointers, and exclude the
13679 // case of zero cast to pointer type?
13680 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13681 (!RHSValue.Base && !RHSValue.Offset.isZero()))
13682 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13683 !RHSValue.Base);
13684 // It's implementation-defined whether distinct literals will have
13685 // distinct addresses. In clang, the result of such a comparison is
13686 // unspecified, so it is not a constant expression. However, we do know
13687 // that the address of a literal will be non-null.
13688 if ((IsLiteralLValue(Value: LHSValue) || IsLiteralLValue(Value: RHSValue)) &&
13689 LHSValue.Base && RHSValue.Base)
13690 return DiagComparison(diag::note_constexpr_literal_comparison);
13691 // We can't tell whether weak symbols will end up pointing to the same
13692 // object.
13693 if (IsWeakLValue(Value: LHSValue) || IsWeakLValue(Value: RHSValue))
13694 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13695 !IsWeakLValue(Value: LHSValue));
13696 // We can't compare the address of the start of one object with the
13697 // past-the-end address of another object, per C++ DR1652.
13698 if (LHSValue.Base && LHSValue.Offset.isZero() &&
13699 isOnePastTheEndOfCompleteObject(Ctx: Info.Ctx, LV: RHSValue))
13700 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13701 true);
13702 if (RHSValue.Base && RHSValue.Offset.isZero() &&
13703 isOnePastTheEndOfCompleteObject(Ctx: Info.Ctx, LV: LHSValue))
13704 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13705 false);
13706 // We can't tell whether an object is at the same address as another
13707 // zero sized object.
13708 if ((RHSValue.Base && isZeroSized(Value: LHSValue)) ||
13709 (LHSValue.Base && isZeroSized(Value: RHSValue)))
13710 return DiagComparison(
13711 diag::note_constexpr_pointer_comparison_zero_sized);
13712 return Success(CmpResult::Unequal, E);
13713 }
13714
13715 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13716 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13717
13718 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13719 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13720
13721 // C++11 [expr.rel]p3:
13722 // Pointers to void (after pointer conversions) can be compared, with a
13723 // result defined as follows: If both pointers represent the same
13724 // address or are both the null pointer value, the result is true if the
13725 // operator is <= or >= and false otherwise; otherwise the result is
13726 // unspecified.
13727 // We interpret this as applying to pointers to *cv* void.
13728 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13729 Info.CCEDiag(E, DiagId: diag::note_constexpr_void_comparison);
13730
13731 // C++11 [expr.rel]p2:
13732 // - If two pointers point to non-static data members of the same object,
13733 // or to subobjects or array elements fo such members, recursively, the
13734 // pointer to the later declared member compares greater provided the
13735 // two members have the same access control and provided their class is
13736 // not a union.
13737 // [...]
13738 // - Otherwise pointer comparisons are unspecified.
13739 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13740 bool WasArrayIndex;
13741 unsigned Mismatch = FindDesignatorMismatch(
13742 ObjType: getType(B: LHSValue.Base), A: LHSDesignator, B: RHSDesignator, WasArrayIndex);
13743 // At the point where the designators diverge, the comparison has a
13744 // specified value if:
13745 // - we are comparing array indices
13746 // - we are comparing fields of a union, or fields with the same access
13747 // Otherwise, the result is unspecified and thus the comparison is not a
13748 // constant expression.
13749 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13750 Mismatch < RHSDesignator.Entries.size()) {
13751 const FieldDecl *LF = getAsField(E: LHSDesignator.Entries[Mismatch]);
13752 const FieldDecl *RF = getAsField(E: RHSDesignator.Entries[Mismatch]);
13753 if (!LF && !RF)
13754 Info.CCEDiag(E, DiagId: diag::note_constexpr_pointer_comparison_base_classes);
13755 else if (!LF)
13756 Info.CCEDiag(E, DiagId: diag::note_constexpr_pointer_comparison_base_field)
13757 << getAsBaseClass(E: LHSDesignator.Entries[Mismatch])
13758 << RF->getParent() << RF;
13759 else if (!RF)
13760 Info.CCEDiag(E, DiagId: diag::note_constexpr_pointer_comparison_base_field)
13761 << getAsBaseClass(E: RHSDesignator.Entries[Mismatch])
13762 << LF->getParent() << LF;
13763 else if (!LF->getParent()->isUnion() &&
13764 LF->getAccess() != RF->getAccess())
13765 Info.CCEDiag(E,
13766 DiagId: diag::note_constexpr_pointer_comparison_differing_access)
13767 << LF << LF->getAccess() << RF << RF->getAccess()
13768 << LF->getParent();
13769 }
13770 }
13771
13772 // The comparison here must be unsigned, and performed with the same
13773 // width as the pointer.
13774 unsigned PtrSize = Info.Ctx.getTypeSize(T: LHSTy);
13775 uint64_t CompareLHS = LHSOffset.getQuantity();
13776 uint64_t CompareRHS = RHSOffset.getQuantity();
13777 assert(PtrSize <= 64 && "Unexpected pointer width");
13778 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13779 CompareLHS &= Mask;
13780 CompareRHS &= Mask;
13781
13782 // If there is a base and this is a relational operator, we can only
13783 // compare pointers within the object in question; otherwise, the result
13784 // depends on where the object is located in memory.
13785 if (!LHSValue.Base.isNull() && IsRelational) {
13786 QualType BaseTy = getType(B: LHSValue.Base);
13787 if (BaseTy->isIncompleteType())
13788 return Error(E);
13789 CharUnits Size = Info.Ctx.getTypeSizeInChars(T: BaseTy);
13790 uint64_t OffsetLimit = Size.getQuantity();
13791 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13792 return Error(E);
13793 }
13794
13795 if (CompareLHS < CompareRHS)
13796 return Success(CmpResult::Less, E);
13797 if (CompareLHS > CompareRHS)
13798 return Success(CmpResult::Greater, E);
13799 return Success(CmpResult::Equal, E);
13800 }
13801
13802 if (LHSTy->isMemberPointerType()) {
13803 assert(IsEquality && "unexpected member pointer operation");
13804 assert(RHSTy->isMemberPointerType() && "invalid comparison");
13805
13806 MemberPtr LHSValue, RHSValue;
13807
13808 bool LHSOK = EvaluateMemberPointer(E: E->getLHS(), Result&: LHSValue, Info);
13809 if (!LHSOK && !Info.noteFailure())
13810 return false;
13811
13812 if (!EvaluateMemberPointer(E: E->getRHS(), Result&: RHSValue, Info) || !LHSOK)
13813 return false;
13814
13815 // If either operand is a pointer to a weak function, the comparison is not
13816 // constant.
13817 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13818 Info.FFDiag(E, DiagId: diag::note_constexpr_mem_pointer_weak_comparison)
13819 << LHSValue.getDecl();
13820 return false;
13821 }
13822 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13823 Info.FFDiag(E, DiagId: diag::note_constexpr_mem_pointer_weak_comparison)
13824 << RHSValue.getDecl();
13825 return false;
13826 }
13827
13828 // C++11 [expr.eq]p2:
13829 // If both operands are null, they compare equal. Otherwise if only one is
13830 // null, they compare unequal.
13831 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13832 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13833 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13834 }
13835
13836 // Otherwise if either is a pointer to a virtual member function, the
13837 // result is unspecified.
13838 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: LHSValue.getDecl()))
13839 if (MD->isVirtual())
13840 Info.CCEDiag(E, DiagId: diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13841 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: RHSValue.getDecl()))
13842 if (MD->isVirtual())
13843 Info.CCEDiag(E, DiagId: diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13844
13845 // Otherwise they compare equal if and only if they would refer to the
13846 // same member of the same most derived object or the same subobject if
13847 // they were dereferenced with a hypothetical object of the associated
13848 // class type.
13849 bool Equal = LHSValue == RHSValue;
13850 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13851 }
13852
13853 if (LHSTy->isNullPtrType()) {
13854 assert(E->isComparisonOp() && "unexpected nullptr operation");
13855 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13856 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13857 // are compared, the result is true of the operator is <=, >= or ==, and
13858 // false otherwise.
13859 LValue Res;
13860 if (!EvaluatePointer(E: E->getLHS(), Result&: Res, Info) ||
13861 !EvaluatePointer(E: E->getRHS(), Result&: Res, Info))
13862 return false;
13863 return Success(CmpResult::Equal, E);
13864 }
13865
13866 return DoAfter();
13867}
13868
13869bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13870 if (!CheckLiteralType(Info, E))
13871 return false;
13872
13873 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13874 ComparisonCategoryResult CCR;
13875 switch (CR) {
13876 case CmpResult::Unequal:
13877 llvm_unreachable("should never produce Unequal for three-way comparison");
13878 case CmpResult::Less:
13879 CCR = ComparisonCategoryResult::Less;
13880 break;
13881 case CmpResult::Equal:
13882 CCR = ComparisonCategoryResult::Equal;
13883 break;
13884 case CmpResult::Greater:
13885 CCR = ComparisonCategoryResult::Greater;
13886 break;
13887 case CmpResult::Unordered:
13888 CCR = ComparisonCategoryResult::Unordered;
13889 break;
13890 }
13891 // Evaluation succeeded. Lookup the information for the comparison category
13892 // type and fetch the VarDecl for the result.
13893 const ComparisonCategoryInfo &CmpInfo =
13894 Info.Ctx.CompCategories.getInfoForType(Ty: E->getType());
13895 const VarDecl *VD = CmpInfo.getValueInfo(ValueKind: CmpInfo.makeWeakResult(Res: CCR))->VD;
13896 // Check and evaluate the result as a constant expression.
13897 LValue LV;
13898 LV.set(B: VD);
13899 if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getType(), LVal: LV, RVal&: Result))
13900 return false;
13901 return CheckConstantExpression(Info, DiagLoc: E->getExprLoc(), Type: E->getType(), Value: Result,
13902 Kind: ConstantExprKind::Normal);
13903 };
13904 return EvaluateComparisonBinaryOperator(Info, E, Success&: OnSuccess, DoAfter: [&]() {
13905 return ExprEvaluatorBaseTy::VisitBinCmp(S: E);
13906 });
13907}
13908
13909bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13910 const CXXParenListInitExpr *E) {
13911 return VisitCXXParenListOrInitListExpr(ExprToVisit: E, Args: E->getInitExprs());
13912}
13913
13914bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13915 // We don't support assignment in C. C++ assignments don't get here because
13916 // assignment is an lvalue in C++.
13917 if (E->isAssignmentOp()) {
13918 Error(E);
13919 if (!Info.noteFailure())
13920 return false;
13921 }
13922
13923 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13924 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13925
13926 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13927 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13928 "DataRecursiveIntBinOpEvaluator should have handled integral types");
13929
13930 if (E->isComparisonOp()) {
13931 // Evaluate builtin binary comparisons by evaluating them as three-way
13932 // comparisons and then translating the result.
13933 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13934 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13935 "should only produce Unequal for equality comparisons");
13936 bool IsEqual = CR == CmpResult::Equal,
13937 IsLess = CR == CmpResult::Less,
13938 IsGreater = CR == CmpResult::Greater;
13939 auto Op = E->getOpcode();
13940 switch (Op) {
13941 default:
13942 llvm_unreachable("unsupported binary operator");
13943 case BO_EQ:
13944 case BO_NE:
13945 return Success(Value: IsEqual == (Op == BO_EQ), E);
13946 case BO_LT:
13947 return Success(Value: IsLess, E);
13948 case BO_GT:
13949 return Success(Value: IsGreater, E);
13950 case BO_LE:
13951 return Success(Value: IsEqual || IsLess, E);
13952 case BO_GE:
13953 return Success(Value: IsEqual || IsGreater, E);
13954 }
13955 };
13956 return EvaluateComparisonBinaryOperator(Info, E, Success&: OnSuccess, DoAfter: [&]() {
13957 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13958 });
13959 }
13960
13961 QualType LHSTy = E->getLHS()->getType();
13962 QualType RHSTy = E->getRHS()->getType();
13963
13964 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13965 E->getOpcode() == BO_Sub) {
13966 LValue LHSValue, RHSValue;
13967
13968 bool LHSOK = EvaluatePointer(E: E->getLHS(), Result&: LHSValue, Info);
13969 if (!LHSOK && !Info.noteFailure())
13970 return false;
13971
13972 if (!EvaluatePointer(E: E->getRHS(), Result&: RHSValue, Info) || !LHSOK)
13973 return false;
13974
13975 // Reject differing bases from the normal codepath; we special-case
13976 // comparisons to null.
13977 if (!HasSameBase(A: LHSValue, B: RHSValue)) {
13978 // Handle &&A - &&B.
13979 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13980 return Error(E);
13981 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13982 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13983 if (!LHSExpr || !RHSExpr)
13984 return Error(E);
13985 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(Val: LHSExpr);
13986 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(Val: RHSExpr);
13987 if (!LHSAddrExpr || !RHSAddrExpr)
13988 return Error(E);
13989 // Make sure both labels come from the same function.
13990 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13991 RHSAddrExpr->getLabel()->getDeclContext())
13992 return Error(E);
13993 return Success(V: APValue(LHSAddrExpr, RHSAddrExpr), E);
13994 }
13995 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13996 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13997
13998 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13999 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14000
14001 // C++11 [expr.add]p6:
14002 // Unless both pointers point to elements of the same array object, or
14003 // one past the last element of the array object, the behavior is
14004 // undefined.
14005 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14006 !AreElementsOfSameArray(ObjType: getType(B: LHSValue.Base), A: LHSDesignator,
14007 B: RHSDesignator))
14008 Info.CCEDiag(E, DiagId: diag::note_constexpr_pointer_subtraction_not_same_array);
14009
14010 QualType Type = E->getLHS()->getType();
14011 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14012
14013 CharUnits ElementSize;
14014 if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: ElementType, Size&: ElementSize))
14015 return false;
14016
14017 // As an extension, a type may have zero size (empty struct or union in
14018 // C, array of zero length). Pointer subtraction in such cases has
14019 // undefined behavior, so is not constant.
14020 if (ElementSize.isZero()) {
14021 Info.FFDiag(E, DiagId: diag::note_constexpr_pointer_subtraction_zero_size)
14022 << ElementType;
14023 return false;
14024 }
14025
14026 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14027 // and produce incorrect results when it overflows. Such behavior
14028 // appears to be non-conforming, but is common, so perhaps we should
14029 // assume the standard intended for such cases to be undefined behavior
14030 // and check for them.
14031
14032 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14033 // overflow in the final conversion to ptrdiff_t.
14034 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14035 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14036 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14037 false);
14038 APSInt TrueResult = (LHS - RHS) / ElemSize;
14039 APSInt Result = TrueResult.trunc(width: Info.Ctx.getIntWidth(T: E->getType()));
14040
14041 if (Result.extend(width: 65) != TrueResult &&
14042 !HandleOverflow(Info, E, SrcValue: TrueResult, DestType: E->getType()))
14043 return false;
14044 return Success(SI: Result, E);
14045 }
14046
14047 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14048}
14049
14050/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14051/// a result as the expression's type.
14052bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14053 const UnaryExprOrTypeTraitExpr *E) {
14054 switch(E->getKind()) {
14055 case UETT_PreferredAlignOf:
14056 case UETT_AlignOf: {
14057 if (E->isArgumentType())
14058 return Success(Size: GetAlignOfType(Info, T: E->getArgumentType(), ExprKind: E->getKind()),
14059 E);
14060 else
14061 return Success(Size: GetAlignOfExpr(Info, E: E->getArgumentExpr(), ExprKind: E->getKind()),
14062 E);
14063 }
14064
14065 case UETT_PtrAuthTypeDiscriminator: {
14066 if (E->getArgumentType()->isDependentType())
14067 return false;
14068 return Success(
14069 Value: Info.Ctx.getPointerAuthTypeDiscriminator(T: E->getArgumentType()), E);
14070 }
14071 case UETT_VecStep: {
14072 QualType Ty = E->getTypeOfArgument();
14073
14074 if (Ty->isVectorType()) {
14075 unsigned n = Ty->castAs<VectorType>()->getNumElements();
14076
14077 // The vec_step built-in functions that take a 3-component
14078 // vector return 4. (OpenCL 1.1 spec 6.11.12)
14079 if (n == 3)
14080 n = 4;
14081
14082 return Success(Value: n, E);
14083 } else
14084 return Success(Value: 1, E);
14085 }
14086
14087 case UETT_DataSizeOf:
14088 case UETT_SizeOf: {
14089 QualType SrcTy = E->getTypeOfArgument();
14090 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14091 // the result is the size of the referenced type."
14092 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14093 SrcTy = Ref->getPointeeType();
14094
14095 CharUnits Sizeof;
14096 if (!HandleSizeof(Info, Loc: E->getExprLoc(), Type: SrcTy, Size&: Sizeof,
14097 SOT: E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14098 : SizeOfType::SizeOf)) {
14099 return false;
14100 }
14101 return Success(Size: Sizeof, E);
14102 }
14103 case UETT_OpenMPRequiredSimdAlign:
14104 assert(E->isArgumentType());
14105 return Success(
14106 Value: Info.Ctx.toCharUnitsFromBits(
14107 BitSize: Info.Ctx.getOpenMPDefaultSimdAlign(T: E->getArgumentType()))
14108 .getQuantity(),
14109 E);
14110 case UETT_VectorElements: {
14111 QualType Ty = E->getTypeOfArgument();
14112 // If the vector has a fixed size, we can determine the number of elements
14113 // at compile time.
14114 if (const auto *VT = Ty->getAs<VectorType>())
14115 return Success(Value: VT->getNumElements(), E);
14116
14117 assert(Ty->isSizelessVectorType());
14118 if (Info.InConstantContext)
14119 Info.CCEDiag(E, DiagId: diag::note_constexpr_non_const_vectorelements)
14120 << E->getSourceRange();
14121
14122 return false;
14123 }
14124 }
14125
14126 llvm_unreachable("unknown expr/type trait");
14127}
14128
14129bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14130 CharUnits Result;
14131 unsigned n = OOE->getNumComponents();
14132 if (n == 0)
14133 return Error(E: OOE);
14134 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14135 for (unsigned i = 0; i != n; ++i) {
14136 OffsetOfNode ON = OOE->getComponent(Idx: i);
14137 switch (ON.getKind()) {
14138 case OffsetOfNode::Array: {
14139 const Expr *Idx = OOE->getIndexExpr(Idx: ON.getArrayExprIndex());
14140 APSInt IdxResult;
14141 if (!EvaluateInteger(E: Idx, Result&: IdxResult, Info))
14142 return false;
14143 const ArrayType *AT = Info.Ctx.getAsArrayType(T: CurrentType);
14144 if (!AT)
14145 return Error(E: OOE);
14146 CurrentType = AT->getElementType();
14147 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(T: CurrentType);
14148 Result += IdxResult.getSExtValue() * ElementSize;
14149 break;
14150 }
14151
14152 case OffsetOfNode::Field: {
14153 FieldDecl *MemberDecl = ON.getField();
14154 const RecordType *RT = CurrentType->getAs<RecordType>();
14155 if (!RT)
14156 return Error(E: OOE);
14157 RecordDecl *RD = RT->getDecl();
14158 if (RD->isInvalidDecl()) return false;
14159 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(D: RD);
14160 unsigned i = MemberDecl->getFieldIndex();
14161 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14162 Result += Info.Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: i));
14163 CurrentType = MemberDecl->getType().getNonReferenceType();
14164 break;
14165 }
14166
14167 case OffsetOfNode::Identifier:
14168 llvm_unreachable("dependent __builtin_offsetof");
14169
14170 case OffsetOfNode::Base: {
14171 CXXBaseSpecifier *BaseSpec = ON.getBase();
14172 if (BaseSpec->isVirtual())
14173 return Error(E: OOE);
14174
14175 // Find the layout of the class whose base we are looking into.
14176 const RecordType *RT = CurrentType->getAs<RecordType>();
14177 if (!RT)
14178 return Error(E: OOE);
14179 RecordDecl *RD = RT->getDecl();
14180 if (RD->isInvalidDecl()) return false;
14181 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(D: RD);
14182
14183 // Find the base class itself.
14184 CurrentType = BaseSpec->getType();
14185 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14186 if (!BaseRT)
14187 return Error(E: OOE);
14188
14189 // Add the offset to the base.
14190 Result += RL.getBaseClassOffset(Base: cast<CXXRecordDecl>(Val: BaseRT->getDecl()));
14191 break;
14192 }
14193 }
14194 }
14195 return Success(Size: Result, E: OOE);
14196}
14197
14198bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14199 switch (E->getOpcode()) {
14200 default:
14201 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14202 // See C99 6.6p3.
14203 return Error(E);
14204 case UO_Extension:
14205 // FIXME: Should extension allow i-c-e extension expressions in its scope?
14206 // If so, we could clear the diagnostic ID.
14207 return Visit(S: E->getSubExpr());
14208 case UO_Plus:
14209 // The result is just the value.
14210 return Visit(S: E->getSubExpr());
14211 case UO_Minus: {
14212 if (!Visit(S: E->getSubExpr()))
14213 return false;
14214 if (!Result.isInt()) return Error(E);
14215 const APSInt &Value = Result.getInt();
14216 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14217 if (Info.checkingForUndefinedBehavior())
14218 Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(),
14219 DiagID: diag::warn_integer_constant_overflow)
14220 << toString(I: Value, Radix: 10, Signed: Value.isSigned(), /*formatAsCLiteral=*/false,
14221 /*UpperCase=*/true, /*InsertSeparators=*/true)
14222 << E->getType() << E->getSourceRange();
14223
14224 if (!HandleOverflow(Info, E, SrcValue: -Value.extend(width: Value.getBitWidth() + 1),
14225 DestType: E->getType()))
14226 return false;
14227 }
14228 return Success(SI: -Value, E);
14229 }
14230 case UO_Not: {
14231 if (!Visit(S: E->getSubExpr()))
14232 return false;
14233 if (!Result.isInt()) return Error(E);
14234 return Success(SI: ~Result.getInt(), E);
14235 }
14236 case UO_LNot: {
14237 bool bres;
14238 if (!EvaluateAsBooleanCondition(E: E->getSubExpr(), Result&: bres, Info))
14239 return false;
14240 return Success(Value: !bres, E);
14241 }
14242 }
14243}
14244
14245/// HandleCast - This is used to evaluate implicit or explicit casts where the
14246/// result type is integer.
14247bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14248 const Expr *SubExpr = E->getSubExpr();
14249 QualType DestType = E->getType();
14250 QualType SrcType = SubExpr->getType();
14251
14252 switch (E->getCastKind()) {
14253 case CK_BaseToDerived:
14254 case CK_DerivedToBase:
14255 case CK_UncheckedDerivedToBase:
14256 case CK_Dynamic:
14257 case CK_ToUnion:
14258 case CK_ArrayToPointerDecay:
14259 case CK_FunctionToPointerDecay:
14260 case CK_NullToPointer:
14261 case CK_NullToMemberPointer:
14262 case CK_BaseToDerivedMemberPointer:
14263 case CK_DerivedToBaseMemberPointer:
14264 case CK_ReinterpretMemberPointer:
14265 case CK_ConstructorConversion:
14266 case CK_IntegralToPointer:
14267 case CK_ToVoid:
14268 case CK_VectorSplat:
14269 case CK_IntegralToFloating:
14270 case CK_FloatingCast:
14271 case CK_CPointerToObjCPointerCast:
14272 case CK_BlockPointerToObjCPointerCast:
14273 case CK_AnyPointerToBlockPointerCast:
14274 case CK_ObjCObjectLValueCast:
14275 case CK_FloatingRealToComplex:
14276 case CK_FloatingComplexToReal:
14277 case CK_FloatingComplexCast:
14278 case CK_FloatingComplexToIntegralComplex:
14279 case CK_IntegralRealToComplex:
14280 case CK_IntegralComplexCast:
14281 case CK_IntegralComplexToFloatingComplex:
14282 case CK_BuiltinFnToFnPtr:
14283 case CK_ZeroToOCLOpaqueType:
14284 case CK_NonAtomicToAtomic:
14285 case CK_AddressSpaceConversion:
14286 case CK_IntToOCLSampler:
14287 case CK_FloatingToFixedPoint:
14288 case CK_FixedPointToFloating:
14289 case CK_FixedPointCast:
14290 case CK_IntegralToFixedPoint:
14291 case CK_MatrixCast:
14292 case CK_HLSLVectorTruncation:
14293 llvm_unreachable("invalid cast kind for integral value");
14294
14295 case CK_BitCast:
14296 case CK_Dependent:
14297 case CK_LValueBitCast:
14298 case CK_ARCProduceObject:
14299 case CK_ARCConsumeObject:
14300 case CK_ARCReclaimReturnedObject:
14301 case CK_ARCExtendBlockObject:
14302 case CK_CopyAndAutoreleaseBlockObject:
14303 return Error(E);
14304
14305 case CK_UserDefinedConversion:
14306 case CK_LValueToRValue:
14307 case CK_AtomicToNonAtomic:
14308 case CK_NoOp:
14309 case CK_LValueToRValueBitCast:
14310 case CK_HLSLArrayRValue:
14311 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14312
14313 case CK_MemberPointerToBoolean:
14314 case CK_PointerToBoolean:
14315 case CK_IntegralToBoolean:
14316 case CK_FloatingToBoolean:
14317 case CK_BooleanToSignedIntegral:
14318 case CK_FloatingComplexToBoolean:
14319 case CK_IntegralComplexToBoolean: {
14320 bool BoolResult;
14321 if (!EvaluateAsBooleanCondition(E: SubExpr, Result&: BoolResult, Info))
14322 return false;
14323 uint64_t IntResult = BoolResult;
14324 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
14325 IntResult = (uint64_t)-1;
14326 return Success(Value: IntResult, E);
14327 }
14328
14329 case CK_FixedPointToIntegral: {
14330 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(Ty: SrcType));
14331 if (!EvaluateFixedPoint(E: SubExpr, Result&: Src, Info))
14332 return false;
14333 bool Overflowed;
14334 llvm::APSInt Result = Src.convertToInt(
14335 DstWidth: Info.Ctx.getIntWidth(T: DestType),
14336 DstSign: DestType->isSignedIntegerOrEnumerationType(), Overflow: &Overflowed);
14337 if (Overflowed && !HandleOverflow(Info, E, SrcValue: Result, DestType))
14338 return false;
14339 return Success(SI: Result, E);
14340 }
14341
14342 case CK_FixedPointToBoolean: {
14343 // Unsigned padding does not affect this.
14344 APValue Val;
14345 if (!Evaluate(Result&: Val, Info, E: SubExpr))
14346 return false;
14347 return Success(Value: Val.getFixedPoint().getBoolValue(), E);
14348 }
14349
14350 case CK_IntegralCast: {
14351 if (!Visit(S: SubExpr))
14352 return false;
14353
14354 if (!Result.isInt()) {
14355 // Allow casts of address-of-label differences if they are no-ops
14356 // or narrowing. (The narrowing case isn't actually guaranteed to
14357 // be constant-evaluatable except in some narrow cases which are hard
14358 // to detect here. We let it through on the assumption the user knows
14359 // what they are doing.)
14360 if (Result.isAddrLabelDiff())
14361 return Info.Ctx.getTypeSize(T: DestType) <= Info.Ctx.getTypeSize(T: SrcType);
14362 // Only allow casts of lvalues if they are lossless.
14363 return Info.Ctx.getTypeSize(T: DestType) == Info.Ctx.getTypeSize(T: SrcType);
14364 }
14365
14366 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
14367 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
14368 DestType->isEnumeralType()) {
14369
14370 bool ConstexprVar = true;
14371
14372 // We know if we are here that we are in a context that we might require
14373 // a constant expression or a context that requires a constant
14374 // value. But if we are initializing a value we don't know if it is a
14375 // constexpr variable or not. We can check the EvaluatingDecl to determine
14376 // if it constexpr or not. If not then we don't want to emit a diagnostic.
14377 if (const auto *VD = dyn_cast_or_null<VarDecl>(
14378 Val: Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
14379 ConstexprVar = VD->isConstexpr();
14380
14381 const EnumType *ET = dyn_cast<EnumType>(Val: DestType.getCanonicalType());
14382 const EnumDecl *ED = ET->getDecl();
14383 // Check that the value is within the range of the enumeration values.
14384 //
14385 // This corressponds to [expr.static.cast]p10 which says:
14386 // A value of integral or enumeration type can be explicitly converted
14387 // to a complete enumeration type ... If the enumeration type does not
14388 // have a fixed underlying type, the value is unchanged if the original
14389 // value is within the range of the enumeration values ([dcl.enum]), and
14390 // otherwise, the behavior is undefined.
14391 //
14392 // This was resolved as part of DR2338 which has CD5 status.
14393 if (!ED->isFixed()) {
14394 llvm::APInt Min;
14395 llvm::APInt Max;
14396
14397 ED->getValueRange(Max, Min);
14398 --Max;
14399
14400 if (ED->getNumNegativeBits() && ConstexprVar &&
14401 (Max.slt(RHS: Result.getInt().getSExtValue()) ||
14402 Min.sgt(RHS: Result.getInt().getSExtValue())))
14403 Info.Ctx.getDiagnostics().Report(
14404 Loc: E->getExprLoc(), DiagID: diag::warn_constexpr_unscoped_enum_out_of_range)
14405 << llvm::toString(I: Result.getInt(), Radix: 10) << Min.getSExtValue()
14406 << Max.getSExtValue() << ED;
14407 else if (!ED->getNumNegativeBits() && ConstexprVar &&
14408 Max.ult(RHS: Result.getInt().getZExtValue()))
14409 Info.Ctx.getDiagnostics().Report(
14410 Loc: E->getExprLoc(), DiagID: diag::warn_constexpr_unscoped_enum_out_of_range)
14411 << llvm::toString(I: Result.getInt(), Radix: 10) << Min.getZExtValue()
14412 << Max.getZExtValue() << ED;
14413 }
14414 }
14415
14416 return Success(SI: HandleIntToIntCast(Info, E, DestType, SrcType,
14417 Value: Result.getInt()), E);
14418 }
14419
14420 case CK_PointerToIntegral: {
14421 CCEDiag(E, D: diag::note_constexpr_invalid_cast)
14422 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14423
14424 LValue LV;
14425 if (!EvaluatePointer(E: SubExpr, Result&: LV, Info))
14426 return false;
14427
14428 if (LV.getLValueBase()) {
14429 // Only allow based lvalue casts if they are lossless.
14430 // FIXME: Allow a larger integer size than the pointer size, and allow
14431 // narrowing back down to pointer width in subsequent integral casts.
14432 // FIXME: Check integer type's active bits, not its type size.
14433 if (Info.Ctx.getTypeSize(T: DestType) != Info.Ctx.getTypeSize(T: SrcType))
14434 return Error(E);
14435
14436 LV.Designator.setInvalid();
14437 LV.moveInto(V&: Result);
14438 return true;
14439 }
14440
14441 APSInt AsInt;
14442 APValue V;
14443 LV.moveInto(V);
14444 if (!V.toIntegralConstant(Result&: AsInt, SrcTy: SrcType, Ctx: Info.Ctx))
14445 llvm_unreachable("Can't cast this!");
14446
14447 return Success(SI: HandleIntToIntCast(Info, E, DestType, SrcType, Value: AsInt), E);
14448 }
14449
14450 case CK_IntegralComplexToReal: {
14451 ComplexValue C;
14452 if (!EvaluateComplex(E: SubExpr, Res&: C, Info))
14453 return false;
14454 return Success(SI: C.getComplexIntReal(), E);
14455 }
14456
14457 case CK_FloatingToIntegral: {
14458 APFloat F(0.0);
14459 if (!EvaluateFloat(E: SubExpr, Result&: F, Info))
14460 return false;
14461
14462 APSInt Value;
14463 if (!HandleFloatToIntCast(Info, E, SrcType, Value: F, DestType, Result&: Value))
14464 return false;
14465 return Success(SI: Value, E);
14466 }
14467 }
14468
14469 llvm_unreachable("unknown cast resulting in integral value");
14470}
14471
14472bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14473 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14474 ComplexValue LV;
14475 if (!EvaluateComplex(E: E->getSubExpr(), Res&: LV, Info))
14476 return false;
14477 if (!LV.isComplexInt())
14478 return Error(E);
14479 return Success(SI: LV.getComplexIntReal(), E);
14480 }
14481
14482 return Visit(S: E->getSubExpr());
14483}
14484
14485bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14486 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
14487 ComplexValue LV;
14488 if (!EvaluateComplex(E: E->getSubExpr(), Res&: LV, Info))
14489 return false;
14490 if (!LV.isComplexInt())
14491 return Error(E);
14492 return Success(SI: LV.getComplexIntImag(), E);
14493 }
14494
14495 VisitIgnoredValue(E: E->getSubExpr());
14496 return Success(Value: 0, E);
14497}
14498
14499bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
14500 return Success(Value: E->getPackLength(), E);
14501}
14502
14503bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
14504 return Success(Value: E->getValue(), E);
14505}
14506
14507bool IntExprEvaluator::VisitConceptSpecializationExpr(
14508 const ConceptSpecializationExpr *E) {
14509 return Success(Value: E->isSatisfied(), E);
14510}
14511
14512bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
14513 return Success(Value: E->isSatisfied(), E);
14514}
14515
14516bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14517 switch (E->getOpcode()) {
14518 default:
14519 // Invalid unary operators
14520 return Error(E);
14521 case UO_Plus:
14522 // The result is just the value.
14523 return Visit(S: E->getSubExpr());
14524 case UO_Minus: {
14525 if (!Visit(S: E->getSubExpr())) return false;
14526 if (!Result.isFixedPoint())
14527 return Error(E);
14528 bool Overflowed;
14529 APFixedPoint Negated = Result.getFixedPoint().negate(Overflow: &Overflowed);
14530 if (Overflowed && !HandleOverflow(Info, E, SrcValue: Negated, DestType: E->getType()))
14531 return false;
14532 return Success(V: Negated, E);
14533 }
14534 case UO_LNot: {
14535 bool bres;
14536 if (!EvaluateAsBooleanCondition(E: E->getSubExpr(), Result&: bres, Info))
14537 return false;
14538 return Success(Value: !bres, E);
14539 }
14540 }
14541}
14542
14543bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
14544 const Expr *SubExpr = E->getSubExpr();
14545 QualType DestType = E->getType();
14546 assert(DestType->isFixedPointType() &&
14547 "Expected destination type to be a fixed point type");
14548 auto DestFXSema = Info.Ctx.getFixedPointSemantics(Ty: DestType);
14549
14550 switch (E->getCastKind()) {
14551 case CK_FixedPointCast: {
14552 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(Ty: SubExpr->getType()));
14553 if (!EvaluateFixedPoint(E: SubExpr, Result&: Src, Info))
14554 return false;
14555 bool Overflowed;
14556 APFixedPoint Result = Src.convert(DstSema: DestFXSema, Overflow: &Overflowed);
14557 if (Overflowed) {
14558 if (Info.checkingForUndefinedBehavior())
14559 Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(),
14560 DiagID: diag::warn_fixedpoint_constant_overflow)
14561 << Result.toString() << E->getType();
14562 if (!HandleOverflow(Info, E, SrcValue: Result, DestType: E->getType()))
14563 return false;
14564 }
14565 return Success(V: Result, E);
14566 }
14567 case CK_IntegralToFixedPoint: {
14568 APSInt Src;
14569 if (!EvaluateInteger(E: SubExpr, Result&: Src, Info))
14570 return false;
14571
14572 bool Overflowed;
14573 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
14574 Value: Src, DstFXSema: Info.Ctx.getFixedPointSemantics(Ty: DestType), Overflow: &Overflowed);
14575
14576 if (Overflowed) {
14577 if (Info.checkingForUndefinedBehavior())
14578 Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(),
14579 DiagID: diag::warn_fixedpoint_constant_overflow)
14580 << IntResult.toString() << E->getType();
14581 if (!HandleOverflow(Info, E, SrcValue: IntResult, DestType: E->getType()))
14582 return false;
14583 }
14584
14585 return Success(V: IntResult, E);
14586 }
14587 case CK_FloatingToFixedPoint: {
14588 APFloat Src(0.0);
14589 if (!EvaluateFloat(E: SubExpr, Result&: Src, Info))
14590 return false;
14591
14592 bool Overflowed;
14593 APFixedPoint Result = APFixedPoint::getFromFloatValue(
14594 Value: Src, DstFXSema: Info.Ctx.getFixedPointSemantics(Ty: DestType), Overflow: &Overflowed);
14595
14596 if (Overflowed) {
14597 if (Info.checkingForUndefinedBehavior())
14598 Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(),
14599 DiagID: diag::warn_fixedpoint_constant_overflow)
14600 << Result.toString() << E->getType();
14601 if (!HandleOverflow(Info, E, SrcValue: Result, DestType: E->getType()))
14602 return false;
14603 }
14604
14605 return Success(V: Result, E);
14606 }
14607 case CK_NoOp:
14608 case CK_LValueToRValue:
14609 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14610 default:
14611 return Error(E);
14612 }
14613}
14614
14615bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14616 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14617 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14618
14619 const Expr *LHS = E->getLHS();
14620 const Expr *RHS = E->getRHS();
14621 FixedPointSemantics ResultFXSema =
14622 Info.Ctx.getFixedPointSemantics(Ty: E->getType());
14623
14624 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(Ty: LHS->getType()));
14625 if (!EvaluateFixedPointOrInteger(E: LHS, Result&: LHSFX, Info))
14626 return false;
14627 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(Ty: RHS->getType()));
14628 if (!EvaluateFixedPointOrInteger(E: RHS, Result&: RHSFX, Info))
14629 return false;
14630
14631 bool OpOverflow = false, ConversionOverflow = false;
14632 APFixedPoint Result(LHSFX.getSemantics());
14633 switch (E->getOpcode()) {
14634 case BO_Add: {
14635 Result = LHSFX.add(Other: RHSFX, Overflow: &OpOverflow)
14636 .convert(DstSema: ResultFXSema, Overflow: &ConversionOverflow);
14637 break;
14638 }
14639 case BO_Sub: {
14640 Result = LHSFX.sub(Other: RHSFX, Overflow: &OpOverflow)
14641 .convert(DstSema: ResultFXSema, Overflow: &ConversionOverflow);
14642 break;
14643 }
14644 case BO_Mul: {
14645 Result = LHSFX.mul(Other: RHSFX, Overflow: &OpOverflow)
14646 .convert(DstSema: ResultFXSema, Overflow: &ConversionOverflow);
14647 break;
14648 }
14649 case BO_Div: {
14650 if (RHSFX.getValue() == 0) {
14651 Info.FFDiag(E, DiagId: diag::note_expr_divide_by_zero);
14652 return false;
14653 }
14654 Result = LHSFX.div(Other: RHSFX, Overflow: &OpOverflow)
14655 .convert(DstSema: ResultFXSema, Overflow: &ConversionOverflow);
14656 break;
14657 }
14658 case BO_Shl:
14659 case BO_Shr: {
14660 FixedPointSemantics LHSSema = LHSFX.getSemantics();
14661 llvm::APSInt RHSVal = RHSFX.getValue();
14662
14663 unsigned ShiftBW =
14664 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14665 unsigned Amt = RHSVal.getLimitedValue(Limit: ShiftBW - 1);
14666 // Embedded-C 4.1.6.2.2:
14667 // The right operand must be nonnegative and less than the total number
14668 // of (nonpadding) bits of the fixed-point operand ...
14669 if (RHSVal.isNegative())
14670 Info.CCEDiag(E, DiagId: diag::note_constexpr_negative_shift) << RHSVal;
14671 else if (Amt != RHSVal)
14672 Info.CCEDiag(E, DiagId: diag::note_constexpr_large_shift)
14673 << RHSVal << E->getType() << ShiftBW;
14674
14675 if (E->getOpcode() == BO_Shl)
14676 Result = LHSFX.shl(Amt, Overflow: &OpOverflow);
14677 else
14678 Result = LHSFX.shr(Amt, Overflow: &OpOverflow);
14679 break;
14680 }
14681 default:
14682 return false;
14683 }
14684 if (OpOverflow || ConversionOverflow) {
14685 if (Info.checkingForUndefinedBehavior())
14686 Info.Ctx.getDiagnostics().Report(Loc: E->getExprLoc(),
14687 DiagID: diag::warn_fixedpoint_constant_overflow)
14688 << Result.toString() << E->getType();
14689 if (!HandleOverflow(Info, E, SrcValue: Result, DestType: E->getType()))
14690 return false;
14691 }
14692 return Success(V: Result, E);
14693}
14694
14695//===----------------------------------------------------------------------===//
14696// Float Evaluation
14697//===----------------------------------------------------------------------===//
14698
14699namespace {
14700class FloatExprEvaluator
14701 : public ExprEvaluatorBase<FloatExprEvaluator> {
14702 APFloat &Result;
14703public:
14704 FloatExprEvaluator(EvalInfo &info, APFloat &result)
14705 : ExprEvaluatorBaseTy(info), Result(result) {}
14706
14707 bool Success(const APValue &V, const Expr *e) {
14708 Result = V.getFloat();
14709 return true;
14710 }
14711
14712 bool ZeroInitialization(const Expr *E) {
14713 Result = APFloat::getZero(Sem: Info.Ctx.getFloatTypeSemantics(T: E->getType()));
14714 return true;
14715 }
14716
14717 bool VisitCallExpr(const CallExpr *E);
14718
14719 bool VisitUnaryOperator(const UnaryOperator *E);
14720 bool VisitBinaryOperator(const BinaryOperator *E);
14721 bool VisitFloatingLiteral(const FloatingLiteral *E);
14722 bool VisitCastExpr(const CastExpr *E);
14723
14724 bool VisitUnaryReal(const UnaryOperator *E);
14725 bool VisitUnaryImag(const UnaryOperator *E);
14726
14727 // FIXME: Missing: array subscript of vector, member of vector
14728};
14729} // end anonymous namespace
14730
14731static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14732 assert(!E->isValueDependent());
14733 assert(E->isPRValue() && E->getType()->isRealFloatingType());
14734 return FloatExprEvaluator(Info, Result).Visit(S: E);
14735}
14736
14737static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14738 QualType ResultTy,
14739 const Expr *Arg,
14740 bool SNaN,
14741 llvm::APFloat &Result) {
14742 const StringLiteral *S = dyn_cast<StringLiteral>(Val: Arg->IgnoreParenCasts());
14743 if (!S) return false;
14744
14745 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(T: ResultTy);
14746
14747 llvm::APInt fill;
14748
14749 // Treat empty strings as if they were zero.
14750 if (S->getString().empty())
14751 fill = llvm::APInt(32, 0);
14752 else if (S->getString().getAsInteger(Radix: 0, Result&: fill))
14753 return false;
14754
14755 if (Context.getTargetInfo().isNan2008()) {
14756 if (SNaN)
14757 Result = llvm::APFloat::getSNaN(Sem, Negative: false, payload: &fill);
14758 else
14759 Result = llvm::APFloat::getQNaN(Sem, Negative: false, payload: &fill);
14760 } else {
14761 // Prior to IEEE 754-2008, architectures were allowed to choose whether
14762 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14763 // a different encoding to what became a standard in 2008, and for pre-
14764 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14765 // sNaN. This is now known as "legacy NaN" encoding.
14766 if (SNaN)
14767 Result = llvm::APFloat::getQNaN(Sem, Negative: false, payload: &fill);
14768 else
14769 Result = llvm::APFloat::getSNaN(Sem, Negative: false, payload: &fill);
14770 }
14771
14772 return true;
14773}
14774
14775bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14776 if (!IsConstantEvaluatedBuiltinCall(E))
14777 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14778
14779 switch (E->getBuiltinCallee()) {
14780 default:
14781 return false;
14782
14783 case Builtin::BI__builtin_huge_val:
14784 case Builtin::BI__builtin_huge_valf:
14785 case Builtin::BI__builtin_huge_vall:
14786 case Builtin::BI__builtin_huge_valf16:
14787 case Builtin::BI__builtin_huge_valf128:
14788 case Builtin::BI__builtin_inf:
14789 case Builtin::BI__builtin_inff:
14790 case Builtin::BI__builtin_infl:
14791 case Builtin::BI__builtin_inff16:
14792 case Builtin::BI__builtin_inff128: {
14793 const llvm::fltSemantics &Sem =
14794 Info.Ctx.getFloatTypeSemantics(T: E->getType());
14795 Result = llvm::APFloat::getInf(Sem);
14796 return true;
14797 }
14798
14799 case Builtin::BI__builtin_nans:
14800 case Builtin::BI__builtin_nansf:
14801 case Builtin::BI__builtin_nansl:
14802 case Builtin::BI__builtin_nansf16:
14803 case Builtin::BI__builtin_nansf128:
14804 if (!TryEvaluateBuiltinNaN(Context: Info.Ctx, ResultTy: E->getType(), Arg: E->getArg(Arg: 0),
14805 SNaN: true, Result))
14806 return Error(E);
14807 return true;
14808
14809 case Builtin::BI__builtin_nan:
14810 case Builtin::BI__builtin_nanf:
14811 case Builtin::BI__builtin_nanl:
14812 case Builtin::BI__builtin_nanf16:
14813 case Builtin::BI__builtin_nanf128:
14814 // If this is __builtin_nan() turn this into a nan, otherwise we
14815 // can't constant fold it.
14816 if (!TryEvaluateBuiltinNaN(Context: Info.Ctx, ResultTy: E->getType(), Arg: E->getArg(Arg: 0),
14817 SNaN: false, Result))
14818 return Error(E);
14819 return true;
14820
14821 case Builtin::BI__builtin_fabs:
14822 case Builtin::BI__builtin_fabsf:
14823 case Builtin::BI__builtin_fabsl:
14824 case Builtin::BI__builtin_fabsf128:
14825 // The C standard says "fabs raises no floating-point exceptions,
14826 // even if x is a signaling NaN. The returned value is independent of
14827 // the current rounding direction mode." Therefore constant folding can
14828 // proceed without regard to the floating point settings.
14829 // Reference, WG14 N2478 F.10.4.3
14830 if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info))
14831 return false;
14832
14833 if (Result.isNegative())
14834 Result.changeSign();
14835 return true;
14836
14837 case Builtin::BI__arithmetic_fence:
14838 return EvaluateFloat(E: E->getArg(Arg: 0), Result, Info);
14839
14840 // FIXME: Builtin::BI__builtin_powi
14841 // FIXME: Builtin::BI__builtin_powif
14842 // FIXME: Builtin::BI__builtin_powil
14843
14844 case Builtin::BI__builtin_copysign:
14845 case Builtin::BI__builtin_copysignf:
14846 case Builtin::BI__builtin_copysignl:
14847 case Builtin::BI__builtin_copysignf128: {
14848 APFloat RHS(0.);
14849 if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info) ||
14850 !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info))
14851 return false;
14852 Result.copySign(RHS);
14853 return true;
14854 }
14855
14856 case Builtin::BI__builtin_fmax:
14857 case Builtin::BI__builtin_fmaxf:
14858 case Builtin::BI__builtin_fmaxl:
14859 case Builtin::BI__builtin_fmaxf16:
14860 case Builtin::BI__builtin_fmaxf128: {
14861 // TODO: Handle sNaN.
14862 APFloat RHS(0.);
14863 if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info) ||
14864 !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info))
14865 return false;
14866 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14867 if (Result.isZero() && RHS.isZero() && Result.isNegative())
14868 Result = RHS;
14869 else if (Result.isNaN() || RHS > Result)
14870 Result = RHS;
14871 return true;
14872 }
14873
14874 case Builtin::BI__builtin_fmin:
14875 case Builtin::BI__builtin_fminf:
14876 case Builtin::BI__builtin_fminl:
14877 case Builtin::BI__builtin_fminf16:
14878 case Builtin::BI__builtin_fminf128: {
14879 // TODO: Handle sNaN.
14880 APFloat RHS(0.);
14881 if (!EvaluateFloat(E: E->getArg(Arg: 0), Result, Info) ||
14882 !EvaluateFloat(E: E->getArg(Arg: 1), Result&: RHS, Info))
14883 return false;
14884 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14885 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14886 Result = RHS;
14887 else if (Result.isNaN() || RHS < Result)
14888 Result = RHS;
14889 return true;
14890 }
14891 }
14892}
14893
14894bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14895 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14896 ComplexValue CV;
14897 if (!EvaluateComplex(E: E->getSubExpr(), Res&: CV, Info))
14898 return false;
14899 Result = CV.FloatReal;
14900 return true;
14901 }
14902
14903 return Visit(S: E->getSubExpr());
14904}
14905
14906bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14907 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14908 ComplexValue CV;
14909 if (!EvaluateComplex(E: E->getSubExpr(), Res&: CV, Info))
14910 return false;
14911 Result = CV.FloatImag;
14912 return true;
14913 }
14914
14915 VisitIgnoredValue(E: E->getSubExpr());
14916 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(T: E->getType());
14917 Result = llvm::APFloat::getZero(Sem);
14918 return true;
14919}
14920
14921bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14922 switch (E->getOpcode()) {
14923 default: return Error(E);
14924 case UO_Plus:
14925 return EvaluateFloat(E: E->getSubExpr(), Result, Info);
14926 case UO_Minus:
14927 // In C standard, WG14 N2478 F.3 p4
14928 // "the unary - raises no floating point exceptions,
14929 // even if the operand is signalling."
14930 if (!EvaluateFloat(E: E->getSubExpr(), Result, Info))
14931 return false;
14932 Result.changeSign();
14933 return true;
14934 }
14935}
14936
14937bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14938 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14939 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14940
14941 APFloat RHS(0.0);
14942 bool LHSOK = EvaluateFloat(E: E->getLHS(), Result, Info);
14943 if (!LHSOK && !Info.noteFailure())
14944 return false;
14945 return EvaluateFloat(E: E->getRHS(), Result&: RHS, Info) && LHSOK &&
14946 handleFloatFloatBinOp(Info, E, LHS&: Result, Opcode: E->getOpcode(), RHS);
14947}
14948
14949bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14950 Result = E->getValue();
14951 return true;
14952}
14953
14954bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14955 const Expr* SubExpr = E->getSubExpr();
14956
14957 switch (E->getCastKind()) {
14958 default:
14959 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14960
14961 case CK_IntegralToFloating: {
14962 APSInt IntResult;
14963 const FPOptions FPO = E->getFPFeaturesInEffect(
14964 LO: Info.Ctx.getLangOpts());
14965 return EvaluateInteger(E: SubExpr, Result&: IntResult, Info) &&
14966 HandleIntToFloatCast(Info, E, FPO, SrcType: SubExpr->getType(),
14967 Value: IntResult, DestType: E->getType(), Result);
14968 }
14969
14970 case CK_FixedPointToFloating: {
14971 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(Ty: SubExpr->getType()));
14972 if (!EvaluateFixedPoint(E: SubExpr, Result&: FixResult, Info))
14973 return false;
14974 Result =
14975 FixResult.convertToFloat(FloatSema: Info.Ctx.getFloatTypeSemantics(T: E->getType()));
14976 return true;
14977 }
14978
14979 case CK_FloatingCast: {
14980 if (!Visit(S: SubExpr))
14981 return false;
14982 return HandleFloatToFloatCast(Info, E, SrcType: SubExpr->getType(), DestType: E->getType(),
14983 Result);
14984 }
14985
14986 case CK_FloatingComplexToReal: {
14987 ComplexValue V;
14988 if (!EvaluateComplex(E: SubExpr, Res&: V, Info))
14989 return false;
14990 Result = V.getComplexFloatReal();
14991 return true;
14992 }
14993 }
14994}
14995
14996//===----------------------------------------------------------------------===//
14997// Complex Evaluation (for float and integer)
14998//===----------------------------------------------------------------------===//
14999
15000namespace {
15001class ComplexExprEvaluator
15002 : public ExprEvaluatorBase<ComplexExprEvaluator> {
15003 ComplexValue &Result;
15004
15005public:
15006 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15007 : ExprEvaluatorBaseTy(info), Result(Result) {}
15008
15009 bool Success(const APValue &V, const Expr *e) {
15010 Result.setFrom(V);
15011 return true;
15012 }
15013
15014 bool ZeroInitialization(const Expr *E);
15015
15016 //===--------------------------------------------------------------------===//
15017 // Visitor Methods
15018 //===--------------------------------------------------------------------===//
15019
15020 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15021 bool VisitCastExpr(const CastExpr *E);
15022 bool VisitBinaryOperator(const BinaryOperator *E);
15023 bool VisitUnaryOperator(const UnaryOperator *E);
15024 bool VisitInitListExpr(const InitListExpr *E);
15025 bool VisitCallExpr(const CallExpr *E);
15026};
15027} // end anonymous namespace
15028
15029static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15030 EvalInfo &Info) {
15031 assert(!E->isValueDependent());
15032 assert(E->isPRValue() && E->getType()->isAnyComplexType());
15033 return ComplexExprEvaluator(Info, Result).Visit(S: E);
15034}
15035
15036bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15037 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15038 if (ElemTy->isRealFloatingType()) {
15039 Result.makeComplexFloat();
15040 APFloat Zero = APFloat::getZero(Sem: Info.Ctx.getFloatTypeSemantics(T: ElemTy));
15041 Result.FloatReal = Zero;
15042 Result.FloatImag = Zero;
15043 } else {
15044 Result.makeComplexInt();
15045 APSInt Zero = Info.Ctx.MakeIntValue(Value: 0, Type: ElemTy);
15046 Result.IntReal = Zero;
15047 Result.IntImag = Zero;
15048 }
15049 return true;
15050}
15051
15052bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15053 const Expr* SubExpr = E->getSubExpr();
15054
15055 if (SubExpr->getType()->isRealFloatingType()) {
15056 Result.makeComplexFloat();
15057 APFloat &Imag = Result.FloatImag;
15058 if (!EvaluateFloat(E: SubExpr, Result&: Imag, Info))
15059 return false;
15060
15061 Result.FloatReal = APFloat(Imag.getSemantics());
15062 return true;
15063 } else {
15064 assert(SubExpr->getType()->isIntegerType() &&
15065 "Unexpected imaginary literal.");
15066
15067 Result.makeComplexInt();
15068 APSInt &Imag = Result.IntImag;
15069 if (!EvaluateInteger(E: SubExpr, Result&: Imag, Info))
15070 return false;
15071
15072 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15073 return true;
15074 }
15075}
15076
15077bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15078
15079 switch (E->getCastKind()) {
15080 case CK_BitCast:
15081 case CK_BaseToDerived:
15082 case CK_DerivedToBase:
15083 case CK_UncheckedDerivedToBase:
15084 case CK_Dynamic:
15085 case CK_ToUnion:
15086 case CK_ArrayToPointerDecay:
15087 case CK_FunctionToPointerDecay:
15088 case CK_NullToPointer:
15089 case CK_NullToMemberPointer:
15090 case CK_BaseToDerivedMemberPointer:
15091 case CK_DerivedToBaseMemberPointer:
15092 case CK_MemberPointerToBoolean:
15093 case CK_ReinterpretMemberPointer:
15094 case CK_ConstructorConversion:
15095 case CK_IntegralToPointer:
15096 case CK_PointerToIntegral:
15097 case CK_PointerToBoolean:
15098 case CK_ToVoid:
15099 case CK_VectorSplat:
15100 case CK_IntegralCast:
15101 case CK_BooleanToSignedIntegral:
15102 case CK_IntegralToBoolean:
15103 case CK_IntegralToFloating:
15104 case CK_FloatingToIntegral:
15105 case CK_FloatingToBoolean:
15106 case CK_FloatingCast:
15107 case CK_CPointerToObjCPointerCast:
15108 case CK_BlockPointerToObjCPointerCast:
15109 case CK_AnyPointerToBlockPointerCast:
15110 case CK_ObjCObjectLValueCast:
15111 case CK_FloatingComplexToReal:
15112 case CK_FloatingComplexToBoolean:
15113 case CK_IntegralComplexToReal:
15114 case CK_IntegralComplexToBoolean:
15115 case CK_ARCProduceObject:
15116 case CK_ARCConsumeObject:
15117 case CK_ARCReclaimReturnedObject:
15118 case CK_ARCExtendBlockObject:
15119 case CK_CopyAndAutoreleaseBlockObject:
15120 case CK_BuiltinFnToFnPtr:
15121 case CK_ZeroToOCLOpaqueType:
15122 case CK_NonAtomicToAtomic:
15123 case CK_AddressSpaceConversion:
15124 case CK_IntToOCLSampler:
15125 case CK_FloatingToFixedPoint:
15126 case CK_FixedPointToFloating:
15127 case CK_FixedPointCast:
15128 case CK_FixedPointToBoolean:
15129 case CK_FixedPointToIntegral:
15130 case CK_IntegralToFixedPoint:
15131 case CK_MatrixCast:
15132 case CK_HLSLVectorTruncation:
15133 llvm_unreachable("invalid cast kind for complex value");
15134
15135 case CK_LValueToRValue:
15136 case CK_AtomicToNonAtomic:
15137 case CK_NoOp:
15138 case CK_LValueToRValueBitCast:
15139 case CK_HLSLArrayRValue:
15140 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15141
15142 case CK_Dependent:
15143 case CK_LValueBitCast:
15144 case CK_UserDefinedConversion:
15145 return Error(E);
15146
15147 case CK_FloatingRealToComplex: {
15148 APFloat &Real = Result.FloatReal;
15149 if (!EvaluateFloat(E: E->getSubExpr(), Result&: Real, Info))
15150 return false;
15151
15152 Result.makeComplexFloat();
15153 Result.FloatImag = APFloat(Real.getSemantics());
15154 return true;
15155 }
15156
15157 case CK_FloatingComplexCast: {
15158 if (!Visit(S: E->getSubExpr()))
15159 return false;
15160
15161 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15162 QualType From
15163 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15164
15165 return HandleFloatToFloatCast(Info, E, SrcType: From, DestType: To, Result&: Result.FloatReal) &&
15166 HandleFloatToFloatCast(Info, E, SrcType: From, DestType: To, Result&: Result.FloatImag);
15167 }
15168
15169 case CK_FloatingComplexToIntegralComplex: {
15170 if (!Visit(S: E->getSubExpr()))
15171 return false;
15172
15173 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15174 QualType From
15175 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15176 Result.makeComplexInt();
15177 return HandleFloatToIntCast(Info, E, SrcType: From, Value: Result.FloatReal,
15178 DestType: To, Result&: Result.IntReal) &&
15179 HandleFloatToIntCast(Info, E, SrcType: From, Value: Result.FloatImag,
15180 DestType: To, Result&: Result.IntImag);
15181 }
15182
15183 case CK_IntegralRealToComplex: {
15184 APSInt &Real = Result.IntReal;
15185 if (!EvaluateInteger(E: E->getSubExpr(), Result&: Real, Info))
15186 return false;
15187
15188 Result.makeComplexInt();
15189 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15190 return true;
15191 }
15192
15193 case CK_IntegralComplexCast: {
15194 if (!Visit(S: E->getSubExpr()))
15195 return false;
15196
15197 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15198 QualType From
15199 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15200
15201 Result.IntReal = HandleIntToIntCast(Info, E, DestType: To, SrcType: From, Value: Result.IntReal);
15202 Result.IntImag = HandleIntToIntCast(Info, E, DestType: To, SrcType: From, Value: Result.IntImag);
15203 return true;
15204 }
15205
15206 case CK_IntegralComplexToFloatingComplex: {
15207 if (!Visit(S: E->getSubExpr()))
15208 return false;
15209
15210 const FPOptions FPO = E->getFPFeaturesInEffect(
15211 LO: Info.Ctx.getLangOpts());
15212 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15213 QualType From
15214 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15215 Result.makeComplexFloat();
15216 return HandleIntToFloatCast(Info, E, FPO, SrcType: From, Value: Result.IntReal,
15217 DestType: To, Result&: Result.FloatReal) &&
15218 HandleIntToFloatCast(Info, E, FPO, SrcType: From, Value: Result.IntImag,
15219 DestType: To, Result&: Result.FloatImag);
15220 }
15221 }
15222
15223 llvm_unreachable("unknown cast resulting in complex value");
15224}
15225
15226void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
15227 APFloat &ResR, APFloat &ResI) {
15228 // This is an implementation of complex multiplication according to the
15229 // constraints laid out in C11 Annex G. The implementation uses the
15230 // following naming scheme:
15231 // (a + ib) * (c + id)
15232
15233 APFloat AC = A * C;
15234 APFloat BD = B * D;
15235 APFloat AD = A * D;
15236 APFloat BC = B * C;
15237 ResR = AC - BD;
15238 ResI = AD + BC;
15239 if (ResR.isNaN() && ResI.isNaN()) {
15240 bool Recalc = false;
15241 if (A.isInfinity() || B.isInfinity()) {
15242 A = APFloat::copySign(Value: APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15243 Sign: A);
15244 B = APFloat::copySign(Value: APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15245 Sign: B);
15246 if (C.isNaN())
15247 C = APFloat::copySign(Value: APFloat(C.getSemantics()), Sign: C);
15248 if (D.isNaN())
15249 D = APFloat::copySign(Value: APFloat(D.getSemantics()), Sign: D);
15250 Recalc = true;
15251 }
15252 if (C.isInfinity() || D.isInfinity()) {
15253 C = APFloat::copySign(Value: APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15254 Sign: C);
15255 D = APFloat::copySign(Value: APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15256 Sign: D);
15257 if (A.isNaN())
15258 A = APFloat::copySign(Value: APFloat(A.getSemantics()), Sign: A);
15259 if (B.isNaN())
15260 B = APFloat::copySign(Value: APFloat(B.getSemantics()), Sign: B);
15261 Recalc = true;
15262 }
15263 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
15264 BC.isInfinity())) {
15265 if (A.isNaN())
15266 A = APFloat::copySign(Value: APFloat(A.getSemantics()), Sign: A);
15267 if (B.isNaN())
15268 B = APFloat::copySign(Value: APFloat(B.getSemantics()), Sign: B);
15269 if (C.isNaN())
15270 C = APFloat::copySign(Value: APFloat(C.getSemantics()), Sign: C);
15271 if (D.isNaN())
15272 D = APFloat::copySign(Value: APFloat(D.getSemantics()), Sign: D);
15273 Recalc = true;
15274 }
15275 if (Recalc) {
15276 ResR = APFloat::getInf(Sem: A.getSemantics()) * (A * C - B * D);
15277 ResI = APFloat::getInf(Sem: A.getSemantics()) * (A * D + B * C);
15278 }
15279 }
15280}
15281
15282void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
15283 APFloat &ResR, APFloat &ResI) {
15284 // This is an implementation of complex division according to the
15285 // constraints laid out in C11 Annex G. The implementation uses the
15286 // following naming scheme:
15287 // (a + ib) / (c + id)
15288
15289 int DenomLogB = 0;
15290 APFloat MaxCD = maxnum(A: abs(X: C), B: abs(X: D));
15291 if (MaxCD.isFinite()) {
15292 DenomLogB = ilogb(Arg: MaxCD);
15293 C = scalbn(X: C, Exp: -DenomLogB, RM: APFloat::rmNearestTiesToEven);
15294 D = scalbn(X: D, Exp: -DenomLogB, RM: APFloat::rmNearestTiesToEven);
15295 }
15296 APFloat Denom = C * C + D * D;
15297 ResR =
15298 scalbn(X: (A * C + B * D) / Denom, Exp: -DenomLogB, RM: APFloat::rmNearestTiesToEven);
15299 ResI =
15300 scalbn(X: (B * C - A * D) / Denom, Exp: -DenomLogB, RM: APFloat::rmNearestTiesToEven);
15301 if (ResR.isNaN() && ResI.isNaN()) {
15302 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15303 ResR = APFloat::getInf(Sem: ResR.getSemantics(), Negative: C.isNegative()) * A;
15304 ResI = APFloat::getInf(Sem: ResR.getSemantics(), Negative: C.isNegative()) * B;
15305 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15306 D.isFinite()) {
15307 A = APFloat::copySign(Value: APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15308 Sign: A);
15309 B = APFloat::copySign(Value: APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15310 Sign: B);
15311 ResR = APFloat::getInf(Sem: ResR.getSemantics()) * (A * C + B * D);
15312 ResI = APFloat::getInf(Sem: ResI.getSemantics()) * (B * C - A * D);
15313 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15314 C = APFloat::copySign(Value: APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15315 Sign: C);
15316 D = APFloat::copySign(Value: APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15317 Sign: D);
15318 ResR = APFloat::getZero(Sem: ResR.getSemantics()) * (A * C + B * D);
15319 ResI = APFloat::getZero(Sem: ResI.getSemantics()) * (B * C - A * D);
15320 }
15321 }
15322}
15323
15324bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15325 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15326 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15327
15328 // Track whether the LHS or RHS is real at the type system level. When this is
15329 // the case we can simplify our evaluation strategy.
15330 bool LHSReal = false, RHSReal = false;
15331
15332 bool LHSOK;
15333 if (E->getLHS()->getType()->isRealFloatingType()) {
15334 LHSReal = true;
15335 APFloat &Real = Result.FloatReal;
15336 LHSOK = EvaluateFloat(E: E->getLHS(), Result&: Real, Info);
15337 if (LHSOK) {
15338 Result.makeComplexFloat();
15339 Result.FloatImag = APFloat(Real.getSemantics());
15340 }
15341 } else {
15342 LHSOK = Visit(S: E->getLHS());
15343 }
15344 if (!LHSOK && !Info.noteFailure())
15345 return false;
15346
15347 ComplexValue RHS;
15348 if (E->getRHS()->getType()->isRealFloatingType()) {
15349 RHSReal = true;
15350 APFloat &Real = RHS.FloatReal;
15351 if (!EvaluateFloat(E: E->getRHS(), Result&: Real, Info) || !LHSOK)
15352 return false;
15353 RHS.makeComplexFloat();
15354 RHS.FloatImag = APFloat(Real.getSemantics());
15355 } else if (!EvaluateComplex(E: E->getRHS(), Result&: RHS, Info) || !LHSOK)
15356 return false;
15357
15358 assert(!(LHSReal && RHSReal) &&
15359 "Cannot have both operands of a complex operation be real.");
15360 switch (E->getOpcode()) {
15361 default: return Error(E);
15362 case BO_Add:
15363 if (Result.isComplexFloat()) {
15364 Result.getComplexFloatReal().add(RHS: RHS.getComplexFloatReal(),
15365 RM: APFloat::rmNearestTiesToEven);
15366 if (LHSReal)
15367 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15368 else if (!RHSReal)
15369 Result.getComplexFloatImag().add(RHS: RHS.getComplexFloatImag(),
15370 RM: APFloat::rmNearestTiesToEven);
15371 } else {
15372 Result.getComplexIntReal() += RHS.getComplexIntReal();
15373 Result.getComplexIntImag() += RHS.getComplexIntImag();
15374 }
15375 break;
15376 case BO_Sub:
15377 if (Result.isComplexFloat()) {
15378 Result.getComplexFloatReal().subtract(RHS: RHS.getComplexFloatReal(),
15379 RM: APFloat::rmNearestTiesToEven);
15380 if (LHSReal) {
15381 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15382 Result.getComplexFloatImag().changeSign();
15383 } else if (!RHSReal) {
15384 Result.getComplexFloatImag().subtract(RHS: RHS.getComplexFloatImag(),
15385 RM: APFloat::rmNearestTiesToEven);
15386 }
15387 } else {
15388 Result.getComplexIntReal() -= RHS.getComplexIntReal();
15389 Result.getComplexIntImag() -= RHS.getComplexIntImag();
15390 }
15391 break;
15392 case BO_Mul:
15393 if (Result.isComplexFloat()) {
15394 // This is an implementation of complex multiplication according to the
15395 // constraints laid out in C11 Annex G. The implementation uses the
15396 // following naming scheme:
15397 // (a + ib) * (c + id)
15398 ComplexValue LHS = Result;
15399 APFloat &A = LHS.getComplexFloatReal();
15400 APFloat &B = LHS.getComplexFloatImag();
15401 APFloat &C = RHS.getComplexFloatReal();
15402 APFloat &D = RHS.getComplexFloatImag();
15403 APFloat &ResR = Result.getComplexFloatReal();
15404 APFloat &ResI = Result.getComplexFloatImag();
15405 if (LHSReal) {
15406 assert(!RHSReal && "Cannot have two real operands for a complex op!");
15407 ResR = A;
15408 ResI = A;
15409 // ResR = A * C;
15410 // ResI = A * D;
15411 if (!handleFloatFloatBinOp(Info, E, LHS&: ResR, Opcode: BO_Mul, RHS: C) ||
15412 !handleFloatFloatBinOp(Info, E, LHS&: ResI, Opcode: BO_Mul, RHS: D))
15413 return false;
15414 } else if (RHSReal) {
15415 // ResR = C * A;
15416 // ResI = C * B;
15417 ResR = C;
15418 ResI = C;
15419 if (!handleFloatFloatBinOp(Info, E, LHS&: ResR, Opcode: BO_Mul, RHS: A) ||
15420 !handleFloatFloatBinOp(Info, E, LHS&: ResI, Opcode: BO_Mul, RHS: B))
15421 return false;
15422 } else {
15423 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
15424 }
15425 } else {
15426 ComplexValue LHS = Result;
15427 Result.getComplexIntReal() =
15428 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
15429 LHS.getComplexIntImag() * RHS.getComplexIntImag());
15430 Result.getComplexIntImag() =
15431 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
15432 LHS.getComplexIntImag() * RHS.getComplexIntReal());
15433 }
15434 break;
15435 case BO_Div:
15436 if (Result.isComplexFloat()) {
15437 // This is an implementation of complex division according to the
15438 // constraints laid out in C11 Annex G. The implementation uses the
15439 // following naming scheme:
15440 // (a + ib) / (c + id)
15441 ComplexValue LHS = Result;
15442 APFloat &A = LHS.getComplexFloatReal();
15443 APFloat &B = LHS.getComplexFloatImag();
15444 APFloat &C = RHS.getComplexFloatReal();
15445 APFloat &D = RHS.getComplexFloatImag();
15446 APFloat &ResR = Result.getComplexFloatReal();
15447 APFloat &ResI = Result.getComplexFloatImag();
15448 if (RHSReal) {
15449 ResR = A;
15450 ResI = B;
15451 // ResR = A / C;
15452 // ResI = B / C;
15453 if (!handleFloatFloatBinOp(Info, E, LHS&: ResR, Opcode: BO_Div, RHS: C) ||
15454 !handleFloatFloatBinOp(Info, E, LHS&: ResI, Opcode: BO_Div, RHS: C))
15455 return false;
15456 } else {
15457 if (LHSReal) {
15458 // No real optimizations we can do here, stub out with zero.
15459 B = APFloat::getZero(Sem: A.getSemantics());
15460 }
15461 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
15462 }
15463 } else {
15464 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
15465 return Error(E, D: diag::note_expr_divide_by_zero);
15466
15467 ComplexValue LHS = Result;
15468 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
15469 RHS.getComplexIntImag() * RHS.getComplexIntImag();
15470 Result.getComplexIntReal() =
15471 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
15472 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
15473 Result.getComplexIntImag() =
15474 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
15475 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
15476 }
15477 break;
15478 }
15479
15480 return true;
15481}
15482
15483bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15484 // Get the operand value into 'Result'.
15485 if (!Visit(S: E->getSubExpr()))
15486 return false;
15487
15488 switch (E->getOpcode()) {
15489 default:
15490 return Error(E);
15491 case UO_Extension:
15492 return true;
15493 case UO_Plus:
15494 // The result is always just the subexpr.
15495 return true;
15496 case UO_Minus:
15497 if (Result.isComplexFloat()) {
15498 Result.getComplexFloatReal().changeSign();
15499 Result.getComplexFloatImag().changeSign();
15500 }
15501 else {
15502 Result.getComplexIntReal() = -Result.getComplexIntReal();
15503 Result.getComplexIntImag() = -Result.getComplexIntImag();
15504 }
15505 return true;
15506 case UO_Not:
15507 if (Result.isComplexFloat())
15508 Result.getComplexFloatImag().changeSign();
15509 else
15510 Result.getComplexIntImag() = -Result.getComplexIntImag();
15511 return true;
15512 }
15513}
15514
15515bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15516 if (E->getNumInits() == 2) {
15517 if (E->getType()->isComplexType()) {
15518 Result.makeComplexFloat();
15519 if (!EvaluateFloat(E: E->getInit(Init: 0), Result&: Result.FloatReal, Info))
15520 return false;
15521 if (!EvaluateFloat(E: E->getInit(Init: 1), Result&: Result.FloatImag, Info))
15522 return false;
15523 } else {
15524 Result.makeComplexInt();
15525 if (!EvaluateInteger(E: E->getInit(Init: 0), Result&: Result.IntReal, Info))
15526 return false;
15527 if (!EvaluateInteger(E: E->getInit(Init: 1), Result&: Result.IntImag, Info))
15528 return false;
15529 }
15530 return true;
15531 }
15532 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
15533}
15534
15535bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
15536 if (!IsConstantEvaluatedBuiltinCall(E))
15537 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15538
15539 switch (E->getBuiltinCallee()) {
15540 case Builtin::BI__builtin_complex:
15541 Result.makeComplexFloat();
15542 if (!EvaluateFloat(E: E->getArg(Arg: 0), Result&: Result.FloatReal, Info))
15543 return false;
15544 if (!EvaluateFloat(E: E->getArg(Arg: 1), Result&: Result.FloatImag, Info))
15545 return false;
15546 return true;
15547
15548 default:
15549 return false;
15550 }
15551}
15552
15553//===----------------------------------------------------------------------===//
15554// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
15555// implicit conversion.
15556//===----------------------------------------------------------------------===//
15557
15558namespace {
15559class AtomicExprEvaluator :
15560 public ExprEvaluatorBase<AtomicExprEvaluator> {
15561 const LValue *This;
15562 APValue &Result;
15563public:
15564 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
15565 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15566
15567 bool Success(const APValue &V, const Expr *E) {
15568 Result = V;
15569 return true;
15570 }
15571
15572 bool ZeroInitialization(const Expr *E) {
15573 ImplicitValueInitExpr VIE(
15574 E->getType()->castAs<AtomicType>()->getValueType());
15575 // For atomic-qualified class (and array) types in C++, initialize the
15576 // _Atomic-wrapped subobject directly, in-place.
15577 return This ? EvaluateInPlace(Result, Info, This: *This, E: &VIE)
15578 : Evaluate(Result, Info, E: &VIE);
15579 }
15580
15581 bool VisitCastExpr(const CastExpr *E) {
15582 switch (E->getCastKind()) {
15583 default:
15584 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15585 case CK_NullToPointer:
15586 VisitIgnoredValue(E: E->getSubExpr());
15587 return ZeroInitialization(E);
15588 case CK_NonAtomicToAtomic:
15589 return This ? EvaluateInPlace(Result, Info, This: *This, E: E->getSubExpr())
15590 : Evaluate(Result, Info, E: E->getSubExpr());
15591 }
15592 }
15593};
15594} // end anonymous namespace
15595
15596static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
15597 EvalInfo &Info) {
15598 assert(!E->isValueDependent());
15599 assert(E->isPRValue() && E->getType()->isAtomicType());
15600 return AtomicExprEvaluator(Info, This, Result).Visit(S: E);
15601}
15602
15603//===----------------------------------------------------------------------===//
15604// Void expression evaluation, primarily for a cast to void on the LHS of a
15605// comma operator
15606//===----------------------------------------------------------------------===//
15607
15608namespace {
15609class VoidExprEvaluator
15610 : public ExprEvaluatorBase<VoidExprEvaluator> {
15611public:
15612 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
15613
15614 bool Success(const APValue &V, const Expr *e) { return true; }
15615
15616 bool ZeroInitialization(const Expr *E) { return true; }
15617
15618 bool VisitCastExpr(const CastExpr *E) {
15619 switch (E->getCastKind()) {
15620 default:
15621 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15622 case CK_ToVoid:
15623 VisitIgnoredValue(E: E->getSubExpr());
15624 return true;
15625 }
15626 }
15627
15628 bool VisitCallExpr(const CallExpr *E) {
15629 if (!IsConstantEvaluatedBuiltinCall(E))
15630 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15631
15632 switch (E->getBuiltinCallee()) {
15633 case Builtin::BI__assume:
15634 case Builtin::BI__builtin_assume:
15635 // The argument is not evaluated!
15636 return true;
15637
15638 case Builtin::BI__builtin_operator_delete:
15639 return HandleOperatorDeleteCall(Info, E);
15640
15641 default:
15642 return false;
15643 }
15644 }
15645
15646 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
15647};
15648} // end anonymous namespace
15649
15650bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
15651 // We cannot speculatively evaluate a delete expression.
15652 if (Info.SpeculativeEvaluationDepth)
15653 return false;
15654
15655 FunctionDecl *OperatorDelete = E->getOperatorDelete();
15656 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
15657 Info.FFDiag(E, DiagId: diag::note_constexpr_new_non_replaceable)
15658 << isa<CXXMethodDecl>(Val: OperatorDelete) << OperatorDelete;
15659 return false;
15660 }
15661
15662 const Expr *Arg = E->getArgument();
15663
15664 LValue Pointer;
15665 if (!EvaluatePointer(E: Arg, Result&: Pointer, Info))
15666 return false;
15667 if (Pointer.Designator.Invalid)
15668 return false;
15669
15670 // Deleting a null pointer has no effect.
15671 if (Pointer.isNullPointer()) {
15672 // This is the only case where we need to produce an extension warning:
15673 // the only other way we can succeed is if we find a dynamic allocation,
15674 // and we will have warned when we allocated it in that case.
15675 if (!Info.getLangOpts().CPlusPlus20)
15676 Info.CCEDiag(E, DiagId: diag::note_constexpr_new);
15677 return true;
15678 }
15679
15680 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
15681 Info, E, Pointer, DeallocKind: E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
15682 if (!Alloc)
15683 return false;
15684 QualType AllocType = Pointer.Base.getDynamicAllocType();
15685
15686 // For the non-array case, the designator must be empty if the static type
15687 // does not have a virtual destructor.
15688 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
15689 !hasVirtualDestructor(T: Arg->getType()->getPointeeType())) {
15690 Info.FFDiag(E, DiagId: diag::note_constexpr_delete_base_nonvirt_dtor)
15691 << Arg->getType()->getPointeeType() << AllocType;
15692 return false;
15693 }
15694
15695 // For a class type with a virtual destructor, the selected operator delete
15696 // is the one looked up when building the destructor.
15697 if (!E->isArrayForm() && !E->isGlobalDelete()) {
15698 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(T: AllocType);
15699 if (VirtualDelete &&
15700 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
15701 Info.FFDiag(E, DiagId: diag::note_constexpr_new_non_replaceable)
15702 << isa<CXXMethodDecl>(Val: VirtualDelete) << VirtualDelete;
15703 return false;
15704 }
15705 }
15706
15707 if (!HandleDestruction(Info, Loc: E->getExprLoc(), LVBase: Pointer.getLValueBase(),
15708 Value&: (*Alloc)->Value, T: AllocType))
15709 return false;
15710
15711 if (!Info.HeapAllocs.erase(x: Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
15712 // The element was already erased. This means the destructor call also
15713 // deleted the object.
15714 // FIXME: This probably results in undefined behavior before we get this
15715 // far, and should be diagnosed elsewhere first.
15716 Info.FFDiag(E, DiagId: diag::note_constexpr_double_delete);
15717 return false;
15718 }
15719
15720 return true;
15721}
15722
15723static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
15724 assert(!E->isValueDependent());
15725 assert(E->isPRValue() && E->getType()->isVoidType());
15726 return VoidExprEvaluator(Info).Visit(S: E);
15727}
15728
15729//===----------------------------------------------------------------------===//
15730// Top level Expr::EvaluateAsRValue method.
15731//===----------------------------------------------------------------------===//
15732
15733static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
15734 assert(!E->isValueDependent());
15735 // In C, function designators are not lvalues, but we evaluate them as if they
15736 // are.
15737 QualType T = E->getType();
15738 if (E->isGLValue() || T->isFunctionType()) {
15739 LValue LV;
15740 if (!EvaluateLValue(E, Result&: LV, Info))
15741 return false;
15742 LV.moveInto(V&: Result);
15743 } else if (T->isVectorType()) {
15744 if (!EvaluateVector(E, Result, Info))
15745 return false;
15746 } else if (T->isIntegralOrEnumerationType()) {
15747 if (!IntExprEvaluator(Info, Result).Visit(S: E))
15748 return false;
15749 } else if (T->hasPointerRepresentation()) {
15750 LValue LV;
15751 if (!EvaluatePointer(E, Result&: LV, Info))
15752 return false;
15753 LV.moveInto(V&: Result);
15754 } else if (T->isRealFloatingType()) {
15755 llvm::APFloat F(0.0);
15756 if (!EvaluateFloat(E, Result&: F, Info))
15757 return false;
15758 Result = APValue(F);
15759 } else if (T->isAnyComplexType()) {
15760 ComplexValue C;
15761 if (!EvaluateComplex(E, Result&: C, Info))
15762 return false;
15763 C.moveInto(v&: Result);
15764 } else if (T->isFixedPointType()) {
15765 if (!FixedPointExprEvaluator(Info, Result).Visit(S: E)) return false;
15766 } else if (T->isMemberPointerType()) {
15767 MemberPtr P;
15768 if (!EvaluateMemberPointer(E, Result&: P, Info))
15769 return false;
15770 P.moveInto(V&: Result);
15771 return true;
15772 } else if (T->isArrayType()) {
15773 LValue LV;
15774 APValue &Value =
15775 Info.CurrentCall->createTemporary(Key: E, T, Scope: ScopeKind::FullExpression, LV);
15776 if (!EvaluateArray(E, This: LV, Result&: Value, Info))
15777 return false;
15778 Result = Value;
15779 } else if (T->isRecordType()) {
15780 LValue LV;
15781 APValue &Value =
15782 Info.CurrentCall->createTemporary(Key: E, T, Scope: ScopeKind::FullExpression, LV);
15783 if (!EvaluateRecord(E, This: LV, Result&: Value, Info))
15784 return false;
15785 Result = Value;
15786 } else if (T->isVoidType()) {
15787 if (!Info.getLangOpts().CPlusPlus11)
15788 Info.CCEDiag(E, DiagId: diag::note_constexpr_nonliteral)
15789 << E->getType();
15790 if (!EvaluateVoid(E, Info))
15791 return false;
15792 } else if (T->isAtomicType()) {
15793 QualType Unqual = T.getAtomicUnqualifiedType();
15794 if (Unqual->isArrayType() || Unqual->isRecordType()) {
15795 LValue LV;
15796 APValue &Value = Info.CurrentCall->createTemporary(
15797 Key: E, T: Unqual, Scope: ScopeKind::FullExpression, LV);
15798 if (!EvaluateAtomic(E, This: &LV, Result&: Value, Info))
15799 return false;
15800 Result = Value;
15801 } else {
15802 if (!EvaluateAtomic(E, This: nullptr, Result, Info))
15803 return false;
15804 }
15805 } else if (Info.getLangOpts().CPlusPlus11) {
15806 Info.FFDiag(E, DiagId: diag::note_constexpr_nonliteral) << E->getType();
15807 return false;
15808 } else {
15809 Info.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
15810 return false;
15811 }
15812
15813 return true;
15814}
15815
15816/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15817/// cases, the in-place evaluation is essential, since later initializers for
15818/// an object can indirectly refer to subobjects which were initialized earlier.
15819static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15820 const Expr *E, bool AllowNonLiteralTypes) {
15821 assert(!E->isValueDependent());
15822
15823 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, This: &This))
15824 return false;
15825
15826 if (E->isPRValue()) {
15827 // Evaluate arrays and record types in-place, so that later initializers can
15828 // refer to earlier-initialized members of the object.
15829 QualType T = E->getType();
15830 if (T->isArrayType())
15831 return EvaluateArray(E, This, Result, Info);
15832 else if (T->isRecordType())
15833 return EvaluateRecord(E, This, Result, Info);
15834 else if (T->isAtomicType()) {
15835 QualType Unqual = T.getAtomicUnqualifiedType();
15836 if (Unqual->isArrayType() || Unqual->isRecordType())
15837 return EvaluateAtomic(E, This: &This, Result, Info);
15838 }
15839 }
15840
15841 // For any other type, in-place evaluation is unimportant.
15842 return Evaluate(Result, Info, E);
15843}
15844
15845/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15846/// lvalue-to-rvalue cast if it is an lvalue.
15847static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15848 assert(!E->isValueDependent());
15849
15850 if (E->getType().isNull())
15851 return false;
15852
15853 if (!CheckLiteralType(Info, E))
15854 return false;
15855
15856 if (Info.EnableNewConstInterp) {
15857 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Parent&: Info, E, Result))
15858 return false;
15859 return CheckConstantExpression(Info, DiagLoc: E->getExprLoc(), Type: E->getType(), Value: Result,
15860 Kind: ConstantExprKind::Normal);
15861 }
15862
15863 if (!::Evaluate(Result, Info, E))
15864 return false;
15865
15866 // Implicit lvalue-to-rvalue cast.
15867 if (E->isGLValue()) {
15868 LValue LV;
15869 LV.setFrom(Ctx&: Info.Ctx, V: Result);
15870 if (!handleLValueToRValueConversion(Info, Conv: E, Type: E->getType(), LVal: LV, RVal&: Result))
15871 return false;
15872 }
15873
15874 // Check this core constant expression is a constant expression.
15875 return CheckConstantExpression(Info, DiagLoc: E->getExprLoc(), Type: E->getType(), Value: Result,
15876 Kind: ConstantExprKind::Normal) &&
15877 CheckMemoryLeaks(Info);
15878}
15879
15880static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15881 const ASTContext &Ctx, bool &IsConst) {
15882 // Fast-path evaluations of integer literals, since we sometimes see files
15883 // containing vast quantities of these.
15884 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Val: Exp)) {
15885 Result.Val = APValue(APSInt(L->getValue(),
15886 L->getType()->isUnsignedIntegerType()));
15887 IsConst = true;
15888 return true;
15889 }
15890
15891 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Val: Exp)) {
15892 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15893 IsConst = true;
15894 return true;
15895 }
15896
15897 if (const auto *CE = dyn_cast<ConstantExpr>(Val: Exp)) {
15898 if (CE->hasAPValueResult()) {
15899 APValue APV = CE->getAPValueResult();
15900 if (!APV.isLValue()) {
15901 Result.Val = std::move(APV);
15902 IsConst = true;
15903 return true;
15904 }
15905 }
15906
15907 // The SubExpr is usually just an IntegerLiteral.
15908 return FastEvaluateAsRValue(Exp: CE->getSubExpr(), Result, Ctx, IsConst);
15909 }
15910
15911 // This case should be rare, but we need to check it before we check on
15912 // the type below.
15913 if (Exp->getType().isNull()) {
15914 IsConst = false;
15915 return true;
15916 }
15917
15918 return false;
15919}
15920
15921static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15922 Expr::SideEffectsKind SEK) {
15923 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15924 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15925}
15926
15927static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15928 const ASTContext &Ctx, EvalInfo &Info) {
15929 assert(!E->isValueDependent());
15930 bool IsConst;
15931 if (FastEvaluateAsRValue(Exp: E, Result, Ctx, IsConst))
15932 return IsConst;
15933
15934 return EvaluateAsRValue(Info, E, Result&: Result.Val);
15935}
15936
15937static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15938 const ASTContext &Ctx,
15939 Expr::SideEffectsKind AllowSideEffects,
15940 EvalInfo &Info) {
15941 assert(!E->isValueDependent());
15942 if (!E->getType()->isIntegralOrEnumerationType())
15943 return false;
15944
15945 if (!::EvaluateAsRValue(E, Result&: ExprResult, Ctx, Info) ||
15946 !ExprResult.Val.isInt() ||
15947 hasUnacceptableSideEffect(Result&: ExprResult, SEK: AllowSideEffects))
15948 return false;
15949
15950 return true;
15951}
15952
15953static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15954 const ASTContext &Ctx,
15955 Expr::SideEffectsKind AllowSideEffects,
15956 EvalInfo &Info) {
15957 assert(!E->isValueDependent());
15958 if (!E->getType()->isFixedPointType())
15959 return false;
15960
15961 if (!::EvaluateAsRValue(E, Result&: ExprResult, Ctx, Info))
15962 return false;
15963
15964 if (!ExprResult.Val.isFixedPoint() ||
15965 hasUnacceptableSideEffect(Result&: ExprResult, SEK: AllowSideEffects))
15966 return false;
15967
15968 return true;
15969}
15970
15971/// EvaluateAsRValue - Return true if this is a constant which we can fold using
15972/// any crazy technique (that has nothing to do with language standards) that
15973/// we want to. If this function returns true, it returns the folded constant
15974/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15975/// will be applied to the result.
15976bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15977 bool InConstantContext) const {
15978 assert(!isValueDependent() &&
15979 "Expression evaluator can't be called on a dependent expression.");
15980 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15981 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15982 Info.InConstantContext = InConstantContext;
15983 return ::EvaluateAsRValue(E: this, Result, Ctx, Info);
15984}
15985
15986bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15987 bool InConstantContext) const {
15988 assert(!isValueDependent() &&
15989 "Expression evaluator can't be called on a dependent expression.");
15990 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15991 EvalResult Scratch;
15992 return EvaluateAsRValue(Result&: Scratch, Ctx, InConstantContext) &&
15993 HandleConversionToBool(Val: Scratch.Val, Result);
15994}
15995
15996bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15997 SideEffectsKind AllowSideEffects,
15998 bool InConstantContext) const {
15999 assert(!isValueDependent() &&
16000 "Expression evaluator can't be called on a dependent expression.");
16001 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16002 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16003 Info.InConstantContext = InConstantContext;
16004 return ::EvaluateAsInt(E: this, ExprResult&: Result, Ctx, AllowSideEffects, Info);
16005}
16006
16007bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
16008 SideEffectsKind AllowSideEffects,
16009 bool InConstantContext) const {
16010 assert(!isValueDependent() &&
16011 "Expression evaluator can't be called on a dependent expression.");
16012 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16013 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16014 Info.InConstantContext = InConstantContext;
16015 return ::EvaluateAsFixedPoint(E: this, ExprResult&: Result, Ctx, AllowSideEffects, Info);
16016}
16017
16018bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16019 SideEffectsKind AllowSideEffects,
16020 bool InConstantContext) const {
16021 assert(!isValueDependent() &&
16022 "Expression evaluator can't be called on a dependent expression.");
16023
16024 if (!getType()->isRealFloatingType())
16025 return false;
16026
16027 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16028 EvalResult ExprResult;
16029 if (!EvaluateAsRValue(Result&: ExprResult, Ctx, InConstantContext) ||
16030 !ExprResult.Val.isFloat() ||
16031 hasUnacceptableSideEffect(Result&: ExprResult, SEK: AllowSideEffects))
16032 return false;
16033
16034 Result = ExprResult.Val.getFloat();
16035 return true;
16036}
16037
16038bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
16039 bool InConstantContext) const {
16040 assert(!isValueDependent() &&
16041 "Expression evaluator can't be called on a dependent expression.");
16042
16043 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16044 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16045 Info.InConstantContext = InConstantContext;
16046 LValue LV;
16047 CheckedTemporaries CheckedTemps;
16048 if (!EvaluateLValue(E: this, Result&: LV, Info) || !Info.discardCleanups() ||
16049 Result.HasSideEffects ||
16050 !CheckLValueConstantExpression(Info, Loc: getExprLoc(),
16051 Type: Ctx.getLValueReferenceType(T: getType()), LVal: LV,
16052 Kind: ConstantExprKind::Normal, CheckedTemps))
16053 return false;
16054
16055 LV.moveInto(V&: Result.Val);
16056 return true;
16057}
16058
16059static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
16060 APValue DestroyedValue, QualType Type,
16061 SourceLocation Loc, Expr::EvalStatus &EStatus,
16062 bool IsConstantDestruction) {
16063 EvalInfo Info(Ctx, EStatus,
16064 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16065 : EvalInfo::EM_ConstantFold);
16066 Info.setEvaluatingDecl(Base, Value&: DestroyedValue,
16067 EDK: EvalInfo::EvaluatingDeclKind::Dtor);
16068 Info.InConstantContext = IsConstantDestruction;
16069
16070 LValue LVal;
16071 LVal.set(B: Base);
16072
16073 if (!HandleDestruction(Info, Loc, LVBase: Base, Value&: DestroyedValue, T: Type) ||
16074 EStatus.HasSideEffects)
16075 return false;
16076
16077 if (!Info.discardCleanups())
16078 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16079
16080 return true;
16081}
16082
16083bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
16084 ConstantExprKind Kind) const {
16085 assert(!isValueDependent() &&
16086 "Expression evaluator can't be called on a dependent expression.");
16087 bool IsConst;
16088 if (FastEvaluateAsRValue(Exp: this, Result, Ctx, IsConst) && Result.Val.hasValue())
16089 return true;
16090
16091 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
16092 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
16093 EvalInfo Info(Ctx, Result, EM);
16094 Info.InConstantContext = true;
16095
16096 if (Info.EnableNewConstInterp) {
16097 if (!Info.Ctx.getInterpContext().evaluate(Parent&: Info, E: this, Result&: Result.Val))
16098 return false;
16099 return CheckConstantExpression(Info, DiagLoc: getExprLoc(),
16100 Type: getStorageType(Ctx, E: this), Value: Result.Val, Kind);
16101 }
16102
16103 // The type of the object we're initializing is 'const T' for a class NTTP.
16104 QualType T = getType();
16105 if (Kind == ConstantExprKind::ClassTemplateArgument)
16106 T.addConst();
16107
16108 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
16109 // represent the result of the evaluation. CheckConstantExpression ensures
16110 // this doesn't escape.
16111 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
16112 APValue::LValueBase Base(&BaseMTE);
16113 Info.setEvaluatingDecl(Base, Value&: Result.Val);
16114
16115 if (Info.EnableNewConstInterp) {
16116 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Parent&: Info, E: this, Result&: Result.Val))
16117 return false;
16118 } else {
16119 LValue LVal;
16120 LVal.set(B: Base);
16121 // C++23 [intro.execution]/p5
16122 // A full-expression is [...] a constant-expression
16123 // So we need to make sure temporary objects are destroyed after having
16124 // evaluating the expression (per C++23 [class.temporary]/p4).
16125 FullExpressionRAII Scope(Info);
16126 if (!::EvaluateInPlace(Result&: Result.Val, Info, This: LVal, E: this) ||
16127 Result.HasSideEffects || !Scope.destroy())
16128 return false;
16129
16130 if (!Info.discardCleanups())
16131 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16132 }
16133
16134 if (!CheckConstantExpression(Info, DiagLoc: getExprLoc(), Type: getStorageType(Ctx, E: this),
16135 Value: Result.Val, Kind))
16136 return false;
16137 if (!CheckMemoryLeaks(Info))
16138 return false;
16139
16140 // If this is a class template argument, it's required to have constant
16141 // destruction too.
16142 if (Kind == ConstantExprKind::ClassTemplateArgument &&
16143 (!EvaluateDestruction(Ctx, Base, DestroyedValue: Result.Val, Type: T, Loc: getBeginLoc(), EStatus&: Result,
16144 IsConstantDestruction: true) ||
16145 Result.HasSideEffects)) {
16146 // FIXME: Prefix a note to indicate that the problem is lack of constant
16147 // destruction.
16148 return false;
16149 }
16150
16151 return true;
16152}
16153
16154bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
16155 const VarDecl *VD,
16156 SmallVectorImpl<PartialDiagnosticAt> &Notes,
16157 bool IsConstantInitialization) const {
16158 assert(!isValueDependent() &&
16159 "Expression evaluator can't be called on a dependent expression.");
16160
16161 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16162 std::string Name;
16163 llvm::raw_string_ostream OS(Name);
16164 VD->printQualifiedName(OS);
16165 return Name;
16166 });
16167
16168 Expr::EvalStatus EStatus;
16169 EStatus.Diag = &Notes;
16170
16171 EvalInfo Info(Ctx, EStatus,
16172 (IsConstantInitialization &&
16173 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16174 ? EvalInfo::EM_ConstantExpression
16175 : EvalInfo::EM_ConstantFold);
16176 Info.setEvaluatingDecl(Base: VD, Value);
16177 Info.InConstantContext = IsConstantInitialization;
16178
16179 SourceLocation DeclLoc = VD->getLocation();
16180 QualType DeclTy = VD->getType();
16181
16182 if (Info.EnableNewConstInterp) {
16183 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16184 if (!InterpCtx.evaluateAsInitializer(Parent&: Info, VD, Result&: Value))
16185 return false;
16186
16187 return CheckConstantExpression(Info, DiagLoc: DeclLoc, Type: DeclTy, Value,
16188 Kind: ConstantExprKind::Normal);
16189 } else {
16190 LValue LVal;
16191 LVal.set(B: VD);
16192
16193 {
16194 // C++23 [intro.execution]/p5
16195 // A full-expression is ... an init-declarator ([dcl.decl]) or a
16196 // mem-initializer.
16197 // So we need to make sure temporary objects are destroyed after having
16198 // evaluated the expression (per C++23 [class.temporary]/p4).
16199 //
16200 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16201 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16202 // outermost FullExpr, such as ExprWithCleanups.
16203 FullExpressionRAII Scope(Info);
16204 if (!EvaluateInPlace(Result&: Value, Info, This: LVal, E: this,
16205 /*AllowNonLiteralTypes=*/true) ||
16206 EStatus.HasSideEffects)
16207 return false;
16208 }
16209
16210 // At this point, any lifetime-extended temporaries are completely
16211 // initialized.
16212 Info.performLifetimeExtension();
16213
16214 if (!Info.discardCleanups())
16215 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16216 }
16217
16218 return CheckConstantExpression(Info, DiagLoc: DeclLoc, Type: DeclTy, Value,
16219 Kind: ConstantExprKind::Normal) &&
16220 CheckMemoryLeaks(Info);
16221}
16222
16223bool VarDecl::evaluateDestruction(
16224 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
16225 Expr::EvalStatus EStatus;
16226 EStatus.Diag = &Notes;
16227
16228 // Only treat the destruction as constant destruction if we formally have
16229 // constant initialization (or are usable in a constant expression).
16230 bool IsConstantDestruction = hasConstantInitialization();
16231
16232 // Make a copy of the value for the destructor to mutate, if we know it.
16233 // Otherwise, treat the value as default-initialized; if the destructor works
16234 // anyway, then the destruction is constant (and must be essentially empty).
16235 APValue DestroyedValue;
16236 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
16237 DestroyedValue = *getEvaluatedValue();
16238 else if (!handleDefaultInitValue(T: getType(), Result&: DestroyedValue))
16239 return false;
16240
16241 if (!EvaluateDestruction(Ctx: getASTContext(), Base: this, DestroyedValue: std::move(DestroyedValue),
16242 Type: getType(), Loc: getLocation(), EStatus,
16243 IsConstantDestruction) ||
16244 EStatus.HasSideEffects)
16245 return false;
16246
16247 ensureEvaluatedStmt()->HasConstantDestruction = true;
16248 return true;
16249}
16250
16251/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
16252/// constant folded, but discard the result.
16253bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
16254 assert(!isValueDependent() &&
16255 "Expression evaluator can't be called on a dependent expression.");
16256
16257 EvalResult Result;
16258 return EvaluateAsRValue(Result, Ctx, /* in constant context */ InConstantContext: true) &&
16259 !hasUnacceptableSideEffect(Result, SEK);
16260}
16261
16262APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
16263 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
16264 assert(!isValueDependent() &&
16265 "Expression evaluator can't be called on a dependent expression.");
16266
16267 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
16268 EvalResult EVResult;
16269 EVResult.Diag = Diag;
16270 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16271 Info.InConstantContext = true;
16272
16273 bool Result = ::EvaluateAsRValue(E: this, Result&: EVResult, Ctx, Info);
16274 (void)Result;
16275 assert(Result && "Could not evaluate expression");
16276 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16277
16278 return EVResult.Val.getInt();
16279}
16280
16281APSInt Expr::EvaluateKnownConstIntCheckOverflow(
16282 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
16283 assert(!isValueDependent() &&
16284 "Expression evaluator can't be called on a dependent expression.");
16285
16286 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
16287 EvalResult EVResult;
16288 EVResult.Diag = Diag;
16289 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16290 Info.InConstantContext = true;
16291 Info.CheckingForUndefinedBehavior = true;
16292
16293 bool Result = ::EvaluateAsRValue(Info, E: this, Result&: EVResult.Val);
16294 (void)Result;
16295 assert(Result && "Could not evaluate expression");
16296 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16297
16298 return EVResult.Val.getInt();
16299}
16300
16301void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
16302 assert(!isValueDependent() &&
16303 "Expression evaluator can't be called on a dependent expression.");
16304
16305 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
16306 bool IsConst;
16307 EvalResult EVResult;
16308 if (!FastEvaluateAsRValue(Exp: this, Result&: EVResult, Ctx, IsConst)) {
16309 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16310 Info.CheckingForUndefinedBehavior = true;
16311 (void)::EvaluateAsRValue(Info, E: this, Result&: EVResult.Val);
16312 }
16313}
16314
16315bool Expr::EvalResult::isGlobalLValue() const {
16316 assert(Val.isLValue());
16317 return IsGlobalLValue(B: Val.getLValueBase());
16318}
16319
16320/// isIntegerConstantExpr - this recursive routine will test if an expression is
16321/// an integer constant expression.
16322
16323/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
16324/// comma, etc
16325
16326// CheckICE - This function does the fundamental ICE checking: the returned
16327// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
16328// and a (possibly null) SourceLocation indicating the location of the problem.
16329//
16330// Note that to reduce code duplication, this helper does no evaluation
16331// itself; the caller checks whether the expression is evaluatable, and
16332// in the rare cases where CheckICE actually cares about the evaluated
16333// value, it calls into Evaluate.
16334
16335namespace {
16336
16337enum ICEKind {
16338 /// This expression is an ICE.
16339 IK_ICE,
16340 /// This expression is not an ICE, but if it isn't evaluated, it's
16341 /// a legal subexpression for an ICE. This return value is used to handle
16342 /// the comma operator in C99 mode, and non-constant subexpressions.
16343 IK_ICEIfUnevaluated,
16344 /// This expression is not an ICE, and is not a legal subexpression for one.
16345 IK_NotICE
16346};
16347
16348struct ICEDiag {
16349 ICEKind Kind;
16350 SourceLocation Loc;
16351
16352 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
16353};
16354
16355}
16356
16357static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
16358
16359static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
16360
16361static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
16362 Expr::EvalResult EVResult;
16363 Expr::EvalStatus Status;
16364 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16365
16366 Info.InConstantContext = true;
16367 if (!::EvaluateAsRValue(E, Result&: EVResult, Ctx, Info) || EVResult.HasSideEffects ||
16368 !EVResult.Val.isInt())
16369 return ICEDiag(IK_NotICE, E->getBeginLoc());
16370
16371 return NoDiag();
16372}
16373
16374static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
16375 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
16376 if (!E->getType()->isIntegralOrEnumerationType())
16377 return ICEDiag(IK_NotICE, E->getBeginLoc());
16378
16379 switch (E->getStmtClass()) {
16380#define ABSTRACT_STMT(Node)
16381#define STMT(Node, Base) case Expr::Node##Class:
16382#define EXPR(Node, Base)
16383#include "clang/AST/StmtNodes.inc"
16384 case Expr::PredefinedExprClass:
16385 case Expr::FloatingLiteralClass:
16386 case Expr::ImaginaryLiteralClass:
16387 case Expr::StringLiteralClass:
16388 case Expr::ArraySubscriptExprClass:
16389 case Expr::MatrixSubscriptExprClass:
16390 case Expr::ArraySectionExprClass:
16391 case Expr::OMPArrayShapingExprClass:
16392 case Expr::OMPIteratorExprClass:
16393 case Expr::MemberExprClass:
16394 case Expr::CompoundAssignOperatorClass:
16395 case Expr::CompoundLiteralExprClass:
16396 case Expr::ExtVectorElementExprClass:
16397 case Expr::DesignatedInitExprClass:
16398 case Expr::ArrayInitLoopExprClass:
16399 case Expr::ArrayInitIndexExprClass:
16400 case Expr::NoInitExprClass:
16401 case Expr::DesignatedInitUpdateExprClass:
16402 case Expr::ImplicitValueInitExprClass:
16403 case Expr::ParenListExprClass:
16404 case Expr::VAArgExprClass:
16405 case Expr::AddrLabelExprClass:
16406 case Expr::StmtExprClass:
16407 case Expr::CXXMemberCallExprClass:
16408 case Expr::CUDAKernelCallExprClass:
16409 case Expr::CXXAddrspaceCastExprClass:
16410 case Expr::CXXDynamicCastExprClass:
16411 case Expr::CXXTypeidExprClass:
16412 case Expr::CXXUuidofExprClass:
16413 case Expr::MSPropertyRefExprClass:
16414 case Expr::MSPropertySubscriptExprClass:
16415 case Expr::CXXNullPtrLiteralExprClass:
16416 case Expr::UserDefinedLiteralClass:
16417 case Expr::CXXThisExprClass:
16418 case Expr::CXXThrowExprClass:
16419 case Expr::CXXNewExprClass:
16420 case Expr::CXXDeleteExprClass:
16421 case Expr::CXXPseudoDestructorExprClass:
16422 case Expr::UnresolvedLookupExprClass:
16423 case Expr::TypoExprClass:
16424 case Expr::RecoveryExprClass:
16425 case Expr::DependentScopeDeclRefExprClass:
16426 case Expr::CXXConstructExprClass:
16427 case Expr::CXXInheritedCtorInitExprClass:
16428 case Expr::CXXStdInitializerListExprClass:
16429 case Expr::CXXBindTemporaryExprClass:
16430 case Expr::ExprWithCleanupsClass:
16431 case Expr::CXXTemporaryObjectExprClass:
16432 case Expr::CXXUnresolvedConstructExprClass:
16433 case Expr::CXXDependentScopeMemberExprClass:
16434 case Expr::UnresolvedMemberExprClass:
16435 case Expr::ObjCStringLiteralClass:
16436 case Expr::ObjCBoxedExprClass:
16437 case Expr::ObjCArrayLiteralClass:
16438 case Expr::ObjCDictionaryLiteralClass:
16439 case Expr::ObjCEncodeExprClass:
16440 case Expr::ObjCMessageExprClass:
16441 case Expr::ObjCSelectorExprClass:
16442 case Expr::ObjCProtocolExprClass:
16443 case Expr::ObjCIvarRefExprClass:
16444 case Expr::ObjCPropertyRefExprClass:
16445 case Expr::ObjCSubscriptRefExprClass:
16446 case Expr::ObjCIsaExprClass:
16447 case Expr::ObjCAvailabilityCheckExprClass:
16448 case Expr::ShuffleVectorExprClass:
16449 case Expr::ConvertVectorExprClass:
16450 case Expr::BlockExprClass:
16451 case Expr::NoStmtClass:
16452 case Expr::OpaqueValueExprClass:
16453 case Expr::PackExpansionExprClass:
16454 case Expr::SubstNonTypeTemplateParmPackExprClass:
16455 case Expr::FunctionParmPackExprClass:
16456 case Expr::AsTypeExprClass:
16457 case Expr::ObjCIndirectCopyRestoreExprClass:
16458 case Expr::MaterializeTemporaryExprClass:
16459 case Expr::PseudoObjectExprClass:
16460 case Expr::AtomicExprClass:
16461 case Expr::LambdaExprClass:
16462 case Expr::CXXFoldExprClass:
16463 case Expr::CoawaitExprClass:
16464 case Expr::DependentCoawaitExprClass:
16465 case Expr::CoyieldExprClass:
16466 case Expr::SYCLUniqueStableNameExprClass:
16467 case Expr::CXXParenListInitExprClass:
16468 return ICEDiag(IK_NotICE, E->getBeginLoc());
16469
16470 case Expr::InitListExprClass: {
16471 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
16472 // form "T x = { a };" is equivalent to "T x = a;".
16473 // Unless we're initializing a reference, T is a scalar as it is known to be
16474 // of integral or enumeration type.
16475 if (E->isPRValue())
16476 if (cast<InitListExpr>(Val: E)->getNumInits() == 1)
16477 return CheckICE(E: cast<InitListExpr>(Val: E)->getInit(Init: 0), Ctx);
16478 return ICEDiag(IK_NotICE, E->getBeginLoc());
16479 }
16480
16481 case Expr::SizeOfPackExprClass:
16482 case Expr::GNUNullExprClass:
16483 case Expr::SourceLocExprClass:
16484 case Expr::EmbedExprClass:
16485 return NoDiag();
16486
16487 case Expr::PackIndexingExprClass:
16488 return CheckICE(E: cast<PackIndexingExpr>(Val: E)->getSelectedExpr(), Ctx);
16489
16490 case Expr::SubstNonTypeTemplateParmExprClass:
16491 return
16492 CheckICE(E: cast<SubstNonTypeTemplateParmExpr>(Val: E)->getReplacement(), Ctx);
16493
16494 case Expr::ConstantExprClass:
16495 return CheckICE(E: cast<ConstantExpr>(Val: E)->getSubExpr(), Ctx);
16496
16497 case Expr::ParenExprClass:
16498 return CheckICE(E: cast<ParenExpr>(Val: E)->getSubExpr(), Ctx);
16499 case Expr::GenericSelectionExprClass:
16500 return CheckICE(E: cast<GenericSelectionExpr>(Val: E)->getResultExpr(), Ctx);
16501 case Expr::IntegerLiteralClass:
16502 case Expr::FixedPointLiteralClass:
16503 case Expr::CharacterLiteralClass:
16504 case Expr::ObjCBoolLiteralExprClass:
16505 case Expr::CXXBoolLiteralExprClass:
16506 case Expr::CXXScalarValueInitExprClass:
16507 case Expr::TypeTraitExprClass:
16508 case Expr::ConceptSpecializationExprClass:
16509 case Expr::RequiresExprClass:
16510 case Expr::ArrayTypeTraitExprClass:
16511 case Expr::ExpressionTraitExprClass:
16512 case Expr::CXXNoexceptExprClass:
16513 return NoDiag();
16514 case Expr::CallExprClass:
16515 case Expr::CXXOperatorCallExprClass: {
16516 // C99 6.6/3 allows function calls within unevaluated subexpressions of
16517 // constant expressions, but they can never be ICEs because an ICE cannot
16518 // contain an operand of (pointer to) function type.
16519 const CallExpr *CE = cast<CallExpr>(Val: E);
16520 if (CE->getBuiltinCallee())
16521 return CheckEvalInICE(E, Ctx);
16522 return ICEDiag(IK_NotICE, E->getBeginLoc());
16523 }
16524 case Expr::CXXRewrittenBinaryOperatorClass:
16525 return CheckICE(E: cast<CXXRewrittenBinaryOperator>(Val: E)->getSemanticForm(),
16526 Ctx);
16527 case Expr::DeclRefExprClass: {
16528 const NamedDecl *D = cast<DeclRefExpr>(Val: E)->getDecl();
16529 if (isa<EnumConstantDecl>(Val: D))
16530 return NoDiag();
16531
16532 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16533 // integer variables in constant expressions:
16534 //
16535 // C++ 7.1.5.1p2
16536 // A variable of non-volatile const-qualified integral or enumeration
16537 // type initialized by an ICE can be used in ICEs.
16538 //
16539 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
16540 // that mode, use of reference variables should not be allowed.
16541 const VarDecl *VD = dyn_cast<VarDecl>(Val: D);
16542 if (VD && VD->isUsableInConstantExpressions(C: Ctx) &&
16543 !VD->getType()->isReferenceType())
16544 return NoDiag();
16545
16546 return ICEDiag(IK_NotICE, E->getBeginLoc());
16547 }
16548 case Expr::UnaryOperatorClass: {
16549 const UnaryOperator *Exp = cast<UnaryOperator>(Val: E);
16550 switch (Exp->getOpcode()) {
16551 case UO_PostInc:
16552 case UO_PostDec:
16553 case UO_PreInc:
16554 case UO_PreDec:
16555 case UO_AddrOf:
16556 case UO_Deref:
16557 case UO_Coawait:
16558 // C99 6.6/3 allows increment and decrement within unevaluated
16559 // subexpressions of constant expressions, but they can never be ICEs
16560 // because an ICE cannot contain an lvalue operand.
16561 return ICEDiag(IK_NotICE, E->getBeginLoc());
16562 case UO_Extension:
16563 case UO_LNot:
16564 case UO_Plus:
16565 case UO_Minus:
16566 case UO_Not:
16567 case UO_Real:
16568 case UO_Imag:
16569 return CheckICE(E: Exp->getSubExpr(), Ctx);
16570 }
16571 llvm_unreachable("invalid unary operator class");
16572 }
16573 case Expr::OffsetOfExprClass: {
16574 // Note that per C99, offsetof must be an ICE. And AFAIK, using
16575 // EvaluateAsRValue matches the proposed gcc behavior for cases like
16576 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
16577 // compliance: we should warn earlier for offsetof expressions with
16578 // array subscripts that aren't ICEs, and if the array subscripts
16579 // are ICEs, the value of the offsetof must be an integer constant.
16580 return CheckEvalInICE(E, Ctx);
16581 }
16582 case Expr::UnaryExprOrTypeTraitExprClass: {
16583 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(Val: E);
16584 if ((Exp->getKind() == UETT_SizeOf) &&
16585 Exp->getTypeOfArgument()->isVariableArrayType())
16586 return ICEDiag(IK_NotICE, E->getBeginLoc());
16587 return NoDiag();
16588 }
16589 case Expr::BinaryOperatorClass: {
16590 const BinaryOperator *Exp = cast<BinaryOperator>(Val: E);
16591 switch (Exp->getOpcode()) {
16592 case BO_PtrMemD:
16593 case BO_PtrMemI:
16594 case BO_Assign:
16595 case BO_MulAssign:
16596 case BO_DivAssign:
16597 case BO_RemAssign:
16598 case BO_AddAssign:
16599 case BO_SubAssign:
16600 case BO_ShlAssign:
16601 case BO_ShrAssign:
16602 case BO_AndAssign:
16603 case BO_XorAssign:
16604 case BO_OrAssign:
16605 // C99 6.6/3 allows assignments within unevaluated subexpressions of
16606 // constant expressions, but they can never be ICEs because an ICE cannot
16607 // contain an lvalue operand.
16608 return ICEDiag(IK_NotICE, E->getBeginLoc());
16609
16610 case BO_Mul:
16611 case BO_Div:
16612 case BO_Rem:
16613 case BO_Add:
16614 case BO_Sub:
16615 case BO_Shl:
16616 case BO_Shr:
16617 case BO_LT:
16618 case BO_GT:
16619 case BO_LE:
16620 case BO_GE:
16621 case BO_EQ:
16622 case BO_NE:
16623 case BO_And:
16624 case BO_Xor:
16625 case BO_Or:
16626 case BO_Comma:
16627 case BO_Cmp: {
16628 ICEDiag LHSResult = CheckICE(E: Exp->getLHS(), Ctx);
16629 ICEDiag RHSResult = CheckICE(E: Exp->getRHS(), Ctx);
16630 if (Exp->getOpcode() == BO_Div ||
16631 Exp->getOpcode() == BO_Rem) {
16632 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
16633 // we don't evaluate one.
16634 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
16635 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
16636 if (REval == 0)
16637 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16638 if (REval.isSigned() && REval.isAllOnes()) {
16639 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
16640 if (LEval.isMinSignedValue())
16641 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16642 }
16643 }
16644 }
16645 if (Exp->getOpcode() == BO_Comma) {
16646 if (Ctx.getLangOpts().C99) {
16647 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
16648 // if it isn't evaluated.
16649 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
16650 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16651 } else {
16652 // In both C89 and C++, commas in ICEs are illegal.
16653 return ICEDiag(IK_NotICE, E->getBeginLoc());
16654 }
16655 }
16656 return Worst(A: LHSResult, B: RHSResult);
16657 }
16658 case BO_LAnd:
16659 case BO_LOr: {
16660 ICEDiag LHSResult = CheckICE(E: Exp->getLHS(), Ctx);
16661 ICEDiag RHSResult = CheckICE(E: Exp->getRHS(), Ctx);
16662 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
16663 // Rare case where the RHS has a comma "side-effect"; we need
16664 // to actually check the condition to see whether the side
16665 // with the comma is evaluated.
16666 if ((Exp->getOpcode() == BO_LAnd) !=
16667 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
16668 return RHSResult;
16669 return NoDiag();
16670 }
16671
16672 return Worst(A: LHSResult, B: RHSResult);
16673 }
16674 }
16675 llvm_unreachable("invalid binary operator kind");
16676 }
16677 case Expr::ImplicitCastExprClass:
16678 case Expr::CStyleCastExprClass:
16679 case Expr::CXXFunctionalCastExprClass:
16680 case Expr::CXXStaticCastExprClass:
16681 case Expr::CXXReinterpretCastExprClass:
16682 case Expr::CXXConstCastExprClass:
16683 case Expr::ObjCBridgedCastExprClass: {
16684 const Expr *SubExpr = cast<CastExpr>(Val: E)->getSubExpr();
16685 if (isa<ExplicitCastExpr>(Val: E)) {
16686 if (const FloatingLiteral *FL
16687 = dyn_cast<FloatingLiteral>(Val: SubExpr->IgnoreParenImpCasts())) {
16688 unsigned DestWidth = Ctx.getIntWidth(T: E->getType());
16689 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
16690 APSInt IgnoredVal(DestWidth, !DestSigned);
16691 bool Ignored;
16692 // If the value does not fit in the destination type, the behavior is
16693 // undefined, so we are not required to treat it as a constant
16694 // expression.
16695 if (FL->getValue().convertToInteger(Result&: IgnoredVal,
16696 RM: llvm::APFloat::rmTowardZero,
16697 IsExact: &Ignored) & APFloat::opInvalidOp)
16698 return ICEDiag(IK_NotICE, E->getBeginLoc());
16699 return NoDiag();
16700 }
16701 }
16702 switch (cast<CastExpr>(Val: E)->getCastKind()) {
16703 case CK_LValueToRValue:
16704 case CK_AtomicToNonAtomic:
16705 case CK_NonAtomicToAtomic:
16706 case CK_NoOp:
16707 case CK_IntegralToBoolean:
16708 case CK_IntegralCast:
16709 return CheckICE(E: SubExpr, Ctx);
16710 default:
16711 return ICEDiag(IK_NotICE, E->getBeginLoc());
16712 }
16713 }
16714 case Expr::BinaryConditionalOperatorClass: {
16715 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(Val: E);
16716 ICEDiag CommonResult = CheckICE(E: Exp->getCommon(), Ctx);
16717 if (CommonResult.Kind == IK_NotICE) return CommonResult;
16718 ICEDiag FalseResult = CheckICE(E: Exp->getFalseExpr(), Ctx);
16719 if (FalseResult.Kind == IK_NotICE) return FalseResult;
16720 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
16721 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
16722 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
16723 return FalseResult;
16724 }
16725 case Expr::ConditionalOperatorClass: {
16726 const ConditionalOperator *Exp = cast<ConditionalOperator>(Val: E);
16727 // If the condition (ignoring parens) is a __builtin_constant_p call,
16728 // then only the true side is actually considered in an integer constant
16729 // expression, and it is fully evaluated. This is an important GNU
16730 // extension. See GCC PR38377 for discussion.
16731 if (const CallExpr *CallCE
16732 = dyn_cast<CallExpr>(Val: Exp->getCond()->IgnoreParenCasts()))
16733 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16734 return CheckEvalInICE(E, Ctx);
16735 ICEDiag CondResult = CheckICE(E: Exp->getCond(), Ctx);
16736 if (CondResult.Kind == IK_NotICE)
16737 return CondResult;
16738
16739 ICEDiag TrueResult = CheckICE(E: Exp->getTrueExpr(), Ctx);
16740 ICEDiag FalseResult = CheckICE(E: Exp->getFalseExpr(), Ctx);
16741
16742 if (TrueResult.Kind == IK_NotICE)
16743 return TrueResult;
16744 if (FalseResult.Kind == IK_NotICE)
16745 return FalseResult;
16746 if (CondResult.Kind == IK_ICEIfUnevaluated)
16747 return CondResult;
16748 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
16749 return NoDiag();
16750 // Rare case where the diagnostics depend on which side is evaluated
16751 // Note that if we get here, CondResult is 0, and at least one of
16752 // TrueResult and FalseResult is non-zero.
16753 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16754 return FalseResult;
16755 return TrueResult;
16756 }
16757 case Expr::CXXDefaultArgExprClass:
16758 return CheckICE(E: cast<CXXDefaultArgExpr>(Val: E)->getExpr(), Ctx);
16759 case Expr::CXXDefaultInitExprClass:
16760 return CheckICE(E: cast<CXXDefaultInitExpr>(Val: E)->getExpr(), Ctx);
16761 case Expr::ChooseExprClass: {
16762 return CheckICE(E: cast<ChooseExpr>(Val: E)->getChosenSubExpr(), Ctx);
16763 }
16764 case Expr::BuiltinBitCastExprClass: {
16765 if (!checkBitCastConstexprEligibility(Info: nullptr, Ctx, BCE: cast<CastExpr>(Val: E)))
16766 return ICEDiag(IK_NotICE, E->getBeginLoc());
16767 return CheckICE(E: cast<CastExpr>(Val: E)->getSubExpr(), Ctx);
16768 }
16769 }
16770
16771 llvm_unreachable("Invalid StmtClass!");
16772}
16773
16774/// Evaluate an expression as a C++11 integral constant expression.
16775static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
16776 const Expr *E,
16777 llvm::APSInt *Value,
16778 SourceLocation *Loc) {
16779 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16780 if (Loc) *Loc = E->getExprLoc();
16781 return false;
16782 }
16783
16784 APValue Result;
16785 if (!E->isCXX11ConstantExpr(Ctx, Result: &Result, Loc))
16786 return false;
16787
16788 if (!Result.isInt()) {
16789 if (Loc) *Loc = E->getExprLoc();
16790 return false;
16791 }
16792
16793 if (Value) *Value = Result.getInt();
16794 return true;
16795}
16796
16797bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
16798 SourceLocation *Loc) const {
16799 assert(!isValueDependent() &&
16800 "Expression evaluator can't be called on a dependent expression.");
16801
16802 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16803
16804 if (Ctx.getLangOpts().CPlusPlus11)
16805 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, E: this, Value: nullptr, Loc);
16806
16807 ICEDiag D = CheckICE(E: this, Ctx);
16808 if (D.Kind != IK_ICE) {
16809 if (Loc) *Loc = D.Loc;
16810 return false;
16811 }
16812 return true;
16813}
16814
16815std::optional<llvm::APSInt>
16816Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const {
16817 if (isValueDependent()) {
16818 // Expression evaluator can't succeed on a dependent expression.
16819 return std::nullopt;
16820 }
16821
16822 APSInt Value;
16823
16824 if (Ctx.getLangOpts().CPlusPlus11) {
16825 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, E: this, Value: &Value, Loc))
16826 return Value;
16827 return std::nullopt;
16828 }
16829
16830 if (!isIntegerConstantExpr(Ctx, Loc))
16831 return std::nullopt;
16832
16833 // The only possible side-effects here are due to UB discovered in the
16834 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16835 // required to treat the expression as an ICE, so we produce the folded
16836 // value.
16837 EvalResult ExprResult;
16838 Expr::EvalStatus Status;
16839 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16840 Info.InConstantContext = true;
16841
16842 if (!::EvaluateAsInt(E: this, ExprResult, Ctx, AllowSideEffects: SE_AllowSideEffects, Info))
16843 llvm_unreachable("ICE cannot be evaluated!");
16844
16845 return ExprResult.Val.getInt();
16846}
16847
16848bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16849 assert(!isValueDependent() &&
16850 "Expression evaluator can't be called on a dependent expression.");
16851
16852 return CheckICE(E: this, Ctx).Kind == IK_ICE;
16853}
16854
16855bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16856 SourceLocation *Loc) const {
16857 assert(!isValueDependent() &&
16858 "Expression evaluator can't be called on a dependent expression.");
16859
16860 // We support this checking in C++98 mode in order to diagnose compatibility
16861 // issues.
16862 assert(Ctx.getLangOpts().CPlusPlus);
16863
16864 // Build evaluation settings.
16865 Expr::EvalStatus Status;
16866 SmallVector<PartialDiagnosticAt, 8> Diags;
16867 Status.Diag = &Diags;
16868 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16869
16870 APValue Scratch;
16871 bool IsConstExpr =
16872 ::EvaluateAsRValue(Info, E: this, Result&: Result ? *Result : Scratch) &&
16873 // FIXME: We don't produce a diagnostic for this, but the callers that
16874 // call us on arbitrary full-expressions should generally not care.
16875 Info.discardCleanups() && !Status.HasSideEffects;
16876
16877 if (!Diags.empty()) {
16878 IsConstExpr = false;
16879 if (Loc) *Loc = Diags[0].first;
16880 } else if (!IsConstExpr) {
16881 // FIXME: This shouldn't happen.
16882 if (Loc) *Loc = getExprLoc();
16883 }
16884
16885 return IsConstExpr;
16886}
16887
16888bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16889 const FunctionDecl *Callee,
16890 ArrayRef<const Expr*> Args,
16891 const Expr *This) const {
16892 assert(!isValueDependent() &&
16893 "Expression evaluator can't be called on a dependent expression.");
16894
16895 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16896 std::string Name;
16897 llvm::raw_string_ostream OS(Name);
16898 Callee->getNameForDiagnostic(OS, Policy: Ctx.getPrintingPolicy(),
16899 /*Qualified=*/true);
16900 return Name;
16901 });
16902
16903 Expr::EvalStatus Status;
16904 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16905 Info.InConstantContext = true;
16906
16907 LValue ThisVal;
16908 const LValue *ThisPtr = nullptr;
16909 if (This) {
16910#ifndef NDEBUG
16911 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16912 assert(MD && "Don't provide `this` for non-methods.");
16913 assert(MD->isImplicitObjectMemberFunction() &&
16914 "Don't provide `this` for methods without an implicit object.");
16915#endif
16916 if (!This->isValueDependent() &&
16917 EvaluateObjectArgument(Info, Object: This, This&: ThisVal) &&
16918 !Info.EvalStatus.HasSideEffects)
16919 ThisPtr = &ThisVal;
16920
16921 // Ignore any side-effects from a failed evaluation. This is safe because
16922 // they can't interfere with any other argument evaluation.
16923 Info.EvalStatus.HasSideEffects = false;
16924 }
16925
16926 CallRef Call = Info.CurrentCall->createCall(Callee);
16927 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16928 I != E; ++I) {
16929 unsigned Idx = I - Args.begin();
16930 if (Idx >= Callee->getNumParams())
16931 break;
16932 const ParmVarDecl *PVD = Callee->getParamDecl(i: Idx);
16933 if ((*I)->isValueDependent() ||
16934 !EvaluateCallArg(PVD, Arg: *I, Call, Info) ||
16935 Info.EvalStatus.HasSideEffects) {
16936 // If evaluation fails, throw away the argument entirely.
16937 if (APValue *Slot = Info.getParamSlot(Call, PVD))
16938 *Slot = APValue();
16939 }
16940
16941 // Ignore any side-effects from a failed evaluation. This is safe because
16942 // they can't interfere with any other argument evaluation.
16943 Info.EvalStatus.HasSideEffects = false;
16944 }
16945
16946 // Parameter cleanups happen in the caller and are not part of this
16947 // evaluation.
16948 Info.discardCleanups();
16949 Info.EvalStatus.HasSideEffects = false;
16950
16951 // Build fake call to Callee.
16952 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
16953 Call);
16954 // FIXME: Missing ExprWithCleanups in enable_if conditions?
16955 FullExpressionRAII Scope(Info);
16956 return Evaluate(Result&: Value, Info, E: this) && Scope.destroy() &&
16957 !Info.EvalStatus.HasSideEffects;
16958}
16959
16960bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16961 SmallVectorImpl<
16962 PartialDiagnosticAt> &Diags) {
16963 // FIXME: It would be useful to check constexpr function templates, but at the
16964 // moment the constant expression evaluator cannot cope with the non-rigorous
16965 // ASTs which we build for dependent expressions.
16966 if (FD->isDependentContext())
16967 return true;
16968
16969 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16970 std::string Name;
16971 llvm::raw_string_ostream OS(Name);
16972 FD->getNameForDiagnostic(OS, Policy: FD->getASTContext().getPrintingPolicy(),
16973 /*Qualified=*/true);
16974 return Name;
16975 });
16976
16977 Expr::EvalStatus Status;
16978 Status.Diag = &Diags;
16979
16980 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16981 Info.InConstantContext = true;
16982 Info.CheckingPotentialConstantExpression = true;
16983
16984 // The constexpr VM attempts to compile all methods to bytecode here.
16985 if (Info.EnableNewConstInterp) {
16986 Info.Ctx.getInterpContext().isPotentialConstantExpr(Parent&: Info, FnDecl: FD);
16987 return Diags.empty();
16988 }
16989
16990 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
16991 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16992
16993 // Fabricate an arbitrary expression on the stack and pretend that it
16994 // is a temporary being used as the 'this' pointer.
16995 LValue This;
16996 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(Decl: RD) : Info.Ctx.IntTy);
16997 This.set(B: {&VIE, Info.CurrentCall->Index});
16998
16999 ArrayRef<const Expr*> Args;
17000
17001 APValue Scratch;
17002 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: FD)) {
17003 // Evaluate the call as a constant initializer, to allow the construction
17004 // of objects of non-literal types.
17005 Info.setEvaluatingDecl(Base: This.getLValueBase(), Value&: Scratch);
17006 HandleConstructorCall(E: &VIE, This, Args, Definition: CD, Info, Result&: Scratch);
17007 } else {
17008 SourceLocation Loc = FD->getLocation();
17009 HandleFunctionCall(
17010 CallLoc: Loc, Callee: FD, This: (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17011 E: &VIE, Args, Call: CallRef(), Body: FD->getBody(), Info, Result&: Scratch,
17012 /*ResultSlot=*/nullptr);
17013 }
17014
17015 return Diags.empty();
17016}
17017
17018bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
17019 const FunctionDecl *FD,
17020 SmallVectorImpl<
17021 PartialDiagnosticAt> &Diags) {
17022 assert(!E->isValueDependent() &&
17023 "Expression evaluator can't be called on a dependent expression.");
17024
17025 Expr::EvalStatus Status;
17026 Status.Diag = &Diags;
17027
17028 EvalInfo Info(FD->getASTContext(), Status,
17029 EvalInfo::EM_ConstantExpressionUnevaluated);
17030 Info.InConstantContext = true;
17031 Info.CheckingPotentialConstantExpression = true;
17032
17033 // Fabricate a call stack frame to give the arguments a plausible cover story.
17034 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17035 /*CallExpr=*/nullptr, CallRef());
17036
17037 APValue ResultScratch;
17038 Evaluate(Result&: ResultScratch, Info, E);
17039 return Diags.empty();
17040}
17041
17042bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17043 unsigned Type) const {
17044 if (!getType()->isPointerType())
17045 return false;
17046
17047 Expr::EvalStatus Status;
17048 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17049 return tryEvaluateBuiltinObjectSize(E: this, Type, Info, Size&: Result);
17050}
17051
17052static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17053 EvalInfo &Info, std::string *StringResult) {
17054 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17055 return false;
17056
17057 LValue String;
17058
17059 if (!EvaluatePointer(E, Result&: String, Info))
17060 return false;
17061
17062 QualType CharTy = E->getType()->getPointeeType();
17063
17064 // Fast path: if it's a string literal, search the string value.
17065 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17066 Val: String.getLValueBase().dyn_cast<const Expr *>())) {
17067 StringRef Str = S->getBytes();
17068 int64_t Off = String.Offset.getQuantity();
17069 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17070 S->getCharByteWidth() == 1 &&
17071 // FIXME: Add fast-path for wchar_t too.
17072 Info.Ctx.hasSameUnqualifiedType(T1: CharTy, T2: Info.Ctx.CharTy)) {
17073 Str = Str.substr(Start: Off);
17074
17075 StringRef::size_type Pos = Str.find(C: 0);
17076 if (Pos != StringRef::npos)
17077 Str = Str.substr(Start: 0, N: Pos);
17078
17079 Result = Str.size();
17080 if (StringResult)
17081 *StringResult = Str;
17082 return true;
17083 }
17084
17085 // Fall through to slow path.
17086 }
17087
17088 // Slow path: scan the bytes of the string looking for the terminating 0.
17089 for (uint64_t Strlen = 0; /**/; ++Strlen) {
17090 APValue Char;
17091 if (!handleLValueToRValueConversion(Info, Conv: E, Type: CharTy, LVal: String, RVal&: Char) ||
17092 !Char.isInt())
17093 return false;
17094 if (!Char.getInt()) {
17095 Result = Strlen;
17096 return true;
17097 } else if (StringResult)
17098 StringResult->push_back(c: Char.getInt().getExtValue());
17099 if (!HandleLValueArrayAdjustment(Info, E, LVal&: String, EltTy: CharTy, Adjustment: 1))
17100 return false;
17101 }
17102}
17103
17104std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
17105 Expr::EvalStatus Status;
17106 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17107 uint64_t Result;
17108 std::string StringResult;
17109
17110 if (EvaluateBuiltinStrLen(E: this, Result, Info, StringResult: &StringResult))
17111 return StringResult;
17112 return {};
17113}
17114
17115bool Expr::EvaluateCharRangeAsString(std::string &Result,
17116 const Expr *SizeExpression,
17117 const Expr *PtrExpression, ASTContext &Ctx,
17118 EvalResult &Status) const {
17119 LValue String;
17120 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17121 Info.InConstantContext = true;
17122
17123 FullExpressionRAII Scope(Info);
17124 APSInt SizeValue;
17125 if (!::EvaluateInteger(E: SizeExpression, Result&: SizeValue, Info))
17126 return false;
17127
17128 uint64_t Size = SizeValue.getZExtValue();
17129
17130 if (!::EvaluatePointer(E: PtrExpression, Result&: String, Info))
17131 return false;
17132
17133 QualType CharTy = PtrExpression->getType()->getPointeeType();
17134 for (uint64_t I = 0; I < Size; ++I) {
17135 APValue Char;
17136 if (!handleLValueToRValueConversion(Info, Conv: PtrExpression, Type: CharTy, LVal: String,
17137 RVal&: Char))
17138 return false;
17139
17140 APSInt C = Char.getInt();
17141 Result.push_back(c: static_cast<char>(C.getExtValue()));
17142 if (!HandleLValueArrayAdjustment(Info, E: PtrExpression, LVal&: String, EltTy: CharTy, Adjustment: 1))
17143 return false;
17144 }
17145 if (!Scope.destroy())
17146 return false;
17147
17148 if (!CheckMemoryLeaks(Info))
17149 return false;
17150
17151 return true;
17152}
17153
17154bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17155 Expr::EvalStatus Status;
17156 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17157 return EvaluateBuiltinStrLen(E: this, Result, Info);
17158}
17159