clang 22.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
47#include "clang/AST/OSLog.h"
51#include "clang/AST/Type.h"
52#include "clang/AST/TypeLoc.h"
57#include "llvm/ADT/APFixedPoint.h"
58#include "llvm/ADT/Sequence.h"
59#include "llvm/ADT/SmallBitVector.h"
60#include "llvm/ADT/StringExtras.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/Debug.h"
63#include "llvm/Support/SaveAndRestore.h"
64#include "llvm/Support/SipHash.h"
65#include "llvm/Support/TimeProfiler.h"
66#include "llvm/Support/raw_ostream.h"
67#include <cstring>
68#include <functional>
69#include <limits>
70#include <optional>
71
72#define DEBUG_TYPE "exprconstant"
73
74using namespace clang;
75using llvm::APFixedPoint;
76using llvm::APInt;
77using llvm::APSInt;
78using llvm::APFloat;
79using llvm::FixedPointSemantics;
80
81namespace {
82 struct LValue;
83 class CallStackFrame;
84 class EvalInfo;
85
86 using SourceLocExprScopeGuard =
88
89 static QualType getType(APValue::LValueBase B) {
90 return B.getType();
91 }
92
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// field declaration.
95 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
96 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
97 }
98 /// Get an LValue path entry, which is known to not be an array index, as a
99 /// base class declaration.
100 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
101 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
102 }
103 /// Determine whether this LValue path entry for a base class names a virtual
104 /// base class.
105 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
106 return E.getAsBaseOrMember().getInt();
107 }
108
109 /// Given an expression, determine the type used to store the result of
110 /// evaluating that expression.
111 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
112 if (E->isPRValue())
113 return E->getType();
114 return Ctx.getLValueReferenceType(E->getType());
115 }
116
117 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
118 /// This will look through a single cast.
119 ///
120 /// Returns null if we couldn't unwrap a function with alloc_size.
121 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
122 if (!E->getType()->isPointerType())
123 return nullptr;
124
125 E = E->IgnoreParens();
126 // If we're doing a variable assignment from e.g. malloc(N), there will
127 // probably be a cast of some kind. In exotic cases, we might also see a
128 // top-level ExprWithCleanups. Ignore them either way.
129 if (const auto *FE = dyn_cast<FullExpr>(E))
130 E = FE->getSubExpr()->IgnoreParens();
131
132 if (const auto *Cast = dyn_cast<CastExpr>(E))
133 E = Cast->getSubExpr()->IgnoreParens();
134
135 if (const auto *CE = dyn_cast<CallExpr>(E))
136 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
137 return nullptr;
138 }
139
140 /// Determines whether or not the given Base contains a call to a function
141 /// with the alloc_size attribute.
142 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
143 const auto *E = Base.dyn_cast<const Expr *>();
144 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
145 }
146
147 /// Determines whether the given kind of constant expression is only ever
148 /// used for name mangling. If so, it's permitted to reference things that we
149 /// can't generate code for (in particular, dllimported functions).
150 static bool isForManglingOnly(ConstantExprKind Kind) {
151 switch (Kind) {
152 case ConstantExprKind::Normal:
153 case ConstantExprKind::ClassTemplateArgument:
154 case ConstantExprKind::ImmediateInvocation:
155 // Note that non-type template arguments of class type are emitted as
156 // template parameter objects.
157 return false;
158
159 case ConstantExprKind::NonClassTemplateArgument:
160 return true;
161 }
162 llvm_unreachable("unknown ConstantExprKind");
163 }
164
165 static bool isTemplateArgument(ConstantExprKind Kind) {
166 switch (Kind) {
167 case ConstantExprKind::Normal:
168 case ConstantExprKind::ImmediateInvocation:
169 return false;
170
171 case ConstantExprKind::ClassTemplateArgument:
172 case ConstantExprKind::NonClassTemplateArgument:
173 return true;
174 }
175 llvm_unreachable("unknown ConstantExprKind");
176 }
177
178 /// The bound to claim that an array of unknown bound has.
179 /// The value in MostDerivedArraySize is undefined in this case. So, set it
180 /// to an arbitrary value that's likely to loudly break things if it's used.
181 static const uint64_t AssumedSizeForUnsizedArray =
182 std::numeric_limits<uint64_t>::max() / 2;
183
184 /// Determines if an LValue with the given LValueBase will have an unsized
185 /// array in its designator.
186 /// Find the path length and type of the most-derived subobject in the given
187 /// path, and find the size of the containing array, if any.
188 static unsigned
189 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191 uint64_t &ArraySize, QualType &Type, bool &IsArray,
192 bool &FirstEntryIsUnsizedArray) {
193 // This only accepts LValueBases from APValues, and APValues don't support
194 // arrays that lack size info.
195 assert(!isBaseAnAllocSizeCall(Base) &&
196 "Unsized arrays shouldn't appear here");
197 unsigned MostDerivedLength = 0;
198 // The type of Base is a reference type if the base is a constexpr-unknown
199 // variable. In that case, look through the reference type.
200 Type = getType(Base).getNonReferenceType();
201
202 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
203 if (Type->isArrayType()) {
204 const ArrayType *AT = Ctx.getAsArrayType(Type);
205 Type = AT->getElementType();
206 MostDerivedLength = I + 1;
207 IsArray = true;
208
209 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
210 ArraySize = CAT->getZExtSize();
211 } else {
212 assert(I == 0 && "unexpected unsized array designator");
213 FirstEntryIsUnsizedArray = true;
214 ArraySize = AssumedSizeForUnsizedArray;
215 }
216 } else if (Type->isAnyComplexType()) {
217 const ComplexType *CT = Type->castAs<ComplexType>();
218 Type = CT->getElementType();
219 ArraySize = 2;
220 MostDerivedLength = I + 1;
221 IsArray = true;
222 } else if (const auto *VT = Type->getAs<VectorType>()) {
223 Type = VT->getElementType();
224 ArraySize = VT->getNumElements();
225 MostDerivedLength = I + 1;
226 IsArray = true;
227 } else if (const FieldDecl *FD = getAsField(Path[I])) {
228 Type = FD->getType();
229 ArraySize = 0;
230 MostDerivedLength = I + 1;
231 IsArray = false;
232 } else {
233 // Path[I] describes a base class.
234 ArraySize = 0;
235 IsArray = false;
236 }
237 }
238 return MostDerivedLength;
239 }
240
241 /// A path from a glvalue to a subobject of that glvalue.
242 struct SubobjectDesignator {
243 /// True if the subobject was named in a manner not supported by C++11. Such
244 /// lvalues can still be folded, but they are not core constant expressions
245 /// and we cannot perform lvalue-to-rvalue conversions on them.
246 LLVM_PREFERRED_TYPE(bool)
247 unsigned Invalid : 1;
248
249 /// Is this a pointer one past the end of an object?
250 LLVM_PREFERRED_TYPE(bool)
251 unsigned IsOnePastTheEnd : 1;
252
253 /// Indicator of whether the first entry is an unsized array.
254 LLVM_PREFERRED_TYPE(bool)
255 unsigned FirstEntryIsAnUnsizedArray : 1;
256
257 /// Indicator of whether the most-derived object is an array element.
258 LLVM_PREFERRED_TYPE(bool)
259 unsigned MostDerivedIsArrayElement : 1;
260
261 /// The length of the path to the most-derived object of which this is a
262 /// subobject.
263 unsigned MostDerivedPathLength : 28;
264
265 /// The size of the array of which the most-derived object is an element.
266 /// This will always be 0 if the most-derived object is not an array
267 /// element. 0 is not an indicator of whether or not the most-derived object
268 /// is an array, however, because 0-length arrays are allowed.
269 ///
270 /// If the current array is an unsized array, the value of this is
271 /// undefined.
272 uint64_t MostDerivedArraySize;
273 /// The type of the most derived object referred to by this address.
274 QualType MostDerivedType;
275
276 typedef APValue::LValuePathEntry PathEntry;
277
278 /// The entries on the path from the glvalue to the designated subobject.
280
281 SubobjectDesignator() : Invalid(true) {}
282
283 explicit SubobjectDesignator(QualType T)
284 : Invalid(false), IsOnePastTheEnd(false),
285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
286 MostDerivedPathLength(0), MostDerivedArraySize(0),
287 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
288
289 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
290 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
291 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
292 MostDerivedPathLength(0), MostDerivedArraySize(0) {
293 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
294 if (!Invalid) {
295 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
296 llvm::append_range(Entries, V.getLValuePath());
297 if (V.getLValueBase()) {
298 bool IsArray = false;
299 bool FirstIsUnsizedArray = false;
300 MostDerivedPathLength = findMostDerivedSubobject(
301 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
302 MostDerivedType, IsArray, FirstIsUnsizedArray);
303 MostDerivedIsArrayElement = IsArray;
304 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
305 }
306 }
307 }
308
309 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
310 unsigned NewLength) {
311 if (Invalid)
312 return;
313
314 assert(Base && "cannot truncate path for null pointer");
315 assert(NewLength <= Entries.size() && "not a truncation");
316
317 if (NewLength == Entries.size())
318 return;
319 Entries.resize(NewLength);
320
321 bool IsArray = false;
322 bool FirstIsUnsizedArray = false;
323 MostDerivedPathLength = findMostDerivedSubobject(
324 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
325 FirstIsUnsizedArray);
326 MostDerivedIsArrayElement = IsArray;
327 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
328 }
329
330 void setInvalid() {
331 Invalid = true;
332 Entries.clear();
333 }
334
335 /// Determine whether the most derived subobject is an array without a
336 /// known bound.
337 bool isMostDerivedAnUnsizedArray() const {
338 assert(!Invalid && "Calling this makes no sense on invalid designators");
339 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
340 }
341
342 /// Determine what the most derived array's size is. Results in an assertion
343 /// failure if the most derived array lacks a size.
344 uint64_t getMostDerivedArraySize() const {
345 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
346 return MostDerivedArraySize;
347 }
348
349 /// Determine whether this is a one-past-the-end pointer.
350 bool isOnePastTheEnd() const {
351 assert(!Invalid);
352 if (IsOnePastTheEnd)
353 return true;
354 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
355 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
356 MostDerivedArraySize)
357 return true;
358 return false;
359 }
360
361 /// Get the range of valid index adjustments in the form
362 /// {maximum value that can be subtracted from this pointer,
363 /// maximum value that can be added to this pointer}
364 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
365 if (Invalid || isMostDerivedAnUnsizedArray())
366 return {0, 0};
367
368 // [expr.add]p4: For the purposes of these operators, a pointer to a
369 // nonarray object behaves the same as a pointer to the first element of
370 // an array of length one with the type of the object as its element type.
371 bool IsArray = MostDerivedPathLength == Entries.size() &&
372 MostDerivedIsArrayElement;
373 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
374 : (uint64_t)IsOnePastTheEnd;
375 uint64_t ArraySize =
376 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
377 return {ArrayIndex, ArraySize - ArrayIndex};
378 }
379
380 /// Check that this refers to a valid subobject.
381 bool isValidSubobject() const {
382 if (Invalid)
383 return false;
384 return !isOnePastTheEnd();
385 }
386 /// Check that this refers to a valid subobject, and if not, produce a
387 /// relevant diagnostic and set the designator as invalid.
388 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
389
390 /// Get the type of the designated object.
391 QualType getType(ASTContext &Ctx) const {
392 assert(!Invalid && "invalid designator has no subobject type");
393 return MostDerivedPathLength == Entries.size()
394 ? MostDerivedType
395 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
396 }
397
398 /// Update this designator to refer to the first element within this array.
399 void addArrayUnchecked(const ConstantArrayType *CAT) {
400 Entries.push_back(PathEntry::ArrayIndex(0));
401
402 // This is a most-derived object.
403 MostDerivedType = CAT->getElementType();
404 MostDerivedIsArrayElement = true;
405 MostDerivedArraySize = CAT->getZExtSize();
406 MostDerivedPathLength = Entries.size();
407 }
408 /// Update this designator to refer to the first element within the array of
409 /// elements of type T. This is an array of unknown size.
410 void addUnsizedArrayUnchecked(QualType ElemTy) {
411 Entries.push_back(PathEntry::ArrayIndex(0));
412
413 MostDerivedType = ElemTy;
414 MostDerivedIsArrayElement = true;
415 // The value in MostDerivedArraySize is undefined in this case. So, set it
416 // to an arbitrary value that's likely to loudly break things if it's
417 // used.
418 MostDerivedArraySize = AssumedSizeForUnsizedArray;
419 MostDerivedPathLength = Entries.size();
420 }
421 /// Update this designator to refer to the given base or member of this
422 /// object.
423 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
424 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
425
426 // If this isn't a base class, it's a new most-derived object.
427 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
428 MostDerivedType = FD->getType();
429 MostDerivedIsArrayElement = false;
430 MostDerivedArraySize = 0;
431 MostDerivedPathLength = Entries.size();
432 }
433 }
434 /// Update this designator to refer to the given complex component.
435 void addComplexUnchecked(QualType EltTy, bool Imag) {
436 Entries.push_back(PathEntry::ArrayIndex(Imag));
437
438 // This is technically a most-derived object, though in practice this
439 // is unlikely to matter.
440 MostDerivedType = EltTy;
441 MostDerivedIsArrayElement = true;
442 MostDerivedArraySize = 2;
443 MostDerivedPathLength = Entries.size();
444 }
445
446 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
447 uint64_t Idx) {
448 Entries.push_back(PathEntry::ArrayIndex(Idx));
449 MostDerivedType = EltTy;
450 MostDerivedPathLength = Entries.size();
451 MostDerivedArraySize = 0;
452 MostDerivedIsArrayElement = false;
453 }
454
455 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
456 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
457 const APSInt &N);
458 /// Add N to the address of this subobject.
459 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
460 };
461
462 /// A scope at the end of which an object can need to be destroyed.
463 enum class ScopeKind {
464 Block,
465 FullExpression,
466 Call
467 };
468
469 /// A reference to a particular call and its arguments.
470 struct CallRef {
471 CallRef() : OrigCallee(), CallIndex(0), Version() {}
472 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
473 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
474
475 explicit operator bool() const { return OrigCallee; }
476
477 /// Get the parameter that the caller initialized, corresponding to the
478 /// given parameter in the callee.
479 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
480 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
481 : PVD;
482 }
483
484 /// The callee at the point where the arguments were evaluated. This might
485 /// be different from the actual callee (a different redeclaration, or a
486 /// virtual override), but this function's parameters are the ones that
487 /// appear in the parameter map.
488 const FunctionDecl *OrigCallee;
489 /// The call index of the frame that holds the argument values.
490 unsigned CallIndex;
491 /// The version of the parameters corresponding to this call.
492 unsigned Version;
493 };
494
495 /// A stack frame in the constexpr call stack.
496 class CallStackFrame : public interp::Frame {
497 public:
498 EvalInfo &Info;
499
500 /// Parent - The caller of this stack frame.
501 CallStackFrame *Caller;
502
503 /// Callee - The function which was called.
504 const FunctionDecl *Callee;
505
506 /// This - The binding for the this pointer in this call, if any.
507 const LValue *This;
508
509 /// CallExpr - The syntactical structure of member function calls
510 const Expr *CallExpr;
511
512 /// Information on how to find the arguments to this call. Our arguments
513 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
514 /// key and this value as the version.
515 CallRef Arguments;
516
517 /// Source location information about the default argument or default
518 /// initializer expression we're evaluating, if any.
519 CurrentSourceLocExprScope CurSourceLocExprScope;
520
521 // Note that we intentionally use std::map here so that references to
522 // values are stable.
523 typedef std::pair<const void *, unsigned> MapKeyTy;
524 typedef std::map<MapKeyTy, APValue> MapTy;
525 /// Temporaries - Temporary lvalues materialized within this stack frame.
526 MapTy Temporaries;
527
528 /// CallRange - The source range of the call expression for this call.
529 SourceRange CallRange;
530
531 /// Index - The call index of this call.
532 unsigned Index;
533
534 /// The stack of integers for tracking version numbers for temporaries.
535 SmallVector<unsigned, 2> TempVersionStack = {1};
536 unsigned CurTempVersion = TempVersionStack.back();
537
538 unsigned getTempVersion() const { return TempVersionStack.back(); }
539
540 void pushTempVersion() {
541 TempVersionStack.push_back(++CurTempVersion);
542 }
543
544 void popTempVersion() {
545 TempVersionStack.pop_back();
546 }
547
548 CallRef createCall(const FunctionDecl *Callee) {
549 return {Callee, Index, ++CurTempVersion};
550 }
551
552 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
553 // on the overall stack usage of deeply-recursing constexpr evaluations.
554 // (We should cache this map rather than recomputing it repeatedly.)
555 // But let's try this and see how it goes; we can look into caching the map
556 // as a later change.
557
558 /// LambdaCaptureFields - Mapping from captured variables/this to
559 /// corresponding data members in the closure class.
560 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
561 FieldDecl *LambdaThisCaptureField = nullptr;
562
563 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
564 const FunctionDecl *Callee, const LValue *This,
565 const Expr *CallExpr, CallRef Arguments);
566 ~CallStackFrame();
567
568 // Return the temporary for Key whose version number is Version.
569 APValue *getTemporary(const void *Key, unsigned Version) {
570 MapKeyTy KV(Key, Version);
571 auto LB = Temporaries.lower_bound(KV);
572 if (LB != Temporaries.end() && LB->first == KV)
573 return &LB->second;
574 return nullptr;
575 }
576
577 // Return the current temporary for Key in the map.
578 APValue *getCurrentTemporary(const void *Key) {
579 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
580 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
581 return &std::prev(UB)->second;
582 return nullptr;
583 }
584
585 // Return the version number of the current temporary for Key.
586 unsigned getCurrentTemporaryVersion(const void *Key) const {
587 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
588 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
589 return std::prev(UB)->first.second;
590 return 0;
591 }
592
593 /// Allocate storage for an object of type T in this stack frame.
594 /// Populates LV with a handle to the created object. Key identifies
595 /// the temporary within the stack frame, and must not be reused without
596 /// bumping the temporary version number.
597 template<typename KeyT>
598 APValue &createTemporary(const KeyT *Key, QualType T,
599 ScopeKind Scope, LValue &LV);
600
601 /// Allocate storage for a parameter of a function call made in this frame.
602 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
603
604 void describe(llvm::raw_ostream &OS) const override;
605
606 Frame *getCaller() const override { return Caller; }
607 SourceRange getCallRange() const override { return CallRange; }
608 const FunctionDecl *getCallee() const override { return Callee; }
609
610 bool isStdFunction() const {
611 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
612 if (DC->isStdNamespace())
613 return true;
614 return false;
615 }
616
617 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
618 /// permitted. See MSConstexprDocs for description of permitted contexts.
619 bool CanEvalMSConstexpr = false;
620
621 private:
622 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
623 ScopeKind Scope);
624 };
625
626 /// Temporarily override 'this'.
627 class ThisOverrideRAII {
628 public:
629 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
630 : Frame(Frame), OldThis(Frame.This) {
631 if (Enable)
632 Frame.This = NewThis;
633 }
634 ~ThisOverrideRAII() {
635 Frame.This = OldThis;
636 }
637 private:
638 CallStackFrame &Frame;
639 const LValue *OldThis;
640 };
641
642 // A shorthand time trace scope struct, prints source range, for example
643 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
644 class ExprTimeTraceScope {
645 public:
646 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
647 : TimeScope(Name, [E, &Ctx] {
648 return E->getSourceRange().printToString(Ctx.getSourceManager());
649 }) {}
650
651 private:
652 llvm::TimeTraceScope TimeScope;
653 };
654
655 /// RAII object used to change the current ability of
656 /// [[msvc::constexpr]] evaulation.
657 struct MSConstexprContextRAII {
658 CallStackFrame &Frame;
659 bool OldValue;
660 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
661 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
662 Frame.CanEvalMSConstexpr = Value;
663 }
664
665 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
666 };
667}
668
669static bool HandleDestruction(EvalInfo &Info, const Expr *E,
670 const LValue &This, QualType ThisType);
671static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
673 QualType T);
674
675namespace {
676 /// A cleanup, and a flag indicating whether it is lifetime-extended.
677 class Cleanup {
678 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
680 QualType T;
681
682 public:
683 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
684 ScopeKind Scope)
685 : Value(Val, Scope), Base(Base), T(T) {}
686
687 /// Determine whether this cleanup should be performed at the end of the
688 /// given kind of scope.
689 bool isDestroyedAtEndOf(ScopeKind K) const {
690 return (int)Value.getInt() >= (int)K;
691 }
692 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
693 if (RunDestructors) {
695 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
696 Loc = VD->getLocation();
697 else if (const Expr *E = Base.dyn_cast<const Expr*>())
698 Loc = E->getExprLoc();
699 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
700 }
701 *Value.getPointer() = APValue();
702 return true;
703 }
704
705 bool hasSideEffect() {
706 return T.isDestructedType();
707 }
708 };
709
710 /// A reference to an object whose construction we are currently evaluating.
711 struct ObjectUnderConstruction {
714 friend bool operator==(const ObjectUnderConstruction &LHS,
715 const ObjectUnderConstruction &RHS) {
716 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
717 }
718 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
719 return llvm::hash_combine(Obj.Base, Obj.Path);
720 }
721 };
722 enum class ConstructionPhase {
723 None,
724 Bases,
725 AfterBases,
726 AfterFields,
727 Destroying,
728 DestroyingBases
729 };
730}
731
732namespace llvm {
733template<> struct DenseMapInfo<ObjectUnderConstruction> {
734 using Base = DenseMapInfo<APValue::LValueBase>;
735 static ObjectUnderConstruction getEmptyKey() {
736 return {Base::getEmptyKey(), {}}; }
737 static ObjectUnderConstruction getTombstoneKey() {
738 return {Base::getTombstoneKey(), {}};
739 }
740 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
741 return hash_value(Object);
742 }
743 static bool isEqual(const ObjectUnderConstruction &LHS,
744 const ObjectUnderConstruction &RHS) {
745 return LHS == RHS;
746 }
747};
748}
749
750namespace {
751 /// A dynamically-allocated heap object.
752 struct DynAlloc {
753 /// The value of this heap-allocated object.
755 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
756 /// or a CallExpr (the latter is for direct calls to operator new inside
757 /// std::allocator<T>::allocate).
758 const Expr *AllocExpr = nullptr;
759
760 enum Kind {
761 New,
762 ArrayNew,
763 StdAllocator
764 };
765
766 /// Get the kind of the allocation. This must match between allocation
767 /// and deallocation.
768 Kind getKind() const {
769 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
770 return NE->isArray() ? ArrayNew : New;
771 assert(isa<CallExpr>(AllocExpr));
772 return StdAllocator;
773 }
774 };
775
776 struct DynAllocOrder {
777 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
778 return L.getIndex() < R.getIndex();
779 }
780 };
781
782 /// EvalInfo - This is a private struct used by the evaluator to capture
783 /// information about a subexpression as it is folded. It retains information
784 /// about the AST context, but also maintains information about the folded
785 /// expression.
786 ///
787 /// If an expression could be evaluated, it is still possible it is not a C
788 /// "integer constant expression" or constant expression. If not, this struct
789 /// captures information about how and why not.
790 ///
791 /// One bit of information passed *into* the request for constant folding
792 /// indicates whether the subexpression is "evaluated" or not according to C
793 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
794 /// evaluate the expression regardless of what the RHS is, but C only allows
795 /// certain things in certain situations.
796 class EvalInfo : public interp::State {
797 public:
798 ASTContext &Ctx;
799
800 /// EvalStatus - Contains information about the evaluation.
801 Expr::EvalStatus &EvalStatus;
802
803 /// CurrentCall - The top of the constexpr call stack.
804 CallStackFrame *CurrentCall;
805
806 /// CallStackDepth - The number of calls in the call stack right now.
807 unsigned CallStackDepth;
808
809 /// NextCallIndex - The next call index to assign.
810 unsigned NextCallIndex;
811
812 /// StepsLeft - The remaining number of evaluation steps we're permitted
813 /// to perform. This is essentially a limit for the number of statements
814 /// we will evaluate.
815 unsigned StepsLeft;
816
817 /// Enable the experimental new constant interpreter. If an expression is
818 /// not supported by the interpreter, an error is triggered.
819 bool EnableNewConstInterp;
820
821 /// BottomFrame - The frame in which evaluation started. This must be
822 /// initialized after CurrentCall and CallStackDepth.
823 CallStackFrame BottomFrame;
824
825 /// A stack of values whose lifetimes end at the end of some surrounding
826 /// evaluation frame.
828
829 /// EvaluatingDecl - This is the declaration whose initializer is being
830 /// evaluated, if any.
831 APValue::LValueBase EvaluatingDecl;
832
833 enum class EvaluatingDeclKind {
834 None,
835 /// We're evaluating the construction of EvaluatingDecl.
836 Ctor,
837 /// We're evaluating the destruction of EvaluatingDecl.
838 Dtor,
839 };
840 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
841
842 /// EvaluatingDeclValue - This is the value being constructed for the
843 /// declaration whose initializer is being evaluated, if any.
844 APValue *EvaluatingDeclValue;
845
846 /// Stack of loops and 'switch' statements which we're currently
847 /// breaking/continuing; null entries are used to mark unlabeled
848 /// break/continue.
849 SmallVector<const Stmt *> BreakContinueStack;
850
851 /// Set of objects that are currently being constructed.
852 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
853 ObjectsUnderConstruction;
854
855 /// Current heap allocations, along with the location where each was
856 /// allocated. We use std::map here because we need stable addresses
857 /// for the stored APValues.
858 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
859
860 /// The number of heap allocations performed so far in this evaluation.
861 unsigned NumHeapAllocs = 0;
862
863 struct EvaluatingConstructorRAII {
864 EvalInfo &EI;
865 ObjectUnderConstruction Object;
866 bool DidInsert;
867 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
868 bool HasBases)
869 : EI(EI), Object(Object) {
870 DidInsert =
871 EI.ObjectsUnderConstruction
872 .insert({Object, HasBases ? ConstructionPhase::Bases
873 : ConstructionPhase::AfterBases})
874 .second;
875 }
876 void finishedConstructingBases() {
877 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
878 }
879 void finishedConstructingFields() {
880 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
881 }
882 ~EvaluatingConstructorRAII() {
883 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
884 }
885 };
886
887 struct EvaluatingDestructorRAII {
888 EvalInfo &EI;
889 ObjectUnderConstruction Object;
890 bool DidInsert;
891 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
892 : EI(EI), Object(Object) {
893 DidInsert = EI.ObjectsUnderConstruction
894 .insert({Object, ConstructionPhase::Destroying})
895 .second;
896 }
897 void startedDestroyingBases() {
898 EI.ObjectsUnderConstruction[Object] =
899 ConstructionPhase::DestroyingBases;
900 }
901 ~EvaluatingDestructorRAII() {
902 if (DidInsert)
903 EI.ObjectsUnderConstruction.erase(Object);
904 }
905 };
906
907 ConstructionPhase
908 isEvaluatingCtorDtor(APValue::LValueBase Base,
910 return ObjectsUnderConstruction.lookup({Base, Path});
911 }
912
913 /// If we're currently speculatively evaluating, the outermost call stack
914 /// depth at which we can mutate state, otherwise 0.
915 unsigned SpeculativeEvaluationDepth = 0;
916
917 /// The current array initialization index, if we're performing array
918 /// initialization.
919 uint64_t ArrayInitIndex = -1;
920
921 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
922 /// notes attached to it will also be stored, otherwise they will not be.
923 bool HasActiveDiagnostic;
924
925 /// Have we emitted a diagnostic explaining why we couldn't constant
926 /// fold (not just why it's not strictly a constant expression)?
927 bool HasFoldFailureDiagnostic;
928
929 /// Whether we're checking that an expression is a potential constant
930 /// expression. If so, do not fail on constructs that could become constant
931 /// later on (such as a use of an undefined global).
932 bool CheckingPotentialConstantExpression = false;
933
934 /// Whether we're checking for an expression that has undefined behavior.
935 /// If so, we will produce warnings if we encounter an operation that is
936 /// always undefined.
937 ///
938 /// Note that we still need to evaluate the expression normally when this
939 /// is set; this is used when evaluating ICEs in C.
940 bool CheckingForUndefinedBehavior = false;
941
942 enum EvaluationMode {
943 /// Evaluate as a constant expression. Stop if we find that the expression
944 /// is not a constant expression.
945 EM_ConstantExpression,
946
947 /// Evaluate as a constant expression. Stop if we find that the expression
948 /// is not a constant expression. Some expressions can be retried in the
949 /// optimizer if we don't constant fold them here, but in an unevaluated
950 /// context we try to fold them immediately since the optimizer never
951 /// gets a chance to look at it.
952 EM_ConstantExpressionUnevaluated,
953
954 /// Fold the expression to a constant. Stop if we hit a side-effect that
955 /// we can't model.
956 EM_ConstantFold,
957
958 /// Evaluate in any way we know how. Don't worry about side-effects that
959 /// can't be modeled.
960 EM_IgnoreSideEffects,
961 } EvalMode;
962
963 /// Are we checking whether the expression is a potential constant
964 /// expression?
965 bool checkingPotentialConstantExpression() const override {
966 return CheckingPotentialConstantExpression;
967 }
968
969 /// Are we checking an expression for overflow?
970 // FIXME: We should check for any kind of undefined or suspicious behavior
971 // in such constructs, not just overflow.
972 bool checkingForUndefinedBehavior() const override {
973 return CheckingForUndefinedBehavior;
974 }
975
976 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
977 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
978 CallStackDepth(0), NextCallIndex(1),
979 StepsLeft(C.getLangOpts().ConstexprStepLimit),
980 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
981 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
982 /*This=*/nullptr,
983 /*CallExpr=*/nullptr, CallRef()),
984 EvaluatingDecl((const ValueDecl *)nullptr),
985 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
986 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
987
988 ~EvalInfo() {
989 discardCleanups();
990 }
991
992 ASTContext &getASTContext() const override { return Ctx; }
993
994 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
995 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
996 EvaluatingDecl = Base;
997 IsEvaluatingDecl = EDK;
998 EvaluatingDeclValue = &Value;
999 }
1000
1001 bool CheckCallLimit(SourceLocation Loc) {
1002 // Don't perform any constexpr calls (other than the call we're checking)
1003 // when checking a potential constant expression.
1004 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1005 return false;
1006 if (NextCallIndex == 0) {
1007 // NextCallIndex has wrapped around.
1008 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1009 return false;
1010 }
1011 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1012 return true;
1013 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1014 << getLangOpts().ConstexprCallDepth;
1015 return false;
1016 }
1017
1018 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1019 uint64_t ElemCount, bool Diag) {
1020 // FIXME: GH63562
1021 // APValue stores array extents as unsigned,
1022 // so anything that is greater that unsigned would overflow when
1023 // constructing the array, we catch this here.
1024 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1025 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1026 if (Diag)
1027 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1028 return false;
1029 }
1030
1031 // FIXME: GH63562
1032 // Arrays allocate an APValue per element.
1033 // We use the number of constexpr steps as a proxy for the maximum size
1034 // of arrays to avoid exhausting the system resources, as initialization
1035 // of each element is likely to take some number of steps anyway.
1036 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1037 if (ElemCount > Limit) {
1038 if (Diag)
1039 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1040 << ElemCount << Limit;
1041 return false;
1042 }
1043 return true;
1044 }
1045
1046 std::pair<CallStackFrame *, unsigned>
1047 getCallFrameAndDepth(unsigned CallIndex) {
1048 assert(CallIndex && "no call index in getCallFrameAndDepth");
1049 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1050 // be null in this loop.
1051 unsigned Depth = CallStackDepth;
1052 CallStackFrame *Frame = CurrentCall;
1053 while (Frame->Index > CallIndex) {
1054 Frame = Frame->Caller;
1055 --Depth;
1056 }
1057 if (Frame->Index == CallIndex)
1058 return {Frame, Depth};
1059 return {nullptr, 0};
1060 }
1061
1062 bool nextStep(const Stmt *S) {
1063 if (!StepsLeft) {
1064 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1065 return false;
1066 }
1067 --StepsLeft;
1068 return true;
1069 }
1070
1071 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1072
1073 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1074 std::optional<DynAlloc *> Result;
1075 auto It = HeapAllocs.find(DA);
1076 if (It != HeapAllocs.end())
1077 Result = &It->second;
1078 return Result;
1079 }
1080
1081 /// Get the allocated storage for the given parameter of the given call.
1082 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1083 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1084 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1085 : nullptr;
1086 }
1087
1088 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1089 struct StdAllocatorCaller {
1090 unsigned FrameIndex;
1091 QualType ElemType;
1092 const Expr *Call;
1093 explicit operator bool() const { return FrameIndex != 0; };
1094 };
1095
1096 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1097 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1098 Call = Call->Caller) {
1099 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1100 if (!MD)
1101 continue;
1102 const IdentifierInfo *FnII = MD->getIdentifier();
1103 if (!FnII || !FnII->isStr(FnName))
1104 continue;
1105
1106 const auto *CTSD =
1107 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1108 if (!CTSD)
1109 continue;
1110
1111 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1112 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1113 if (CTSD->isInStdNamespace() && ClassII &&
1114 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1115 TAL[0].getKind() == TemplateArgument::Type)
1116 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1117 }
1118
1119 return {};
1120 }
1121
1122 void performLifetimeExtension() {
1123 // Disable the cleanups for lifetime-extended temporaries.
1124 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1125 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1126 });
1127 }
1128
1129 /// Throw away any remaining cleanups at the end of evaluation. If any
1130 /// cleanups would have had a side-effect, note that as an unmodeled
1131 /// side-effect and return false. Otherwise, return true.
1132 bool discardCleanups() {
1133 for (Cleanup &C : CleanupStack) {
1134 if (C.hasSideEffect() && !noteSideEffect()) {
1135 CleanupStack.clear();
1136 return false;
1137 }
1138 }
1139 CleanupStack.clear();
1140 return true;
1141 }
1142
1143 private:
1144 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1145 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1146
1147 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1148 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1149
1150 void setFoldFailureDiagnostic(bool Flag) override {
1151 HasFoldFailureDiagnostic = Flag;
1152 }
1153
1154 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1155
1156 // If we have a prior diagnostic, it will be noting that the expression
1157 // isn't a constant expression. This diagnostic is more important,
1158 // unless we require this evaluation to produce a constant expression.
1159 //
1160 // FIXME: We might want to show both diagnostics to the user in
1161 // EM_ConstantFold mode.
1162 bool hasPriorDiagnostic() override {
1163 if (!EvalStatus.Diag->empty()) {
1164 switch (EvalMode) {
1165 case EM_ConstantFold:
1166 case EM_IgnoreSideEffects:
1167 if (!HasFoldFailureDiagnostic)
1168 break;
1169 // We've already failed to fold something. Keep that diagnostic.
1170 [[fallthrough]];
1171 case EM_ConstantExpression:
1172 case EM_ConstantExpressionUnevaluated:
1173 setActiveDiagnostic(false);
1174 return true;
1175 }
1176 }
1177 return false;
1178 }
1179
1180 unsigned getCallStackDepth() override { return CallStackDepth; }
1181
1182 public:
1183 /// Should we continue evaluation after encountering a side-effect that we
1184 /// couldn't model?
1185 bool keepEvaluatingAfterSideEffect() const override {
1186 switch (EvalMode) {
1187 case EM_IgnoreSideEffects:
1188 return true;
1189
1190 case EM_ConstantExpression:
1191 case EM_ConstantExpressionUnevaluated:
1192 case EM_ConstantFold:
1193 // By default, assume any side effect might be valid in some other
1194 // evaluation of this expression from a different context.
1195 return checkingPotentialConstantExpression() ||
1196 checkingForUndefinedBehavior();
1197 }
1198 llvm_unreachable("Missed EvalMode case");
1199 }
1200
1201 /// Note that we have had a side-effect, and determine whether we should
1202 /// keep evaluating.
1203 bool noteSideEffect() override {
1204 EvalStatus.HasSideEffects = true;
1205 return keepEvaluatingAfterSideEffect();
1206 }
1207
1208 /// Should we continue evaluation after encountering undefined behavior?
1209 bool keepEvaluatingAfterUndefinedBehavior() {
1210 switch (EvalMode) {
1211 case EM_IgnoreSideEffects:
1212 case EM_ConstantFold:
1213 return true;
1214
1215 case EM_ConstantExpression:
1216 case EM_ConstantExpressionUnevaluated:
1217 return checkingForUndefinedBehavior();
1218 }
1219 llvm_unreachable("Missed EvalMode case");
1220 }
1221
1222 /// Note that we hit something that was technically undefined behavior, but
1223 /// that we can evaluate past it (such as signed overflow or floating-point
1224 /// division by zero.)
1225 bool noteUndefinedBehavior() override {
1226 EvalStatus.HasUndefinedBehavior = true;
1227 return keepEvaluatingAfterUndefinedBehavior();
1228 }
1229
1230 /// Should we continue evaluation as much as possible after encountering a
1231 /// construct which can't be reduced to a value?
1232 bool keepEvaluatingAfterFailure() const override {
1233 if (!StepsLeft)
1234 return false;
1235
1236 switch (EvalMode) {
1237 case EM_ConstantExpression:
1238 case EM_ConstantExpressionUnevaluated:
1239 case EM_ConstantFold:
1240 case EM_IgnoreSideEffects:
1241 return checkingPotentialConstantExpression() ||
1242 checkingForUndefinedBehavior();
1243 }
1244 llvm_unreachable("Missed EvalMode case");
1245 }
1246
1247 /// Notes that we failed to evaluate an expression that other expressions
1248 /// directly depend on, and determine if we should keep evaluating. This
1249 /// should only be called if we actually intend to keep evaluating.
1250 ///
1251 /// Call noteSideEffect() instead if we may be able to ignore the value that
1252 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1253 ///
1254 /// (Foo(), 1) // use noteSideEffect
1255 /// (Foo() || true) // use noteSideEffect
1256 /// Foo() + 1 // use noteFailure
1257 [[nodiscard]] bool noteFailure() {
1258 // Failure when evaluating some expression often means there is some
1259 // subexpression whose evaluation was skipped. Therefore, (because we
1260 // don't track whether we skipped an expression when unwinding after an
1261 // evaluation failure) every evaluation failure that bubbles up from a
1262 // subexpression implies that a side-effect has potentially happened. We
1263 // skip setting the HasSideEffects flag to true until we decide to
1264 // continue evaluating after that point, which happens here.
1265 bool KeepGoing = keepEvaluatingAfterFailure();
1266 EvalStatus.HasSideEffects |= KeepGoing;
1267 return KeepGoing;
1268 }
1269
1270 class ArrayInitLoopIndex {
1271 EvalInfo &Info;
1272 uint64_t OuterIndex;
1273
1274 public:
1275 ArrayInitLoopIndex(EvalInfo &Info)
1276 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1277 Info.ArrayInitIndex = 0;
1278 }
1279 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1280
1281 operator uint64_t&() { return Info.ArrayInitIndex; }
1282 };
1283 };
1284
1285 /// Object used to treat all foldable expressions as constant expressions.
1286 struct FoldConstant {
1287 EvalInfo &Info;
1288 bool Enabled;
1289 bool HadNoPriorDiags;
1290 EvalInfo::EvaluationMode OldMode;
1291
1292 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1293 : Info(Info),
1294 Enabled(Enabled),
1295 HadNoPriorDiags(Info.EvalStatus.Diag &&
1296 Info.EvalStatus.Diag->empty() &&
1297 !Info.EvalStatus.HasSideEffects),
1298 OldMode(Info.EvalMode) {
1299 if (Enabled)
1300 Info.EvalMode = EvalInfo::EM_ConstantFold;
1301 }
1302 void keepDiagnostics() { Enabled = false; }
1303 ~FoldConstant() {
1304 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1305 !Info.EvalStatus.HasSideEffects)
1306 Info.EvalStatus.Diag->clear();
1307 Info.EvalMode = OldMode;
1308 }
1309 };
1310
1311 /// RAII object used to set the current evaluation mode to ignore
1312 /// side-effects.
1313 struct IgnoreSideEffectsRAII {
1314 EvalInfo &Info;
1315 EvalInfo::EvaluationMode OldMode;
1316 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1317 : Info(Info), OldMode(Info.EvalMode) {
1318 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1319 }
1320
1321 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1322 };
1323
1324 /// RAII object used to optionally suppress diagnostics and side-effects from
1325 /// a speculative evaluation.
1326 class SpeculativeEvaluationRAII {
1327 EvalInfo *Info = nullptr;
1328 Expr::EvalStatus OldStatus;
1329 unsigned OldSpeculativeEvaluationDepth = 0;
1330
1331 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1332 Info = Other.Info;
1333 OldStatus = Other.OldStatus;
1334 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1335 Other.Info = nullptr;
1336 }
1337
1338 void maybeRestoreState() {
1339 if (!Info)
1340 return;
1341
1342 Info->EvalStatus = OldStatus;
1343 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1344 }
1345
1346 public:
1347 SpeculativeEvaluationRAII() = default;
1348
1349 SpeculativeEvaluationRAII(
1350 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1351 : Info(&Info), OldStatus(Info.EvalStatus),
1352 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1353 Info.EvalStatus.Diag = NewDiag;
1354 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1355 }
1356
1357 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1358 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1359 moveFromAndCancel(std::move(Other));
1360 }
1361
1362 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1363 maybeRestoreState();
1364 moveFromAndCancel(std::move(Other));
1365 return *this;
1366 }
1367
1368 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1369 };
1370
1371 /// RAII object wrapping a full-expression or block scope, and handling
1372 /// the ending of the lifetime of temporaries created within it.
1373 template<ScopeKind Kind>
1374 class ScopeRAII {
1375 EvalInfo &Info;
1376 unsigned OldStackSize;
1377 public:
1378 ScopeRAII(EvalInfo &Info)
1379 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1380 // Push a new temporary version. This is needed to distinguish between
1381 // temporaries created in different iterations of a loop.
1382 Info.CurrentCall->pushTempVersion();
1383 }
1384 bool destroy(bool RunDestructors = true) {
1385 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1386 OldStackSize = std::numeric_limits<unsigned>::max();
1387 return OK;
1388 }
1389 ~ScopeRAII() {
1390 if (OldStackSize != std::numeric_limits<unsigned>::max())
1391 destroy(false);
1392 // Body moved to a static method to encourage the compiler to inline away
1393 // instances of this class.
1394 Info.CurrentCall->popTempVersion();
1395 }
1396 private:
1397 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1398 unsigned OldStackSize) {
1399 assert(OldStackSize <= Info.CleanupStack.size() &&
1400 "running cleanups out of order?");
1401
1402 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1403 // for a full-expression scope.
1404 bool Success = true;
1405 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1406 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1407 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1408 Success = false;
1409 break;
1410 }
1411 }
1412 }
1413
1414 // Compact any retained cleanups.
1415 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1416 if (Kind != ScopeKind::Block)
1417 NewEnd =
1418 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1419 return C.isDestroyedAtEndOf(Kind);
1420 });
1421 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1422 return Success;
1423 }
1424 };
1425 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1426 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1427 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1428}
1429
1430bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1431 CheckSubobjectKind CSK) {
1432 if (Invalid)
1433 return false;
1434 if (isOnePastTheEnd()) {
1435 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1436 << CSK;
1437 setInvalid();
1438 return false;
1439 }
1440 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1441 // must actually be at least one array element; even a VLA cannot have a
1442 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1443 return true;
1444}
1445
1446void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1447 const Expr *E) {
1448 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1449 // Do not set the designator as invalid: we can represent this situation,
1450 // and correct handling of __builtin_object_size requires us to do so.
1451}
1452
1453void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1454 const Expr *E,
1455 const APSInt &N) {
1456 // If we're complaining, we must be able to statically determine the size of
1457 // the most derived array.
1458 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1459 Info.CCEDiag(E, diag::note_constexpr_array_index)
1460 << N << /*array*/ 0
1461 << static_cast<unsigned>(getMostDerivedArraySize());
1462 else
1463 Info.CCEDiag(E, diag::note_constexpr_array_index)
1464 << N << /*non-array*/ 1;
1465 setInvalid();
1466}
1467
1468CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1469 const FunctionDecl *Callee, const LValue *This,
1470 const Expr *CallExpr, CallRef Call)
1471 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1472 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1473 Index(Info.NextCallIndex++) {
1474 Info.CurrentCall = this;
1475 ++Info.CallStackDepth;
1476}
1477
1478CallStackFrame::~CallStackFrame() {
1479 assert(Info.CurrentCall == this && "calls retired out of order");
1480 --Info.CallStackDepth;
1481 Info.CurrentCall = Caller;
1482}
1483
1484static bool isRead(AccessKinds AK) {
1485 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1486 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1487}
1488
1490 switch (AK) {
1491 case AK_Read:
1493 case AK_MemberCall:
1494 case AK_DynamicCast:
1495 case AK_TypeId:
1497 case AK_Dereference:
1498 return false;
1499 case AK_Assign:
1500 case AK_Increment:
1501 case AK_Decrement:
1502 case AK_Construct:
1503 case AK_Destroy:
1504 return true;
1505 }
1506 llvm_unreachable("unknown access kind");
1507}
1508
1509static bool isAnyAccess(AccessKinds AK) {
1510 return isRead(AK) || isModification(AK);
1511}
1512
1513/// Is this an access per the C++ definition?
1515 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1516 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1517}
1518
1519/// Is this kind of access valid on an indeterminate object value?
1521 switch (AK) {
1522 case AK_Read:
1523 case AK_Increment:
1524 case AK_Decrement:
1525 case AK_Dereference:
1526 // These need the object's value.
1527 return false;
1528
1531 case AK_Assign:
1532 case AK_Construct:
1533 case AK_Destroy:
1534 // Construction and destruction don't need the value.
1535 return true;
1536
1537 case AK_MemberCall:
1538 case AK_DynamicCast:
1539 case AK_TypeId:
1540 // These aren't really meaningful on scalars.
1541 return true;
1542 }
1543 llvm_unreachable("unknown access kind");
1544}
1545
1546namespace {
1547 struct ComplexValue {
1548 private:
1549 bool IsInt;
1550
1551 public:
1552 APSInt IntReal, IntImag;
1553 APFloat FloatReal, FloatImag;
1554
1555 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1556
1557 void makeComplexFloat() { IsInt = false; }
1558 bool isComplexFloat() const { return !IsInt; }
1559 APFloat &getComplexFloatReal() { return FloatReal; }
1560 APFloat &getComplexFloatImag() { return FloatImag; }
1561
1562 void makeComplexInt() { IsInt = true; }
1563 bool isComplexInt() const { return IsInt; }
1564 APSInt &getComplexIntReal() { return IntReal; }
1565 APSInt &getComplexIntImag() { return IntImag; }
1566
1567 void moveInto(APValue &v) const {
1568 if (isComplexFloat())
1569 v = APValue(FloatReal, FloatImag);
1570 else
1571 v = APValue(IntReal, IntImag);
1572 }
1573 void setFrom(const APValue &v) {
1574 assert(v.isComplexFloat() || v.isComplexInt());
1575 if (v.isComplexFloat()) {
1576 makeComplexFloat();
1577 FloatReal = v.getComplexFloatReal();
1578 FloatImag = v.getComplexFloatImag();
1579 } else {
1580 makeComplexInt();
1581 IntReal = v.getComplexIntReal();
1582 IntImag = v.getComplexIntImag();
1583 }
1584 }
1585 };
1586
1587 struct LValue {
1589 CharUnits Offset;
1590 SubobjectDesignator Designator;
1591 bool IsNullPtr : 1;
1592 bool InvalidBase : 1;
1593 // P2280R4 track if we have an unknown reference or pointer.
1594 bool AllowConstexprUnknown = false;
1595
1596 const APValue::LValueBase getLValueBase() const { return Base; }
1597 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1598 CharUnits &getLValueOffset() { return Offset; }
1599 const CharUnits &getLValueOffset() const { return Offset; }
1600 SubobjectDesignator &getLValueDesignator() { return Designator; }
1601 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1602 bool isNullPointer() const { return IsNullPtr;}
1603
1604 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1605 unsigned getLValueVersion() const { return Base.getVersion(); }
1606
1607 void moveInto(APValue &V) const {
1608 if (Designator.Invalid)
1609 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1610 else {
1611 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1612 V = APValue(Base, Offset, Designator.Entries,
1613 Designator.IsOnePastTheEnd, IsNullPtr);
1614 }
1615 if (AllowConstexprUnknown)
1616 V.setConstexprUnknown();
1617 }
1618 void setFrom(ASTContext &Ctx, const APValue &V) {
1619 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1620 Base = V.getLValueBase();
1621 Offset = V.getLValueOffset();
1622 InvalidBase = false;
1623 Designator = SubobjectDesignator(Ctx, V);
1624 IsNullPtr = V.isNullPointer();
1625 AllowConstexprUnknown = V.allowConstexprUnknown();
1626 }
1627
1628 void set(APValue::LValueBase B, bool BInvalid = false) {
1629#ifndef NDEBUG
1630 // We only allow a few types of invalid bases. Enforce that here.
1631 if (BInvalid) {
1632 const auto *E = B.get<const Expr *>();
1633 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1634 "Unexpected type of invalid base");
1635 }
1636#endif
1637
1638 Base = B;
1639 Offset = CharUnits::fromQuantity(0);
1640 InvalidBase = BInvalid;
1641 Designator = SubobjectDesignator(getType(B));
1642 IsNullPtr = false;
1643 AllowConstexprUnknown = false;
1644 }
1645
1646 void setNull(ASTContext &Ctx, QualType PointerTy) {
1647 Base = (const ValueDecl *)nullptr;
1648 Offset =
1650 InvalidBase = false;
1651 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1652 IsNullPtr = true;
1653 AllowConstexprUnknown = false;
1654 }
1655
1656 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1657 set(B, true);
1658 }
1659
1660 std::string toString(ASTContext &Ctx, QualType T) const {
1661 APValue Printable;
1662 moveInto(Printable);
1663 return Printable.getAsString(Ctx, T);
1664 }
1665
1666 private:
1667 // Check that this LValue is not based on a null pointer. If it is, produce
1668 // a diagnostic and mark the designator as invalid.
1669 template <typename GenDiagType>
1670 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1671 if (Designator.Invalid)
1672 return false;
1673 if (IsNullPtr) {
1674 GenDiag();
1675 Designator.setInvalid();
1676 return false;
1677 }
1678 return true;
1679 }
1680
1681 public:
1682 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1683 CheckSubobjectKind CSK) {
1684 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1685 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1686 });
1687 }
1688
1689 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1690 AccessKinds AK) {
1691 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1692 if (AK == AccessKinds::AK_Dereference)
1693 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1694 else
1695 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1696 });
1697 }
1698
1699 // Check this LValue refers to an object. If not, set the designator to be
1700 // invalid and emit a diagnostic.
1701 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1702 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1703 Designator.checkSubobject(Info, E, CSK);
1704 }
1705
1706 void addDecl(EvalInfo &Info, const Expr *E,
1707 const Decl *D, bool Virtual = false) {
1708 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1709 Designator.addDeclUnchecked(D, Virtual);
1710 }
1711 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1712 if (!Designator.Entries.empty()) {
1713 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1714 Designator.setInvalid();
1715 return;
1716 }
1717 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1718 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1719 getType(Base).getNonReferenceType()->isArrayType());
1720 Designator.FirstEntryIsAnUnsizedArray = true;
1721 Designator.addUnsizedArrayUnchecked(ElemTy);
1722 }
1723 }
1724 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1725 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1726 Designator.addArrayUnchecked(CAT);
1727 }
1728 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1729 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1730 Designator.addComplexUnchecked(EltTy, Imag);
1731 }
1732 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1733 uint64_t Size, uint64_t Idx) {
1734 if (checkSubobject(Info, E, CSK_VectorElement))
1735 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1736 }
1737 void clearIsNullPointer() {
1738 IsNullPtr = false;
1739 }
1740 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1741 const APSInt &Index, CharUnits ElementSize) {
1742 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1743 // but we're not required to diagnose it and it's valid in C++.)
1744 if (!Index)
1745 return;
1746
1747 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1748 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1749 // offsets.
1750 uint64_t Offset64 = Offset.getQuantity();
1751 uint64_t ElemSize64 = ElementSize.getQuantity();
1752 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1753 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1754
1755 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1756 Designator.adjustIndex(Info, E, Index, *this);
1757 clearIsNullPointer();
1758 }
1759 void adjustOffset(CharUnits N) {
1760 Offset += N;
1761 if (N.getQuantity())
1762 clearIsNullPointer();
1763 }
1764 };
1765
1766 struct MemberPtr {
1767 MemberPtr() {}
1768 explicit MemberPtr(const ValueDecl *Decl)
1769 : DeclAndIsDerivedMember(Decl, false) {}
1770
1771 /// The member or (direct or indirect) field referred to by this member
1772 /// pointer, or 0 if this is a null member pointer.
1773 const ValueDecl *getDecl() const {
1774 return DeclAndIsDerivedMember.getPointer();
1775 }
1776 /// Is this actually a member of some type derived from the relevant class?
1777 bool isDerivedMember() const {
1778 return DeclAndIsDerivedMember.getInt();
1779 }
1780 /// Get the class which the declaration actually lives in.
1781 const CXXRecordDecl *getContainingRecord() const {
1782 return cast<CXXRecordDecl>(
1783 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1784 }
1785
1786 void moveInto(APValue &V) const {
1787 V = APValue(getDecl(), isDerivedMember(), Path);
1788 }
1789 void setFrom(const APValue &V) {
1790 assert(V.isMemberPointer());
1791 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1792 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1793 Path.clear();
1794 llvm::append_range(Path, V.getMemberPointerPath());
1795 }
1796
1797 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1798 /// whether the member is a member of some class derived from the class type
1799 /// of the member pointer.
1800 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1801 /// Path - The path of base/derived classes from the member declaration's
1802 /// class (exclusive) to the class type of the member pointer (inclusive).
1804
1805 /// Perform a cast towards the class of the Decl (either up or down the
1806 /// hierarchy).
1807 bool castBack(const CXXRecordDecl *Class) {
1808 assert(!Path.empty());
1809 const CXXRecordDecl *Expected;
1810 if (Path.size() >= 2)
1811 Expected = Path[Path.size() - 2];
1812 else
1813 Expected = getContainingRecord();
1814 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1815 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1816 // if B does not contain the original member and is not a base or
1817 // derived class of the class containing the original member, the result
1818 // of the cast is undefined.
1819 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1820 // (D::*). We consider that to be a language defect.
1821 return false;
1822 }
1823 Path.pop_back();
1824 return true;
1825 }
1826 /// Perform a base-to-derived member pointer cast.
1827 bool castToDerived(const CXXRecordDecl *Derived) {
1828 if (!getDecl())
1829 return true;
1830 if (!isDerivedMember()) {
1831 Path.push_back(Derived);
1832 return true;
1833 }
1834 if (!castBack(Derived))
1835 return false;
1836 if (Path.empty())
1837 DeclAndIsDerivedMember.setInt(false);
1838 return true;
1839 }
1840 /// Perform a derived-to-base member pointer cast.
1841 bool castToBase(const CXXRecordDecl *Base) {
1842 if (!getDecl())
1843 return true;
1844 if (Path.empty())
1845 DeclAndIsDerivedMember.setInt(true);
1846 if (isDerivedMember()) {
1847 Path.push_back(Base);
1848 return true;
1849 }
1850 return castBack(Base);
1851 }
1852 };
1853
1854 /// Compare two member pointers, which are assumed to be of the same type.
1855 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1856 if (!LHS.getDecl() || !RHS.getDecl())
1857 return !LHS.getDecl() && !RHS.getDecl();
1858 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1859 return false;
1860 return LHS.Path == RHS.Path;
1861 }
1862}
1863
1864void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1865 const LValue &LV) {
1866 if (Invalid || !N)
1867 return;
1868 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1869 if (isMostDerivedAnUnsizedArray()) {
1870 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1871 // Can't verify -- trust that the user is doing the right thing (or if
1872 // not, trust that the caller will catch the bad behavior).
1873 // FIXME: Should we reject if this overflows, at least?
1874 Entries.back() =
1875 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1876 return;
1877 }
1878
1879 // [expr.add]p4: For the purposes of these operators, a pointer to a
1880 // nonarray object behaves the same as a pointer to the first element of
1881 // an array of length one with the type of the object as its element type.
1882 bool IsArray =
1883 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1884 uint64_t ArrayIndex =
1885 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1886 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1887
1888 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1889 if (!Info.checkingPotentialConstantExpression() ||
1890 !LV.AllowConstexprUnknown) {
1891 // Calculate the actual index in a wide enough type, so we can include
1892 // it in the note.
1893 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1894 (llvm::APInt &)N += ArrayIndex;
1895 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1896 diagnosePointerArithmetic(Info, E, N);
1897 }
1898 setInvalid();
1899 return;
1900 }
1901
1902 ArrayIndex += TruncatedN;
1903 assert(ArrayIndex <= ArraySize &&
1904 "bounds check succeeded for out-of-bounds index");
1905
1906 if (IsArray)
1907 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1908 else
1909 IsOnePastTheEnd = (ArrayIndex != 0);
1910}
1911
1912static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1913static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1914 const LValue &This, const Expr *E,
1915 bool AllowNonLiteralTypes = false);
1916static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1917 bool InvalidBaseOK = false);
1918static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1919 bool InvalidBaseOK = false);
1920static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1921 EvalInfo &Info);
1922static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1923static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1924static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1925 EvalInfo &Info);
1926static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1927static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1928static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1929 EvalInfo &Info);
1930static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1931static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1932 EvalInfo &Info,
1933 std::string *StringResult = nullptr);
1934
1935/// Evaluate an integer or fixed point expression into an APResult.
1936static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1937 EvalInfo &Info);
1938
1939/// Evaluate only a fixed point expression into an APResult.
1940static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1941 EvalInfo &Info);
1942
1943//===----------------------------------------------------------------------===//
1944// Misc utilities
1945//===----------------------------------------------------------------------===//
1946
1947/// Negate an APSInt in place, converting it to a signed form if necessary, and
1948/// preserving its value (by extending by up to one bit as needed).
1949static void negateAsSigned(APSInt &Int) {
1950 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1951 Int = Int.extend(Int.getBitWidth() + 1);
1952 Int.setIsSigned(true);
1953 }
1954 Int = -Int;
1955}
1956
1957template<typename KeyT>
1958APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1959 ScopeKind Scope, LValue &LV) {
1960 unsigned Version = getTempVersion();
1961 APValue::LValueBase Base(Key, Index, Version);
1962 LV.set(Base);
1963 return createLocal(Base, Key, T, Scope);
1964}
1965
1966/// Allocate storage for a parameter of a function call made in this frame.
1967APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1968 LValue &LV) {
1969 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1970 APValue::LValueBase Base(PVD, Index, Args.Version);
1971 LV.set(Base);
1972 // We always destroy parameters at the end of the call, even if we'd allow
1973 // them to live to the end of the full-expression at runtime, in order to
1974 // give portable results and match other compilers.
1975 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1976}
1977
1978APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1979 QualType T, ScopeKind Scope) {
1980 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1981 unsigned Version = Base.getVersion();
1982 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1983 assert(Result.isAbsent() && "local created multiple times");
1984
1985 // If we're creating a local immediately in the operand of a speculative
1986 // evaluation, don't register a cleanup to be run outside the speculative
1987 // evaluation context, since we won't actually be able to initialize this
1988 // object.
1989 if (Index <= Info.SpeculativeEvaluationDepth) {
1990 if (T.isDestructedType())
1991 Info.noteSideEffect();
1992 } else {
1993 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1994 }
1995 return Result;
1996}
1997
1998APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1999 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
2000 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
2001 return nullptr;
2002 }
2003
2004 DynamicAllocLValue DA(NumHeapAllocs++);
2006 auto Result = HeapAllocs.emplace(std::piecewise_construct,
2007 std::forward_as_tuple(DA), std::tuple<>());
2008 assert(Result.second && "reused a heap alloc index?");
2009 Result.first->second.AllocExpr = E;
2010 return &Result.first->second.Value;
2011}
2012
2013/// Produce a string describing the given constexpr call.
2014void CallStackFrame::describe(raw_ostream &Out) const {
2015 unsigned ArgIndex = 0;
2016 bool IsMemberCall =
2017 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
2018 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
2019
2020 if (!IsMemberCall)
2021 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2022 /*Qualified=*/false);
2023
2024 if (This && IsMemberCall) {
2025 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2026 const Expr *Object = MCE->getImplicitObjectArgument();
2027 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2028 /*Indentation=*/0);
2029 if (Object->getType()->isPointerType())
2030 Out << "->";
2031 else
2032 Out << ".";
2033 } else if (const auto *OCE =
2034 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2035 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2036 Info.Ctx.getPrintingPolicy(),
2037 /*Indentation=*/0);
2038 Out << ".";
2039 } else {
2040 APValue Val;
2041 This->moveInto(Val);
2042 Val.printPretty(
2043 Out, Info.Ctx,
2044 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2045 Out << ".";
2046 }
2047 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2048 /*Qualified=*/false);
2049 IsMemberCall = false;
2050 }
2051
2052 Out << '(';
2053
2054 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2055 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2056 if (ArgIndex > (unsigned)IsMemberCall)
2057 Out << ", ";
2058
2059 const ParmVarDecl *Param = *I;
2060 APValue *V = Info.getParamSlot(Arguments, Param);
2061 if (V)
2062 V->printPretty(Out, Info.Ctx, Param->getType());
2063 else
2064 Out << "<...>";
2065
2066 if (ArgIndex == 0 && IsMemberCall)
2067 Out << "->" << *Callee << '(';
2068 }
2069
2070 Out << ')';
2071}
2072
2073/// Evaluate an expression to see if it had side-effects, and discard its
2074/// result.
2075/// \return \c true if the caller should keep evaluating.
2076static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2077 assert(!E->isValueDependent());
2078 APValue Scratch;
2079 if (!Evaluate(Scratch, Info, E))
2080 // We don't need the value, but we might have skipped a side effect here.
2081 return Info.noteSideEffect();
2082 return true;
2083}
2084
2085/// Should this call expression be treated as forming an opaque constant?
2086static bool IsOpaqueConstantCall(const CallExpr *E) {
2087 unsigned Builtin = E->getBuiltinCallee();
2088 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2089 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2090 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2091 Builtin == Builtin::BI__builtin_function_start);
2092}
2093
2094static bool IsOpaqueConstantCall(const LValue &LVal) {
2095 const auto *BaseExpr =
2096 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2097 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2098}
2099
2101 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2102 // constant expression of pointer type that evaluates to...
2103
2104 // ... a null pointer value, or a prvalue core constant expression of type
2105 // std::nullptr_t.
2106 if (!B)
2107 return true;
2108
2109 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2110 // ... the address of an object with static storage duration,
2111 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2112 return VD->hasGlobalStorage();
2113 if (isa<TemplateParamObjectDecl>(D))
2114 return true;
2115 // ... the address of a function,
2116 // ... the address of a GUID [MS extension],
2117 // ... the address of an unnamed global constant
2118 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2119 }
2120
2121 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2122 return true;
2123
2124 const Expr *E = B.get<const Expr*>();
2125 switch (E->getStmtClass()) {
2126 default:
2127 return false;
2128 case Expr::CompoundLiteralExprClass: {
2129 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2130 return CLE->isFileScope() && CLE->isLValue();
2131 }
2132 case Expr::MaterializeTemporaryExprClass:
2133 // A materialized temporary might have been lifetime-extended to static
2134 // storage duration.
2135 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2136 // A string literal has static storage duration.
2137 case Expr::StringLiteralClass:
2138 case Expr::PredefinedExprClass:
2139 case Expr::ObjCStringLiteralClass:
2140 case Expr::ObjCEncodeExprClass:
2141 return true;
2142 case Expr::ObjCBoxedExprClass:
2143 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2144 case Expr::CallExprClass:
2145 return IsOpaqueConstantCall(cast<CallExpr>(E));
2146 // For GCC compatibility, &&label has static storage duration.
2147 case Expr::AddrLabelExprClass:
2148 return true;
2149 // A Block literal expression may be used as the initialization value for
2150 // Block variables at global or local static scope.
2151 case Expr::BlockExprClass:
2152 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2153 // The APValue generated from a __builtin_source_location will be emitted as a
2154 // literal.
2155 case Expr::SourceLocExprClass:
2156 return true;
2157 case Expr::ImplicitValueInitExprClass:
2158 // FIXME:
2159 // We can never form an lvalue with an implicit value initialization as its
2160 // base through expression evaluation, so these only appear in one case: the
2161 // implicit variable declaration we invent when checking whether a constexpr
2162 // constructor can produce a constant expression. We must assume that such
2163 // an expression might be a global lvalue.
2164 return true;
2165 }
2166}
2167
2168static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2169 return LVal.Base.dyn_cast<const ValueDecl*>();
2170}
2171
2172// Information about an LValueBase that is some kind of string.
2175 StringRef Bytes;
2177};
2178
2179// Gets the lvalue base of LVal as a string.
2180static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2181 LValueBaseString &AsString) {
2182 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2183 if (!BaseExpr)
2184 return false;
2185
2186 // For ObjCEncodeExpr, we need to compute and store the string.
2187 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2188 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2189 AsString.ObjCEncodeStorage);
2190 AsString.Bytes = AsString.ObjCEncodeStorage;
2191 AsString.CharWidth = 1;
2192 return true;
2193 }
2194
2195 // Otherwise, we have a StringLiteral.
2196 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2197 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2198 Lit = PE->getFunctionName();
2199
2200 if (!Lit)
2201 return false;
2202
2203 AsString.Bytes = Lit->getBytes();
2204 AsString.CharWidth = Lit->getCharByteWidth();
2205 return true;
2206}
2207
2208// Determine whether two string literals potentially overlap. This will be the
2209// case if they agree on the values of all the bytes on the overlapping region
2210// between them.
2211//
2212// The overlapping region is the portion of the two string literals that must
2213// overlap in memory if the pointers actually point to the same address at
2214// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2215// the overlapping region is "cdef\0", which in this case does agree, so the
2216// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2217// "bazbar" + 3, the overlapping region contains all of both strings, so they
2218// are not potentially overlapping, even though they agree from the given
2219// addresses onwards.
2220//
2221// See open core issue CWG2765 which is discussing the desired rule here.
2222static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2223 const LValue &LHS,
2224 const LValue &RHS) {
2225 LValueBaseString LHSString, RHSString;
2226 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2227 !GetLValueBaseAsString(Info, RHS, RHSString))
2228 return false;
2229
2230 // This is the byte offset to the location of the first character of LHS
2231 // within RHS. We don't need to look at the characters of one string that
2232 // would appear before the start of the other string if they were merged.
2233 CharUnits Offset = RHS.Offset - LHS.Offset;
2234 if (Offset.isNegative()) {
2235 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2236 return false;
2237 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2238 } else {
2239 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2240 return false;
2241 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2242 }
2243
2244 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2245 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2246 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2247 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2248
2249 // The null terminator isn't included in the string data, so check for it
2250 // manually. If the longer string doesn't have a null terminator where the
2251 // shorter string ends, they aren't potentially overlapping.
2252 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2253 if (Shorter.size() + NullByte >= Longer.size())
2254 break;
2255 if (Longer[Shorter.size() + NullByte])
2256 return false;
2257 }
2258
2259 // Otherwise, they're potentially overlapping if and only if the overlapping
2260 // region is the same.
2261 return Shorter == Longer.take_front(Shorter.size());
2262}
2263
2264static bool IsWeakLValue(const LValue &Value) {
2266 return Decl && Decl->isWeak();
2267}
2268
2269static bool isZeroSized(const LValue &Value) {
2271 if (isa_and_nonnull<VarDecl>(Decl)) {
2272 QualType Ty = Decl->getType();
2273 if (Ty->isArrayType())
2274 return Ty->isIncompleteType() ||
2275 Decl->getASTContext().getTypeSize(Ty) == 0;
2276 }
2277 return false;
2278}
2279
2280static bool HasSameBase(const LValue &A, const LValue &B) {
2281 if (!A.getLValueBase())
2282 return !B.getLValueBase();
2283 if (!B.getLValueBase())
2284 return false;
2285
2286 if (A.getLValueBase().getOpaqueValue() !=
2287 B.getLValueBase().getOpaqueValue())
2288 return false;
2289
2290 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2291 A.getLValueVersion() == B.getLValueVersion();
2292}
2293
2294static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2295 assert(Base && "no location for a null lvalue");
2296 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2297
2298 // For a parameter, find the corresponding call stack frame (if it still
2299 // exists), and point at the parameter of the function definition we actually
2300 // invoked.
2301 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2302 unsigned Idx = PVD->getFunctionScopeIndex();
2303 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2304 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2305 F->Arguments.Version == Base.getVersion() && F->Callee &&
2306 Idx < F->Callee->getNumParams()) {
2307 VD = F->Callee->getParamDecl(Idx);
2308 break;
2309 }
2310 }
2311 }
2312
2313 if (VD)
2314 Info.Note(VD->getLocation(), diag::note_declared_at);
2315 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2316 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2317 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2318 // FIXME: Produce a note for dangling pointers too.
2319 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2320 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2321 diag::note_constexpr_dynamic_alloc_here);
2322 }
2323
2324 // We have no information to show for a typeid(T) object.
2325}
2326
2330};
2331
2332/// Materialized temporaries that we've already checked to determine if they're
2333/// initializsed by a constant expression.
2336
2338 EvalInfo &Info, SourceLocation DiagLoc,
2339 QualType Type, const APValue &Value,
2340 ConstantExprKind Kind,
2341 const FieldDecl *SubobjectDecl,
2342 CheckedTemporaries &CheckedTemps);
2343
2344/// Check that this reference or pointer core constant expression is a valid
2345/// value for an address or reference constant expression. Return true if we
2346/// can fold this expression, whether or not it's a constant expression.
2348 QualType Type, const LValue &LVal,
2349 ConstantExprKind Kind,
2350 CheckedTemporaries &CheckedTemps) {
2351 bool IsReferenceType = Type->isReferenceType();
2352
2353 APValue::LValueBase Base = LVal.getLValueBase();
2354 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2355
2356 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2357 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2358
2359 // Additional restrictions apply in a template argument. We only enforce the
2360 // C++20 restrictions here; additional syntactic and semantic restrictions
2361 // are applied elsewhere.
2362 if (isTemplateArgument(Kind)) {
2363 int InvalidBaseKind = -1;
2364 StringRef Ident;
2365 if (Base.is<TypeInfoLValue>())
2366 InvalidBaseKind = 0;
2367 else if (isa_and_nonnull<StringLiteral>(BaseE))
2368 InvalidBaseKind = 1;
2369 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2370 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2371 InvalidBaseKind = 2;
2372 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2373 InvalidBaseKind = 3;
2374 Ident = PE->getIdentKindName();
2375 }
2376
2377 if (InvalidBaseKind != -1) {
2378 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2379 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2380 << Ident;
2381 return false;
2382 }
2383 }
2384
2385 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2386 FD && FD->isImmediateFunction()) {
2387 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2388 << !Type->isAnyPointerType();
2389 Info.Note(FD->getLocation(), diag::note_declared_at);
2390 return false;
2391 }
2392
2393 // Check that the object is a global. Note that the fake 'this' object we
2394 // manufacture when checking potential constant expressions is conservatively
2395 // assumed to be global here.
2396 if (!IsGlobalLValue(Base)) {
2397 if (Info.getLangOpts().CPlusPlus11) {
2398 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2399 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2400 << BaseVD;
2401 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2402 if (VarD && VarD->isConstexpr()) {
2403 // Non-static local constexpr variables have unintuitive semantics:
2404 // constexpr int a = 1;
2405 // constexpr const int *p = &a;
2406 // ... is invalid because the address of 'a' is not constant. Suggest
2407 // adding a 'static' in this case.
2408 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2409 << VarD
2410 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2411 } else {
2412 NoteLValueLocation(Info, Base);
2413 }
2414 } else {
2415 Info.FFDiag(Loc);
2416 }
2417 // Don't allow references to temporaries to escape.
2418 return false;
2419 }
2420 assert((Info.checkingPotentialConstantExpression() ||
2421 LVal.getLValueCallIndex() == 0) &&
2422 "have call index for global lvalue");
2423
2424 if (LVal.allowConstexprUnknown()) {
2425 if (BaseVD) {
2426 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2427 NoteLValueLocation(Info, Base);
2428 } else {
2429 Info.FFDiag(Loc);
2430 }
2431 return false;
2432 }
2433
2434 if (Base.is<DynamicAllocLValue>()) {
2435 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2436 << IsReferenceType << !Designator.Entries.empty();
2437 NoteLValueLocation(Info, Base);
2438 return false;
2439 }
2440
2441 if (BaseVD) {
2442 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2443 // Check if this is a thread-local variable.
2444 if (Var->getTLSKind())
2445 // FIXME: Diagnostic!
2446 return false;
2447
2448 // A dllimport variable never acts like a constant, unless we're
2449 // evaluating a value for use only in name mangling.
2450 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2451 // FIXME: Diagnostic!
2452 return false;
2453
2454 // In CUDA/HIP device compilation, only device side variables have
2455 // constant addresses.
2456 if (Info.getASTContext().getLangOpts().CUDA &&
2457 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2458 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2459 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2460 !Var->hasAttr<CUDAConstantAttr>() &&
2461 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2462 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2463 Var->hasAttr<HIPManagedAttr>())
2464 return false;
2465 }
2466 }
2467 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2468 // __declspec(dllimport) must be handled very carefully:
2469 // We must never initialize an expression with the thunk in C++.
2470 // Doing otherwise would allow the same id-expression to yield
2471 // different addresses for the same function in different translation
2472 // units. However, this means that we must dynamically initialize the
2473 // expression with the contents of the import address table at runtime.
2474 //
2475 // The C language has no notion of ODR; furthermore, it has no notion of
2476 // dynamic initialization. This means that we are permitted to
2477 // perform initialization with the address of the thunk.
2478 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2479 FD->hasAttr<DLLImportAttr>())
2480 // FIXME: Diagnostic!
2481 return false;
2482 }
2483 } else if (const auto *MTE =
2484 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2485 if (CheckedTemps.insert(MTE).second) {
2486 QualType TempType = getType(Base);
2487 if (TempType.isDestructedType()) {
2488 Info.FFDiag(MTE->getExprLoc(),
2489 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2490 << TempType;
2491 return false;
2492 }
2493
2494 APValue *V = MTE->getOrCreateValue(false);
2495 assert(V && "evasluation result refers to uninitialised temporary");
2496 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2497 Info, MTE->getExprLoc(), TempType, *V, Kind,
2498 /*SubobjectDecl=*/nullptr, CheckedTemps))
2499 return false;
2500 }
2501 }
2502
2503 // Allow address constant expressions to be past-the-end pointers. This is
2504 // an extension: the standard requires them to point to an object.
2505 if (!IsReferenceType)
2506 return true;
2507
2508 // A reference constant expression must refer to an object.
2509 if (!Base) {
2510 // FIXME: diagnostic
2511 Info.CCEDiag(Loc);
2512 return true;
2513 }
2514
2515 // Does this refer one past the end of some object?
2516 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2517 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2518 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2519 NoteLValueLocation(Info, Base);
2520 }
2521
2522 return true;
2523}
2524
2525/// Member pointers are constant expressions unless they point to a
2526/// non-virtual dllimport member function.
2527static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2529 QualType Type,
2530 const APValue &Value,
2531 ConstantExprKind Kind) {
2532 const ValueDecl *Member = Value.getMemberPointerDecl();
2533 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2534 if (!FD)
2535 return true;
2536 if (FD->isImmediateFunction()) {
2537 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2538 Info.Note(FD->getLocation(), diag::note_declared_at);
2539 return false;
2540 }
2541 return isForManglingOnly(Kind) || FD->isVirtual() ||
2542 !FD->hasAttr<DLLImportAttr>();
2543}
2544
2545/// Check that this core constant expression is of literal type, and if not,
2546/// produce an appropriate diagnostic.
2547static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2548 const LValue *This = nullptr) {
2549 // The restriction to literal types does not exist in C++23 anymore.
2550 if (Info.getLangOpts().CPlusPlus23)
2551 return true;
2552
2553 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2554 return true;
2555
2556 // C++1y: A constant initializer for an object o [...] may also invoke
2557 // constexpr constructors for o and its subobjects even if those objects
2558 // are of non-literal class types.
2559 //
2560 // C++11 missed this detail for aggregates, so classes like this:
2561 // struct foo_t { union { int i; volatile int j; } u; };
2562 // are not (obviously) initializable like so:
2563 // __attribute__((__require_constant_initialization__))
2564 // static const foo_t x = {{0}};
2565 // because "i" is a subobject with non-literal initialization (due to the
2566 // volatile member of the union). See:
2567 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2568 // Therefore, we use the C++1y behavior.
2569 if (This && Info.EvaluatingDecl == This->getLValueBase())
2570 return true;
2571
2572 // Prvalue constant expressions must be of literal types.
2573 if (Info.getLangOpts().CPlusPlus11)
2574 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2575 << E->getType();
2576 else
2577 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2578 return false;
2579}
2580
2582 EvalInfo &Info, SourceLocation DiagLoc,
2583 QualType Type, const APValue &Value,
2584 ConstantExprKind Kind,
2585 const FieldDecl *SubobjectDecl,
2586 CheckedTemporaries &CheckedTemps) {
2587 if (!Value.hasValue()) {
2588 if (SubobjectDecl) {
2589 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2590 << /*(name)*/ 1 << SubobjectDecl;
2591 Info.Note(SubobjectDecl->getLocation(),
2592 diag::note_constexpr_subobject_declared_here);
2593 } else {
2594 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2595 << /*of type*/ 0 << Type;
2596 }
2597 return false;
2598 }
2599
2600 // We allow _Atomic(T) to be initialized from anything that T can be
2601 // initialized from.
2602 if (const AtomicType *AT = Type->getAs<AtomicType>())
2603 Type = AT->getValueType();
2604
2605 // Core issue 1454: For a literal constant expression of array or class type,
2606 // each subobject of its value shall have been initialized by a constant
2607 // expression.
2608 if (Value.isArray()) {
2610 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2611 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2612 Value.getArrayInitializedElt(I), Kind,
2613 SubobjectDecl, CheckedTemps))
2614 return false;
2615 }
2616 if (!Value.hasArrayFiller())
2617 return true;
2618 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2619 Value.getArrayFiller(), Kind, SubobjectDecl,
2620 CheckedTemps);
2621 }
2622 if (Value.isUnion() && Value.getUnionField()) {
2623 return CheckEvaluationResult(
2624 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2625 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2626 }
2627 if (Value.isStruct()) {
2628 auto *RD = Type->castAsRecordDecl();
2629 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2630 unsigned BaseIndex = 0;
2631 for (const CXXBaseSpecifier &BS : CD->bases()) {
2632 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2633 if (!BaseValue.hasValue()) {
2634 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2635 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2636 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2637 return false;
2638 }
2639 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2640 Kind, /*SubobjectDecl=*/nullptr,
2641 CheckedTemps))
2642 return false;
2643 ++BaseIndex;
2644 }
2645 }
2646 for (const auto *I : RD->fields()) {
2647 if (I->isUnnamedBitField())
2648 continue;
2649
2650 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2651 Value.getStructField(I->getFieldIndex()), Kind,
2652 I, CheckedTemps))
2653 return false;
2654 }
2655 }
2656
2657 if (Value.isLValue() &&
2658 CERK == CheckEvaluationResultKind::ConstantExpression) {
2659 LValue LVal;
2660 LVal.setFrom(Info.Ctx, Value);
2661 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2662 CheckedTemps);
2663 }
2664
2665 if (Value.isMemberPointer() &&
2666 CERK == CheckEvaluationResultKind::ConstantExpression)
2667 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2668
2669 // Everything else is fine.
2670 return true;
2671}
2672
2673/// Check that this core constant expression value is a valid value for a
2674/// constant expression. If not, report an appropriate diagnostic. Does not
2675/// check that the expression is of literal type.
2676static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2677 QualType Type, const APValue &Value,
2678 ConstantExprKind Kind) {
2679 // Nothing to check for a constant expression of type 'cv void'.
2680 if (Type->isVoidType())
2681 return true;
2682
2683 CheckedTemporaries CheckedTemps;
2684 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2685 Info, DiagLoc, Type, Value, Kind,
2686 /*SubobjectDecl=*/nullptr, CheckedTemps);
2687}
2688
2689/// Check that this evaluated value is fully-initialized and can be loaded by
2690/// an lvalue-to-rvalue conversion.
2691static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2692 QualType Type, const APValue &Value) {
2693 CheckedTemporaries CheckedTemps;
2694 return CheckEvaluationResult(
2695 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2696 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2697}
2698
2699/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2700/// "the allocated storage is deallocated within the evaluation".
2701static bool CheckMemoryLeaks(EvalInfo &Info) {
2702 if (!Info.HeapAllocs.empty()) {
2703 // We can still fold to a constant despite a compile-time memory leak,
2704 // so long as the heap allocation isn't referenced in the result (we check
2705 // that in CheckConstantExpression).
2706 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2707 diag::note_constexpr_memory_leak)
2708 << unsigned(Info.HeapAllocs.size() - 1);
2709 }
2710 return true;
2711}
2712
2713static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2714 // A null base expression indicates a null pointer. These are always
2715 // evaluatable, and they are false unless the offset is zero.
2716 if (!Value.getLValueBase()) {
2717 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2718 Result = !Value.getLValueOffset().isZero();
2719 return true;
2720 }
2721
2722 // We have a non-null base. These are generally known to be true, but if it's
2723 // a weak declaration it can be null at runtime.
2724 Result = true;
2725 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2726 return !Decl || !Decl->isWeak();
2727}
2728
2729static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2730 // TODO: This function should produce notes if it fails.
2731 switch (Val.getKind()) {
2732 case APValue::None:
2734 return false;
2735 case APValue::Int:
2736 Result = Val.getInt().getBoolValue();
2737 return true;
2739 Result = Val.getFixedPoint().getBoolValue();
2740 return true;
2741 case APValue::Float:
2742 Result = !Val.getFloat().isZero();
2743 return true;
2745 Result = Val.getComplexIntReal().getBoolValue() ||
2746 Val.getComplexIntImag().getBoolValue();
2747 return true;
2749 Result = !Val.getComplexFloatReal().isZero() ||
2750 !Val.getComplexFloatImag().isZero();
2751 return true;
2752 case APValue::LValue:
2753 return EvalPointerValueAsBool(Val, Result);
2755 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2756 return false;
2757 }
2758 Result = Val.getMemberPointerDecl();
2759 return true;
2760 case APValue::Vector:
2761 case APValue::Array:
2762 case APValue::Struct:
2763 case APValue::Union:
2765 return false;
2766 }
2767
2768 llvm_unreachable("unknown APValue kind");
2769}
2770
2771static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2772 EvalInfo &Info) {
2773 assert(!E->isValueDependent());
2774 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2775 APValue Val;
2776 if (!Evaluate(Val, Info, E))
2777 return false;
2778 return HandleConversionToBool(Val, Result);
2779}
2780
2781template<typename T>
2782static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2783 const T &SrcValue, QualType DestType) {
2784 Info.CCEDiag(E, diag::note_constexpr_overflow)
2785 << SrcValue << DestType;
2786 return Info.noteUndefinedBehavior();
2787}
2788
2789static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2790 QualType SrcType, const APFloat &Value,
2791 QualType DestType, APSInt &Result) {
2792 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2793 // Determine whether we are converting to unsigned or signed.
2794 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2795
2796 Result = APSInt(DestWidth, !DestSigned);
2797 bool ignored;
2798 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2799 & APFloat::opInvalidOp)
2800 return HandleOverflow(Info, E, Value, DestType);
2801 return true;
2802}
2803
2804/// Get rounding mode to use in evaluation of the specified expression.
2805///
2806/// If rounding mode is unknown at compile time, still try to evaluate the
2807/// expression. If the result is exact, it does not depend on rounding mode.
2808/// So return "tonearest" mode instead of "dynamic".
2809static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2810 llvm::RoundingMode RM =
2811 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2812 if (RM == llvm::RoundingMode::Dynamic)
2813 RM = llvm::RoundingMode::NearestTiesToEven;
2814 return RM;
2815}
2816
2817/// Check if the given evaluation result is allowed for constant evaluation.
2818static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2819 APFloat::opStatus St) {
2820 // In a constant context, assume that any dynamic rounding mode or FP
2821 // exception state matches the default floating-point environment.
2822 if (Info.InConstantContext)
2823 return true;
2824
2825 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2826 if ((St & APFloat::opInexact) &&
2827 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2828 // Inexact result means that it depends on rounding mode. If the requested
2829 // mode is dynamic, the evaluation cannot be made in compile time.
2830 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2831 return false;
2832 }
2833
2834 if ((St != APFloat::opOK) &&
2835 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2836 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2837 FPO.getAllowFEnvAccess())) {
2838 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2839 return false;
2840 }
2841
2842 if ((St & APFloat::opStatus::opInvalidOp) &&
2843 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2844 // There is no usefully definable result.
2845 Info.FFDiag(E);
2846 return false;
2847 }
2848
2849 // FIXME: if:
2850 // - evaluation triggered other FP exception, and
2851 // - exception mode is not "ignore", and
2852 // - the expression being evaluated is not a part of global variable
2853 // initializer,
2854 // the evaluation probably need to be rejected.
2855 return true;
2856}
2857
2858static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2859 QualType SrcType, QualType DestType,
2860 APFloat &Result) {
2861 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2862 isa<ConvertVectorExpr>(E)) &&
2863 "HandleFloatToFloatCast has been checked with only CastExpr, "
2864 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2865 "the new expression or address the root cause of this usage.");
2866 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2867 APFloat::opStatus St;
2868 APFloat Value = Result;
2869 bool ignored;
2870 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2871 return checkFloatingPointResult(Info, E, St);
2872}
2873
2874static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2875 QualType DestType, QualType SrcType,
2876 const APSInt &Value) {
2877 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2878 // Figure out if this is a truncate, extend or noop cast.
2879 // If the input is signed, do a sign extend, noop, or truncate.
2880 APSInt Result = Value.extOrTrunc(DestWidth);
2881 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2882 if (DestType->isBooleanType())
2883 Result = Value.getBoolValue();
2884 return Result;
2885}
2886
2887static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2888 const FPOptions FPO,
2889 QualType SrcType, const APSInt &Value,
2890 QualType DestType, APFloat &Result) {
2891 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2892 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2893 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2894 return checkFloatingPointResult(Info, E, St);
2895}
2896
2897static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2898 APValue &Value, const FieldDecl *FD) {
2899 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2900
2901 if (!Value.isInt()) {
2902 // Trying to store a pointer-cast-to-integer into a bitfield.
2903 // FIXME: In this case, we should provide the diagnostic for casting
2904 // a pointer to an integer.
2905 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2906 Info.FFDiag(E);
2907 return false;
2908 }
2909
2910 APSInt &Int = Value.getInt();
2911 unsigned OldBitWidth = Int.getBitWidth();
2912 unsigned NewBitWidth = FD->getBitWidthValue();
2913 if (NewBitWidth < OldBitWidth)
2914 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2915 return true;
2916}
2917
2918/// Perform the given integer operation, which is known to need at most BitWidth
2919/// bits, and check for overflow in the original type (if that type was not an
2920/// unsigned type).
2921template<typename Operation>
2922static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2923 const APSInt &LHS, const APSInt &RHS,
2924 unsigned BitWidth, Operation Op,
2925 APSInt &Result) {
2926 if (LHS.isUnsigned()) {
2927 Result = Op(LHS, RHS);
2928 return true;
2929 }
2930
2931 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2932 Result = Value.trunc(LHS.getBitWidth());
2933 if (Result.extend(BitWidth) != Value) {
2934 if (Info.checkingForUndefinedBehavior())
2935 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2936 diag::warn_integer_constant_overflow)
2937 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2938 /*UpperCase=*/true, /*InsertSeparators=*/true)
2939 << E->getType() << E->getSourceRange();
2940 return HandleOverflow(Info, E, Value, E->getType());
2941 }
2942 return true;
2943}
2944
2945/// Perform the given binary integer operation.
2946static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2947 const APSInt &LHS, BinaryOperatorKind Opcode,
2948 APSInt RHS, APSInt &Result) {
2949 bool HandleOverflowResult = true;
2950 switch (Opcode) {
2951 default:
2952 Info.FFDiag(E);
2953 return false;
2954 case BO_Mul:
2955 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2956 std::multiplies<APSInt>(), Result);
2957 case BO_Add:
2958 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2959 std::plus<APSInt>(), Result);
2960 case BO_Sub:
2961 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2962 std::minus<APSInt>(), Result);
2963 case BO_And: Result = LHS & RHS; return true;
2964 case BO_Xor: Result = LHS ^ RHS; return true;
2965 case BO_Or: Result = LHS | RHS; return true;
2966 case BO_Div:
2967 case BO_Rem:
2968 if (RHS == 0) {
2969 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2970 << E->getRHS()->getSourceRange();
2971 return false;
2972 }
2973 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2974 // this operation and gives the two's complement result.
2975 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2976 LHS.isMinSignedValue())
2977 HandleOverflowResult = HandleOverflow(
2978 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2979 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2980 return HandleOverflowResult;
2981 case BO_Shl: {
2982 if (Info.getLangOpts().OpenCL)
2983 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2984 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2985 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2986 RHS.isUnsigned());
2987 else if (RHS.isSigned() && RHS.isNegative()) {
2988 // During constant-folding, a negative shift is an opposite shift. Such
2989 // a shift is not a constant expression.
2990 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2991 if (!Info.noteUndefinedBehavior())
2992 return false;
2993 RHS = -RHS;
2994 goto shift_right;
2995 }
2996 shift_left:
2997 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2998 // the shifted type.
2999 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3000 if (SA != RHS) {
3001 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3002 << RHS << E->getType() << LHS.getBitWidth();
3003 if (!Info.noteUndefinedBehavior())
3004 return false;
3005 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
3006 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
3007 // operand, and must not overflow the corresponding unsigned type.
3008 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
3009 // E1 x 2^E2 module 2^N.
3010 if (LHS.isNegative()) {
3011 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
3012 if (!Info.noteUndefinedBehavior())
3013 return false;
3014 } else if (LHS.countl_zero() < SA) {
3015 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
3016 if (!Info.noteUndefinedBehavior())
3017 return false;
3018 }
3019 }
3020 Result = LHS << SA;
3021 return true;
3022 }
3023 case BO_Shr: {
3024 if (Info.getLangOpts().OpenCL)
3025 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3026 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
3027 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
3028 RHS.isUnsigned());
3029 else if (RHS.isSigned() && RHS.isNegative()) {
3030 // During constant-folding, a negative shift is an opposite shift. Such a
3031 // shift is not a constant expression.
3032 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
3033 if (!Info.noteUndefinedBehavior())
3034 return false;
3035 RHS = -RHS;
3036 goto shift_left;
3037 }
3038 shift_right:
3039 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3040 // shifted type.
3041 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3042 if (SA != RHS) {
3043 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3044 << RHS << E->getType() << LHS.getBitWidth();
3045 if (!Info.noteUndefinedBehavior())
3046 return false;
3047 }
3048
3049 Result = LHS >> SA;
3050 return true;
3051 }
3052
3053 case BO_LT: Result = LHS < RHS; return true;
3054 case BO_GT: Result = LHS > RHS; return true;
3055 case BO_LE: Result = LHS <= RHS; return true;
3056 case BO_GE: Result = LHS >= RHS; return true;
3057 case BO_EQ: Result = LHS == RHS; return true;
3058 case BO_NE: Result = LHS != RHS; return true;
3059 case BO_Cmp:
3060 llvm_unreachable("BO_Cmp should be handled elsewhere");
3061 }
3062}
3063
3064/// Perform the given binary floating-point operation, in-place, on LHS.
3065static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3066 APFloat &LHS, BinaryOperatorKind Opcode,
3067 const APFloat &RHS) {
3068 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3069 APFloat::opStatus St;
3070 switch (Opcode) {
3071 default:
3072 Info.FFDiag(E);
3073 return false;
3074 case BO_Mul:
3075 St = LHS.multiply(RHS, RM);
3076 break;
3077 case BO_Add:
3078 St = LHS.add(RHS, RM);
3079 break;
3080 case BO_Sub:
3081 St = LHS.subtract(RHS, RM);
3082 break;
3083 case BO_Div:
3084 // [expr.mul]p4:
3085 // If the second operand of / or % is zero the behavior is undefined.
3086 if (RHS.isZero())
3087 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3088 St = LHS.divide(RHS, RM);
3089 break;
3090 }
3091
3092 // [expr.pre]p4:
3093 // If during the evaluation of an expression, the result is not
3094 // mathematically defined [...], the behavior is undefined.
3095 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3096 if (LHS.isNaN()) {
3097 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3098 return Info.noteUndefinedBehavior();
3099 }
3100
3101 return checkFloatingPointResult(Info, E, St);
3102}
3103
3104static bool handleLogicalOpForVector(const APInt &LHSValue,
3105 BinaryOperatorKind Opcode,
3106 const APInt &RHSValue, APInt &Result) {
3107 bool LHS = (LHSValue != 0);
3108 bool RHS = (RHSValue != 0);
3109
3110 if (Opcode == BO_LAnd)
3111 Result = LHS && RHS;
3112 else
3113 Result = LHS || RHS;
3114 return true;
3115}
3116static bool handleLogicalOpForVector(const APFloat &LHSValue,
3117 BinaryOperatorKind Opcode,
3118 const APFloat &RHSValue, APInt &Result) {
3119 bool LHS = !LHSValue.isZero();
3120 bool RHS = !RHSValue.isZero();
3121
3122 if (Opcode == BO_LAnd)
3123 Result = LHS && RHS;
3124 else
3125 Result = LHS || RHS;
3126 return true;
3127}
3128
3129static bool handleLogicalOpForVector(const APValue &LHSValue,
3130 BinaryOperatorKind Opcode,
3131 const APValue &RHSValue, APInt &Result) {
3132 // The result is always an int type, however operands match the first.
3133 if (LHSValue.getKind() == APValue::Int)
3134 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3135 RHSValue.getInt(), Result);
3136 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3137 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3138 RHSValue.getFloat(), Result);
3139}
3140
3141template <typename APTy>
3142static bool
3144 const APTy &RHSValue, APInt &Result) {
3145 switch (Opcode) {
3146 default:
3147 llvm_unreachable("unsupported binary operator");
3148 case BO_EQ:
3149 Result = (LHSValue == RHSValue);
3150 break;
3151 case BO_NE:
3152 Result = (LHSValue != RHSValue);
3153 break;
3154 case BO_LT:
3155 Result = (LHSValue < RHSValue);
3156 break;
3157 case BO_GT:
3158 Result = (LHSValue > RHSValue);
3159 break;
3160 case BO_LE:
3161 Result = (LHSValue <= RHSValue);
3162 break;
3163 case BO_GE:
3164 Result = (LHSValue >= RHSValue);
3165 break;
3166 }
3167
3168 // The boolean operations on these vector types use an instruction that
3169 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3170 // to -1 to make sure that we produce the correct value.
3171 Result.negate();
3172
3173 return true;
3174}
3175
3176static bool handleCompareOpForVector(const APValue &LHSValue,
3177 BinaryOperatorKind Opcode,
3178 const APValue &RHSValue, APInt &Result) {
3179 // The result is always an int type, however operands match the first.
3180 if (LHSValue.getKind() == APValue::Int)
3181 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3182 RHSValue.getInt(), Result);
3183 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3184 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3185 RHSValue.getFloat(), Result);
3186}
3187
3188// Perform binary operations for vector types, in place on the LHS.
3189static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3190 BinaryOperatorKind Opcode,
3191 APValue &LHSValue,
3192 const APValue &RHSValue) {
3193 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3194 "Operation not supported on vector types");
3195
3196 const auto *VT = E->getType()->castAs<VectorType>();
3197 unsigned NumElements = VT->getNumElements();
3198 QualType EltTy = VT->getElementType();
3199
3200 // In the cases (typically C as I've observed) where we aren't evaluating
3201 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3202 // just give up.
3203 if (!LHSValue.isVector()) {
3204 assert(LHSValue.isLValue() &&
3205 "A vector result that isn't a vector OR uncalculated LValue");
3206 Info.FFDiag(E);
3207 return false;
3208 }
3209
3210 assert(LHSValue.getVectorLength() == NumElements &&
3211 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3212
3213 SmallVector<APValue, 4> ResultElements;
3214
3215 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3216 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3217 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3218
3219 if (EltTy->isIntegerType()) {
3220 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3221 EltTy->isUnsignedIntegerType()};
3222 bool Success = true;
3223
3224 if (BinaryOperator::isLogicalOp(Opcode))
3225 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3226 else if (BinaryOperator::isComparisonOp(Opcode))
3227 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3228 else
3229 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3230 RHSElt.getInt(), EltResult);
3231
3232 if (!Success) {
3233 Info.FFDiag(E);
3234 return false;
3235 }
3236 ResultElements.emplace_back(EltResult);
3237
3238 } else if (EltTy->isFloatingType()) {
3239 assert(LHSElt.getKind() == APValue::Float &&
3240 RHSElt.getKind() == APValue::Float &&
3241 "Mismatched LHS/RHS/Result Type");
3242 APFloat LHSFloat = LHSElt.getFloat();
3243
3244 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3245 RHSElt.getFloat())) {
3246 Info.FFDiag(E);
3247 return false;
3248 }
3249
3250 ResultElements.emplace_back(LHSFloat);
3251 }
3252 }
3253
3254 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3255 return true;
3256}
3257
3258/// Cast an lvalue referring to a base subobject to a derived class, by
3259/// truncating the lvalue's path to the given length.
3260static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3261 const RecordDecl *TruncatedType,
3262 unsigned TruncatedElements) {
3263 SubobjectDesignator &D = Result.Designator;
3264
3265 // Check we actually point to a derived class object.
3266 if (TruncatedElements == D.Entries.size())
3267 return true;
3268 assert(TruncatedElements >= D.MostDerivedPathLength &&
3269 "not casting to a derived class");
3270 if (!Result.checkSubobject(Info, E, CSK_Derived))
3271 return false;
3272
3273 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3274 const RecordDecl *RD = TruncatedType;
3275 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3276 if (RD->isInvalidDecl()) return false;
3277 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3278 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3279 if (isVirtualBaseClass(D.Entries[I]))
3280 Result.Offset -= Layout.getVBaseClassOffset(Base);
3281 else
3282 Result.Offset -= Layout.getBaseClassOffset(Base);
3283 RD = Base;
3284 }
3285 D.Entries.resize(TruncatedElements);
3286 return true;
3287}
3288
3289static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3290 const CXXRecordDecl *Derived,
3291 const CXXRecordDecl *Base,
3292 const ASTRecordLayout *RL = nullptr) {
3293 if (!RL) {
3294 if (Derived->isInvalidDecl()) return false;
3295 RL = &Info.Ctx.getASTRecordLayout(Derived);
3296 }
3297
3298 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3299 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3300 return true;
3301}
3302
3303static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3304 const CXXRecordDecl *DerivedDecl,
3305 const CXXBaseSpecifier *Base) {
3306 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3307
3308 if (!Base->isVirtual())
3309 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3310
3311 SubobjectDesignator &D = Obj.Designator;
3312 if (D.Invalid)
3313 return false;
3314
3315 // Extract most-derived object and corresponding type.
3316 // FIXME: After implementing P2280R4 it became possible to get references
3317 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3318 // locations and if we see crashes in those locations in the future
3319 // it may make more sense to move this fix into Lvalue::set.
3320 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3321 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3322 return false;
3323
3324 // Find the virtual base class.
3325 if (DerivedDecl->isInvalidDecl()) return false;
3326 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3327 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3328 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3329 return true;
3330}
3331
3332static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3333 QualType Type, LValue &Result) {
3334 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3335 PathE = E->path_end();
3336 PathI != PathE; ++PathI) {
3337 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3338 *PathI))
3339 return false;
3340 Type = (*PathI)->getType();
3341 }
3342 return true;
3343}
3344
3345/// Cast an lvalue referring to a derived class to a known base subobject.
3346static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3347 const CXXRecordDecl *DerivedRD,
3348 const CXXRecordDecl *BaseRD) {
3349 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3350 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3351 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3352 llvm_unreachable("Class must be derived from the passed in base class!");
3353
3354 for (CXXBasePathElement &Elem : Paths.front())
3355 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3356 return false;
3357 return true;
3358}
3359
3360/// Update LVal to refer to the given field, which must be a member of the type
3361/// currently described by LVal.
3362static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3363 const FieldDecl *FD,
3364 const ASTRecordLayout *RL = nullptr) {
3365 if (!RL) {
3366 if (FD->getParent()->isInvalidDecl()) return false;
3367 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3368 }
3369
3370 unsigned I = FD->getFieldIndex();
3371 LVal.addDecl(Info, E, FD);
3372 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3373 return true;
3374}
3375
3376/// Update LVal to refer to the given indirect field.
3377static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3378 LValue &LVal,
3379 const IndirectFieldDecl *IFD) {
3380 for (const auto *C : IFD->chain())
3381 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3382 return false;
3383 return true;
3384}
3385
3386enum class SizeOfType {
3387 SizeOf,
3388 DataSizeOf,
3389};
3390
3391/// Get the size of the given type in char units.
3392static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3393 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3394 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3395 // extension.
3396 if (Type->isVoidType() || Type->isFunctionType()) {
3397 Size = CharUnits::One();
3398 return true;
3399 }
3400
3401 if (Type->isDependentType()) {
3402 Info.FFDiag(Loc);
3403 return false;
3404 }
3405
3406 if (!Type->isConstantSizeType()) {
3407 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3408 // FIXME: Better diagnostic.
3409 Info.FFDiag(Loc);
3410 return false;
3411 }
3412
3413 if (SOT == SizeOfType::SizeOf)
3414 Size = Info.Ctx.getTypeSizeInChars(Type);
3415 else
3416 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3417 return true;
3418}
3419
3420/// Update a pointer value to model pointer arithmetic.
3421/// \param Info - Information about the ongoing evaluation.
3422/// \param E - The expression being evaluated, for diagnostic purposes.
3423/// \param LVal - The pointer value to be updated.
3424/// \param EltTy - The pointee type represented by LVal.
3425/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3426static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3427 LValue &LVal, QualType EltTy,
3428 APSInt Adjustment) {
3429 CharUnits SizeOfPointee;
3430 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3431 return false;
3432
3433 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3434 return true;
3435}
3436
3437static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3438 LValue &LVal, QualType EltTy,
3439 int64_t Adjustment) {
3440 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3441 APSInt::get(Adjustment));
3442}
3443
3444/// Update an lvalue to refer to a component of a complex number.
3445/// \param Info - Information about the ongoing evaluation.
3446/// \param LVal - The lvalue to be updated.
3447/// \param EltTy - The complex number's component type.
3448/// \param Imag - False for the real component, true for the imaginary.
3449static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3450 LValue &LVal, QualType EltTy,
3451 bool Imag) {
3452 if (Imag) {
3453 CharUnits SizeOfComponent;
3454 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3455 return false;
3456 LVal.Offset += SizeOfComponent;
3457 }
3458 LVal.addComplex(Info, E, EltTy, Imag);
3459 return true;
3460}
3461
3462static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3463 LValue &LVal, QualType EltTy,
3464 uint64_t Size, uint64_t Idx) {
3465 if (Idx) {
3466 CharUnits SizeOfElement;
3467 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3468 return false;
3469 LVal.Offset += SizeOfElement * Idx;
3470 }
3471 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3472 return true;
3473}
3474
3475/// Try to evaluate the initializer for a variable declaration.
3476///
3477/// \param Info Information about the ongoing evaluation.
3478/// \param E An expression to be used when printing diagnostics.
3479/// \param VD The variable whose initializer should be obtained.
3480/// \param Version The version of the variable within the frame.
3481/// \param Frame The frame in which the variable was created. Must be null
3482/// if this variable is not local to the evaluation.
3483/// \param Result Filled in with a pointer to the value of the variable.
3484static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3485 const VarDecl *VD, CallStackFrame *Frame,
3486 unsigned Version, APValue *&Result) {
3487 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3488 // and pointers.
3489 bool AllowConstexprUnknown =
3490 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3491
3492 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3493
3494 auto CheckUninitReference = [&](bool IsLocalVariable) {
3495 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3496 // C++23 [expr.const]p8
3497 // ... For such an object that is not usable in constant expressions, the
3498 // dynamic type of the object is constexpr-unknown. For such a reference
3499 // that is not usable in constant expressions, the reference is treated
3500 // as binding to an unspecified object of the referenced type whose
3501 // lifetime and that of all subobjects includes the entire constant
3502 // evaluation and whose dynamic type is constexpr-unknown.
3503 //
3504 // Variables that are part of the current evaluation are not
3505 // constexpr-unknown.
3506 if (!AllowConstexprUnknown || IsLocalVariable) {
3507 if (!Info.checkingPotentialConstantExpression())
3508 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3509 return false;
3510 }
3511 Result = nullptr;
3512 }
3513 return true;
3514 };
3515
3516 // If this is a local variable, dig out its value.
3517 if (Frame) {
3518 Result = Frame->getTemporary(VD, Version);
3519 if (Result)
3520 return CheckUninitReference(/*IsLocalVariable=*/true);
3521
3522 if (!isa<ParmVarDecl>(VD)) {
3523 // Assume variables referenced within a lambda's call operator that were
3524 // not declared within the call operator are captures and during checking
3525 // of a potential constant expression, assume they are unknown constant
3526 // expressions.
3527 assert(isLambdaCallOperator(Frame->Callee) &&
3528 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3529 "missing value for local variable");
3530 if (Info.checkingPotentialConstantExpression())
3531 return false;
3532 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3533 // still reachable at all?
3534 Info.FFDiag(E->getBeginLoc(),
3535 diag::note_unimplemented_constexpr_lambda_feature_ast)
3536 << "captures not currently allowed";
3537 return false;
3538 }
3539 }
3540
3541 // If we're currently evaluating the initializer of this declaration, use that
3542 // in-flight value.
3543 if (Info.EvaluatingDecl == Base) {
3544 Result = Info.EvaluatingDeclValue;
3545 return CheckUninitReference(/*IsLocalVariable=*/false);
3546 }
3547
3548 // P2280R4 struck the restriction that variable of reference type lifetime
3549 // should begin within the evaluation of E
3550 // Used to be C++20 [expr.const]p5.12.2:
3551 // ... its lifetime began within the evaluation of E;
3552 if (isa<ParmVarDecl>(VD)) {
3553 if (AllowConstexprUnknown) {
3554 Result = nullptr;
3555 return true;
3556 }
3557
3558 // Assume parameters of a potential constant expression are usable in
3559 // constant expressions.
3560 if (!Info.checkingPotentialConstantExpression() ||
3561 !Info.CurrentCall->Callee ||
3562 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3563 if (Info.getLangOpts().CPlusPlus11) {
3564 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3565 << VD;
3566 NoteLValueLocation(Info, Base);
3567 } else {
3568 Info.FFDiag(E);
3569 }
3570 }
3571 return false;
3572 }
3573
3574 if (E->isValueDependent())
3575 return false;
3576
3577 // Dig out the initializer, and use the declaration which it's attached to.
3578 // FIXME: We should eventually check whether the variable has a reachable
3579 // initializing declaration.
3580 const Expr *Init = VD->getAnyInitializer(VD);
3581 // P2280R4 struck the restriction that variable of reference type should have
3582 // a preceding initialization.
3583 // Used to be C++20 [expr.const]p5.12:
3584 // ... reference has a preceding initialization and either ...
3585 if (!Init && !AllowConstexprUnknown) {
3586 // Don't diagnose during potential constant expression checking; an
3587 // initializer might be added later.
3588 if (!Info.checkingPotentialConstantExpression()) {
3589 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3590 << VD;
3591 NoteLValueLocation(Info, Base);
3592 }
3593 return false;
3594 }
3595
3596 // P2280R4 struck the initialization requirement for variables of reference
3597 // type so we can no longer assume we have an Init.
3598 // Used to be C++20 [expr.const]p5.12:
3599 // ... reference has a preceding initialization and either ...
3600 if (Init && Init->isValueDependent()) {
3601 // The DeclRefExpr is not value-dependent, but the variable it refers to
3602 // has a value-dependent initializer. This should only happen in
3603 // constant-folding cases, where the variable is not actually of a suitable
3604 // type for use in a constant expression (otherwise the DeclRefExpr would
3605 // have been value-dependent too), so diagnose that.
3606 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3607 if (!Info.checkingPotentialConstantExpression()) {
3608 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3609 ? diag::note_constexpr_ltor_non_constexpr
3610 : diag::note_constexpr_ltor_non_integral, 1)
3611 << VD << VD->getType();
3612 NoteLValueLocation(Info, Base);
3613 }
3614 return false;
3615 }
3616
3617 // Check that we can fold the initializer. In C++, we will have already done
3618 // this in the cases where it matters for conformance.
3619 // P2280R4 struck the initialization requirement for variables of reference
3620 // type so we can no longer assume we have an Init.
3621 // Used to be C++20 [expr.const]p5.12:
3622 // ... reference has a preceding initialization and either ...
3623 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3624 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3625 NoteLValueLocation(Info, Base);
3626 return false;
3627 }
3628
3629 // Check that the variable is actually usable in constant expressions. For a
3630 // const integral variable or a reference, we might have a non-constant
3631 // initializer that we can nonetheless evaluate the initializer for. Such
3632 // variables are not usable in constant expressions. In C++98, the
3633 // initializer also syntactically needs to be an ICE.
3634 //
3635 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3636 // expressions here; doing so would regress diagnostics for things like
3637 // reading from a volatile constexpr variable.
3638 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3639 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3640 !AllowConstexprUnknown) ||
3641 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3642 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3643 if (Init) {
3644 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3645 NoteLValueLocation(Info, Base);
3646 } else {
3647 Info.CCEDiag(E);
3648 }
3649 }
3650
3651 // Never use the initializer of a weak variable, not even for constant
3652 // folding. We can't be sure that this is the definition that will be used.
3653 if (VD->isWeak()) {
3654 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3655 NoteLValueLocation(Info, Base);
3656 return false;
3657 }
3658
3659 Result = VD->getEvaluatedValue();
3660
3661 if (!Result && !AllowConstexprUnknown)
3662 return false;
3663
3664 return CheckUninitReference(/*IsLocalVariable=*/false);
3665}
3666
3667/// Get the base index of the given base class within an APValue representing
3668/// the given derived class.
3669static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3670 const CXXRecordDecl *Base) {
3671 Base = Base->getCanonicalDecl();
3672 unsigned Index = 0;
3674 E = Derived->bases_end(); I != E; ++I, ++Index) {
3675 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3676 return Index;
3677 }
3678
3679 llvm_unreachable("base class missing from derived class's bases list");
3680}
3681
3682/// Extract the value of a character from a string literal.
3683static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3684 uint64_t Index) {
3685 assert(!isa<SourceLocExpr>(Lit) &&
3686 "SourceLocExpr should have already been converted to a StringLiteral");
3687
3688 // FIXME: Support MakeStringConstant
3689 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3690 std::string Str;
3691 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3692 assert(Index <= Str.size() && "Index too large");
3693 return APSInt::getUnsigned(Str.c_str()[Index]);
3694 }
3695
3696 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3697 Lit = PE->getFunctionName();
3698 const StringLiteral *S = cast<StringLiteral>(Lit);
3699 const ConstantArrayType *CAT =
3700 Info.Ctx.getAsConstantArrayType(S->getType());
3701 assert(CAT && "string literal isn't an array");
3702 QualType CharType = CAT->getElementType();
3703 assert(CharType->isIntegerType() && "unexpected character type");
3704 APSInt Value(Info.Ctx.getTypeSize(CharType),
3705 CharType->isUnsignedIntegerType());
3706 if (Index < S->getLength())
3707 Value = S->getCodeUnit(Index);
3708 return Value;
3709}
3710
3711// Expand a string literal into an array of characters.
3712//
3713// FIXME: This is inefficient; we should probably introduce something similar
3714// to the LLVM ConstantDataArray to make this cheaper.
3715static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3716 APValue &Result,
3717 QualType AllocType = QualType()) {
3718 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3719 AllocType.isNull() ? S->getType() : AllocType);
3720 assert(CAT && "string literal isn't an array");
3721 QualType CharType = CAT->getElementType();
3722 assert(CharType->isIntegerType() && "unexpected character type");
3723
3724 unsigned Elts = CAT->getZExtSize();
3725 Result = APValue(APValue::UninitArray(),
3726 std::min(S->getLength(), Elts), Elts);
3727 APSInt Value(Info.Ctx.getTypeSize(CharType),
3728 CharType->isUnsignedIntegerType());
3729 if (Result.hasArrayFiller())
3730 Result.getArrayFiller() = APValue(Value);
3731 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3732 Value = S->getCodeUnit(I);
3733 Result.getArrayInitializedElt(I) = APValue(Value);
3734 }
3735}
3736
3737// Expand an array so that it has more than Index filled elements.
3738static void expandArray(APValue &Array, unsigned Index) {
3739 unsigned Size = Array.getArraySize();
3740 assert(Index < Size);
3741
3742 // Always at least double the number of elements for which we store a value.
3743 unsigned OldElts = Array.getArrayInitializedElts();
3744 unsigned NewElts = std::max(Index+1, OldElts * 2);
3745 NewElts = std::min(Size, std::max(NewElts, 8u));
3746
3747 // Copy the data across.
3748 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3749 for (unsigned I = 0; I != OldElts; ++I)
3750 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3751 for (unsigned I = OldElts; I != NewElts; ++I)
3752 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3753 if (NewValue.hasArrayFiller())
3754 NewValue.getArrayFiller() = Array.getArrayFiller();
3755 Array.swap(NewValue);
3756}
3757
3758/// Determine whether a type would actually be read by an lvalue-to-rvalue
3759/// conversion. If it's of class type, we may assume that the copy operation
3760/// is trivial. Note that this is never true for a union type with fields
3761/// (because the copy always "reads" the active member) and always true for
3762/// a non-class type.
3763static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3766 return !RD || isReadByLvalueToRvalueConversion(RD);
3767}
3769 // FIXME: A trivial copy of a union copies the object representation, even if
3770 // the union is empty.
3771 if (RD->isUnion())
3772 return !RD->field_empty();
3773 if (RD->isEmpty())
3774 return false;
3775
3776 for (auto *Field : RD->fields())
3777 if (!Field->isUnnamedBitField() &&
3778 isReadByLvalueToRvalueConversion(Field->getType()))
3779 return true;
3780
3781 for (auto &BaseSpec : RD->bases())
3782 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3783 return true;
3784
3785 return false;
3786}
3787
3788/// Diagnose an attempt to read from any unreadable field within the specified
3789/// type, which might be a class type.
3790static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3791 QualType T) {
3793 if (!RD)
3794 return false;
3795
3796 if (!RD->hasMutableFields())
3797 return false;
3798
3799 for (auto *Field : RD->fields()) {
3800 // If we're actually going to read this field in some way, then it can't
3801 // be mutable. If we're in a union, then assigning to a mutable field
3802 // (even an empty one) can change the active member, so that's not OK.
3803 // FIXME: Add core issue number for the union case.
3804 if (Field->isMutable() &&
3805 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3806 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3807 Info.Note(Field->getLocation(), diag::note_declared_at);
3808 return true;
3809 }
3810
3811 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3812 return true;
3813 }
3814
3815 for (auto &BaseSpec : RD->bases())
3816 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3817 return true;
3818
3819 // All mutable fields were empty, and thus not actually read.
3820 return false;
3821}
3822
3823static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3825 bool MutableSubobject = false) {
3826 // A temporary or transient heap allocation we created.
3827 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3828 return true;
3829
3830 switch (Info.IsEvaluatingDecl) {
3831 case EvalInfo::EvaluatingDeclKind::None:
3832 return false;
3833
3834 case EvalInfo::EvaluatingDeclKind::Ctor:
3835 // The variable whose initializer we're evaluating.
3836 if (Info.EvaluatingDecl == Base)
3837 return true;
3838
3839 // A temporary lifetime-extended by the variable whose initializer we're
3840 // evaluating.
3841 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3842 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3843 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3844 return false;
3845
3846 case EvalInfo::EvaluatingDeclKind::Dtor:
3847 // C++2a [expr.const]p6:
3848 // [during constant destruction] the lifetime of a and its non-mutable
3849 // subobjects (but not its mutable subobjects) [are] considered to start
3850 // within e.
3851 if (MutableSubobject || Base != Info.EvaluatingDecl)
3852 return false;
3853 // FIXME: We can meaningfully extend this to cover non-const objects, but
3854 // we will need special handling: we should be able to access only
3855 // subobjects of such objects that are themselves declared const.
3856 QualType T = getType(Base);
3857 return T.isConstQualified() || T->isReferenceType();
3858 }
3859
3860 llvm_unreachable("unknown evaluating decl kind");
3861}
3862
3863static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3864 SourceLocation CallLoc = {}) {
3865 return Info.CheckArraySize(
3866 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3867 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3868 /*Diag=*/true);
3869}
3870
3871namespace {
3872/// A handle to a complete object (an object that is not a subobject of
3873/// another object).
3874struct CompleteObject {
3875 /// The identity of the object.
3877 /// The value of the complete object.
3878 APValue *Value;
3879 /// The type of the complete object.
3880 QualType Type;
3881
3882 CompleteObject() : Value(nullptr) {}
3884 : Base(Base), Value(Value), Type(Type) {}
3885
3886 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3887 // If this isn't a "real" access (eg, if it's just accessing the type
3888 // info), allow it. We assume the type doesn't change dynamically for
3889 // subobjects of constexpr objects (even though we'd hit UB here if it
3890 // did). FIXME: Is this right?
3891 if (!isAnyAccess(AK))
3892 return true;
3893
3894 // In C++14 onwards, it is permitted to read a mutable member whose
3895 // lifetime began within the evaluation.
3896 // FIXME: Should we also allow this in C++11?
3897 if (!Info.getLangOpts().CPlusPlus14 &&
3898 AK != AccessKinds::AK_IsWithinLifetime)
3899 return false;
3900 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3901 }
3902
3903 explicit operator bool() const { return !Type.isNull(); }
3904};
3905} // end anonymous namespace
3906
3907static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3908 bool IsMutable = false) {
3909 // C++ [basic.type.qualifier]p1:
3910 // - A const object is an object of type const T or a non-mutable subobject
3911 // of a const object.
3912 if (ObjType.isConstQualified() && !IsMutable)
3913 SubobjType.addConst();
3914 // - A volatile object is an object of type const T or a subobject of a
3915 // volatile object.
3916 if (ObjType.isVolatileQualified())
3917 SubobjType.addVolatile();
3918 return SubobjType;
3919}
3920
3921/// Find the designated sub-object of an rvalue.
3922template <typename SubobjectHandler>
3923static typename SubobjectHandler::result_type
3924findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3925 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3926 if (Sub.Invalid)
3927 // A diagnostic will have already been produced.
3928 return handler.failed();
3929 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3930 if (Info.getLangOpts().CPlusPlus11)
3931 Info.FFDiag(E, Sub.isOnePastTheEnd()
3932 ? diag::note_constexpr_access_past_end
3933 : diag::note_constexpr_access_unsized_array)
3934 << handler.AccessKind;
3935 else
3936 Info.FFDiag(E);
3937 return handler.failed();
3938 }
3939
3940 APValue *O = Obj.Value;
3941 QualType ObjType = Obj.Type;
3942 const FieldDecl *LastField = nullptr;
3943 const FieldDecl *VolatileField = nullptr;
3944
3945 // Walk the designator's path to find the subobject.
3946 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3947 // Reading an indeterminate value is undefined, but assigning over one is OK.
3948 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3949 (O->isIndeterminate() &&
3950 !isValidIndeterminateAccess(handler.AccessKind))) {
3951 // Object has ended lifetime.
3952 // If I is non-zero, some subobject (member or array element) of a
3953 // complete object has ended its lifetime, so this is valid for
3954 // IsWithinLifetime, resulting in false.
3955 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3956 return false;
3957 if (!Info.checkingPotentialConstantExpression())
3958 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3959 << handler.AccessKind << O->isIndeterminate()
3960 << E->getSourceRange();
3961 return handler.failed();
3962 }
3963
3964 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3965 // const and volatile semantics are not applied on an object under
3966 // {con,de}struction.
3967 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3968 ObjType->isRecordType() &&
3969 Info.isEvaluatingCtorDtor(
3970 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3971 ConstructionPhase::None) {
3972 ObjType = Info.Ctx.getCanonicalType(ObjType);
3973 ObjType.removeLocalConst();
3974 ObjType.removeLocalVolatile();
3975 }
3976
3977 // If this is our last pass, check that the final object type is OK.
3978 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3979 // Accesses to volatile objects are prohibited.
3980 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3981 if (Info.getLangOpts().CPlusPlus) {
3982 int DiagKind;
3984 const NamedDecl *Decl = nullptr;
3985 if (VolatileField) {
3986 DiagKind = 2;
3987 Loc = VolatileField->getLocation();
3988 Decl = VolatileField;
3989 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3990 DiagKind = 1;
3991 Loc = VD->getLocation();
3992 Decl = VD;
3993 } else {
3994 DiagKind = 0;
3995 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3996 Loc = E->getExprLoc();
3997 }
3998 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3999 << handler.AccessKind << DiagKind << Decl;
4000 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4001 } else {
4002 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4003 }
4004 return handler.failed();
4005 }
4006
4007 // If we are reading an object of class type, there may still be more
4008 // things we need to check: if there are any mutable subobjects, we
4009 // cannot perform this read. (This only happens when performing a trivial
4010 // copy or assignment.)
4011 if (ObjType->isRecordType() &&
4012 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4013 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4014 return handler.failed();
4015 }
4016
4017 if (I == N) {
4018 if (!handler.found(*O, ObjType))
4019 return false;
4020
4021 // If we modified a bit-field, truncate it to the right width.
4022 if (isModification(handler.AccessKind) &&
4023 LastField && LastField->isBitField() &&
4024 !truncateBitfieldValue(Info, E, *O, LastField))
4025 return false;
4026
4027 return true;
4028 }
4029
4030 LastField = nullptr;
4031 if (ObjType->isArrayType()) {
4032 // Next subobject is an array element.
4033 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
4034 assert(CAT && "vla in literal type?");
4035 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4036 if (CAT->getSize().ule(Index)) {
4037 // Note, it should not be possible to form a pointer with a valid
4038 // designator which points more than one past the end of the array.
4039 if (Info.getLangOpts().CPlusPlus11)
4040 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4041 << handler.AccessKind;
4042 else
4043 Info.FFDiag(E);
4044 return handler.failed();
4045 }
4046
4047 ObjType = CAT->getElementType();
4048
4049 if (O->getArrayInitializedElts() > Index)
4050 O = &O->getArrayInitializedElt(Index);
4051 else if (!isRead(handler.AccessKind)) {
4052 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
4053 return handler.failed();
4054
4055 expandArray(*O, Index);
4056 O = &O->getArrayInitializedElt(Index);
4057 } else
4058 O = &O->getArrayFiller();
4059 } else if (ObjType->isAnyComplexType()) {
4060 // Next subobject is a complex number.
4061 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4062 if (Index > 1) {
4063 if (Info.getLangOpts().CPlusPlus11)
4064 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4065 << handler.AccessKind;
4066 else
4067 Info.FFDiag(E);
4068 return handler.failed();
4069 }
4070
4071 ObjType = getSubobjectType(
4072 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4073
4074 assert(I == N - 1 && "extracting subobject of scalar?");
4075 if (O->isComplexInt()) {
4076 return handler.found(Index ? O->getComplexIntImag()
4077 : O->getComplexIntReal(), ObjType);
4078 } else {
4079 assert(O->isComplexFloat());
4080 return handler.found(Index ? O->getComplexFloatImag()
4081 : O->getComplexFloatReal(), ObjType);
4082 }
4083 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4084 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4085 unsigned NumElements = VT->getNumElements();
4086 if (Index == NumElements) {
4087 if (Info.getLangOpts().CPlusPlus11)
4088 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4089 << handler.AccessKind;
4090 else
4091 Info.FFDiag(E);
4092 return handler.failed();
4093 }
4094
4095 if (Index > NumElements) {
4096 Info.CCEDiag(E, diag::note_constexpr_array_index)
4097 << Index << /*array*/ 0 << NumElements;
4098 return handler.failed();
4099 }
4100
4101 ObjType = VT->getElementType();
4102 assert(I == N - 1 && "extracting subobject of scalar?");
4103 return handler.found(O->getVectorElt(Index), ObjType);
4104 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4105 if (Field->isMutable() &&
4106 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4107 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4108 << handler.AccessKind << Field;
4109 Info.Note(Field->getLocation(), diag::note_declared_at);
4110 return handler.failed();
4111 }
4112
4113 // Next subobject is a class, struct or union field.
4114 RecordDecl *RD =
4115 ObjType->castAsCanonical<RecordType>()->getOriginalDecl();
4116 if (RD->isUnion()) {
4117 const FieldDecl *UnionField = O->getUnionField();
4118 if (!UnionField ||
4119 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4120 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4121 // Placement new onto an inactive union member makes it active.
4122 O->setUnion(Field, APValue());
4123 } else {
4124 // Pointer to/into inactive union member: Not within lifetime
4125 if (handler.AccessKind == AK_IsWithinLifetime)
4126 return false;
4127 // FIXME: If O->getUnionValue() is absent, report that there's no
4128 // active union member rather than reporting the prior active union
4129 // member. We'll need to fix nullptr_t to not use APValue() as its
4130 // representation first.
4131 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4132 << handler.AccessKind << Field << !UnionField << UnionField;
4133 return handler.failed();
4134 }
4135 }
4136 O = &O->getUnionValue();
4137 } else
4138 O = &O->getStructField(Field->getFieldIndex());
4139
4140 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4141 LastField = Field;
4142 if (Field->getType().isVolatileQualified())
4143 VolatileField = Field;
4144 } else {
4145 // Next subobject is a base class.
4146 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4147 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4148 O = &O->getStructBase(getBaseIndex(Derived, Base));
4149
4150 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4151 }
4152 }
4153}
4154
4155namespace {
4156struct ExtractSubobjectHandler {
4157 EvalInfo &Info;
4158 const Expr *E;
4159 APValue &Result;
4160 const AccessKinds AccessKind;
4161
4162 typedef bool result_type;
4163 bool failed() { return false; }
4164 bool found(APValue &Subobj, QualType SubobjType) {
4165 Result = Subobj;
4166 if (AccessKind == AK_ReadObjectRepresentation)
4167 return true;
4168 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4169 }
4170 bool found(APSInt &Value, QualType SubobjType) {
4171 Result = APValue(Value);
4172 return true;
4173 }
4174 bool found(APFloat &Value, QualType SubobjType) {
4175 Result = APValue(Value);
4176 return true;
4177 }
4178};
4179} // end anonymous namespace
4180
4181/// Extract the designated sub-object of an rvalue.
4182static bool extractSubobject(EvalInfo &Info, const Expr *E,
4183 const CompleteObject &Obj,
4184 const SubobjectDesignator &Sub, APValue &Result,
4185 AccessKinds AK = AK_Read) {
4186 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4187 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4188 return findSubobject(Info, E, Obj, Sub, Handler);
4189}
4190
4191namespace {
4192struct ModifySubobjectHandler {
4193 EvalInfo &Info;
4194 APValue &NewVal;
4195 const Expr *E;
4196
4197 typedef bool result_type;
4198 static const AccessKinds AccessKind = AK_Assign;
4199
4200 bool checkConst(QualType QT) {
4201 // Assigning to a const object has undefined behavior.
4202 if (QT.isConstQualified()) {
4203 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4204 return false;
4205 }
4206 return true;
4207 }
4208
4209 bool failed() { return false; }
4210 bool found(APValue &Subobj, QualType SubobjType) {
4211 if (!checkConst(SubobjType))
4212 return false;
4213 // We've been given ownership of NewVal, so just swap it in.
4214 Subobj.swap(NewVal);
4215 return true;
4216 }
4217 bool found(APSInt &Value, QualType SubobjType) {
4218 if (!checkConst(SubobjType))
4219 return false;
4220 if (!NewVal.isInt()) {
4221 // Maybe trying to write a cast pointer value into a complex?
4222 Info.FFDiag(E);
4223 return false;
4224 }
4225 Value = NewVal.getInt();
4226 return true;
4227 }
4228 bool found(APFloat &Value, QualType SubobjType) {
4229 if (!checkConst(SubobjType))
4230 return false;
4231 Value = NewVal.getFloat();
4232 return true;
4233 }
4234};
4235} // end anonymous namespace
4236
4237const AccessKinds ModifySubobjectHandler::AccessKind;
4238
4239/// Update the designated sub-object of an rvalue to the given value.
4240static bool modifySubobject(EvalInfo &Info, const Expr *E,
4241 const CompleteObject &Obj,
4242 const SubobjectDesignator &Sub,
4243 APValue &NewVal) {
4244 ModifySubobjectHandler Handler = { Info, NewVal, E };
4245 return findSubobject(Info, E, Obj, Sub, Handler);
4246}
4247
4248/// Find the position where two subobject designators diverge, or equivalently
4249/// the length of the common initial subsequence.
4250static unsigned FindDesignatorMismatch(QualType ObjType,
4251 const SubobjectDesignator &A,
4252 const SubobjectDesignator &B,
4253 bool &WasArrayIndex) {
4254 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4255 for (/**/; I != N; ++I) {
4256 if (!ObjType.isNull() &&
4257 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4258 // Next subobject is an array element.
4259 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4260 WasArrayIndex = true;
4261 return I;
4262 }
4263 if (ObjType->isAnyComplexType())
4264 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4265 else
4266 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4267 } else {
4268 if (A.Entries[I].getAsBaseOrMember() !=
4269 B.Entries[I].getAsBaseOrMember()) {
4270 WasArrayIndex = false;
4271 return I;
4272 }
4273 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4274 // Next subobject is a field.
4275 ObjType = FD->getType();
4276 else
4277 // Next subobject is a base class.
4278 ObjType = QualType();
4279 }
4280 }
4281 WasArrayIndex = false;
4282 return I;
4283}
4284
4285/// Determine whether the given subobject designators refer to elements of the
4286/// same array object.
4288 const SubobjectDesignator &A,
4289 const SubobjectDesignator &B) {
4290 if (A.Entries.size() != B.Entries.size())
4291 return false;
4292
4293 bool IsArray = A.MostDerivedIsArrayElement;
4294 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4295 // A is a subobject of the array element.
4296 return false;
4297
4298 // If A (and B) designates an array element, the last entry will be the array
4299 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4300 // of length 1' case, and the entire path must match.
4301 bool WasArrayIndex;
4302 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4303 return CommonLength >= A.Entries.size() - IsArray;
4304}
4305
4306/// Find the complete object to which an LValue refers.
4307static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4308 AccessKinds AK, const LValue &LVal,
4309 QualType LValType) {
4310 if (LVal.InvalidBase) {
4311 Info.FFDiag(E);
4312 return CompleteObject();
4313 }
4314
4315 if (!LVal.Base) {
4316 if (AK == AccessKinds::AK_Dereference)
4317 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4318 else
4319 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4320 return CompleteObject();
4321 }
4322
4323 CallStackFrame *Frame = nullptr;
4324 unsigned Depth = 0;
4325 if (LVal.getLValueCallIndex()) {
4326 std::tie(Frame, Depth) =
4327 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4328 if (!Frame) {
4329 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4330 << AK << LVal.Base.is<const ValueDecl*>();
4331 NoteLValueLocation(Info, LVal.Base);
4332 return CompleteObject();
4333 }
4334 }
4335
4336 bool IsAccess = isAnyAccess(AK);
4337
4338 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4339 // is not a constant expression (even if the object is non-volatile). We also
4340 // apply this rule to C++98, in order to conform to the expected 'volatile'
4341 // semantics.
4342 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4343 if (Info.getLangOpts().CPlusPlus)
4344 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4345 << AK << LValType;
4346 else
4347 Info.FFDiag(E);
4348 return CompleteObject();
4349 }
4350
4351 // Compute value storage location and type of base object.
4352 APValue *BaseVal = nullptr;
4353 QualType BaseType = getType(LVal.Base);
4354
4355 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4356 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4357 // This is the object whose initializer we're evaluating, so its lifetime
4358 // started in the current evaluation.
4359 BaseVal = Info.EvaluatingDeclValue;
4360 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4361 // Allow reading from a GUID declaration.
4362 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4363 if (isModification(AK)) {
4364 // All the remaining cases do not permit modification of the object.
4365 Info.FFDiag(E, diag::note_constexpr_modify_global);
4366 return CompleteObject();
4367 }
4368 APValue &V = GD->getAsAPValue();
4369 if (V.isAbsent()) {
4370 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4371 << GD->getType();
4372 return CompleteObject();
4373 }
4374 return CompleteObject(LVal.Base, &V, GD->getType());
4375 }
4376
4377 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4378 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4379 if (isModification(AK)) {
4380 Info.FFDiag(E, diag::note_constexpr_modify_global);
4381 return CompleteObject();
4382 }
4383 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4384 GCD->getType());
4385 }
4386
4387 // Allow reading from template parameter objects.
4388 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4389 if (isModification(AK)) {
4390 Info.FFDiag(E, diag::note_constexpr_modify_global);
4391 return CompleteObject();
4392 }
4393 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4394 TPO->getType());
4395 }
4396
4397 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4398 // In C++11, constexpr, non-volatile variables initialized with constant
4399 // expressions are constant expressions too. Inside constexpr functions,
4400 // parameters are constant expressions even if they're non-const.
4401 // In C++1y, objects local to a constant expression (those with a Frame) are
4402 // both readable and writable inside constant expressions.
4403 // In C, such things can also be folded, although they are not ICEs.
4404 const VarDecl *VD = dyn_cast<VarDecl>(D);
4405 if (VD) {
4406 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4407 VD = VDef;
4408 }
4409 if (!VD || VD->isInvalidDecl()) {
4410 Info.FFDiag(E);
4411 return CompleteObject();
4412 }
4413
4414 bool IsConstant = BaseType.isConstant(Info.Ctx);
4415 bool ConstexprVar = false;
4416 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4417 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4418 ConstexprVar = VD->isConstexpr();
4419
4420 // Unless we're looking at a local variable or argument in a constexpr call,
4421 // the variable we're reading must be const (unless we are binding to a
4422 // reference).
4423 if (AK != clang::AK_Dereference && !Frame) {
4424 if (IsAccess && isa<ParmVarDecl>(VD)) {
4425 // Access of a parameter that's not associated with a frame isn't going
4426 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4427 // suitable diagnostic.
4428 } else if (Info.getLangOpts().CPlusPlus14 &&
4429 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4430 // OK, we can read and modify an object if we're in the process of
4431 // evaluating its initializer, because its lifetime began in this
4432 // evaluation.
4433 } else if (isModification(AK)) {
4434 // All the remaining cases do not permit modification of the object.
4435 Info.FFDiag(E, diag::note_constexpr_modify_global);
4436 return CompleteObject();
4437 } else if (VD->isConstexpr()) {
4438 // OK, we can read this variable.
4439 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4440 Info.FFDiag(E);
4441 return CompleteObject();
4442 } else if (BaseType->isIntegralOrEnumerationType()) {
4443 if (!IsConstant) {
4444 if (!IsAccess)
4445 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4446 if (Info.getLangOpts().CPlusPlus) {
4447 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4448 Info.Note(VD->getLocation(), diag::note_declared_at);
4449 } else {
4450 Info.FFDiag(E);
4451 }
4452 return CompleteObject();
4453 }
4454 } else if (!IsAccess) {
4455 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4456 } else if ((IsConstant || BaseType->isReferenceType()) &&
4457 Info.checkingPotentialConstantExpression() &&
4458 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4459 // This variable might end up being constexpr. Don't diagnose it yet.
4460 } else if (IsConstant) {
4461 // Keep evaluating to see what we can do. In particular, we support
4462 // folding of const floating-point types, in order to make static const
4463 // data members of such types (supported as an extension) more useful.
4464 if (Info.getLangOpts().CPlusPlus) {
4465 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4466 ? diag::note_constexpr_ltor_non_constexpr
4467 : diag::note_constexpr_ltor_non_integral, 1)
4468 << VD << BaseType;
4469 Info.Note(VD->getLocation(), diag::note_declared_at);
4470 } else {
4471 Info.CCEDiag(E);
4472 }
4473 } else {
4474 // Never allow reading a non-const value.
4475 if (Info.getLangOpts().CPlusPlus) {
4476 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4477 ? diag::note_constexpr_ltor_non_constexpr
4478 : diag::note_constexpr_ltor_non_integral, 1)
4479 << VD << BaseType;
4480 Info.Note(VD->getLocation(), diag::note_declared_at);
4481 } else {
4482 Info.FFDiag(E);
4483 }
4484 return CompleteObject();
4485 }
4486 }
4487
4488 // When binding to a reference, the variable does not need to be constexpr
4489 // or have constant initalization.
4490 if (AK != clang::AK_Dereference &&
4491 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4492 BaseVal))
4493 return CompleteObject();
4494 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4495 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4496 // we can't access a constexpr-unknown object.
4497 if (AK != clang::AK_Dereference && !BaseVal) {
4498 if (!Info.checkingPotentialConstantExpression()) {
4499 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4500 << AK << VD;
4501 Info.Note(VD->getLocation(), diag::note_declared_at);
4502 }
4503 return CompleteObject();
4504 }
4505 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4506 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4507 if (!Alloc) {
4508 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4509 return CompleteObject();
4510 }
4511 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4512 LVal.Base.getDynamicAllocType());
4513 }
4514 // When binding to a reference, the variable does not need to be
4515 // within its lifetime.
4516 else if (AK != clang::AK_Dereference) {
4517 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4518
4519 if (!Frame) {
4520 if (const MaterializeTemporaryExpr *MTE =
4521 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4522 assert(MTE->getStorageDuration() == SD_Static &&
4523 "should have a frame for a non-global materialized temporary");
4524
4525 // C++20 [expr.const]p4: [DR2126]
4526 // An object or reference is usable in constant expressions if it is
4527 // - a temporary object of non-volatile const-qualified literal type
4528 // whose lifetime is extended to that of a variable that is usable
4529 // in constant expressions
4530 //
4531 // C++20 [expr.const]p5:
4532 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4533 // - a non-volatile glvalue that refers to an object that is usable
4534 // in constant expressions, or
4535 // - a non-volatile glvalue of literal type that refers to a
4536 // non-volatile object whose lifetime began within the evaluation
4537 // of E;
4538 //
4539 // C++11 misses the 'began within the evaluation of e' check and
4540 // instead allows all temporaries, including things like:
4541 // int &&r = 1;
4542 // int x = ++r;
4543 // constexpr int k = r;
4544 // Therefore we use the C++14-onwards rules in C++11 too.
4545 //
4546 // Note that temporaries whose lifetimes began while evaluating a
4547 // variable's constructor are not usable while evaluating the
4548 // corresponding destructor, not even if they're of const-qualified
4549 // types.
4550 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4551 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4552 if (!IsAccess)
4553 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4554 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4555 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4556 return CompleteObject();
4557 }
4558
4559 BaseVal = MTE->getOrCreateValue(false);
4560 assert(BaseVal && "got reference to unevaluated temporary");
4561 } else if (const CompoundLiteralExpr *CLE =
4562 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4563 // According to GCC info page:
4564 //
4565 // 6.28 Compound Literals
4566 //
4567 // As an optimization, G++ sometimes gives array compound literals
4568 // longer lifetimes: when the array either appears outside a function or
4569 // has a const-qualified type. If foo and its initializer had elements
4570 // of type char *const rather than char *, or if foo were a global
4571 // variable, the array would have static storage duration. But it is
4572 // probably safest just to avoid the use of array compound literals in
4573 // C++ code.
4574 //
4575 // Obey that rule by checking constness for converted array types.
4576 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4577 !LValType->isArrayType() &&
4578 !CLETy.isConstant(Info.Ctx)) {
4579 Info.FFDiag(E);
4580 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4581 return CompleteObject();
4582 }
4583
4584 BaseVal = &CLE->getStaticValue();
4585 } else {
4586 if (!IsAccess)
4587 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4588 APValue Val;
4589 LVal.moveInto(Val);
4590 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4591 << AK
4592 << Val.getAsString(Info.Ctx,
4593 Info.Ctx.getLValueReferenceType(LValType));
4594 NoteLValueLocation(Info, LVal.Base);
4595 return CompleteObject();
4596 }
4597 } else if (AK != clang::AK_Dereference) {
4598 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4599 assert(BaseVal && "missing value for temporary");
4600 }
4601 }
4602
4603 // In C++14, we can't safely access any mutable state when we might be
4604 // evaluating after an unmodeled side effect. Parameters are modeled as state
4605 // in the caller, but aren't visible once the call returns, so they can be
4606 // modified in a speculatively-evaluated call.
4607 //
4608 // FIXME: Not all local state is mutable. Allow local constant subobjects
4609 // to be read here (but take care with 'mutable' fields).
4610 unsigned VisibleDepth = Depth;
4611 if (llvm::isa_and_nonnull<ParmVarDecl>(
4612 LVal.Base.dyn_cast<const ValueDecl *>()))
4613 ++VisibleDepth;
4614 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4615 Info.EvalStatus.HasSideEffects) ||
4616 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4617 return CompleteObject();
4618
4619 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4620}
4621
4622/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4623/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4624/// glvalue referred to by an entity of reference type.
4625///
4626/// \param Info - Information about the ongoing evaluation.
4627/// \param Conv - The expression for which we are performing the conversion.
4628/// Used for diagnostics.
4629/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4630/// case of a non-class type).
4631/// \param LVal - The glvalue on which we are attempting to perform this action.
4632/// \param RVal - The produced value will be placed here.
4633/// \param WantObjectRepresentation - If true, we're looking for the object
4634/// representation rather than the value, and in particular,
4635/// there is no requirement that the result be fully initialized.
4636static bool
4638 const LValue &LVal, APValue &RVal,
4639 bool WantObjectRepresentation = false) {
4640 if (LVal.Designator.Invalid)
4641 return false;
4642
4643 // Check for special cases where there is no existing APValue to look at.
4644 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4645
4646 AccessKinds AK =
4647 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4648
4649 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4650 if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4651 // Special-case character extraction so we don't have to construct an
4652 // APValue for the whole string.
4653 assert(LVal.Designator.Entries.size() <= 1 &&
4654 "Can only read characters from string literals");
4655 if (LVal.Designator.Entries.empty()) {
4656 // Fail for now for LValue to RValue conversion of an array.
4657 // (This shouldn't show up in C/C++, but it could be triggered by a
4658 // weird EvaluateAsRValue call from a tool.)
4659 Info.FFDiag(Conv);
4660 return false;
4661 }
4662 if (LVal.Designator.isOnePastTheEnd()) {
4663 if (Info.getLangOpts().CPlusPlus11)
4664 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4665 else
4666 Info.FFDiag(Conv);
4667 return false;
4668 }
4669 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4670 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4671 return true;
4672 }
4673 }
4674
4675 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4676 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4677}
4678
4679/// Perform an assignment of Val to LVal. Takes ownership of Val.
4680static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4681 QualType LValType, APValue &Val) {
4682 if (LVal.Designator.Invalid)
4683 return false;
4684
4685 if (!Info.getLangOpts().CPlusPlus14) {
4686 Info.FFDiag(E);
4687 return false;
4688 }
4689
4690 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4691 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4692}
4693
4694namespace {
4695struct CompoundAssignSubobjectHandler {
4696 EvalInfo &Info;
4698 QualType PromotedLHSType;
4700 const APValue &RHS;
4701
4702 static const AccessKinds AccessKind = AK_Assign;
4703
4704 typedef bool result_type;
4705
4706 bool checkConst(QualType QT) {
4707 // Assigning to a const object has undefined behavior.
4708 if (QT.isConstQualified()) {
4709 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4710 return false;
4711 }
4712 return true;
4713 }
4714
4715 bool failed() { return false; }
4716 bool found(APValue &Subobj, QualType SubobjType) {
4717 switch (Subobj.getKind()) {
4718 case APValue::Int:
4719 return found(Subobj.getInt(), SubobjType);
4720 case APValue::Float:
4721 return found(Subobj.getFloat(), SubobjType);
4724 // FIXME: Implement complex compound assignment.
4725 Info.FFDiag(E);
4726 return false;
4727 case APValue::LValue:
4728 return foundPointer(Subobj, SubobjType);
4729 case APValue::Vector:
4730 return foundVector(Subobj, SubobjType);
4732 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4733 << /*read of=*/0 << /*uninitialized object=*/1
4734 << E->getLHS()->getSourceRange();
4735 return false;
4736 default:
4737 // FIXME: can this happen?
4738 Info.FFDiag(E);
4739 return false;
4740 }
4741 }
4742
4743 bool foundVector(APValue &Value, QualType SubobjType) {
4744 if (!checkConst(SubobjType))
4745 return false;
4746
4747 if (!SubobjType->isVectorType()) {
4748 Info.FFDiag(E);
4749 return false;
4750 }
4751 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4752 }
4753
4754 bool found(APSInt &Value, QualType SubobjType) {
4755 if (!checkConst(SubobjType))
4756 return false;
4757
4758 if (!SubobjType->isIntegerType()) {
4759 // We don't support compound assignment on integer-cast-to-pointer
4760 // values.
4761 Info.FFDiag(E);
4762 return false;
4763 }
4764
4765 if (RHS.isInt()) {
4766 APSInt LHS =
4767 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4768 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4769 return false;
4770 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4771 return true;
4772 } else if (RHS.isFloat()) {
4773 const FPOptions FPO = E->getFPFeaturesInEffect(
4774 Info.Ctx.getLangOpts());
4775 APFloat FValue(0.0);
4776 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4777 PromotedLHSType, FValue) &&
4778 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4779 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4780 Value);
4781 }
4782
4783 Info.FFDiag(E);
4784 return false;
4785 }
4786 bool found(APFloat &Value, QualType SubobjType) {
4787 return checkConst(SubobjType) &&
4788 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4789 Value) &&
4790 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4791 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4792 }
4793 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4794 if (!checkConst(SubobjType))
4795 return false;
4796
4797 QualType PointeeType;
4798 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4799 PointeeType = PT->getPointeeType();
4800
4801 if (PointeeType.isNull() || !RHS.isInt() ||
4802 (Opcode != BO_Add && Opcode != BO_Sub)) {
4803 Info.FFDiag(E);
4804 return false;
4805 }
4806
4807 APSInt Offset = RHS.getInt();
4808 if (Opcode == BO_Sub)
4809 negateAsSigned(Offset);
4810
4811 LValue LVal;
4812 LVal.setFrom(Info.Ctx, Subobj);
4813 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4814 return false;
4815 LVal.moveInto(Subobj);
4816 return true;
4817 }
4818};
4819} // end anonymous namespace
4820
4821const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4822
4823/// Perform a compound assignment of LVal <op>= RVal.
4824static bool handleCompoundAssignment(EvalInfo &Info,
4826 const LValue &LVal, QualType LValType,
4827 QualType PromotedLValType,
4828 BinaryOperatorKind Opcode,
4829 const APValue &RVal) {
4830 if (LVal.Designator.Invalid)
4831 return false;
4832
4833 if (!Info.getLangOpts().CPlusPlus14) {
4834 Info.FFDiag(E);
4835 return false;
4836 }
4837
4838 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4839 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4840 RVal };
4841 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4842}
4843
4844namespace {
4845struct IncDecSubobjectHandler {
4846 EvalInfo &Info;
4847 const UnaryOperator *E;
4848 AccessKinds AccessKind;
4849 APValue *Old;
4850
4851 typedef bool result_type;
4852
4853 bool checkConst(QualType QT) {
4854 // Assigning to a const object has undefined behavior.
4855 if (QT.isConstQualified()) {
4856 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4857 return false;
4858 }
4859 return true;
4860 }
4861
4862 bool failed() { return false; }
4863 bool found(APValue &Subobj, QualType SubobjType) {
4864 // Stash the old value. Also clear Old, so we don't clobber it later
4865 // if we're post-incrementing a complex.
4866 if (Old) {
4867 *Old = Subobj;
4868 Old = nullptr;
4869 }
4870
4871 switch (Subobj.getKind()) {
4872 case APValue::Int:
4873 return found(Subobj.getInt(), SubobjType);
4874 case APValue::Float:
4875 return found(Subobj.getFloat(), SubobjType);
4877 return found(Subobj.getComplexIntReal(),
4878 SubobjType->castAs<ComplexType>()->getElementType()
4879 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4881 return found(Subobj.getComplexFloatReal(),
4882 SubobjType->castAs<ComplexType>()->getElementType()
4883 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4884 case APValue::LValue:
4885 return foundPointer(Subobj, SubobjType);
4886 default:
4887 // FIXME: can this happen?
4888 Info.FFDiag(E);
4889 return false;
4890 }
4891 }
4892 bool found(APSInt &Value, QualType SubobjType) {
4893 if (!checkConst(SubobjType))
4894 return false;
4895
4896 if (!SubobjType->isIntegerType()) {
4897 // We don't support increment / decrement on integer-cast-to-pointer
4898 // values.
4899 Info.FFDiag(E);
4900 return false;
4901 }
4902
4903 if (Old) *Old = APValue(Value);
4904
4905 // bool arithmetic promotes to int, and the conversion back to bool
4906 // doesn't reduce mod 2^n, so special-case it.
4907 if (SubobjType->isBooleanType()) {
4908 if (AccessKind == AK_Increment)
4909 Value = 1;
4910 else
4911 Value = !Value;
4912 return true;
4913 }
4914
4915 bool WasNegative = Value.isNegative();
4916 if (AccessKind == AK_Increment) {
4917 ++Value;
4918
4919 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4920 APSInt ActualValue(Value, /*IsUnsigned*/true);
4921 return HandleOverflow(Info, E, ActualValue, SubobjType);
4922 }
4923 } else {
4924 --Value;
4925
4926 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4927 unsigned BitWidth = Value.getBitWidth();
4928 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4929 ActualValue.setBit(BitWidth);
4930 return HandleOverflow(Info, E, ActualValue, SubobjType);
4931 }
4932 }
4933 return true;
4934 }
4935 bool found(APFloat &Value, QualType SubobjType) {
4936 if (!checkConst(SubobjType))
4937 return false;
4938
4939 if (Old) *Old = APValue(Value);
4940
4941 APFloat One(Value.getSemantics(), 1);
4942 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4943 APFloat::opStatus St;
4944 if (AccessKind == AK_Increment)
4945 St = Value.add(One, RM);
4946 else
4947 St = Value.subtract(One, RM);
4948 return checkFloatingPointResult(Info, E, St);
4949 }
4950 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4951 if (!checkConst(SubobjType))
4952 return false;
4953
4954 QualType PointeeType;
4955 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4956 PointeeType = PT->getPointeeType();
4957 else {
4958 Info.FFDiag(E);
4959 return false;
4960 }
4961
4962 LValue LVal;
4963 LVal.setFrom(Info.Ctx, Subobj);
4964 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4965 AccessKind == AK_Increment ? 1 : -1))
4966 return false;
4967 LVal.moveInto(Subobj);
4968 return true;
4969 }
4970};
4971} // end anonymous namespace
4972
4973/// Perform an increment or decrement on LVal.
4974static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4975 QualType LValType, bool IsIncrement, APValue *Old) {
4976 if (LVal.Designator.Invalid)
4977 return false;
4978
4979 if (!Info.getLangOpts().CPlusPlus14) {
4980 Info.FFDiag(E);
4981 return false;
4982 }
4983
4984 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4985 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4986 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4987 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4988}
4989
4990/// Build an lvalue for the object argument of a member function call.
4991static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4992 LValue &This) {
4993 if (Object->getType()->isPointerType() && Object->isPRValue())
4994 return EvaluatePointer(Object, This, Info);
4995
4996 if (Object->isGLValue())
4997 return EvaluateLValue(Object, This, Info);
4998
4999 if (Object->getType()->isLiteralType(Info.Ctx))
5000 return EvaluateTemporary(Object, This, Info);
5001
5002 if (Object->getType()->isRecordType() && Object->isPRValue())
5003 return EvaluateTemporary(Object, This, Info);
5004
5005 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5006 return false;
5007}
5008
5009/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5010/// lvalue referring to the result.
5011///
5012/// \param Info - Information about the ongoing evaluation.
5013/// \param LV - An lvalue referring to the base of the member pointer.
5014/// \param RHS - The member pointer expression.
5015/// \param IncludeMember - Specifies whether the member itself is included in
5016/// the resulting LValue subobject designator. This is not possible when
5017/// creating a bound member function.
5018/// \return The field or method declaration to which the member pointer refers,
5019/// or 0 if evaluation fails.
5020static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5021 QualType LVType,
5022 LValue &LV,
5023 const Expr *RHS,
5024 bool IncludeMember = true) {
5025 MemberPtr MemPtr;
5026 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5027 return nullptr;
5028
5029 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5030 // member value, the behavior is undefined.
5031 if (!MemPtr.getDecl()) {
5032 // FIXME: Specific diagnostic.
5033 Info.FFDiag(RHS);
5034 return nullptr;
5035 }
5036
5037 if (MemPtr.isDerivedMember()) {
5038 // This is a member of some derived class. Truncate LV appropriately.
5039 // The end of the derived-to-base path for the base object must match the
5040 // derived-to-base path for the member pointer.
5041 // C++23 [expr.mptr.oper]p4:
5042 // If the result of E1 is an object [...] whose most derived object does
5043 // not contain the member to which E2 refers, the behavior is undefined.
5044 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5045 LV.Designator.Entries.size()) {
5046 Info.FFDiag(RHS);
5047 return nullptr;
5048 }
5049 unsigned PathLengthToMember =
5050 LV.Designator.Entries.size() - MemPtr.Path.size();
5051 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5052 const CXXRecordDecl *LVDecl = getAsBaseClass(
5053 LV.Designator.Entries[PathLengthToMember + I]);
5054 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5055 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5056 Info.FFDiag(RHS);
5057 return nullptr;
5058 }
5059 }
5060 // MemPtr.Path only contains the base classes of the class directly
5061 // containing the member E2. It is still necessary to check that the class
5062 // directly containing the member E2 lies on the derived-to-base path of E1
5063 // to avoid incorrectly permitting member pointer access into a sibling
5064 // class of the class containing the member E2. If this class would
5065 // correspond to the most-derived class of E1, it either isn't contained in
5066 // LV.Designator.Entries or the corresponding entry refers to an array
5067 // element instead. Therefore get the most derived class directly in this
5068 // case. Otherwise the previous entry should correpond to this class.
5069 const CXXRecordDecl *LastLVDecl =
5070 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5071 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5072 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5073 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5074 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5075 Info.FFDiag(RHS);
5076 return nullptr;
5077 }
5078
5079 // Truncate the lvalue to the appropriate derived class.
5080 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5081 PathLengthToMember))
5082 return nullptr;
5083 } else if (!MemPtr.Path.empty()) {
5084 // Extend the LValue path with the member pointer's path.
5085 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5086 MemPtr.Path.size() + IncludeMember);
5087
5088 // Walk down to the appropriate base class.
5089 if (const PointerType *PT = LVType->getAs<PointerType>())
5090 LVType = PT->getPointeeType();
5091 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5092 assert(RD && "member pointer access on non-class-type expression");
5093 // The first class in the path is that of the lvalue.
5094 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5095 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5096 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5097 return nullptr;
5098 RD = Base;
5099 }
5100 // Finally cast to the class containing the member.
5101 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5102 MemPtr.getContainingRecord()))
5103 return nullptr;
5104 }
5105
5106 // Add the member. Note that we cannot build bound member functions here.
5107 if (IncludeMember) {
5108 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5109 if (!HandleLValueMember(Info, RHS, LV, FD))
5110 return nullptr;
5111 } else if (const IndirectFieldDecl *IFD =
5112 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5113 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5114 return nullptr;
5115 } else {
5116 llvm_unreachable("can't construct reference to bound member function");
5117 }
5118 }
5119
5120 return MemPtr.getDecl();
5121}
5122
5123static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5124 const BinaryOperator *BO,
5125 LValue &LV,
5126 bool IncludeMember = true) {
5127 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5128
5129 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5130 if (Info.noteFailure()) {
5131 MemberPtr MemPtr;
5132 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5133 }
5134 return nullptr;
5135 }
5136
5137 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5138 BO->getRHS(), IncludeMember);
5139}
5140
5141/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5142/// the provided lvalue, which currently refers to the base object.
5143static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5144 LValue &Result) {
5145 SubobjectDesignator &D = Result.Designator;
5146 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5147 return false;
5148
5149 QualType TargetQT = E->getType();
5150 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5151 TargetQT = PT->getPointeeType();
5152
5153 auto InvalidCast = [&]() {
5154 if (!Info.checkingPotentialConstantExpression() ||
5155 !Result.AllowConstexprUnknown) {
5156 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5157 << D.MostDerivedType << TargetQT;
5158 }
5159 return false;
5160 };
5161
5162 // Check this cast lands within the final derived-to-base subobject path.
5163 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5164 return InvalidCast();
5165
5166 // Check the type of the final cast. We don't need to check the path,
5167 // since a cast can only be formed if the path is unique.
5168 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5169 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5170 const CXXRecordDecl *FinalType;
5171 if (NewEntriesSize == D.MostDerivedPathLength)
5172 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5173 else
5174 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5175 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5176 return InvalidCast();
5177
5178 // Truncate the lvalue to the appropriate derived class.
5179 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5180}
5181
5182/// Get the value to use for a default-initialized object of type T.
5183/// Return false if it encounters something invalid.
5185 bool Success = true;
5186
5187 // If there is already a value present don't overwrite it.
5188 if (!Result.isAbsent())
5189 return true;
5190
5191 if (auto *RD = T->getAsCXXRecordDecl()) {
5192 if (RD->isInvalidDecl()) {
5193 Result = APValue();
5194 return false;
5195 }
5196 if (RD->isUnion()) {
5197 Result = APValue((const FieldDecl *)nullptr);
5198 return true;
5199 }
5200 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5201 std::distance(RD->field_begin(), RD->field_end()));
5202
5203 unsigned Index = 0;
5204 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5205 End = RD->bases_end();
5206 I != End; ++I, ++Index)
5207 Success &=
5208 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5209
5210 for (const auto *I : RD->fields()) {
5211 if (I->isUnnamedBitField())
5212 continue;
5214 I->getType(), Result.getStructField(I->getFieldIndex()));
5215 }
5216 return Success;
5217 }
5218
5219 if (auto *AT =
5220 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5221 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5222 if (Result.hasArrayFiller())
5223 Success &=
5224 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5225
5226 return Success;
5227 }
5228
5229 Result = APValue::IndeterminateValue();
5230 return true;
5231}
5232
5233namespace {
5234enum EvalStmtResult {
5235 /// Evaluation failed.
5236 ESR_Failed,
5237 /// Hit a 'return' statement.
5238 ESR_Returned,
5239 /// Evaluation succeeded.
5240 ESR_Succeeded,
5241 /// Hit a 'continue' statement.
5242 ESR_Continue,
5243 /// Hit a 'break' statement.
5244 ESR_Break,
5245 /// Still scanning for 'case' or 'default' statement.
5246 ESR_CaseNotFound
5247};
5248}
5249/// Evaluates the initializer of a reference.
5250static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5251 const ValueDecl *D,
5252 const Expr *Init, LValue &Result,
5253 APValue &Val) {
5254 assert(Init->isGLValue() && D->getType()->isReferenceType());
5255 // A reference is an lvalue.
5256 if (!EvaluateLValue(Init, Result, Info))
5257 return false;
5258 // [C++26][decl.ref]
5259 // The object designated by such a glvalue can be outside its lifetime
5260 // Because a null pointer value or a pointer past the end of an object
5261 // does not point to an object, a reference in a well-defined program cannot
5262 // refer to such things;
5263 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5264 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5265 return false;
5266 }
5267
5268 // Save the result.
5269 Result.moveInto(Val);
5270 return true;
5271}
5272
5273static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5274 if (VD->isInvalidDecl())
5275 return false;
5276 // We don't need to evaluate the initializer for a static local.
5277 if (!VD->hasLocalStorage())
5278 return true;
5279
5280 LValue Result;
5281 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5282 ScopeKind::Block, Result);
5283
5284 const Expr *InitE = VD->getInit();
5285 if (!InitE) {
5286 if (VD->getType()->isDependentType())
5287 return Info.noteSideEffect();
5288 return handleDefaultInitValue(VD->getType(), Val);
5289 }
5290 if (InitE->isValueDependent())
5291 return false;
5292
5293 // For references to objects, check they do not designate a one-past-the-end
5294 // object.
5295 if (VD->getType()->isReferenceType()) {
5296 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5297 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5298 // Wipe out any partially-computed value, to allow tracking that this
5299 // evaluation failed.
5300 Val = APValue();
5301 return false;
5302 }
5303
5304 return true;
5305}
5306
5307static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5308 const DecompositionDecl *DD);
5309
5310static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5311 bool EvaluateConditionDecl = false) {
5312 bool OK = true;
5313 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5314 OK &= EvaluateVarDecl(Info, VD);
5315
5316 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5317 EvaluateConditionDecl && DD)
5318 OK &= EvaluateDecompositionDeclInit(Info, DD);
5319
5320 return OK;
5321}
5322
5323static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5324 const DecompositionDecl *DD) {
5325 bool OK = true;
5326 for (auto *BD : DD->flat_bindings())
5327 if (auto *VD = BD->getHoldingVar())
5328 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5329
5330 return OK;
5331}
5332
5333static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5334 const VarDecl *VD) {
5335 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5336 if (!EvaluateDecompositionDeclInit(Info, DD))
5337 return false;
5338 }
5339 return true;
5340}
5341
5342static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5343 assert(E->isValueDependent());
5344 if (Info.noteSideEffect())
5345 return true;
5346 assert(E->containsErrors() && "valid value-dependent expression should never "
5347 "reach invalid code path.");
5348 return false;
5349}
5350
5351/// Evaluate a condition (either a variable declaration or an expression).
5352static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5353 const Expr *Cond, bool &Result) {
5354 if (Cond->isValueDependent())
5355 return false;
5356 FullExpressionRAII Scope(Info);
5357 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5358 return false;
5359 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5360 return false;
5361 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5362 return false;
5363 return Scope.destroy();
5364}
5365
5366namespace {
5367/// A location where the result (returned value) of evaluating a
5368/// statement should be stored.
5369struct StmtResult {
5370 /// The APValue that should be filled in with the returned value.
5371 APValue &Value;
5372 /// The location containing the result, if any (used to support RVO).
5373 const LValue *Slot;
5374};
5375
5376struct TempVersionRAII {
5377 CallStackFrame &Frame;
5378
5379 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5380 Frame.pushTempVersion();
5381 }
5382
5383 ~TempVersionRAII() {
5384 Frame.popTempVersion();
5385 }
5386};
5387
5388}
5389
5390static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5391 const Stmt *S,
5392 const SwitchCase *SC = nullptr);
5393
5394/// Helper to implement named break/continue. Returns 'true' if the evaluation
5395/// result should be propagated up. Otherwise, it sets the evaluation result
5396/// to either Continue to continue the current loop, or Succeeded to break it.
5397static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5398 const Stmt *LoopOrSwitch,
5400 EvalStmtResult &ESR) {
5401 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5402
5403 // For loops, map Succeeded to Continue so we don't have to check for both.
5404 if (!IsSwitch && ESR == ESR_Succeeded) {
5405 ESR = ESR_Continue;
5406 return false;
5407 }
5408
5409 if (ESR != ESR_Break && ESR != ESR_Continue)
5410 return false;
5411
5412 // Are we breaking out of or continuing this statement?
5413 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5414 const Stmt *StackTop = Info.BreakContinueStack.back();
5415 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5416 Info.BreakContinueStack.pop_back();
5417 if (ESR == ESR_Break)
5418 ESR = ESR_Succeeded;
5419 return false;
5420 }
5421
5422 // We're not. Propagate the result up.
5423 for (BlockScopeRAII *S : Scopes) {
5424 if (!S->destroy()) {
5425 ESR = ESR_Failed;
5426 break;
5427 }
5428 }
5429 return true;
5430}
5431
5432/// Evaluate the body of a loop, and translate the result as appropriate.
5433static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5434 const Stmt *Body,
5435 const SwitchCase *Case = nullptr) {
5436 BlockScopeRAII Scope(Info);
5437
5438 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5439 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5440 ESR = ESR_Failed;
5441
5442 return ESR;
5443}
5444
5445/// Evaluate a switch statement.
5446static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5447 const SwitchStmt *SS) {
5448 BlockScopeRAII Scope(Info);
5449
5450 // Evaluate the switch condition.
5451 APSInt Value;
5452 {
5453 if (const Stmt *Init = SS->getInit()) {
5454 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5455 if (ESR != ESR_Succeeded) {
5456 if (ESR != ESR_Failed && !Scope.destroy())
5457 ESR = ESR_Failed;
5458 return ESR;
5459 }
5460 }
5461
5462 FullExpressionRAII CondScope(Info);
5463 if (SS->getConditionVariable() &&
5464 !EvaluateDecl(Info, SS->getConditionVariable()))
5465 return ESR_Failed;
5466 if (SS->getCond()->isValueDependent()) {
5467 // We don't know what the value is, and which branch should jump to.
5468 EvaluateDependentExpr(SS->getCond(), Info);
5469 return ESR_Failed;
5470 }
5471 if (!EvaluateInteger(SS->getCond(), Value, Info))
5472 return ESR_Failed;
5473
5475 return ESR_Failed;
5476
5477 if (!CondScope.destroy())
5478 return ESR_Failed;
5479 }
5480
5481 // Find the switch case corresponding to the value of the condition.
5482 // FIXME: Cache this lookup.
5483 const SwitchCase *Found = nullptr;
5484 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5485 SC = SC->getNextSwitchCase()) {
5486 if (isa<DefaultStmt>(SC)) {
5487 Found = SC;
5488 continue;
5489 }
5490
5491 const CaseStmt *CS = cast<CaseStmt>(SC);
5492 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5493 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5494 : LHS;
5495 if (LHS <= Value && Value <= RHS) {
5496 Found = SC;
5497 break;
5498 }
5499 }
5500
5501 if (!Found)
5502 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5503
5504 // Search the switch body for the switch case and evaluate it from there.
5505 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5506 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5507 return ESR_Failed;
5508 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5509 return ESR;
5510
5511 switch (ESR) {
5512 case ESR_Break:
5513 llvm_unreachable("Should have been converted to Succeeded");
5514 case ESR_Succeeded:
5515 case ESR_Continue:
5516 case ESR_Failed:
5517 case ESR_Returned:
5518 return ESR;
5519 case ESR_CaseNotFound:
5520 // This can only happen if the switch case is nested within a statement
5521 // expression. We have no intention of supporting that.
5522 Info.FFDiag(Found->getBeginLoc(),
5523 diag::note_constexpr_stmt_expr_unsupported);
5524 return ESR_Failed;
5525 }
5526 llvm_unreachable("Invalid EvalStmtResult!");
5527}
5528
5529static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5530 // An expression E is a core constant expression unless the evaluation of E
5531 // would evaluate one of the following: [C++23] - a control flow that passes
5532 // through a declaration of a variable with static or thread storage duration
5533 // unless that variable is usable in constant expressions.
5534 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5535 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5536 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5537 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5538 return false;
5539 }
5540 return true;
5541}
5542
5543// Evaluate a statement.
5544static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5545 const Stmt *S, const SwitchCase *Case) {
5546 if (!Info.nextStep(S))
5547 return ESR_Failed;
5548
5549 // If we're hunting down a 'case' or 'default' label, recurse through
5550 // substatements until we hit the label.
5551 if (Case) {
5552 switch (S->getStmtClass()) {
5553 case Stmt::CompoundStmtClass:
5554 // FIXME: Precompute which substatement of a compound statement we
5555 // would jump to, and go straight there rather than performing a
5556 // linear scan each time.
5557 case Stmt::LabelStmtClass:
5558 case Stmt::AttributedStmtClass:
5559 case Stmt::DoStmtClass:
5560 break;
5561
5562 case Stmt::CaseStmtClass:
5563 case Stmt::DefaultStmtClass:
5564 if (Case == S)
5565 Case = nullptr;
5566 break;
5567
5568 case Stmt::IfStmtClass: {
5569 // FIXME: Precompute which side of an 'if' we would jump to, and go
5570 // straight there rather than scanning both sides.
5571 const IfStmt *IS = cast<IfStmt>(S);
5572
5573 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5574 // preceded by our switch label.
5575 BlockScopeRAII Scope(Info);
5576
5577 // Step into the init statement in case it brings an (uninitialized)
5578 // variable into scope.
5579 if (const Stmt *Init = IS->getInit()) {
5580 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5581 if (ESR != ESR_CaseNotFound) {
5582 assert(ESR != ESR_Succeeded);
5583 return ESR;
5584 }
5585 }
5586
5587 // Condition variable must be initialized if it exists.
5588 // FIXME: We can skip evaluating the body if there's a condition
5589 // variable, as there can't be any case labels within it.
5590 // (The same is true for 'for' statements.)
5591
5592 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5593 if (ESR == ESR_Failed)
5594 return ESR;
5595 if (ESR != ESR_CaseNotFound)
5596 return Scope.destroy() ? ESR : ESR_Failed;
5597 if (!IS->getElse())
5598 return ESR_CaseNotFound;
5599
5600 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5601 if (ESR == ESR_Failed)
5602 return ESR;
5603 if (ESR != ESR_CaseNotFound)
5604 return Scope.destroy() ? ESR : ESR_Failed;
5605 return ESR_CaseNotFound;
5606 }
5607
5608 case Stmt::WhileStmtClass: {
5609 EvalStmtResult ESR =
5610 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5611 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5612 return ESR;
5613 if (ESR != ESR_Continue)
5614 return ESR;
5615 break;
5616 }
5617
5618 case Stmt::ForStmtClass: {
5619 const ForStmt *FS = cast<ForStmt>(S);
5620 BlockScopeRAII Scope(Info);
5621
5622 // Step into the init statement in case it brings an (uninitialized)
5623 // variable into scope.
5624 if (const Stmt *Init = FS->getInit()) {
5625 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5626 if (ESR != ESR_CaseNotFound) {
5627 assert(ESR != ESR_Succeeded);
5628 return ESR;
5629 }
5630 }
5631
5632 EvalStmtResult ESR =
5633 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5634 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5635 return ESR;
5636 if (ESR != ESR_Continue)
5637 return ESR;
5638 if (const auto *Inc = FS->getInc()) {
5639 if (Inc->isValueDependent()) {
5640 if (!EvaluateDependentExpr(Inc, Info))
5641 return ESR_Failed;
5642 } else {
5643 FullExpressionRAII IncScope(Info);
5644 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5645 return ESR_Failed;
5646 }
5647 }
5648 break;
5649 }
5650
5651 case Stmt::DeclStmtClass: {
5652 // Start the lifetime of any uninitialized variables we encounter. They
5653 // might be used by the selected branch of the switch.
5654 const DeclStmt *DS = cast<DeclStmt>(S);
5655 for (const auto *D : DS->decls()) {
5656 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5657 if (!CheckLocalVariableDeclaration(Info, VD))
5658 return ESR_Failed;
5659 if (VD->hasLocalStorage() && !VD->getInit())
5660 if (!EvaluateVarDecl(Info, VD))
5661 return ESR_Failed;
5662 // FIXME: If the variable has initialization that can't be jumped
5663 // over, bail out of any immediately-surrounding compound-statement
5664 // too. There can't be any case labels here.
5665 }
5666 }
5667 return ESR_CaseNotFound;
5668 }
5669
5670 default:
5671 return ESR_CaseNotFound;
5672 }
5673 }
5674
5675 switch (S->getStmtClass()) {
5676 default:
5677 if (const Expr *E = dyn_cast<Expr>(S)) {
5678 if (E->isValueDependent()) {
5679 if (!EvaluateDependentExpr(E, Info))
5680 return ESR_Failed;
5681 } else {
5682 // Don't bother evaluating beyond an expression-statement which couldn't
5683 // be evaluated.
5684 // FIXME: Do we need the FullExpressionRAII object here?
5685 // VisitExprWithCleanups should create one when necessary.
5686 FullExpressionRAII Scope(Info);
5687 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5688 return ESR_Failed;
5689 }
5690 return ESR_Succeeded;
5691 }
5692
5693 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5694 return ESR_Failed;
5695
5696 case Stmt::NullStmtClass:
5697 return ESR_Succeeded;
5698
5699 case Stmt::DeclStmtClass: {
5700 const DeclStmt *DS = cast<DeclStmt>(S);
5701 for (const auto *D : DS->decls()) {
5702 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5703 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5704 return ESR_Failed;
5705 // Each declaration initialization is its own full-expression.
5706 FullExpressionRAII Scope(Info);
5707 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5708 !Info.noteFailure())
5709 return ESR_Failed;
5710 if (!Scope.destroy())
5711 return ESR_Failed;
5712 }
5713 return ESR_Succeeded;
5714 }
5715
5716 case Stmt::ReturnStmtClass: {
5717 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5718 FullExpressionRAII Scope(Info);
5719 if (RetExpr && RetExpr->isValueDependent()) {
5720 EvaluateDependentExpr(RetExpr, Info);
5721 // We know we returned, but we don't know what the value is.
5722 return ESR_Failed;
5723 }
5724 if (RetExpr &&
5725 !(Result.Slot
5726 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5727 : Evaluate(Result.Value, Info, RetExpr)))
5728 return ESR_Failed;
5729 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5730 }
5731
5732 case Stmt::CompoundStmtClass: {
5733 BlockScopeRAII Scope(Info);
5734
5735 const CompoundStmt *CS = cast<CompoundStmt>(S);
5736 for (const auto *BI : CS->body()) {
5737 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5738 if (ESR == ESR_Succeeded)
5739 Case = nullptr;
5740 else if (ESR != ESR_CaseNotFound) {
5741 if (ESR != ESR_Failed && !Scope.destroy())
5742 return ESR_Failed;
5743 return ESR;
5744 }
5745 }
5746 if (Case)
5747 return ESR_CaseNotFound;
5748 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5749 }
5750
5751 case Stmt::IfStmtClass: {
5752 const IfStmt *IS = cast<IfStmt>(S);
5753
5754 // Evaluate the condition, as either a var decl or as an expression.
5755 BlockScopeRAII Scope(Info);
5756 if (const Stmt *Init = IS->getInit()) {
5757 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5758 if (ESR != ESR_Succeeded) {
5759 if (ESR != ESR_Failed && !Scope.destroy())
5760 return ESR_Failed;
5761 return ESR;
5762 }
5763 }
5764 bool Cond;
5765 if (IS->isConsteval()) {
5766 Cond = IS->isNonNegatedConsteval();
5767 // If we are not in a constant context, if consteval should not evaluate
5768 // to true.
5769 if (!Info.InConstantContext)
5770 Cond = !Cond;
5771 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5772 Cond))
5773 return ESR_Failed;
5774
5775 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5776 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5777 if (ESR != ESR_Succeeded) {
5778 if (ESR != ESR_Failed && !Scope.destroy())
5779 return ESR_Failed;
5780 return ESR;
5781 }
5782 }
5783 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5784 }
5785
5786 case Stmt::WhileStmtClass: {
5787 const WhileStmt *WS = cast<WhileStmt>(S);
5788 while (true) {
5789 BlockScopeRAII Scope(Info);
5790 bool Continue;
5791 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5792 Continue))
5793 return ESR_Failed;
5794 if (!Continue)
5795 break;
5796
5797 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5798 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
5799 return ESR;
5800
5801 if (ESR != ESR_Continue) {
5802 if (ESR != ESR_Failed && !Scope.destroy())
5803 return ESR_Failed;
5804 return ESR;
5805 }
5806 if (!Scope.destroy())
5807 return ESR_Failed;
5808 }
5809 return ESR_Succeeded;
5810 }
5811
5812 case Stmt::DoStmtClass: {
5813 const DoStmt *DS = cast<DoStmt>(S);
5814 bool Continue;
5815 do {
5816 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5817 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
5818 return ESR;
5819 if (ESR != ESR_Continue)
5820 return ESR;
5821 Case = nullptr;
5822
5823 if (DS->getCond()->isValueDependent()) {
5824 EvaluateDependentExpr(DS->getCond(), Info);
5825 // Bailout as we don't know whether to keep going or terminate the loop.
5826 return ESR_Failed;
5827 }
5828 FullExpressionRAII CondScope(Info);
5829 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5830 !CondScope.destroy())
5831 return ESR_Failed;
5832 } while (Continue);
5833 return ESR_Succeeded;
5834 }
5835
5836 case Stmt::ForStmtClass: {
5837 const ForStmt *FS = cast<ForStmt>(S);
5838 BlockScopeRAII ForScope(Info);
5839 if (FS->getInit()) {
5840 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5841 if (ESR != ESR_Succeeded) {
5842 if (ESR != ESR_Failed && !ForScope.destroy())
5843 return ESR_Failed;
5844 return ESR;
5845 }
5846 }
5847 while (true) {
5848 BlockScopeRAII IterScope(Info);
5849 bool Continue = true;
5850 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5851 FS->getCond(), Continue))
5852 return ESR_Failed;
5853
5854 if (!Continue) {
5855 if (!IterScope.destroy())
5856 return ESR_Failed;
5857 break;
5858 }
5859
5860 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5861 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
5862 return ESR;
5863 if (ESR != ESR_Continue) {
5864 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5865 return ESR_Failed;
5866 return ESR;
5867 }
5868
5869 if (const auto *Inc = FS->getInc()) {
5870 if (Inc->isValueDependent()) {
5871 if (!EvaluateDependentExpr(Inc, Info))
5872 return ESR_Failed;
5873 } else {
5874 FullExpressionRAII IncScope(Info);
5875 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5876 return ESR_Failed;
5877 }
5878 }
5879
5880 if (!IterScope.destroy())
5881 return ESR_Failed;
5882 }
5883 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5884 }
5885
5886 case Stmt::CXXForRangeStmtClass: {
5887 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5888 BlockScopeRAII Scope(Info);
5889
5890 // Evaluate the init-statement if present.
5891 if (FS->getInit()) {
5892 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5893 if (ESR != ESR_Succeeded) {
5894 if (ESR != ESR_Failed && !Scope.destroy())
5895 return ESR_Failed;
5896 return ESR;
5897 }
5898 }
5899
5900 // Initialize the __range variable.
5901 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5902 if (ESR != ESR_Succeeded) {
5903 if (ESR != ESR_Failed && !Scope.destroy())
5904 return ESR_Failed;
5905 return ESR;
5906 }
5907
5908 // In error-recovery cases it's possible to get here even if we failed to
5909 // synthesize the __begin and __end variables.
5910 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5911 return ESR_Failed;
5912
5913 // Create the __begin and __end iterators.
5914 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5915 if (ESR != ESR_Succeeded) {
5916 if (ESR != ESR_Failed && !Scope.destroy())
5917 return ESR_Failed;
5918 return ESR;
5919 }
5920 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5921 if (ESR != ESR_Succeeded) {
5922 if (ESR != ESR_Failed && !Scope.destroy())
5923 return ESR_Failed;
5924 return ESR;
5925 }
5926
5927 while (true) {
5928 // Condition: __begin != __end.
5929 {
5930 if (FS->getCond()->isValueDependent()) {
5931 EvaluateDependentExpr(FS->getCond(), Info);
5932 // We don't know whether to keep going or terminate the loop.
5933 return ESR_Failed;
5934 }
5935 bool Continue = true;
5936 FullExpressionRAII CondExpr(Info);
5937 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5938 return ESR_Failed;
5939 if (!Continue)
5940 break;
5941 }
5942
5943 // User's variable declaration, initialized by *__begin.
5944 BlockScopeRAII InnerScope(Info);
5945 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5946 if (ESR != ESR_Succeeded) {
5947 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5948 return ESR_Failed;
5949 return ESR;
5950 }
5951
5952 // Loop body.
5953 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5954 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
5955 return ESR;
5956 if (ESR != ESR_Continue) {
5957 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5958 return ESR_Failed;
5959 return ESR;
5960 }
5961 if (FS->getInc()->isValueDependent()) {
5962 if (!EvaluateDependentExpr(FS->getInc(), Info))
5963 return ESR_Failed;
5964 } else {
5965 // Increment: ++__begin
5966 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5967 return ESR_Failed;
5968 }
5969
5970 if (!InnerScope.destroy())
5971 return ESR_Failed;
5972 }
5973
5974 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5975 }
5976
5977 case Stmt::SwitchStmtClass:
5978 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5979
5980 case Stmt::ContinueStmtClass:
5981 case Stmt::BreakStmtClass: {
5982 auto *B = cast<LoopControlStmt>(S);
5983 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
5984 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
5985 }
5986
5987 case Stmt::LabelStmtClass:
5988 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5989
5990 case Stmt::AttributedStmtClass: {
5991 const auto *AS = cast<AttributedStmt>(S);
5992 const auto *SS = AS->getSubStmt();
5993 MSConstexprContextRAII ConstexprContext(
5994 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5995 isa<ReturnStmt>(SS));
5996
5997 auto LO = Info.getASTContext().getLangOpts();
5998 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5999 for (auto *Attr : AS->getAttrs()) {
6000 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6001 if (!AA)
6002 continue;
6003
6004 auto *Assumption = AA->getAssumption();
6005 if (Assumption->isValueDependent())
6006 return ESR_Failed;
6007
6008 if (Assumption->HasSideEffects(Info.getASTContext()))
6009 continue;
6010
6011 bool Value;
6012 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6013 return ESR_Failed;
6014 if (!Value) {
6015 Info.CCEDiag(Assumption->getExprLoc(),
6016 diag::note_constexpr_assumption_failed);
6017 return ESR_Failed;
6018 }
6019 }
6020 }
6021
6022 return EvaluateStmt(Result, Info, SS, Case);
6023 }
6024
6025 case Stmt::CaseStmtClass:
6026 case Stmt::DefaultStmtClass:
6027 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6028 case Stmt::CXXTryStmtClass:
6029 // Evaluate try blocks by evaluating all sub statements.
6030 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6031 }
6032}
6033
6034/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6035/// default constructor. If so, we'll fold it whether or not it's marked as
6036/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6037/// so we need special handling.
6039 const CXXConstructorDecl *CD,
6040 bool IsValueInitialization) {
6041 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6042 return false;
6043
6044 // Value-initialization does not call a trivial default constructor, so such a
6045 // call is a core constant expression whether or not the constructor is
6046 // constexpr.
6047 if (!CD->isConstexpr() && !IsValueInitialization) {
6048 if (Info.getLangOpts().CPlusPlus11) {
6049 // FIXME: If DiagDecl is an implicitly-declared special member function,
6050 // we should be much more explicit about why it's not constexpr.
6051 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6052 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6053 Info.Note(CD->getLocation(), diag::note_declared_at);
6054 } else {
6055 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6056 }
6057 }
6058 return true;
6059}
6060
6061/// CheckConstexprFunction - Check that a function can be called in a constant
6062/// expression.
6063static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6065 const FunctionDecl *Definition,
6066 const Stmt *Body) {
6067 // Potential constant expressions can contain calls to declared, but not yet
6068 // defined, constexpr functions.
6069 if (Info.checkingPotentialConstantExpression() && !Definition &&
6070 Declaration->isConstexpr())
6071 return false;
6072
6073 // Bail out if the function declaration itself is invalid. We will
6074 // have produced a relevant diagnostic while parsing it, so just
6075 // note the problematic sub-expression.
6076 if (Declaration->isInvalidDecl()) {
6077 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6078 return false;
6079 }
6080
6081 // DR1872: An instantiated virtual constexpr function can't be called in a
6082 // constant expression (prior to C++20). We can still constant-fold such a
6083 // call.
6084 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6085 cast<CXXMethodDecl>(Declaration)->isVirtual())
6086 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6087
6088 if (Definition && Definition->isInvalidDecl()) {
6089 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6090 return false;
6091 }
6092
6093 // Can we evaluate this function call?
6094 if (Definition && Body &&
6095 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6096 Definition->hasAttr<MSConstexprAttr>())))
6097 return true;
6098
6099 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6100 // Special note for the assert() macro, as the normal error message falsely
6101 // implies we cannot use an assertion during constant evaluation.
6102 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6103 // FIXME: Instead of checking for an implementation-defined function,
6104 // check and evaluate the assert() macro.
6105 StringRef Name = DiagDecl->getName();
6106 bool AssertFailed =
6107 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6108 if (AssertFailed) {
6109 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6110 return false;
6111 }
6112 }
6113
6114 if (Info.getLangOpts().CPlusPlus11) {
6115 // If this function is not constexpr because it is an inherited
6116 // non-constexpr constructor, diagnose that directly.
6117 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6118 if (CD && CD->isInheritingConstructor()) {
6119 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6120 if (!Inherited->isConstexpr())
6121 DiagDecl = CD = Inherited;
6122 }
6123
6124 // FIXME: If DiagDecl is an implicitly-declared special member function
6125 // or an inheriting constructor, we should be much more explicit about why
6126 // it's not constexpr.
6127 if (CD && CD->isInheritingConstructor())
6128 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6129 << CD->getInheritedConstructor().getConstructor()->getParent();
6130 else
6131 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6132 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6133 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6134 } else {
6135 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6136 }
6137 return false;
6138}
6139
6140namespace {
6141struct CheckDynamicTypeHandler {
6142 AccessKinds AccessKind;
6143 typedef bool result_type;
6144 bool failed() { return false; }
6145 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6146 bool found(APSInt &Value, QualType SubobjType) { return true; }
6147 bool found(APFloat &Value, QualType SubobjType) { return true; }
6148};
6149} // end anonymous namespace
6150
6151/// Check that we can access the notional vptr of an object / determine its
6152/// dynamic type.
6153static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6154 AccessKinds AK, bool Polymorphic) {
6155 if (This.Designator.Invalid)
6156 return false;
6157
6158 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6159
6160 if (!Obj)
6161 return false;
6162
6163 if (!Obj.Value) {
6164 // The object is not usable in constant expressions, so we can't inspect
6165 // its value to see if it's in-lifetime or what the active union members
6166 // are. We can still check for a one-past-the-end lvalue.
6167 if (This.Designator.isOnePastTheEnd() ||
6168 This.Designator.isMostDerivedAnUnsizedArray()) {
6169 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6170 ? diag::note_constexpr_access_past_end
6171 : diag::note_constexpr_access_unsized_array)
6172 << AK;
6173 return false;
6174 } else if (Polymorphic) {
6175 // Conservatively refuse to perform a polymorphic operation if we would
6176 // not be able to read a notional 'vptr' value.
6177 if (!Info.checkingPotentialConstantExpression() ||
6178 !This.AllowConstexprUnknown) {
6179 APValue Val;
6180 This.moveInto(Val);
6181 QualType StarThisType =
6182 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6183 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6184 << AK << Val.getAsString(Info.Ctx, StarThisType);
6185 }
6186 return false;
6187 }
6188 return true;
6189 }
6190
6191 CheckDynamicTypeHandler Handler{AK};
6192 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6193}
6194
6195/// Check that the pointee of the 'this' pointer in a member function call is
6196/// either within its lifetime or in its period of construction or destruction.
6197static bool
6199 const LValue &This,
6200 const CXXMethodDecl *NamedMember) {
6201 return checkDynamicType(
6202 Info, E, This,
6203 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6204}
6205
6207 /// The dynamic class type of the object.
6209 /// The corresponding path length in the lvalue.
6210 unsigned PathLength;
6211};
6212
6213static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6214 unsigned PathLength) {
6215 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6216 Designator.Entries.size() && "invalid path length");
6217 return (PathLength == Designator.MostDerivedPathLength)
6218 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6219 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6220}
6221
6222/// Determine the dynamic type of an object.
6223static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6224 const Expr *E,
6225 LValue &This,
6226 AccessKinds AK) {
6227 // If we don't have an lvalue denoting an object of class type, there is no
6228 // meaningful dynamic type. (We consider objects of non-class type to have no
6229 // dynamic type.)
6230 if (!checkDynamicType(Info, E, This, AK,
6231 AK != AK_TypeId || This.AllowConstexprUnknown))
6232 return std::nullopt;
6233
6234 if (This.Designator.Invalid)
6235 return std::nullopt;
6236
6237 // Refuse to compute a dynamic type in the presence of virtual bases. This
6238 // shouldn't happen other than in constant-folding situations, since literal
6239 // types can't have virtual bases.
6240 //
6241 // Note that consumers of DynamicType assume that the type has no virtual
6242 // bases, and will need modifications if this restriction is relaxed.
6243 const CXXRecordDecl *Class =
6244 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6245 if (!Class || Class->getNumVBases()) {
6246 Info.FFDiag(E);
6247 return std::nullopt;
6248 }
6249
6250 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6251 // binary search here instead. But the overwhelmingly common case is that
6252 // we're not in the middle of a constructor, so it probably doesn't matter
6253 // in practice.
6254 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6255 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6256 PathLength <= Path.size(); ++PathLength) {
6257 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6258 Path.slice(0, PathLength))) {
6259 case ConstructionPhase::Bases:
6260 case ConstructionPhase::DestroyingBases:
6261 // We're constructing or destroying a base class. This is not the dynamic
6262 // type.
6263 break;
6264
6265 case ConstructionPhase::None:
6266 case ConstructionPhase::AfterBases:
6267 case ConstructionPhase::AfterFields:
6268 case ConstructionPhase::Destroying:
6269 // We've finished constructing the base classes and not yet started
6270 // destroying them again, so this is the dynamic type.
6271 return DynamicType{getBaseClassType(This.Designator, PathLength),
6272 PathLength};
6273 }
6274 }
6275
6276 // CWG issue 1517: we're constructing a base class of the object described by
6277 // 'This', so that object has not yet begun its period of construction and
6278 // any polymorphic operation on it results in undefined behavior.
6279 Info.FFDiag(E);
6280 return std::nullopt;
6281}
6282
6283/// Perform virtual dispatch.
6285 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6286 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6287 std::optional<DynamicType> DynType = ComputeDynamicType(
6288 Info, E, This,
6289 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6290 if (!DynType)
6291 return nullptr;
6292
6293 // Find the final overrider. It must be declared in one of the classes on the
6294 // path from the dynamic type to the static type.
6295 // FIXME: If we ever allow literal types to have virtual base classes, that
6296 // won't be true.
6297 const CXXMethodDecl *Callee = Found;
6298 unsigned PathLength = DynType->PathLength;
6299 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6300 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6301 const CXXMethodDecl *Overrider =
6302 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6303 if (Overrider) {
6304 Callee = Overrider;
6305 break;
6306 }
6307 }
6308
6309 // C++2a [class.abstract]p6:
6310 // the effect of making a virtual call to a pure virtual function [...] is
6311 // undefined
6312 if (Callee->isPureVirtual()) {
6313 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6314 Info.Note(Callee->getLocation(), diag::note_declared_at);
6315 return nullptr;
6316 }
6317
6318 // If necessary, walk the rest of the path to determine the sequence of
6319 // covariant adjustment steps to apply.
6320 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6321 Found->getReturnType())) {
6322 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6323 for (unsigned CovariantPathLength = PathLength + 1;
6324 CovariantPathLength != This.Designator.Entries.size();
6325 ++CovariantPathLength) {
6326 const CXXRecordDecl *NextClass =
6327 getBaseClassType(This.Designator, CovariantPathLength);
6328 const CXXMethodDecl *Next =
6329 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6330 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6331 Next->getReturnType(), CovariantAdjustmentPath.back()))
6332 CovariantAdjustmentPath.push_back(Next->getReturnType());
6333 }
6334 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6335 CovariantAdjustmentPath.back()))
6336 CovariantAdjustmentPath.push_back(Found->getReturnType());
6337 }
6338
6339 // Perform 'this' adjustment.
6340 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6341 return nullptr;
6342
6343 return Callee;
6344}
6345
6346/// Perform the adjustment from a value returned by a virtual function to
6347/// a value of the statically expected type, which may be a pointer or
6348/// reference to a base class of the returned type.
6349static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6350 APValue &Result,
6352 assert(Result.isLValue() &&
6353 "unexpected kind of APValue for covariant return");
6354 if (Result.isNullPointer())
6355 return true;
6356
6357 LValue LVal;
6358 LVal.setFrom(Info.Ctx, Result);
6359
6360 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6361 for (unsigned I = 1; I != Path.size(); ++I) {
6362 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6363 assert(OldClass && NewClass && "unexpected kind of covariant return");
6364 if (OldClass != NewClass &&
6365 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6366 return false;
6367 OldClass = NewClass;
6368 }
6369
6370 LVal.moveInto(Result);
6371 return true;
6372}
6373
6374/// Determine whether \p Base, which is known to be a direct base class of
6375/// \p Derived, is a public base class.
6376static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6377 const CXXRecordDecl *Base) {
6378 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6379 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6380 if (BaseClass && declaresSameEntity(BaseClass, Base))
6381 return BaseSpec.getAccessSpecifier() == AS_public;
6382 }
6383 llvm_unreachable("Base is not a direct base of Derived");
6384}
6385
6386/// Apply the given dynamic cast operation on the provided lvalue.
6387///
6388/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6389/// to find a suitable target subobject.
6390static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6391 LValue &Ptr) {
6392 // We can't do anything with a non-symbolic pointer value.
6393 SubobjectDesignator &D = Ptr.Designator;
6394 if (D.Invalid)
6395 return false;
6396
6397 // C++ [expr.dynamic.cast]p6:
6398 // If v is a null pointer value, the result is a null pointer value.
6399 if (Ptr.isNullPointer() && !E->isGLValue())
6400 return true;
6401
6402 // For all the other cases, we need the pointer to point to an object within
6403 // its lifetime / period of construction / destruction, and we need to know
6404 // its dynamic type.
6405 std::optional<DynamicType> DynType =
6406 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6407 if (!DynType)
6408 return false;
6409
6410 // C++ [expr.dynamic.cast]p7:
6411 // If T is "pointer to cv void", then the result is a pointer to the most
6412 // derived object
6413 if (E->getType()->isVoidPointerType())
6414 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6415
6416 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6417 assert(C && "dynamic_cast target is not void pointer nor class");
6418 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6419
6420 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6421 // C++ [expr.dynamic.cast]p9:
6422 if (!E->isGLValue()) {
6423 // The value of a failed cast to pointer type is the null pointer value
6424 // of the required result type.
6425 Ptr.setNull(Info.Ctx, E->getType());
6426 return true;
6427 }
6428
6429 // A failed cast to reference type throws [...] std::bad_cast.
6430 unsigned DiagKind;
6431 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6432 DynType->Type->isDerivedFrom(C)))
6433 DiagKind = 0;
6434 else if (!Paths || Paths->begin() == Paths->end())
6435 DiagKind = 1;
6436 else if (Paths->isAmbiguous(CQT))
6437 DiagKind = 2;
6438 else {
6439 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6440 DiagKind = 3;
6441 }
6442 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6443 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6444 << Info.Ctx.getCanonicalTagType(DynType->Type)
6446 return false;
6447 };
6448
6449 // Runtime check, phase 1:
6450 // Walk from the base subobject towards the derived object looking for the
6451 // target type.
6452 for (int PathLength = Ptr.Designator.Entries.size();
6453 PathLength >= (int)DynType->PathLength; --PathLength) {
6454 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6456 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6457 // We can only walk across public inheritance edges.
6458 if (PathLength > (int)DynType->PathLength &&
6459 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6460 Class))
6461 return RuntimeCheckFailed(nullptr);
6462 }
6463
6464 // Runtime check, phase 2:
6465 // Search the dynamic type for an unambiguous public base of type C.
6466 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6467 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6468 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6469 Paths.front().Access == AS_public) {
6470 // Downcast to the dynamic type...
6471 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6472 return false;
6473 // ... then upcast to the chosen base class subobject.
6474 for (CXXBasePathElement &Elem : Paths.front())
6475 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6476 return false;
6477 return true;
6478 }
6479
6480 // Otherwise, the runtime check fails.
6481 return RuntimeCheckFailed(&Paths);
6482}
6483
6484namespace {
6485struct StartLifetimeOfUnionMemberHandler {
6486 EvalInfo &Info;
6487 const Expr *LHSExpr;
6488 const FieldDecl *Field;
6489 bool DuringInit;
6490 bool Failed = false;
6491 static const AccessKinds AccessKind = AK_Assign;
6492
6493 typedef bool result_type;
6494 bool failed() { return Failed; }
6495 bool found(APValue &Subobj, QualType SubobjType) {
6496 // We are supposed to perform no initialization but begin the lifetime of
6497 // the object. We interpret that as meaning to do what default
6498 // initialization of the object would do if all constructors involved were
6499 // trivial:
6500 // * All base, non-variant member, and array element subobjects' lifetimes
6501 // begin
6502 // * No variant members' lifetimes begin
6503 // * All scalar subobjects whose lifetimes begin have indeterminate values
6504 assert(SubobjType->isUnionType());
6505 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6506 // This union member is already active. If it's also in-lifetime, there's
6507 // nothing to do.
6508 if (Subobj.getUnionValue().hasValue())
6509 return true;
6510 } else if (DuringInit) {
6511 // We're currently in the process of initializing a different union
6512 // member. If we carried on, that initialization would attempt to
6513 // store to an inactive union member, resulting in undefined behavior.
6514 Info.FFDiag(LHSExpr,
6515 diag::note_constexpr_union_member_change_during_init);
6516 return false;
6517 }
6518 APValue Result;
6519 Failed = !handleDefaultInitValue(Field->getType(), Result);
6520 Subobj.setUnion(Field, Result);
6521 return true;
6522 }
6523 bool found(APSInt &Value, QualType SubobjType) {
6524 llvm_unreachable("wrong value kind for union object");
6525 }
6526 bool found(APFloat &Value, QualType SubobjType) {
6527 llvm_unreachable("wrong value kind for union object");
6528 }
6529};
6530} // end anonymous namespace
6531
6532const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6533
6534/// Handle a builtin simple-assignment or a call to a trivial assignment
6535/// operator whose left-hand side might involve a union member access. If it
6536/// does, implicitly start the lifetime of any accessed union elements per
6537/// C++20 [class.union]5.
6538static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6539 const Expr *LHSExpr,
6540 const LValue &LHS) {
6541 if (LHS.InvalidBase || LHS.Designator.Invalid)
6542 return false;
6543
6545 // C++ [class.union]p5:
6546 // define the set S(E) of subexpressions of E as follows:
6547 unsigned PathLength = LHS.Designator.Entries.size();
6548 for (const Expr *E = LHSExpr; E != nullptr;) {
6549 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6550 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6551 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6552 // Note that we can't implicitly start the lifetime of a reference,
6553 // so we don't need to proceed any further if we reach one.
6554 if (!FD || FD->getType()->isReferenceType())
6555 break;
6556
6557 // ... and also contains A.B if B names a union member ...
6558 if (FD->getParent()->isUnion()) {
6559 // ... of a non-class, non-array type, or of a class type with a
6560 // trivial default constructor that is not deleted, or an array of
6561 // such types.
6562 auto *RD =
6563 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6564 if (!RD || RD->hasTrivialDefaultConstructor())
6565 UnionPathLengths.push_back({PathLength - 1, FD});
6566 }
6567
6568 E = ME->getBase();
6569 --PathLength;
6570 assert(declaresSameEntity(FD,
6571 LHS.Designator.Entries[PathLength]
6572 .getAsBaseOrMember().getPointer()));
6573
6574 // -- If E is of the form A[B] and is interpreted as a built-in array
6575 // subscripting operator, S(E) is [S(the array operand, if any)].
6576 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6577 // Step over an ArrayToPointerDecay implicit cast.
6578 auto *Base = ASE->getBase()->IgnoreImplicit();
6579 if (!Base->getType()->isArrayType())
6580 break;
6581
6582 E = Base;
6583 --PathLength;
6584
6585 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6586 // Step over a derived-to-base conversion.
6587 E = ICE->getSubExpr();
6588 if (ICE->getCastKind() == CK_NoOp)
6589 continue;
6590 if (ICE->getCastKind() != CK_DerivedToBase &&
6591 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6592 break;
6593 // Walk path backwards as we walk up from the base to the derived class.
6594 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6595 if (Elt->isVirtual()) {
6596 // A class with virtual base classes never has a trivial default
6597 // constructor, so S(E) is empty in this case.
6598 E = nullptr;
6599 break;
6600 }
6601
6602 --PathLength;
6603 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6604 LHS.Designator.Entries[PathLength]
6605 .getAsBaseOrMember().getPointer()));
6606 }
6607
6608 // -- Otherwise, S(E) is empty.
6609 } else {
6610 break;
6611 }
6612 }
6613
6614 // Common case: no unions' lifetimes are started.
6615 if (UnionPathLengths.empty())
6616 return true;
6617
6618 // if modification of X [would access an inactive union member], an object
6619 // of the type of X is implicitly created
6620 CompleteObject Obj =
6621 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6622 if (!Obj)
6623 return false;
6624 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6625 llvm::reverse(UnionPathLengths)) {
6626 // Form a designator for the union object.
6627 SubobjectDesignator D = LHS.Designator;
6628 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6629
6630 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6631 ConstructionPhase::AfterBases;
6632 StartLifetimeOfUnionMemberHandler StartLifetime{
6633 Info, LHSExpr, LengthAndField.second, DuringInit};
6634 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6635 return false;
6636 }
6637
6638 return true;
6639}
6640
6641static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6642 CallRef Call, EvalInfo &Info, bool NonNull = false,
6643 APValue **EvaluatedArg = nullptr) {
6644 LValue LV;
6645 // Create the parameter slot and register its destruction. For a vararg
6646 // argument, create a temporary.
6647 // FIXME: For calling conventions that destroy parameters in the callee,
6648 // should we consider performing destruction when the function returns
6649 // instead?
6650 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6651 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6652 ScopeKind::Call, LV);
6653 if (!EvaluateInPlace(V, Info, LV, Arg))
6654 return false;
6655
6656 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6657 // undefined behavior, so is non-constant.
6658 if (NonNull && V.isLValue() && V.isNullPointer()) {
6659 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6660 return false;
6661 }
6662
6663 if (EvaluatedArg)
6664 *EvaluatedArg = &V;
6665
6666 return true;
6667}
6668
6669/// Evaluate the arguments to a function call.
6670static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6671 EvalInfo &Info, const FunctionDecl *Callee,
6672 bool RightToLeft = false,
6673 LValue *ObjectArg = nullptr) {
6674 bool Success = true;
6675 llvm::SmallBitVector ForbiddenNullArgs;
6676 if (Callee->hasAttr<NonNullAttr>()) {
6677 ForbiddenNullArgs.resize(Args.size());
6678 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6679 if (!Attr->args_size()) {
6680 ForbiddenNullArgs.set();
6681 break;
6682 } else
6683 for (auto Idx : Attr->args()) {
6684 unsigned ASTIdx = Idx.getASTIndex();
6685 if (ASTIdx >= Args.size())
6686 continue;
6687 ForbiddenNullArgs[ASTIdx] = true;
6688 }
6689 }
6690 }
6691 for (unsigned I = 0; I < Args.size(); I++) {
6692 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6693 const ParmVarDecl *PVD =
6694 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6695 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6696 APValue *That = nullptr;
6697 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6698 // If we're checking for a potential constant expression, evaluate all
6699 // initializers even if some of them fail.
6700 if (!Info.noteFailure())
6701 return false;
6702 Success = false;
6703 }
6704 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6705 ObjectArg->setFrom(Info.Ctx, *That);
6706 }
6707 return Success;
6708}
6709
6710/// Perform a trivial copy from Param, which is the parameter of a copy or move
6711/// constructor or assignment operator.
6712static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6713 const Expr *E, APValue &Result,
6714 bool CopyObjectRepresentation) {
6715 // Find the reference argument.
6716 CallStackFrame *Frame = Info.CurrentCall;
6717 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6718 if (!RefValue) {
6719 Info.FFDiag(E);
6720 return false;
6721 }
6722
6723 // Copy out the contents of the RHS object.
6724 LValue RefLValue;
6725 RefLValue.setFrom(Info.Ctx, *RefValue);
6727 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6728 CopyObjectRepresentation);
6729}
6730
6731/// Evaluate a function call.
6733 const FunctionDecl *Callee,
6734 const LValue *ObjectArg, const Expr *E,
6735 ArrayRef<const Expr *> Args, CallRef Call,
6736 const Stmt *Body, EvalInfo &Info,
6737 APValue &Result, const LValue *ResultSlot) {
6738 if (!Info.CheckCallLimit(CallLoc))
6739 return false;
6740
6741 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
6742
6743 // For a trivial copy or move assignment, perform an APValue copy. This is
6744 // essential for unions, where the operations performed by the assignment
6745 // operator cannot be represented as statements.
6746 //
6747 // Skip this for non-union classes with no fields; in that case, the defaulted
6748 // copy/move does not actually read the object.
6749 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6750 if (MD && MD->isDefaulted() &&
6751 (MD->getParent()->isUnion() ||
6752 (MD->isTrivial() &&
6754 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
6755 assert(ObjectArg &&
6757 APValue RHSValue;
6758 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6759 MD->getParent()->isUnion()))
6760 return false;
6761
6762 LValue Obj;
6763 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
6765 RHSValue))
6766 return false;
6767 ObjectArg->moveInto(Result);
6768 return true;
6769 } else if (MD && isLambdaCallOperator(MD)) {
6770 // We're in a lambda; determine the lambda capture field maps unless we're
6771 // just constexpr checking a lambda's call operator. constexpr checking is
6772 // done before the captures have been added to the closure object (unless
6773 // we're inferring constexpr-ness), so we don't have access to them in this
6774 // case. But since we don't need the captures to constexpr check, we can
6775 // just ignore them.
6776 if (!Info.checkingPotentialConstantExpression())
6777 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6778 Frame.LambdaThisCaptureField);
6779 }
6780
6781 StmtResult Ret = {Result, ResultSlot};
6782 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6783 if (ESR == ESR_Succeeded) {
6784 if (Callee->getReturnType()->isVoidType())
6785 return true;
6786 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6787 }
6788 return ESR == ESR_Returned;
6789}
6790
6791/// Evaluate a constructor call.
6792static bool HandleConstructorCall(const Expr *E, const LValue &This,
6793 CallRef Call,
6795 EvalInfo &Info, APValue &Result) {
6796 SourceLocation CallLoc = E->getExprLoc();
6797 if (!Info.CheckCallLimit(CallLoc))
6798 return false;
6799
6800 const CXXRecordDecl *RD = Definition->getParent();
6801 if (RD->getNumVBases()) {
6802 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6803 return false;
6804 }
6805
6806 EvalInfo::EvaluatingConstructorRAII EvalObj(
6807 Info,
6808 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6809 RD->getNumBases());
6810 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6811
6812 // FIXME: Creating an APValue just to hold a nonexistent return value is
6813 // wasteful.
6814 APValue RetVal;
6815 StmtResult Ret = {RetVal, nullptr};
6816
6817 // If it's a delegating constructor, delegate.
6818 if (Definition->isDelegatingConstructor()) {
6820 if ((*I)->getInit()->isValueDependent()) {
6821 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6822 return false;
6823 } else {
6824 FullExpressionRAII InitScope(Info);
6825 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6826 !InitScope.destroy())
6827 return false;
6828 }
6829 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6830 }
6831
6832 // For a trivial copy or move constructor, perform an APValue copy. This is
6833 // essential for unions (or classes with anonymous union members), where the
6834 // operations performed by the constructor cannot be represented by
6835 // ctor-initializers.
6836 //
6837 // Skip this for empty non-union classes; we should not perform an
6838 // lvalue-to-rvalue conversion on them because their copy constructor does not
6839 // actually read them.
6840 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6841 (Definition->getParent()->isUnion() ||
6842 (Definition->isTrivial() &&
6844 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6845 Definition->getParent()->isUnion());
6846 }
6847
6848 // Reserve space for the struct members.
6849 if (!Result.hasValue()) {
6850 if (!RD->isUnion())
6851 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6852 std::distance(RD->field_begin(), RD->field_end()));
6853 else
6854 // A union starts with no active member.
6855 Result = APValue((const FieldDecl*)nullptr);
6856 }
6857
6858 if (RD->isInvalidDecl()) return false;
6859 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6860
6861 // A scope for temporaries lifetime-extended by reference members.
6862 BlockScopeRAII LifetimeExtendedScope(Info);
6863
6864 bool Success = true;
6865 unsigned BasesSeen = 0;
6866#ifndef NDEBUG
6868#endif
6870 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6871 // We might be initializing the same field again if this is an indirect
6872 // field initialization.
6873 if (FieldIt == RD->field_end() ||
6874 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6875 assert(Indirect && "fields out of order?");
6876 return;
6877 }
6878
6879 // Default-initialize any fields with no explicit initializer.
6880 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6881 assert(FieldIt != RD->field_end() && "missing field?");
6882 if (!FieldIt->isUnnamedBitField())
6884 FieldIt->getType(),
6885 Result.getStructField(FieldIt->getFieldIndex()));
6886 }
6887 ++FieldIt;
6888 };
6889 for (const auto *I : Definition->inits()) {
6890 LValue Subobject = This;
6891 LValue SubobjectParent = This;
6892 APValue *Value = &Result;
6893
6894 // Determine the subobject to initialize.
6895 FieldDecl *FD = nullptr;
6896 if (I->isBaseInitializer()) {
6897 QualType BaseType(I->getBaseClass(), 0);
6898#ifndef NDEBUG
6899 // Non-virtual base classes are initialized in the order in the class
6900 // definition. We have already checked for virtual base classes.
6901 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6902 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6903 "base class initializers not in expected order");
6904 ++BaseIt;
6905#endif
6906 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6907 BaseType->getAsCXXRecordDecl(), &Layout))
6908 return false;
6909 Value = &Result.getStructBase(BasesSeen++);
6910 } else if ((FD = I->getMember())) {
6911 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6912 return false;
6913 if (RD->isUnion()) {
6914 Result = APValue(FD);
6915 Value = &Result.getUnionValue();
6916 } else {
6917 SkipToField(FD, false);
6918 Value = &Result.getStructField(FD->getFieldIndex());
6919 }
6920 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6921 // Walk the indirect field decl's chain to find the object to initialize,
6922 // and make sure we've initialized every step along it.
6923 auto IndirectFieldChain = IFD->chain();
6924 for (auto *C : IndirectFieldChain) {
6925 FD = cast<FieldDecl>(C);
6926 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6927 // Switch the union field if it differs. This happens if we had
6928 // preceding zero-initialization, and we're now initializing a union
6929 // subobject other than the first.
6930 // FIXME: In this case, the values of the other subobjects are
6931 // specified, since zero-initialization sets all padding bits to zero.
6932 if (!Value->hasValue() ||
6933 (Value->isUnion() &&
6934 !declaresSameEntity(Value->getUnionField(), FD))) {
6935 if (CD->isUnion())
6936 *Value = APValue(FD);
6937 else
6938 // FIXME: This immediately starts the lifetime of all members of
6939 // an anonymous struct. It would be preferable to strictly start
6940 // member lifetime in initialization order.
6941 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
6942 *Value);
6943 }
6944 // Store Subobject as its parent before updating it for the last element
6945 // in the chain.
6946 if (C == IndirectFieldChain.back())
6947 SubobjectParent = Subobject;
6948 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6949 return false;
6950 if (CD->isUnion())
6951 Value = &Value->getUnionValue();
6952 else {
6953 if (C == IndirectFieldChain.front() && !RD->isUnion())
6954 SkipToField(FD, true);
6955 Value = &Value->getStructField(FD->getFieldIndex());
6956 }
6957 }
6958 } else {
6959 llvm_unreachable("unknown base initializer kind");
6960 }
6961
6962 // Need to override This for implicit field initializers as in this case
6963 // This refers to innermost anonymous struct/union containing initializer,
6964 // not to currently constructed class.
6965 const Expr *Init = I->getInit();
6966 if (Init->isValueDependent()) {
6967 if (!EvaluateDependentExpr(Init, Info))
6968 return false;
6969 } else {
6970 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6971 isa<CXXDefaultInitExpr>(Init));
6972 FullExpressionRAII InitScope(Info);
6973 if (FD && FD->getType()->isReferenceType() &&
6974 !FD->getType()->isFunctionReferenceType()) {
6975 LValue Result;
6976 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
6977 *Value)) {
6978 if (!Info.noteFailure())
6979 return false;
6980 Success = false;
6981 }
6982 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6983 (FD && FD->isBitField() &&
6984 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6985 // If we're checking for a potential constant expression, evaluate all
6986 // initializers even if some of them fail.
6987 if (!Info.noteFailure())
6988 return false;
6989 Success = false;
6990 }
6991 }
6992
6993 // This is the point at which the dynamic type of the object becomes this
6994 // class type.
6995 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6996 EvalObj.finishedConstructingBases();
6997 }
6998
6999 // Default-initialize any remaining fields.
7000 if (!RD->isUnion()) {
7001 for (; FieldIt != RD->field_end(); ++FieldIt) {
7002 if (!FieldIt->isUnnamedBitField())
7004 FieldIt->getType(),
7005 Result.getStructField(FieldIt->getFieldIndex()));
7006 }
7007 }
7008
7009 EvalObj.finishedConstructingFields();
7010
7011 return Success &&
7012 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7013 LifetimeExtendedScope.destroy();
7014}
7015
7016static bool HandleConstructorCall(const Expr *E, const LValue &This,
7019 EvalInfo &Info, APValue &Result) {
7020 CallScopeRAII CallScope(Info);
7021 CallRef Call = Info.CurrentCall->createCall(Definition);
7022 if (!EvaluateArgs(Args, Call, Info, Definition))
7023 return false;
7024
7025 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7026 CallScope.destroy();
7027}
7028
7029static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7030 const LValue &This, APValue &Value,
7031 QualType T) {
7032 // Objects can only be destroyed while they're within their lifetimes.
7033 // FIXME: We have no representation for whether an object of type nullptr_t
7034 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7035 // as indeterminate instead?
7036 if (Value.isAbsent() && !T->isNullPtrType()) {
7037 APValue Printable;
7038 This.moveInto(Printable);
7039 Info.FFDiag(CallRange.getBegin(),
7040 diag::note_constexpr_destroy_out_of_lifetime)
7041 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7042 return false;
7043 }
7044
7045 // Invent an expression for location purposes.
7046 // FIXME: We shouldn't need to do this.
7047 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7048
7049 // For arrays, destroy elements right-to-left.
7050 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7051 uint64_t Size = CAT->getZExtSize();
7052 QualType ElemT = CAT->getElementType();
7053
7054 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7055 return false;
7056
7057 LValue ElemLV = This;
7058 ElemLV.addArray(Info, &LocE, CAT);
7059 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7060 return false;
7061
7062 // Ensure that we have actual array elements available to destroy; the
7063 // destructors might mutate the value, so we can't run them on the array
7064 // filler.
7065 if (Size && Size > Value.getArrayInitializedElts())
7066 expandArray(Value, Value.getArraySize() - 1);
7067
7068 // The size of the array might have been reduced by
7069 // a placement new.
7070 for (Size = Value.getArraySize(); Size != 0; --Size) {
7071 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7072 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7073 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7074 return false;
7075 }
7076
7077 // End the lifetime of this array now.
7078 Value = APValue();
7079 return true;
7080 }
7081
7082 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7083 if (!RD) {
7084 if (T.isDestructedType()) {
7085 Info.FFDiag(CallRange.getBegin(),
7086 diag::note_constexpr_unsupported_destruction)
7087 << T;
7088 return false;
7089 }
7090
7091 Value = APValue();
7092 return true;
7093 }
7094
7095 if (RD->getNumVBases()) {
7096 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7097 return false;
7098 }
7099
7100 const CXXDestructorDecl *DD = RD->getDestructor();
7101 if (!DD && !RD->hasTrivialDestructor()) {
7102 Info.FFDiag(CallRange.getBegin());
7103 return false;
7104 }
7105
7106 if (!DD || DD->isTrivial() ||
7107 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7108 // A trivial destructor just ends the lifetime of the object. Check for
7109 // this case before checking for a body, because we might not bother
7110 // building a body for a trivial destructor. Note that it doesn't matter
7111 // whether the destructor is constexpr in this case; all trivial
7112 // destructors are constexpr.
7113 //
7114 // If an anonymous union would be destroyed, some enclosing destructor must
7115 // have been explicitly defined, and the anonymous union destruction should
7116 // have no effect.
7117 Value = APValue();
7118 return true;
7119 }
7120
7121 if (!Info.CheckCallLimit(CallRange.getBegin()))
7122 return false;
7123
7124 const FunctionDecl *Definition = nullptr;
7125 const Stmt *Body = DD->getBody(Definition);
7126
7127 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7128 return false;
7129
7130 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7131 CallRef());
7132
7133 // We're now in the period of destruction of this object.
7134 unsigned BasesLeft = RD->getNumBases();
7135 EvalInfo::EvaluatingDestructorRAII EvalObj(
7136 Info,
7137 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7138 if (!EvalObj.DidInsert) {
7139 // C++2a [class.dtor]p19:
7140 // the behavior is undefined if the destructor is invoked for an object
7141 // whose lifetime has ended
7142 // (Note that formally the lifetime ends when the period of destruction
7143 // begins, even though certain uses of the object remain valid until the
7144 // period of destruction ends.)
7145 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7146 return false;
7147 }
7148
7149 // FIXME: Creating an APValue just to hold a nonexistent return value is
7150 // wasteful.
7151 APValue RetVal;
7152 StmtResult Ret = {RetVal, nullptr};
7153 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7154 return false;
7155
7156 // A union destructor does not implicitly destroy its members.
7157 if (RD->isUnion())
7158 return true;
7159
7160 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7161
7162 // We don't have a good way to iterate fields in reverse, so collect all the
7163 // fields first and then walk them backwards.
7164 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7165 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7166 if (FD->isUnnamedBitField())
7167 continue;
7168
7169 LValue Subobject = This;
7170 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7171 return false;
7172
7173 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7174 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7175 FD->getType()))
7176 return false;
7177 }
7178
7179 if (BasesLeft != 0)
7180 EvalObj.startedDestroyingBases();
7181
7182 // Destroy base classes in reverse order.
7183 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7184 --BasesLeft;
7185
7186 QualType BaseType = Base.getType();
7187 LValue Subobject = This;
7188 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7189 BaseType->getAsCXXRecordDecl(), &Layout))
7190 return false;
7191
7192 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7193 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7194 BaseType))
7195 return false;
7196 }
7197 assert(BasesLeft == 0 && "NumBases was wrong?");
7198
7199 // The period of destruction ends now. The object is gone.
7200 Value = APValue();
7201 return true;
7202}
7203
7204namespace {
7205struct DestroyObjectHandler {
7206 EvalInfo &Info;
7207 const Expr *E;
7208 const LValue &This;
7209 const AccessKinds AccessKind;
7210
7211 typedef bool result_type;
7212 bool failed() { return false; }
7213 bool found(APValue &Subobj, QualType SubobjType) {
7214 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7215 SubobjType);
7216 }
7217 bool found(APSInt &Value, QualType SubobjType) {
7218 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7219 return false;
7220 }
7221 bool found(APFloat &Value, QualType SubobjType) {
7222 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7223 return false;
7224 }
7225};
7226}
7227
7228/// Perform a destructor or pseudo-destructor call on the given object, which
7229/// might in general not be a complete object.
7230static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7231 const LValue &This, QualType ThisType) {
7232 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7233 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7234 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7235}
7236
7237/// Destroy and end the lifetime of the given complete object.
7238static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7240 QualType T) {
7241 // If we've had an unmodeled side-effect, we can't rely on mutable state
7242 // (such as the object we're about to destroy) being correct.
7243 if (Info.EvalStatus.HasSideEffects)
7244 return false;
7245
7246 LValue LV;
7247 LV.set({LVBase});
7248 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7249}
7250
7251/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7252static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7253 LValue &Result) {
7254 if (Info.checkingPotentialConstantExpression() ||
7255 Info.SpeculativeEvaluationDepth)
7256 return false;
7257
7258 // This is permitted only within a call to std::allocator<T>::allocate.
7259 auto Caller = Info.getStdAllocatorCaller("allocate");
7260 if (!Caller) {
7261 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7262 ? diag::note_constexpr_new_untyped
7263 : diag::note_constexpr_new);
7264 return false;
7265 }
7266
7267 QualType ElemType = Caller.ElemType;
7268 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7269 Info.FFDiag(E->getExprLoc(),
7270 diag::note_constexpr_new_not_complete_object_type)
7271 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7272 return false;
7273 }
7274
7275 APSInt ByteSize;
7276 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7277 return false;
7278 bool IsNothrow = false;
7279 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7280 EvaluateIgnoredValue(Info, E->getArg(I));
7281 IsNothrow |= E->getType()->isNothrowT();
7282 }
7283
7284 CharUnits ElemSize;
7285 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7286 return false;
7287 APInt Size, Remainder;
7288 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7289 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7290 if (Remainder != 0) {
7291 // This likely indicates a bug in the implementation of 'std::allocator'.
7292 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7293 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7294 return false;
7295 }
7296
7297 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7298 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7299 if (IsNothrow) {
7300 Result.setNull(Info.Ctx, E->getType());
7301 return true;
7302 }
7303 return false;
7304 }
7305
7306 QualType AllocType = Info.Ctx.getConstantArrayType(
7307 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7308 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7309 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7310 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7311 return true;
7312}
7313
7315 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7316 if (CXXDestructorDecl *DD = RD->getDestructor())
7317 return DD->isVirtual();
7318 return false;
7319}
7320
7322 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7323 if (CXXDestructorDecl *DD = RD->getDestructor())
7324 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7325 return nullptr;
7326}
7327
7328/// Check that the given object is a suitable pointer to a heap allocation that
7329/// still exists and is of the right kind for the purpose of a deletion.
7330///
7331/// On success, returns the heap allocation to deallocate. On failure, produces
7332/// a diagnostic and returns std::nullopt.
7333static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7334 const LValue &Pointer,
7335 DynAlloc::Kind DeallocKind) {
7336 auto PointerAsString = [&] {
7337 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7338 };
7339
7340 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7341 if (!DA) {
7342 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7343 << PointerAsString();
7344 if (Pointer.Base)
7345 NoteLValueLocation(Info, Pointer.Base);
7346 return std::nullopt;
7347 }
7348
7349 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7350 if (!Alloc) {
7351 Info.FFDiag(E, diag::note_constexpr_double_delete);
7352 return std::nullopt;
7353 }
7354
7355 if (DeallocKind != (*Alloc)->getKind()) {
7356 QualType AllocType = Pointer.Base.getDynamicAllocType();
7357 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7358 << DeallocKind << (*Alloc)->getKind() << AllocType;
7359 NoteLValueLocation(Info, Pointer.Base);
7360 return std::nullopt;
7361 }
7362
7363 bool Subobject = false;
7364 if (DeallocKind == DynAlloc::New) {
7365 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7366 Pointer.Designator.isOnePastTheEnd();
7367 } else {
7368 Subobject = Pointer.Designator.Entries.size() != 1 ||
7369 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7370 }
7371 if (Subobject) {
7372 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7373 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7374 return std::nullopt;
7375 }
7376
7377 return Alloc;
7378}
7379
7380// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7381static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7382 if (Info.checkingPotentialConstantExpression() ||
7383 Info.SpeculativeEvaluationDepth)
7384 return false;
7385
7386 // This is permitted only within a call to std::allocator<T>::deallocate.
7387 if (!Info.getStdAllocatorCaller("deallocate")) {
7388 Info.FFDiag(E->getExprLoc());
7389 return true;
7390 }
7391
7392 LValue Pointer;
7393 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7394 return false;
7395 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7396 EvaluateIgnoredValue(Info, E->getArg(I));
7397
7398 if (Pointer.Designator.Invalid)
7399 return false;
7400
7401 // Deleting a null pointer would have no effect, but it's not permitted by
7402 // std::allocator<T>::deallocate's contract.
7403 if (Pointer.isNullPointer()) {
7404 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7405 return true;
7406 }
7407
7408 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7409 return false;
7410
7411 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7412 return true;
7413}
7414
7415//===----------------------------------------------------------------------===//
7416// Generic Evaluation
7417//===----------------------------------------------------------------------===//
7418namespace {
7419
7420class BitCastBuffer {
7421 // FIXME: We're going to need bit-level granularity when we support
7422 // bit-fields.
7423 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7424 // we don't support a host or target where that is the case. Still, we should
7425 // use a more generic type in case we ever do.
7427
7428 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7429 "Need at least 8 bit unsigned char");
7430
7431 bool TargetIsLittleEndian;
7432
7433public:
7434 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7435 : Bytes(Width.getQuantity()),
7436 TargetIsLittleEndian(TargetIsLittleEndian) {}
7437
7438 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7439 SmallVectorImpl<unsigned char> &Output) const {
7440 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7441 // If a byte of an integer is uninitialized, then the whole integer is
7442 // uninitialized.
7443 if (!Bytes[I.getQuantity()])
7444 return false;
7445 Output.push_back(*Bytes[I.getQuantity()]);
7446 }
7447 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7448 std::reverse(Output.begin(), Output.end());
7449 return true;
7450 }
7451
7452 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7453 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7454 std::reverse(Input.begin(), Input.end());
7455
7456 size_t Index = 0;
7457 for (unsigned char Byte : Input) {
7458 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7459 Bytes[Offset.getQuantity() + Index] = Byte;
7460 ++Index;
7461 }
7462 }
7463
7464 size_t size() { return Bytes.size(); }
7465};
7466
7467/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7468/// target would represent the value at runtime.
7469class APValueToBufferConverter {
7470 EvalInfo &Info;
7471 BitCastBuffer Buffer;
7472 const CastExpr *BCE;
7473
7474 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7475 const CastExpr *BCE)
7476 : Info(Info),
7477 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7478 BCE(BCE) {}
7479
7480 bool visit(const APValue &Val, QualType Ty) {
7481 return visit(Val, Ty, CharUnits::fromQuantity(0));
7482 }
7483
7484 // Write out Val with type Ty into Buffer starting at Offset.
7485 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7486 assert((size_t)Offset.getQuantity() <= Buffer.size());
7487
7488 // As a special case, nullptr_t has an indeterminate value.
7489 if (Ty->isNullPtrType())
7490 return true;
7491
7492 // Dig through Src to find the byte at SrcOffset.
7493 switch (Val.getKind()) {
7495 case APValue::None:
7496 return true;
7497
7498 case APValue::Int:
7499 return visitInt(Val.getInt(), Ty, Offset);
7500 case APValue::Float:
7501 return visitFloat(Val.getFloat(), Ty, Offset);
7502 case APValue::Array:
7503 return visitArray(Val, Ty, Offset);
7504 case APValue::Struct:
7505 return visitRecord(Val, Ty, Offset);
7506 case APValue::Vector:
7507 return visitVector(Val, Ty, Offset);
7508
7511 return visitComplex(Val, Ty, Offset);
7513 // FIXME: We should support these.
7514
7515 case APValue::Union:
7518 Info.FFDiag(BCE->getBeginLoc(),
7519 diag::note_constexpr_bit_cast_unsupported_type)
7520 << Ty;
7521 return false;
7522 }
7523
7524 case APValue::LValue:
7525 llvm_unreachable("LValue subobject in bit_cast?");
7526 }
7527 llvm_unreachable("Unhandled APValue::ValueKind");
7528 }
7529
7530 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7531 const RecordDecl *RD = Ty->getAsRecordDecl();
7532 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7533
7534 // Visit the base classes.
7535 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7536 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7537 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7538 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7539 const APValue &Base = Val.getStructBase(I);
7540
7541 // Can happen in error cases.
7542 if (!Base.isStruct())
7543 return false;
7544
7545 if (!visitRecord(Base, BS.getType(),
7546 Layout.getBaseClassOffset(BaseDecl) + Offset))
7547 return false;
7548 }
7549 }
7550
7551 // Visit the fields.
7552 unsigned FieldIdx = 0;
7553 for (FieldDecl *FD : RD->fields()) {
7554 if (FD->isBitField()) {
7555 Info.FFDiag(BCE->getBeginLoc(),
7556 diag::note_constexpr_bit_cast_unsupported_bitfield);
7557 return false;
7558 }
7559
7560 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7561
7562 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7563 "only bit-fields can have sub-char alignment");
7564 CharUnits FieldOffset =
7565 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7566 QualType FieldTy = FD->getType();
7567 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7568 return false;
7569 ++FieldIdx;
7570 }
7571
7572 return true;
7573 }
7574
7575 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7576 const auto *CAT =
7577 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7578 if (!CAT)
7579 return false;
7580
7581 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7582 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7583 unsigned ArraySize = Val.getArraySize();
7584 // First, initialize the initialized elements.
7585 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7586 const APValue &SubObj = Val.getArrayInitializedElt(I);
7587 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7588 return false;
7589 }
7590
7591 // Next, initialize the rest of the array using the filler.
7592 if (Val.hasArrayFiller()) {
7593 const APValue &Filler = Val.getArrayFiller();
7594 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7595 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7596 return false;
7597 }
7598 }
7599
7600 return true;
7601 }
7602
7603 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7604 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7605 QualType EltTy = ComplexTy->getElementType();
7606 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7607 bool IsInt = Val.isComplexInt();
7608
7609 if (IsInt) {
7610 if (!visitInt(Val.getComplexIntReal(), EltTy,
7611 Offset + (0 * EltSizeChars)))
7612 return false;
7613 if (!visitInt(Val.getComplexIntImag(), EltTy,
7614 Offset + (1 * EltSizeChars)))
7615 return false;
7616 } else {
7617 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7618 Offset + (0 * EltSizeChars)))
7619 return false;
7620 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7621 Offset + (1 * EltSizeChars)))
7622 return false;
7623 }
7624
7625 return true;
7626 }
7627
7628 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7629 const VectorType *VTy = Ty->castAs<VectorType>();
7630 QualType EltTy = VTy->getElementType();
7631 unsigned NElts = VTy->getNumElements();
7632
7633 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7634 // Special handling for OpenCL bool vectors:
7635 // Since these vectors are stored as packed bits, but we can't write
7636 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7637 // together into an appropriately sized APInt and write them all out at
7638 // once. Because we don't accept vectors where NElts * EltSize isn't a
7639 // multiple of the char size, there will be no padding space, so we don't
7640 // have to worry about writing data which should have been left
7641 // uninitialized.
7642 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7643
7644 llvm::APInt Res = llvm::APInt::getZero(NElts);
7645 for (unsigned I = 0; I < NElts; ++I) {
7646 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7647 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7648 "bool vector element must be 1-bit unsigned integer!");
7649
7650 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7651 }
7652
7653 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7654 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7655 Buffer.writeObject(Offset, Bytes);
7656 } else {
7657 // Iterate over each of the elements and write them out to the buffer at
7658 // the appropriate offset.
7659 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7660 for (unsigned I = 0; I < NElts; ++I) {
7661 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7662 return false;
7663 }
7664 }
7665
7666 return true;
7667 }
7668
7669 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7670 APSInt AdjustedVal = Val;
7671 unsigned Width = AdjustedVal.getBitWidth();
7672 if (Ty->isBooleanType()) {
7673 Width = Info.Ctx.getTypeSize(Ty);
7674 AdjustedVal = AdjustedVal.extend(Width);
7675 }
7676
7677 SmallVector<uint8_t, 8> Bytes(Width / 8);
7678 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7679 Buffer.writeObject(Offset, Bytes);
7680 return true;
7681 }
7682
7683 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7684 APSInt AsInt(Val.bitcastToAPInt());
7685 return visitInt(AsInt, Ty, Offset);
7686 }
7687
7688public:
7689 static std::optional<BitCastBuffer>
7690 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7691 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7692 APValueToBufferConverter Converter(Info, DstSize, BCE);
7693 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7694 return std::nullopt;
7695 return Converter.Buffer;
7696 }
7697};
7698
7699/// Write an BitCastBuffer into an APValue.
7700class BufferToAPValueConverter {
7701 EvalInfo &Info;
7702 const BitCastBuffer &Buffer;
7703 const CastExpr *BCE;
7704
7705 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7706 const CastExpr *BCE)
7707 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7708
7709 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7710 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7711 // Ideally this will be unreachable.
7712 std::nullopt_t unsupportedType(QualType Ty) {
7713 Info.FFDiag(BCE->getBeginLoc(),
7714 diag::note_constexpr_bit_cast_unsupported_type)
7715 << Ty;
7716 return std::nullopt;
7717 }
7718
7719 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7720 Info.FFDiag(BCE->getBeginLoc(),
7721 diag::note_constexpr_bit_cast_unrepresentable_value)
7722 << Ty << toString(Val, /*Radix=*/10);
7723 return std::nullopt;
7724 }
7725
7726 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7727 const EnumType *EnumSugar = nullptr) {
7728 if (T->isNullPtrType()) {
7729 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7730 return APValue((Expr *)nullptr,
7731 /*Offset=*/CharUnits::fromQuantity(NullValue),
7732 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7733 }
7734
7735 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7736
7737 // Work around floating point types that contain unused padding bytes. This
7738 // is really just `long double` on x86, which is the only fundamental type
7739 // with padding bytes.
7740 if (T->isRealFloatingType()) {
7741 const llvm::fltSemantics &Semantics =
7742 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7743 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7744 assert(NumBits % 8 == 0);
7745 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7746 if (NumBytes != SizeOf)
7747 SizeOf = NumBytes;
7748 }
7749
7751 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7752 // If this is std::byte or unsigned char, then its okay to store an
7753 // indeterminate value.
7754 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7755 bool IsUChar =
7756 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7757 T->isSpecificBuiltinType(BuiltinType::Char_U));
7758 if (!IsStdByte && !IsUChar) {
7759 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7760 Info.FFDiag(BCE->getExprLoc(),
7761 diag::note_constexpr_bit_cast_indet_dest)
7762 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7763 return std::nullopt;
7764 }
7765
7767 }
7768
7769 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7770 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7771
7773 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7774
7775 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7776 if (IntWidth != Val.getBitWidth()) {
7777 APSInt Truncated = Val.trunc(IntWidth);
7778 if (Truncated.extend(Val.getBitWidth()) != Val)
7779 return unrepresentableValue(QualType(T, 0), Val);
7780 Val = Truncated;
7781 }
7782
7783 return APValue(Val);
7784 }
7785
7786 if (T->isRealFloatingType()) {
7787 const llvm::fltSemantics &Semantics =
7788 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7789 return APValue(APFloat(Semantics, Val));
7790 }
7791
7792 return unsupportedType(QualType(T, 0));
7793 }
7794
7795 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7796 const RecordDecl *RD = RTy->getAsRecordDecl();
7797 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7798
7799 unsigned NumBases = 0;
7800 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7801 NumBases = CXXRD->getNumBases();
7802
7803 APValue ResultVal(APValue::UninitStruct(), NumBases,
7804 std::distance(RD->field_begin(), RD->field_end()));
7805
7806 // Visit the base classes.
7807 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7808 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7809 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7810 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7811
7812 std::optional<APValue> SubObj = visitType(
7813 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7814 if (!SubObj)
7815 return std::nullopt;
7816 ResultVal.getStructBase(I) = *SubObj;
7817 }
7818 }
7819
7820 // Visit the fields.
7821 unsigned FieldIdx = 0;
7822 for (FieldDecl *FD : RD->fields()) {
7823 // FIXME: We don't currently support bit-fields. A lot of the logic for
7824 // this is in CodeGen, so we need to factor it around.
7825 if (FD->isBitField()) {
7826 Info.FFDiag(BCE->getBeginLoc(),
7827 diag::note_constexpr_bit_cast_unsupported_bitfield);
7828 return std::nullopt;
7829 }
7830
7831 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7832 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7833
7834 CharUnits FieldOffset =
7835 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7836 Offset;
7837 QualType FieldTy = FD->getType();
7838 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7839 if (!SubObj)
7840 return std::nullopt;
7841 ResultVal.getStructField(FieldIdx) = *SubObj;
7842 ++FieldIdx;
7843 }
7844
7845 return ResultVal;
7846 }
7847
7848 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7849 QualType RepresentationType =
7851 assert(!RepresentationType.isNull() &&
7852 "enum forward decl should be caught by Sema");
7853 const auto *AsBuiltin =
7854 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7855 // Recurse into the underlying type. Treat std::byte transparently as
7856 // unsigned char.
7857 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7858 }
7859
7860 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7861 size_t Size = Ty->getLimitedSize();
7862 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7863
7864 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7865 for (size_t I = 0; I != Size; ++I) {
7866 std::optional<APValue> ElementValue =
7867 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7868 if (!ElementValue)
7869 return std::nullopt;
7870 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7871 }
7872
7873 return ArrayValue;
7874 }
7875
7876 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7877 QualType ElementType = Ty->getElementType();
7878 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7879 bool IsInt = ElementType->isIntegerType();
7880
7881 std::optional<APValue> Values[2];
7882 for (unsigned I = 0; I != 2; ++I) {
7883 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7884 if (!Values[I])
7885 return std::nullopt;
7886 }
7887
7888 if (IsInt)
7889 return APValue(Values[0]->getInt(), Values[1]->getInt());
7890 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7891 }
7892
7893 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7894 QualType EltTy = VTy->getElementType();
7895 unsigned NElts = VTy->getNumElements();
7896 unsigned EltSize =
7897 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
7898
7900 Elts.reserve(NElts);
7901 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7902 // Special handling for OpenCL bool vectors:
7903 // Since these vectors are stored as packed bits, but we can't read
7904 // individual bits from the BitCastBuffer, we'll buffer all of the
7905 // elements together into an appropriately sized APInt and write them all
7906 // out at once. Because we don't accept vectors where NElts * EltSize
7907 // isn't a multiple of the char size, there will be no padding space, so
7908 // we don't have to worry about reading any padding data which didn't
7909 // actually need to be accessed.
7910 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7911
7913 Bytes.reserve(NElts / 8);
7914 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7915 return std::nullopt;
7916
7917 APSInt SValInt(NElts, true);
7918 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7919
7920 for (unsigned I = 0; I < NElts; ++I) {
7921 llvm::APInt Elt =
7922 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7923 Elts.emplace_back(
7924 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7925 }
7926 } else {
7927 // Iterate over each of the elements and read them from the buffer at
7928 // the appropriate offset.
7929 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7930 for (unsigned I = 0; I < NElts; ++I) {
7931 std::optional<APValue> EltValue =
7932 visitType(EltTy, Offset + I * EltSizeChars);
7933 if (!EltValue)
7934 return std::nullopt;
7935 Elts.push_back(std::move(*EltValue));
7936 }
7937 }
7938
7939 return APValue(Elts.data(), Elts.size());
7940 }
7941
7942 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7943 return unsupportedType(QualType(Ty, 0));
7944 }
7945
7946 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7947 QualType Can = Ty.getCanonicalType();
7948
7949 switch (Can->getTypeClass()) {
7950#define TYPE(Class, Base) \
7951 case Type::Class: \
7952 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7953#define ABSTRACT_TYPE(Class, Base)
7954#define NON_CANONICAL_TYPE(Class, Base) \
7955 case Type::Class: \
7956 llvm_unreachable("non-canonical type should be impossible!");
7957#define DEPENDENT_TYPE(Class, Base) \
7958 case Type::Class: \
7959 llvm_unreachable( \
7960 "dependent types aren't supported in the constant evaluator!");
7961#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7962 case Type::Class: \
7963 llvm_unreachable("either dependent or not canonical!");
7964#include "clang/AST/TypeNodes.inc"
7965 }
7966 llvm_unreachable("Unhandled Type::TypeClass");
7967 }
7968
7969public:
7970 // Pull out a full value of type DstType.
7971 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7972 const CastExpr *BCE) {
7973 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7974 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7975 }
7976};
7977
7978static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7979 QualType Ty, EvalInfo *Info,
7980 const ASTContext &Ctx,
7981 bool CheckingDest) {
7982 Ty = Ty.getCanonicalType();
7983
7984 auto diag = [&](int Reason) {
7985 if (Info)
7986 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7987 << CheckingDest << (Reason == 4) << Reason;
7988 return false;
7989 };
7990 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7991 if (Info)
7992 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7993 << NoteTy << Construct << Ty;
7994 return false;
7995 };
7996
7997 if (Ty->isUnionType())
7998 return diag(0);
7999 if (Ty->isPointerType())
8000 return diag(1);
8001 if (Ty->isMemberPointerType())
8002 return diag(2);
8003 if (Ty.isVolatileQualified())
8004 return diag(3);
8005
8006 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8007 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8008 for (CXXBaseSpecifier &BS : CXXRD->bases())
8009 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8010 CheckingDest))
8011 return note(1, BS.getType(), BS.getBeginLoc());
8012 }
8013 for (FieldDecl *FD : Record->fields()) {
8014 if (FD->getType()->isReferenceType())
8015 return diag(4);
8016 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8017 CheckingDest))
8018 return note(0, FD->getType(), FD->getBeginLoc());
8019 }
8020 }
8021
8022 if (Ty->isArrayType() &&
8023 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8024 Info, Ctx, CheckingDest))
8025 return false;
8026
8027 if (const auto *VTy = Ty->getAs<VectorType>()) {
8028 QualType EltTy = VTy->getElementType();
8029 unsigned NElts = VTy->getNumElements();
8030 unsigned EltSize =
8031 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8032
8033 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8034 // The vector's size in bits is not a multiple of the target's byte size,
8035 // so its layout is unspecified. For now, we'll simply treat these cases
8036 // as unsupported (this should only be possible with OpenCL bool vectors
8037 // whose element count isn't a multiple of the byte size).
8038 if (Info)
8039 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8040 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8041 return false;
8042 }
8043
8044 if (EltTy->isRealFloatingType() &&
8045 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8046 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8047 // by both clang and LLVM, so for now we won't allow bit_casts involving
8048 // it in a constexpr context.
8049 if (Info)
8050 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8051 << EltTy;
8052 return false;
8053 }
8054 }
8055
8056 return true;
8057}
8058
8059static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8060 const ASTContext &Ctx,
8061 const CastExpr *BCE) {
8062 bool DestOK = checkBitCastConstexprEligibilityType(
8063 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8064 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8065 BCE->getBeginLoc(),
8066 BCE->getSubExpr()->getType(), Info, Ctx, false);
8067 return SourceOK;
8068}
8069
8070static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8071 const APValue &SourceRValue,
8072 const CastExpr *BCE) {
8073 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8074 "no host or target supports non 8-bit chars");
8075
8076 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8077 return false;
8078
8079 // Read out SourceValue into a char buffer.
8080 std::optional<BitCastBuffer> Buffer =
8081 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8082 if (!Buffer)
8083 return false;
8084
8085 // Write out the buffer into a new APValue.
8086 std::optional<APValue> MaybeDestValue =
8087 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8088 if (!MaybeDestValue)
8089 return false;
8090
8091 DestValue = std::move(*MaybeDestValue);
8092 return true;
8093}
8094
8095static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8096 APValue &SourceValue,
8097 const CastExpr *BCE) {
8098 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8099 "no host or target supports non 8-bit chars");
8100 assert(SourceValue.isLValue() &&
8101 "LValueToRValueBitcast requires an lvalue operand!");
8102
8103 LValue SourceLValue;
8104 APValue SourceRValue;
8105 SourceLValue.setFrom(Info.Ctx, SourceValue);
8107 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8108 SourceRValue, /*WantObjectRepresentation=*/true))
8109 return false;
8110
8111 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8112}
8113
8114template <class Derived>
8115class ExprEvaluatorBase
8116 : public ConstStmtVisitor<Derived, bool> {
8117private:
8118 Derived &getDerived() { return static_cast<Derived&>(*this); }
8119 bool DerivedSuccess(const APValue &V, const Expr *E) {
8120 return getDerived().Success(V, E);
8121 }
8122 bool DerivedZeroInitialization(const Expr *E) {
8123 return getDerived().ZeroInitialization(E);
8124 }
8125
8126 // Check whether a conditional operator with a non-constant condition is a
8127 // potential constant expression. If neither arm is a potential constant
8128 // expression, then the conditional operator is not either.
8129 template<typename ConditionalOperator>
8130 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8131 assert(Info.checkingPotentialConstantExpression());
8132
8133 // Speculatively evaluate both arms.
8135 {
8136 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8137 StmtVisitorTy::Visit(E->getFalseExpr());
8138 if (Diag.empty())
8139 return;
8140 }
8141
8142 {
8143 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8144 Diag.clear();
8145 StmtVisitorTy::Visit(E->getTrueExpr());
8146 if (Diag.empty())
8147 return;
8148 }
8149
8150 Error(E, diag::note_constexpr_conditional_never_const);
8151 }
8152
8153
8154 template<typename ConditionalOperator>
8155 bool HandleConditionalOperator(const ConditionalOperator *E) {
8156 bool BoolResult;
8157 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8158 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8159 CheckPotentialConstantConditional(E);
8160 return false;
8161 }
8162 if (Info.noteFailure()) {
8163 StmtVisitorTy::Visit(E->getTrueExpr());
8164 StmtVisitorTy::Visit(E->getFalseExpr());
8165 }
8166 return false;
8167 }
8168
8169 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8170 return StmtVisitorTy::Visit(EvalExpr);
8171 }
8172
8173protected:
8174 EvalInfo &Info;
8175 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8176 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8177
8178 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8179 return Info.CCEDiag(E, D);
8180 }
8181
8182 bool ZeroInitialization(const Expr *E) { return Error(E); }
8183
8184 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8185 unsigned BuiltinOp = E->getBuiltinCallee();
8186 return BuiltinOp != 0 &&
8187 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8188 }
8189
8190public:
8191 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8192
8193 EvalInfo &getEvalInfo() { return Info; }
8194
8195 /// Report an evaluation error. This should only be called when an error is
8196 /// first discovered. When propagating an error, just return false.
8197 bool Error(const Expr *E, diag::kind D) {
8198 Info.FFDiag(E, D) << E->getSourceRange();
8199 return false;
8200 }
8201 bool Error(const Expr *E) {
8202 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8203 }
8204
8205 bool VisitStmt(const Stmt *) {
8206 llvm_unreachable("Expression evaluator should not be called on stmts");
8207 }
8208 bool VisitExpr(const Expr *E) {
8209 return Error(E);
8210 }
8211
8212 bool VisitEmbedExpr(const EmbedExpr *E) {
8213 const auto It = E->begin();
8214 return StmtVisitorTy::Visit(*It);
8215 }
8216
8217 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8218 return StmtVisitorTy::Visit(E->getFunctionName());
8219 }
8220 bool VisitConstantExpr(const ConstantExpr *E) {
8221 if (E->hasAPValueResult())
8222 return DerivedSuccess(E->getAPValueResult(), E);
8223
8224 return StmtVisitorTy::Visit(E->getSubExpr());
8225 }
8226
8227 bool VisitParenExpr(const ParenExpr *E)
8228 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8229 bool VisitUnaryExtension(const UnaryOperator *E)
8230 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8231 bool VisitUnaryPlus(const UnaryOperator *E)
8232 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8233 bool VisitChooseExpr(const ChooseExpr *E)
8234 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8235 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8236 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8237 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8238 { return StmtVisitorTy::Visit(E->getReplacement()); }
8239 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8240 TempVersionRAII RAII(*Info.CurrentCall);
8241 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8242 return StmtVisitorTy::Visit(E->getExpr());
8243 }
8244 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8245 TempVersionRAII RAII(*Info.CurrentCall);
8246 // The initializer may not have been parsed yet, or might be erroneous.
8247 if (!E->getExpr())
8248 return Error(E);
8249 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8250 return StmtVisitorTy::Visit(E->getExpr());
8251 }
8252
8253 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8254 FullExpressionRAII Scope(Info);
8255 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8256 }
8257
8258 // Temporaries are registered when created, so we don't care about
8259 // CXXBindTemporaryExpr.
8260 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8261 return StmtVisitorTy::Visit(E->getSubExpr());
8262 }
8263
8264 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8265 CCEDiag(E, diag::note_constexpr_invalid_cast)
8266 << diag::ConstexprInvalidCastKind::Reinterpret;
8267 return static_cast<Derived*>(this)->VisitCastExpr(E);
8268 }
8269 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8270 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8271 CCEDiag(E, diag::note_constexpr_invalid_cast)
8272 << diag::ConstexprInvalidCastKind::Dynamic;
8273 return static_cast<Derived*>(this)->VisitCastExpr(E);
8274 }
8275 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8276 return static_cast<Derived*>(this)->VisitCastExpr(E);
8277 }
8278
8279 bool VisitBinaryOperator(const BinaryOperator *E) {
8280 switch (E->getOpcode()) {
8281 default:
8282 return Error(E);
8283
8284 case BO_Comma:
8285 VisitIgnoredValue(E->getLHS());
8286 return StmtVisitorTy::Visit(E->getRHS());
8287
8288 case BO_PtrMemD:
8289 case BO_PtrMemI: {
8290 LValue Obj;
8291 if (!HandleMemberPointerAccess(Info, E, Obj))
8292 return false;
8293 APValue Result;
8294 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8295 return false;
8296 return DerivedSuccess(Result, E);
8297 }
8298 }
8299 }
8300
8301 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8302 return StmtVisitorTy::Visit(E->getSemanticForm());
8303 }
8304
8305 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8306 // Evaluate and cache the common expression. We treat it as a temporary,
8307 // even though it's not quite the same thing.
8308 LValue CommonLV;
8309 if (!Evaluate(Info.CurrentCall->createTemporary(
8310 E->getOpaqueValue(),
8311 getStorageType(Info.Ctx, E->getOpaqueValue()),
8312 ScopeKind::FullExpression, CommonLV),
8313 Info, E->getCommon()))
8314 return false;
8315
8316 return HandleConditionalOperator(E);
8317 }
8318
8319 bool VisitConditionalOperator(const ConditionalOperator *E) {
8320 bool IsBcpCall = false;
8321 // If the condition (ignoring parens) is a __builtin_constant_p call,
8322 // the result is a constant expression if it can be folded without
8323 // side-effects. This is an important GNU extension. See GCC PR38377
8324 // for discussion.
8325 if (const CallExpr *CallCE =
8326 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8327 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8328 IsBcpCall = true;
8329
8330 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8331 // constant expression; we can't check whether it's potentially foldable.
8332 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8333 // it would return 'false' in this mode.
8334 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8335 return false;
8336
8337 FoldConstant Fold(Info, IsBcpCall);
8338 if (!HandleConditionalOperator(E)) {
8339 Fold.keepDiagnostics();
8340 return false;
8341 }
8342
8343 return true;
8344 }
8345
8346 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8347 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8348 Value && !Value->isAbsent())
8349 return DerivedSuccess(*Value, E);
8350
8351 const Expr *Source = E->getSourceExpr();
8352 if (!Source)
8353 return Error(E);
8354 if (Source == E) {
8355 assert(0 && "OpaqueValueExpr recursively refers to itself");
8356 return Error(E);
8357 }
8358 return StmtVisitorTy::Visit(Source);
8359 }
8360
8361 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8362 for (const Expr *SemE : E->semantics()) {
8363 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8364 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8365 // result expression: there could be two different LValues that would
8366 // refer to the same object in that case, and we can't model that.
8367 if (SemE == E->getResultExpr())
8368 return Error(E);
8369
8370 // Unique OVEs get evaluated if and when we encounter them when
8371 // emitting the rest of the semantic form, rather than eagerly.
8372 if (OVE->isUnique())
8373 continue;
8374
8375 LValue LV;
8376 if (!Evaluate(Info.CurrentCall->createTemporary(
8377 OVE, getStorageType(Info.Ctx, OVE),
8378 ScopeKind::FullExpression, LV),
8379 Info, OVE->getSourceExpr()))
8380 return false;
8381 } else if (SemE == E->getResultExpr()) {
8382 if (!StmtVisitorTy::Visit(SemE))
8383 return false;
8384 } else {
8385 if (!EvaluateIgnoredValue(Info, SemE))
8386 return false;
8387 }
8388 }
8389 return true;
8390 }
8391
8392 bool VisitCallExpr(const CallExpr *E) {
8393 APValue Result;
8394 if (!handleCallExpr(E, Result, nullptr))
8395 return false;
8396 return DerivedSuccess(Result, E);
8397 }
8398
8399 bool handleCallExpr(const CallExpr *E, APValue &Result,
8400 const LValue *ResultSlot) {
8401 CallScopeRAII CallScope(Info);
8402
8403 const Expr *Callee = E->getCallee()->IgnoreParens();
8404 QualType CalleeType = Callee->getType();
8405
8406 const FunctionDecl *FD = nullptr;
8407 LValue *This = nullptr, ObjectArg;
8408 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8409 bool HasQualifier = false;
8410
8411 CallRef Call;
8412
8413 // Extract function decl and 'this' pointer from the callee.
8414 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8415 const CXXMethodDecl *Member = nullptr;
8416 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8417 // Explicit bound member calls, such as x.f() or p->g();
8418 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8419 return false;
8420 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8421 if (!Member)
8422 return Error(Callee);
8423 This = &ObjectArg;
8424 HasQualifier = ME->hasQualifier();
8425 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8426 // Indirect bound member calls ('.*' or '->*').
8427 const ValueDecl *D =
8428 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8429 if (!D)
8430 return false;
8431 Member = dyn_cast<CXXMethodDecl>(D);
8432 if (!Member)
8433 return Error(Callee);
8434 This = &ObjectArg;
8435 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8436 if (!Info.getLangOpts().CPlusPlus20)
8437 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8438 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8439 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8440 } else
8441 return Error(Callee);
8442 FD = Member;
8443 } else if (CalleeType->isFunctionPointerType()) {
8444 LValue CalleeLV;
8445 if (!EvaluatePointer(Callee, CalleeLV, Info))
8446 return false;
8447
8448 if (!CalleeLV.getLValueOffset().isZero())
8449 return Error(Callee);
8450 if (CalleeLV.isNullPointer()) {
8451 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8452 << const_cast<Expr *>(Callee);
8453 return false;
8454 }
8455 FD = dyn_cast_or_null<FunctionDecl>(
8456 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8457 if (!FD)
8458 return Error(Callee);
8459 // Don't call function pointers which have been cast to some other type.
8460 // Per DR (no number yet), the caller and callee can differ in noexcept.
8461 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8462 CalleeType->getPointeeType(), FD->getType())) {
8463 return Error(E);
8464 }
8465
8466 // For an (overloaded) assignment expression, evaluate the RHS before the
8467 // LHS.
8468 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8469 if (OCE && OCE->isAssignmentOp()) {
8470 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8471 Call = Info.CurrentCall->createCall(FD);
8472 bool HasThis = false;
8473 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8474 HasThis = MD->isImplicitObjectMemberFunction();
8475 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8476 /*RightToLeft=*/true, &ObjectArg))
8477 return false;
8478 }
8479
8480 // Overloaded operator calls to member functions are represented as normal
8481 // calls with '*this' as the first argument.
8482 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8483 if (MD &&
8484 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8485 // FIXME: When selecting an implicit conversion for an overloaded
8486 // operator delete, we sometimes try to evaluate calls to conversion
8487 // operators without a 'this' parameter!
8488 if (Args.empty())
8489 return Error(E);
8490
8491 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8492 return false;
8493
8494 // If we are calling a static operator, the 'this' argument needs to be
8495 // ignored after being evaluated.
8496 if (MD->isInstance())
8497 This = &ObjectArg;
8498
8499 // If this is syntactically a simple assignment using a trivial
8500 // assignment operator, start the lifetimes of union members as needed,
8501 // per C++20 [class.union]5.
8502 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8503 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8504 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8505 return false;
8506
8507 Args = Args.slice(1);
8508 } else if (MD && MD->isLambdaStaticInvoker()) {
8509 // Map the static invoker for the lambda back to the call operator.
8510 // Conveniently, we don't have to slice out the 'this' argument (as is
8511 // being done for the non-static case), since a static member function
8512 // doesn't have an implicit argument passed in.
8513 const CXXRecordDecl *ClosureClass = MD->getParent();
8514 assert(
8515 ClosureClass->captures().empty() &&
8516 "Number of captures must be zero for conversion to function-ptr");
8517
8518 const CXXMethodDecl *LambdaCallOp =
8519 ClosureClass->getLambdaCallOperator();
8520
8521 // Set 'FD', the function that will be called below, to the call
8522 // operator. If the closure object represents a generic lambda, find
8523 // the corresponding specialization of the call operator.
8524
8525 if (ClosureClass->isGenericLambda()) {
8526 assert(MD->isFunctionTemplateSpecialization() &&
8527 "A generic lambda's static-invoker function must be a "
8528 "template specialization");
8530 FunctionTemplateDecl *CallOpTemplate =
8531 LambdaCallOp->getDescribedFunctionTemplate();
8532 void *InsertPos = nullptr;
8533 FunctionDecl *CorrespondingCallOpSpecialization =
8534 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8535 assert(CorrespondingCallOpSpecialization &&
8536 "We must always have a function call operator specialization "
8537 "that corresponds to our static invoker specialization");
8538 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8539 FD = CorrespondingCallOpSpecialization;
8540 } else
8541 FD = LambdaCallOp;
8543 if (FD->getDeclName().isAnyOperatorNew()) {
8544 LValue Ptr;
8545 if (!HandleOperatorNewCall(Info, E, Ptr))
8546 return false;
8547 Ptr.moveInto(Result);
8548 return CallScope.destroy();
8549 } else {
8550 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8551 }
8552 }
8553 } else
8554 return Error(E);
8555
8556 // Evaluate the arguments now if we've not already done so.
8557 if (!Call) {
8558 Call = Info.CurrentCall->createCall(FD);
8559 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8560 &ObjectArg))
8561 return false;
8562 }
8563
8564 SmallVector<QualType, 4> CovariantAdjustmentPath;
8565 if (This) {
8566 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8567 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8568 // Perform virtual dispatch, if necessary.
8569 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8570 CovariantAdjustmentPath);
8571 if (!FD)
8572 return false;
8573 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8574 // Check that the 'this' pointer points to an object of the right type.
8575 // FIXME: If this is an assignment operator call, we may need to change
8576 // the active union member before we check this.
8577 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8578 return false;
8579 }
8580 }
8581
8582 // Destructor calls are different enough that they have their own codepath.
8583 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8584 assert(This && "no 'this' pointer for destructor call");
8585 return HandleDestruction(Info, E, *This,
8586 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8587 CallScope.destroy();
8588 }
8589
8590 const FunctionDecl *Definition = nullptr;
8591 Stmt *Body = FD->getBody(Definition);
8593
8594 // Treat the object argument as `this` when evaluating defaulted
8595 // special menmber functions
8597 This = &ObjectArg;
8598
8599 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8600 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8601 Result, ResultSlot))
8602 return false;
8603
8604 if (!CovariantAdjustmentPath.empty() &&
8605 !HandleCovariantReturnAdjustment(Info, E, Result,
8606 CovariantAdjustmentPath))
8607 return false;
8608
8609 return CallScope.destroy();
8610 }
8611
8612 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8613 return StmtVisitorTy::Visit(E->getInitializer());
8614 }
8615 bool VisitInitListExpr(const InitListExpr *E) {
8616 if (E->getNumInits() == 0)
8617 return DerivedZeroInitialization(E);
8618 if (E->getNumInits() == 1)
8619 return StmtVisitorTy::Visit(E->getInit(0));
8620 return Error(E);
8621 }
8622 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8623 return DerivedZeroInitialization(E);
8624 }
8625 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8626 return DerivedZeroInitialization(E);
8627 }
8628 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8629 return DerivedZeroInitialization(E);
8630 }
8631
8632 /// A member expression where the object is a prvalue is itself a prvalue.
8633 bool VisitMemberExpr(const MemberExpr *E) {
8634 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8635 "missing temporary materialization conversion");
8636 assert(!E->isArrow() && "missing call to bound member function?");
8637
8638 APValue Val;
8639 if (!Evaluate(Val, Info, E->getBase()))
8640 return false;
8641
8642 QualType BaseTy = E->getBase()->getType();
8643
8644 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8645 if (!FD) return Error(E);
8646 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8647 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8648 FD->getParent()->getCanonicalDecl() &&
8649 "record / field mismatch");
8650
8651 // Note: there is no lvalue base here. But this case should only ever
8652 // happen in C or in C++98, where we cannot be evaluating a constexpr
8653 // constructor, which is the only case the base matters.
8654 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8655 SubobjectDesignator Designator(BaseTy);
8656 Designator.addDeclUnchecked(FD);
8657
8658 APValue Result;
8659 return extractSubobject(Info, E, Obj, Designator, Result) &&
8660 DerivedSuccess(Result, E);
8661 }
8662
8663 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8664 APValue Val;
8665 if (!Evaluate(Val, Info, E->getBase()))
8666 return false;
8667
8668 if (Val.isVector()) {
8670 E->getEncodedElementAccess(Indices);
8671 if (Indices.size() == 1) {
8672 // Return scalar.
8673 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8674 } else {
8675 // Construct new APValue vector.
8677 for (unsigned I = 0; I < Indices.size(); ++I) {
8678 Elts.push_back(Val.getVectorElt(Indices[I]));
8679 }
8680 APValue VecResult(Elts.data(), Indices.size());
8681 return DerivedSuccess(VecResult, E);
8682 }
8683 }
8684
8685 return false;
8686 }
8687
8688 bool VisitCastExpr(const CastExpr *E) {
8689 switch (E->getCastKind()) {
8690 default:
8691 break;
8692
8693 case CK_AtomicToNonAtomic: {
8694 APValue AtomicVal;
8695 // This does not need to be done in place even for class/array types:
8696 // atomic-to-non-atomic conversion implies copying the object
8697 // representation.
8698 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8699 return false;
8700 return DerivedSuccess(AtomicVal, E);
8701 }
8702
8703 case CK_NoOp:
8704 case CK_UserDefinedConversion:
8705 return StmtVisitorTy::Visit(E->getSubExpr());
8706
8707 case CK_LValueToRValue: {
8708 LValue LVal;
8709 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8710 return false;
8711 APValue RVal;
8712 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8713 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8714 LVal, RVal))
8715 return false;
8716 return DerivedSuccess(RVal, E);
8717 }
8718 case CK_LValueToRValueBitCast: {
8719 APValue DestValue, SourceValue;
8720 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8721 return false;
8722 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8723 return false;
8724 return DerivedSuccess(DestValue, E);
8725 }
8726
8727 case CK_AddressSpaceConversion: {
8728 APValue Value;
8729 if (!Evaluate(Value, Info, E->getSubExpr()))
8730 return false;
8731 return DerivedSuccess(Value, E);
8732 }
8733 }
8734
8735 return Error(E);
8736 }
8737
8738 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8739 return VisitUnaryPostIncDec(UO);
8740 }
8741 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8742 return VisitUnaryPostIncDec(UO);
8743 }
8744 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8745 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8746 return Error(UO);
8747
8748 LValue LVal;
8749 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8750 return false;
8751 APValue RVal;
8752 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8753 UO->isIncrementOp(), &RVal))
8754 return false;
8755 return DerivedSuccess(RVal, UO);
8756 }
8757
8758 bool VisitStmtExpr(const StmtExpr *E) {
8759 // We will have checked the full-expressions inside the statement expression
8760 // when they were completed, and don't need to check them again now.
8761 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8762 false);
8763
8764 const CompoundStmt *CS = E->getSubStmt();
8765 if (CS->body_empty())
8766 return true;
8767
8768 BlockScopeRAII Scope(Info);
8770 BE = CS->body_end();
8771 /**/; ++BI) {
8772 if (BI + 1 == BE) {
8773 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8774 if (!FinalExpr) {
8775 Info.FFDiag((*BI)->getBeginLoc(),
8776 diag::note_constexpr_stmt_expr_unsupported);
8777 return false;
8778 }
8779 return this->Visit(FinalExpr) && Scope.destroy();
8780 }
8781
8783 StmtResult Result = { ReturnValue, nullptr };
8784 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8785 if (ESR != ESR_Succeeded) {
8786 // FIXME: If the statement-expression terminated due to 'return',
8787 // 'break', or 'continue', it would be nice to propagate that to
8788 // the outer statement evaluation rather than bailing out.
8789 if (ESR != ESR_Failed)
8790 Info.FFDiag((*BI)->getBeginLoc(),
8791 diag::note_constexpr_stmt_expr_unsupported);
8792 return false;
8793 }
8794 }
8795
8796 llvm_unreachable("Return from function from the loop above.");
8797 }
8798
8799 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8800 return StmtVisitorTy::Visit(E->getSelectedExpr());
8801 }
8802
8803 /// Visit a value which is evaluated, but whose value is ignored.
8804 void VisitIgnoredValue(const Expr *E) {
8805 EvaluateIgnoredValue(Info, E);
8806 }
8807
8808 /// Potentially visit a MemberExpr's base expression.
8809 void VisitIgnoredBaseExpression(const Expr *E) {
8810 // While MSVC doesn't evaluate the base expression, it does diagnose the
8811 // presence of side-effecting behavior.
8812 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8813 return;
8814 VisitIgnoredValue(E);
8815 }
8816};
8817
8818} // namespace
8819
8820//===----------------------------------------------------------------------===//
8821// Common base class for lvalue and temporary evaluation.
8822//===----------------------------------------------------------------------===//
8823namespace {
8824template<class Derived>
8825class LValueExprEvaluatorBase
8826 : public ExprEvaluatorBase<Derived> {
8827protected:
8828 LValue &Result;
8829 bool InvalidBaseOK;
8830 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8831 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8832
8834 Result.set(B);
8835 return true;
8836 }
8837
8838 bool evaluatePointer(const Expr *E, LValue &Result) {
8839 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8840 }
8841
8842public:
8843 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8844 : ExprEvaluatorBaseTy(Info), Result(Result),
8845 InvalidBaseOK(InvalidBaseOK) {}
8846
8847 bool Success(const APValue &V, const Expr *E) {
8848 Result.setFrom(this->Info.Ctx, V);
8849 return true;
8850 }
8851
8852 bool VisitMemberExpr(const MemberExpr *E) {
8853 // Handle non-static data members.
8854 QualType BaseTy;
8855 bool EvalOK;
8856 if (E->isArrow()) {
8857 EvalOK = evaluatePointer(E->getBase(), Result);
8858 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8859 } else if (E->getBase()->isPRValue()) {
8860 assert(E->getBase()->getType()->isRecordType());
8861 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8862 BaseTy = E->getBase()->getType();
8863 } else {
8864 EvalOK = this->Visit(E->getBase());
8865 BaseTy = E->getBase()->getType();
8866 }
8867 if (!EvalOK) {
8868 if (!InvalidBaseOK)
8869 return false;
8870 Result.setInvalid(E);
8871 return true;
8872 }
8873
8874 const ValueDecl *MD = E->getMemberDecl();
8875 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8876 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8877 FD->getParent()->getCanonicalDecl() &&
8878 "record / field mismatch");
8879 (void)BaseTy;
8880 if (!HandleLValueMember(this->Info, E, Result, FD))
8881 return false;
8882 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8883 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8884 return false;
8885 } else
8886 return this->Error(E);
8887
8888 if (MD->getType()->isReferenceType()) {
8889 APValue RefValue;
8890 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8891 RefValue))
8892 return false;
8893 return Success(RefValue, E);
8894 }
8895 return true;
8896 }
8897
8898 bool VisitBinaryOperator(const BinaryOperator *E) {
8899 switch (E->getOpcode()) {
8900 default:
8901 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8902
8903 case BO_PtrMemD:
8904 case BO_PtrMemI:
8905 return HandleMemberPointerAccess(this->Info, E, Result);
8906 }
8907 }
8908
8909 bool VisitCastExpr(const CastExpr *E) {
8910 switch (E->getCastKind()) {
8911 default:
8912 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8913
8914 case CK_DerivedToBase:
8915 case CK_UncheckedDerivedToBase:
8916 if (!this->Visit(E->getSubExpr()))
8917 return false;
8918
8919 // Now figure out the necessary offset to add to the base LV to get from
8920 // the derived class to the base class.
8921 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8922 Result);
8923 }
8924 }
8925};
8926}
8927
8928//===----------------------------------------------------------------------===//
8929// LValue Evaluation
8930//
8931// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8932// function designators (in C), decl references to void objects (in C), and
8933// temporaries (if building with -Wno-address-of-temporary).
8934//
8935// LValue evaluation produces values comprising a base expression of one of the
8936// following types:
8937// - Declarations
8938// * VarDecl
8939// * FunctionDecl
8940// - Literals
8941// * CompoundLiteralExpr in C (and in global scope in C++)
8942// * StringLiteral
8943// * PredefinedExpr
8944// * ObjCStringLiteralExpr
8945// * ObjCEncodeExpr
8946// * AddrLabelExpr
8947// * BlockExpr
8948// * CallExpr for a MakeStringConstant builtin
8949// - typeid(T) expressions, as TypeInfoLValues
8950// - Locals and temporaries
8951// * MaterializeTemporaryExpr
8952// * Any Expr, with a CallIndex indicating the function in which the temporary
8953// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8954// from the AST (FIXME).
8955// * A MaterializeTemporaryExpr that has static storage duration, with no
8956// CallIndex, for a lifetime-extended temporary.
8957// * The ConstantExpr that is currently being evaluated during evaluation of an
8958// immediate invocation.
8959// plus an offset in bytes.
8960//===----------------------------------------------------------------------===//
8961namespace {
8962class LValueExprEvaluator
8963 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8964public:
8965 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8966 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8967
8968 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8969 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8970
8971 bool VisitCallExpr(const CallExpr *E);
8972 bool VisitDeclRefExpr(const DeclRefExpr *E);
8973 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8974 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8975 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8976 bool VisitMemberExpr(const MemberExpr *E);
8977 bool VisitStringLiteral(const StringLiteral *E) {
8979 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8980 }
8981 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8982 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8983 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8984 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8985 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8986 bool VisitUnaryDeref(const UnaryOperator *E);
8987 bool VisitUnaryReal(const UnaryOperator *E);
8988 bool VisitUnaryImag(const UnaryOperator *E);
8989 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8990 return VisitUnaryPreIncDec(UO);
8991 }
8992 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8993 return VisitUnaryPreIncDec(UO);
8994 }
8995 bool VisitBinAssign(const BinaryOperator *BO);
8996 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8997
8998 bool VisitCastExpr(const CastExpr *E) {
8999 switch (E->getCastKind()) {
9000 default:
9001 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9002
9003 case CK_LValueBitCast:
9004 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9005 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9006 << Info.Ctx.getLangOpts().CPlusPlus;
9007 if (!Visit(E->getSubExpr()))
9008 return false;
9009 Result.Designator.setInvalid();
9010 return true;
9011
9012 case CK_BaseToDerived:
9013 if (!Visit(E->getSubExpr()))
9014 return false;
9015 return HandleBaseToDerivedCast(Info, E, Result);
9016
9017 case CK_Dynamic:
9018 if (!Visit(E->getSubExpr()))
9019 return false;
9020 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9021 }
9022 }
9023};
9024} // end anonymous namespace
9025
9026/// Get an lvalue to a field of a lambda's closure type.
9027static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9028 const CXXMethodDecl *MD, const FieldDecl *FD,
9029 bool LValueToRValueConversion) {
9030 // Static lambda function call operators can't have captures. We already
9031 // diagnosed this, so bail out here.
9032 if (MD->isStatic()) {
9033 assert(Info.CurrentCall->This == nullptr &&
9034 "This should not be set for a static call operator");
9035 return false;
9036 }
9037
9038 // Start with 'Result' referring to the complete closure object...
9040 // Self may be passed by reference or by value.
9041 const ParmVarDecl *Self = MD->getParamDecl(0);
9042 if (Self->getType()->isReferenceType()) {
9043 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9044 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9045 Result.setFrom(Info.Ctx, *RefValue);
9046 } else {
9047 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9048 CallStackFrame *Frame =
9049 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9050 .first;
9051 unsigned Version = Info.CurrentCall->Arguments.Version;
9052 Result.set({VD, Frame->Index, Version});
9053 }
9054 } else
9055 Result = *Info.CurrentCall->This;
9056
9057 // ... then update it to refer to the field of the closure object
9058 // that represents the capture.
9059 if (!HandleLValueMember(Info, E, Result, FD))
9060 return false;
9061
9062 // And if the field is of reference type (or if we captured '*this' by
9063 // reference), update 'Result' to refer to what
9064 // the field refers to.
9065 if (LValueToRValueConversion) {
9066 APValue RVal;
9067 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9068 return false;
9069 Result.setFrom(Info.Ctx, RVal);
9070 }
9071 return true;
9072}
9073
9074/// Evaluate an expression as an lvalue. This can be legitimately called on
9075/// expressions which are not glvalues, in three cases:
9076/// * function designators in C, and
9077/// * "extern void" objects
9078/// * @selector() expressions in Objective-C
9079static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9080 bool InvalidBaseOK) {
9081 assert(!E->isValueDependent());
9082 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9083 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
9084 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9085}
9086
9087bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9088 const ValueDecl *D = E->getDecl();
9089
9090 // If we are within a lambda's call operator, check whether the 'VD' referred
9091 // to within 'E' actually represents a lambda-capture that maps to a
9092 // data-member/field within the closure object, and if so, evaluate to the
9093 // field or what the field refers to.
9094 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9095 E->refersToEnclosingVariableOrCapture()) {
9096 // We don't always have a complete capture-map when checking or inferring if
9097 // the function call operator meets the requirements of a constexpr function
9098 // - but we don't need to evaluate the captures to determine constexprness
9099 // (dcl.constexpr C++17).
9100 if (Info.checkingPotentialConstantExpression())
9101 return false;
9102
9103 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9104 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9105 return HandleLambdaCapture(Info, E, Result, MD, FD,
9106 FD->getType()->isReferenceType());
9107 }
9108 }
9109
9112 return Success(cast<ValueDecl>(D));
9113 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9114 return VisitVarDecl(E, VD);
9115 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9116 return Visit(BD->getBinding());
9117 return Error(E);
9118}
9119
9120bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9121 CallStackFrame *Frame = nullptr;
9122 unsigned Version = 0;
9123 if (VD->hasLocalStorage()) {
9124 // Only if a local variable was declared in the function currently being
9125 // evaluated, do we expect to be able to find its value in the current
9126 // frame. (Otherwise it was likely declared in an enclosing context and
9127 // could either have a valid evaluatable value (for e.g. a constexpr
9128 // variable) or be ill-formed (and trigger an appropriate evaluation
9129 // diagnostic)).
9130 CallStackFrame *CurrFrame = Info.CurrentCall;
9131 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9132 // Function parameters are stored in some caller's frame. (Usually the
9133 // immediate caller, but for an inherited constructor they may be more
9134 // distant.)
9135 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9136 if (CurrFrame->Arguments) {
9137 VD = CurrFrame->Arguments.getOrigParam(PVD);
9138 Frame =
9139 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9140 Version = CurrFrame->Arguments.Version;
9141 }
9142 } else {
9143 Frame = CurrFrame;
9144 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9145 }
9146 }
9147 }
9148
9149 if (!VD->getType()->isReferenceType()) {
9150 if (Frame) {
9151 Result.set({VD, Frame->Index, Version});
9152 return true;
9153 }
9154 return Success(VD);
9155 }
9156
9157 if (!Info.getLangOpts().CPlusPlus11) {
9158 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9159 << VD << VD->getType();
9160 Info.Note(VD->getLocation(), diag::note_declared_at);
9161 }
9162
9163 APValue *V;
9164 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9165 return false;
9166
9167 if (!V) {
9168 Result.set(VD);
9169 Result.AllowConstexprUnknown = true;
9170 return true;
9171 }
9172
9173 return Success(*V, E);
9174}
9175
9176bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9177 if (!IsConstantEvaluatedBuiltinCall(E))
9178 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9179
9180 switch (E->getBuiltinCallee()) {
9181 default:
9182 return false;
9183 case Builtin::BIas_const:
9184 case Builtin::BIforward:
9185 case Builtin::BIforward_like:
9186 case Builtin::BImove:
9187 case Builtin::BImove_if_noexcept:
9188 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9189 return Visit(E->getArg(0));
9190 break;
9191 }
9192
9193 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9194}
9195
9196bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9197 const MaterializeTemporaryExpr *E) {
9198 // Walk through the expression to find the materialized temporary itself.
9201 const Expr *Inner =
9202 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9203
9204 // If we passed any comma operators, evaluate their LHSs.
9205 for (const Expr *E : CommaLHSs)
9206 if (!EvaluateIgnoredValue(Info, E))
9207 return false;
9208
9209 // A materialized temporary with static storage duration can appear within the
9210 // result of a constant expression evaluation, so we need to preserve its
9211 // value for use outside this evaluation.
9212 APValue *Value;
9213 if (E->getStorageDuration() == SD_Static) {
9214 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
9215 return false;
9216 // FIXME: What about SD_Thread?
9217 Value = E->getOrCreateValue(true);
9218 *Value = APValue();
9219 Result.set(E);
9220 } else {
9221 Value = &Info.CurrentCall->createTemporary(
9222 E, Inner->getType(),
9223 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9224 : ScopeKind::Block,
9225 Result);
9226 }
9227
9228 QualType Type = Inner->getType();
9229
9230 // Materialize the temporary itself.
9231 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9232 *Value = APValue();
9233 return false;
9234 }
9235
9236 // Adjust our lvalue to refer to the desired subobject.
9237 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9238 --I;
9239 switch (Adjustments[I].Kind) {
9241 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9242 Type, Result))
9243 return false;
9244 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9245 break;
9246
9248 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9249 return false;
9250 Type = Adjustments[I].Field->getType();
9251 break;
9252
9254 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9255 Adjustments[I].Ptr.RHS))
9256 return false;
9257 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9258 break;
9259 }
9260 }
9261
9262 return true;
9263}
9264
9265bool
9266LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9267 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9268 "lvalue compound literal in c++?");
9269 APValue *Lit;
9270 // If CompountLiteral has static storage, its value can be used outside
9271 // this expression. So evaluate it once and store it in ASTContext.
9272 if (E->hasStaticStorage()) {
9273 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9274 Result.set(E);
9275 // Reset any previously evaluated state, otherwise evaluation below might
9276 // fail.
9277 // FIXME: Should we just re-use the previously evaluated value instead?
9278 *Lit = APValue();
9279 } else {
9280 assert(!Info.getLangOpts().CPlusPlus);
9281 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9282 ScopeKind::Block, Result);
9283 }
9284 // FIXME: Evaluating in place isn't always right. We should figure out how to
9285 // use appropriate evaluation context here, see
9286 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9287 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9288 *Lit = APValue();
9289 return false;
9290 }
9291 return true;
9292}
9293
9294bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9296
9297 if (!E->isPotentiallyEvaluated()) {
9298 if (E->isTypeOperand())
9299 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9300 else
9301 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9302 } else {
9303 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9304 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9305 << E->getExprOperand()->getType()
9306 << E->getExprOperand()->getSourceRange();
9307 }
9308
9309 if (!Visit(E->getExprOperand()))
9310 return false;
9311
9312 std::optional<DynamicType> DynType =
9313 ComputeDynamicType(Info, E, Result, AK_TypeId);
9314 if (!DynType)
9315 return false;
9316
9318 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9319 }
9320
9322}
9323
9324bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9325 return Success(E->getGuidDecl());
9326}
9327
9328bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9329 // Handle static data members.
9330 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9331 VisitIgnoredBaseExpression(E->getBase());
9332 return VisitVarDecl(E, VD);
9333 }
9334
9335 // Handle static member functions.
9336 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9337 if (MD->isStatic()) {
9338 VisitIgnoredBaseExpression(E->getBase());
9339 return Success(MD);
9340 }
9341 }
9342
9343 // Handle non-static data members.
9344 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9345}
9346
9347bool LValueExprEvaluator::VisitExtVectorElementExpr(
9348 const ExtVectorElementExpr *E) {
9349 bool Success = true;
9350
9351 APValue Val;
9352 if (!Evaluate(Val, Info, E->getBase())) {
9353 if (!Info.noteFailure())
9354 return false;
9355 Success = false;
9356 }
9357
9359 E->getEncodedElementAccess(Indices);
9360 // FIXME: support accessing more than one element
9361 if (Indices.size() > 1)
9362 return false;
9363
9364 if (Success) {
9365 Result.setFrom(Info.Ctx, Val);
9366 QualType BaseType = E->getBase()->getType();
9367 if (E->isArrow())
9368 BaseType = BaseType->getPointeeType();
9369 const auto *VT = BaseType->castAs<VectorType>();
9370 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9371 VT->getNumElements(), Indices[0]);
9372 }
9373
9374 return Success;
9375}
9376
9377bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9378 if (E->getBase()->getType()->isSveVLSBuiltinType())
9379 return Error(E);
9380
9381 APSInt Index;
9382 bool Success = true;
9383
9384 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9385 APValue Val;
9386 if (!Evaluate(Val, Info, E->getBase())) {
9387 if (!Info.noteFailure())
9388 return false;
9389 Success = false;
9390 }
9391
9392 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9393 if (!Info.noteFailure())
9394 return false;
9395 Success = false;
9396 }
9397
9398 if (Success) {
9399 Result.setFrom(Info.Ctx, Val);
9400 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9401 VT->getNumElements(), Index.getExtValue());
9402 }
9403
9404 return Success;
9405 }
9406
9407 // C++17's rules require us to evaluate the LHS first, regardless of which
9408 // side is the base.
9409 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9410 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9411 : !EvaluateInteger(SubExpr, Index, Info)) {
9412 if (!Info.noteFailure())
9413 return false;
9414 Success = false;
9415 }
9416 }
9417
9418 return Success &&
9419 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9420}
9421
9422bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9423 bool Success = evaluatePointer(E->getSubExpr(), Result);
9424 // [C++26][expr.unary.op]
9425 // If the operand points to an object or function, the result
9426 // denotes that object or function; otherwise, the behavior is undefined.
9427 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9428 // immediately.
9430 return Success;
9431 return bool(findCompleteObject(Info, E, AK_Dereference, Result,
9432 E->getType())) ||
9433 Info.noteUndefinedBehavior();
9434}
9435
9436bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9437 if (!Visit(E->getSubExpr()))
9438 return false;
9439 // __real is a no-op on scalar lvalues.
9440 if (E->getSubExpr()->getType()->isAnyComplexType())
9441 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9442 return true;
9443}
9444
9445bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9446 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9447 "lvalue __imag__ on scalar?");
9448 if (!Visit(E->getSubExpr()))
9449 return false;
9450 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9451 return true;
9452}
9453
9454bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9455 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9456 return Error(UO);
9457
9458 if (!this->Visit(UO->getSubExpr()))
9459 return false;
9460
9461 return handleIncDec(
9462 this->Info, UO, Result, UO->getSubExpr()->getType(),
9463 UO->isIncrementOp(), nullptr);
9464}
9465
9466bool LValueExprEvaluator::VisitCompoundAssignOperator(
9467 const CompoundAssignOperator *CAO) {
9468 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9469 return Error(CAO);
9470
9471 bool Success = true;
9472
9473 // C++17 onwards require that we evaluate the RHS first.
9474 APValue RHS;
9475 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9476 if (!Info.noteFailure())
9477 return false;
9478 Success = false;
9479 }
9480
9481 // The overall lvalue result is the result of evaluating the LHS.
9482 if (!this->Visit(CAO->getLHS()) || !Success)
9483 return false;
9484
9486 this->Info, CAO,
9487 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9488 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9489}
9490
9491bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9492 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9493 return Error(E);
9494
9495 bool Success = true;
9496
9497 // C++17 onwards require that we evaluate the RHS first.
9498 APValue NewVal;
9499 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9500 if (!Info.noteFailure())
9501 return false;
9502 Success = false;
9503 }
9504
9505 if (!this->Visit(E->getLHS()) || !Success)
9506 return false;
9507
9508 if (Info.getLangOpts().CPlusPlus20 &&
9509 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9510 return false;
9511
9512 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9513 NewVal);
9514}
9515
9516//===----------------------------------------------------------------------===//
9517// Pointer Evaluation
9518//===----------------------------------------------------------------------===//
9519
9520/// Convenience function. LVal's base must be a call to an alloc_size
9521/// function.
9523 const LValue &LVal,
9524 llvm::APInt &Result) {
9525 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9526 "Can't get the size of a non alloc_size function");
9527 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9528 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9529 std::optional<llvm::APInt> Size =
9530 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9531 if (!Size)
9532 return false;
9533
9534 Result = std::move(*Size);
9535 return true;
9536}
9537
9538/// Attempts to evaluate the given LValueBase as the result of a call to
9539/// a function with the alloc_size attribute. If it was possible to do so, this
9540/// function will return true, make Result's Base point to said function call,
9541/// and mark Result's Base as invalid.
9543 LValue &Result) {
9544 if (Base.isNull())
9545 return false;
9546
9547 // Because we do no form of static analysis, we only support const variables.
9548 //
9549 // Additionally, we can't support parameters, nor can we support static
9550 // variables (in the latter case, use-before-assign isn't UB; in the former,
9551 // we have no clue what they'll be assigned to).
9552 const auto *VD =
9553 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9554 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9555 return false;
9556
9557 const Expr *Init = VD->getAnyInitializer();
9558 if (!Init || Init->getType().isNull())
9559 return false;
9560
9561 const Expr *E = Init->IgnoreParens();
9562 if (!tryUnwrapAllocSizeCall(E))
9563 return false;
9564
9565 // Store E instead of E unwrapped so that the type of the LValue's base is
9566 // what the user wanted.
9567 Result.setInvalid(E);
9568
9569 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9570 Result.addUnsizedArray(Info, E, Pointee);
9571 return true;
9572}
9573
9574namespace {
9575class PointerExprEvaluator
9576 : public ExprEvaluatorBase<PointerExprEvaluator> {
9577 LValue &Result;
9578 bool InvalidBaseOK;
9579
9580 bool Success(const Expr *E) {
9581 Result.set(E);
9582 return true;
9583 }
9584
9585 bool evaluateLValue(const Expr *E, LValue &Result) {
9586 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9587 }
9588
9589 bool evaluatePointer(const Expr *E, LValue &Result) {
9590 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9591 }
9592
9593 bool visitNonBuiltinCallExpr(const CallExpr *E);
9594public:
9595
9596 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9597 : ExprEvaluatorBaseTy(info), Result(Result),
9598 InvalidBaseOK(InvalidBaseOK) {}
9599
9600 bool Success(const APValue &V, const Expr *E) {
9601 Result.setFrom(Info.Ctx, V);
9602 return true;
9603 }
9604 bool ZeroInitialization(const Expr *E) {
9605 Result.setNull(Info.Ctx, E->getType());
9606 return true;
9607 }
9608
9609 bool VisitBinaryOperator(const BinaryOperator *E);
9610 bool VisitCastExpr(const CastExpr* E);
9611 bool VisitUnaryAddrOf(const UnaryOperator *E);
9612 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9613 { return Success(E); }
9614 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9615 if (E->isExpressibleAsConstantInitializer())
9616 return Success(E);
9617 if (Info.noteFailure())
9618 EvaluateIgnoredValue(Info, E->getSubExpr());
9619 return Error(E);
9620 }
9621 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9622 { return Success(E); }
9623 bool VisitCallExpr(const CallExpr *E);
9624 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9625 bool VisitBlockExpr(const BlockExpr *E) {
9626 if (!E->getBlockDecl()->hasCaptures())
9627 return Success(E);
9628 return Error(E);
9629 }
9630 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9631 auto DiagnoseInvalidUseOfThis = [&] {
9632 if (Info.getLangOpts().CPlusPlus11)
9633 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9634 else
9635 Info.FFDiag(E);
9636 };
9637
9638 // Can't look at 'this' when checking a potential constant expression.
9639 if (Info.checkingPotentialConstantExpression())
9640 return false;
9641
9642 bool IsExplicitLambda =
9643 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9644 if (!IsExplicitLambda) {
9645 if (!Info.CurrentCall->This) {
9646 DiagnoseInvalidUseOfThis();
9647 return false;
9648 }
9649
9650 Result = *Info.CurrentCall->This;
9651 }
9652
9653 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9654 // Ensure we actually have captured 'this'. If something was wrong with
9655 // 'this' capture, the error would have been previously reported.
9656 // Otherwise we can be inside of a default initialization of an object
9657 // declared by lambda's body, so no need to return false.
9658 if (!Info.CurrentCall->LambdaThisCaptureField) {
9659 if (IsExplicitLambda && !Info.CurrentCall->This) {
9660 DiagnoseInvalidUseOfThis();
9661 return false;
9662 }
9663
9664 return true;
9665 }
9666
9667 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9668 return HandleLambdaCapture(
9669 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9670 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9671 }
9672 return true;
9673 }
9674
9675 bool VisitCXXNewExpr(const CXXNewExpr *E);
9676
9677 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9678 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9679 APValue LValResult = E->EvaluateInContext(
9680 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9681 Result.setFrom(Info.Ctx, LValResult);
9682 return true;
9683 }
9684
9685 bool VisitEmbedExpr(const EmbedExpr *E) {
9686 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9687 return true;
9688 }
9689
9690 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9691 std::string ResultStr = E->ComputeName(Info.Ctx);
9692
9693 QualType CharTy = Info.Ctx.CharTy.withConst();
9694 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9695 ResultStr.size() + 1);
9696 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9697 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9698
9699 StringLiteral *SL =
9700 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9701 /*Pascal*/ false, ArrayTy, E->getLocation());
9702
9703 evaluateLValue(SL, Result);
9704 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9705 return true;
9706 }
9707
9708 // FIXME: Missing: @protocol, @selector
9709};
9710} // end anonymous namespace
9711
9712static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9713 bool InvalidBaseOK) {
9714 assert(!E->isValueDependent());
9715 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9716 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9717}
9718
9719bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9720 if (E->getOpcode() != BO_Add &&
9721 E->getOpcode() != BO_Sub)
9722 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9723
9724 const Expr *PExp = E->getLHS();
9725 const Expr *IExp = E->getRHS();
9726 if (IExp->getType()->isPointerType())
9727 std::swap(PExp, IExp);
9728
9729 bool EvalPtrOK = evaluatePointer(PExp, Result);
9730 if (!EvalPtrOK && !Info.noteFailure())
9731 return false;
9732
9733 llvm::APSInt Offset;
9734 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9735 return false;
9736
9737 if (E->getOpcode() == BO_Sub)
9738 negateAsSigned(Offset);
9739
9740 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9741 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9742}
9743
9744bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9745 return evaluateLValue(E->getSubExpr(), Result);
9746}
9747
9748// Is the provided decl 'std::source_location::current'?
9750 if (!FD)
9751 return false;
9752 const IdentifierInfo *FnII = FD->getIdentifier();
9753 if (!FnII || !FnII->isStr("current"))
9754 return false;
9755
9756 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9757 if (!RD)
9758 return false;
9759
9760 const IdentifierInfo *ClassII = RD->getIdentifier();
9761 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9762}
9763
9764bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9765 const Expr *SubExpr = E->getSubExpr();
9766
9767 switch (E->getCastKind()) {
9768 default:
9769 break;
9770 case CK_BitCast:
9771 case CK_CPointerToObjCPointerCast:
9772 case CK_BlockPointerToObjCPointerCast:
9773 case CK_AnyPointerToBlockPointerCast:
9774 case CK_AddressSpaceConversion:
9775 if (!Visit(SubExpr))
9776 return false;
9777 if (E->getType()->isFunctionPointerType() ||
9778 SubExpr->getType()->isFunctionPointerType()) {
9779 // Casting between two function pointer types, or between a function
9780 // pointer and an object pointer, is always a reinterpret_cast.
9781 CCEDiag(E, diag::note_constexpr_invalid_cast)
9782 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9783 << Info.Ctx.getLangOpts().CPlusPlus;
9784 Result.Designator.setInvalid();
9785 } else if (!E->getType()->isVoidPointerType()) {
9786 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9787 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9788 // also static_casts, but we disallow them as a resolution to DR1312.
9789 //
9790 // In some circumstances, we permit casting from void* to cv1 T*, when the
9791 // actual pointee object is actually a cv2 T.
9792 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9793 !Result.IsNullPtr;
9794 bool VoidPtrCastMaybeOK =
9795 Result.IsNullPtr ||
9796 (HasValidResult &&
9797 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9798 E->getType()->getPointeeType()));
9799 // 1. We'll allow it in std::allocator::allocate, and anything which that
9800 // calls.
9801 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9802 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9803 // We'll allow it in the body of std::source_location::current. GCC's
9804 // implementation had a parameter of type `void*`, and casts from
9805 // that back to `const __impl*` in its body.
9806 if (VoidPtrCastMaybeOK &&
9807 (Info.getStdAllocatorCaller("allocate") ||
9808 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9809 Info.getLangOpts().CPlusPlus26)) {
9810 // Permitted.
9811 } else {
9812 if (SubExpr->getType()->isVoidPointerType() &&
9813 Info.getLangOpts().CPlusPlus) {
9814 if (HasValidResult)
9815 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9816 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9817 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9818 << E->getType()->getPointeeType();
9819 else
9820 CCEDiag(E, diag::note_constexpr_invalid_cast)
9821 << diag::ConstexprInvalidCastKind::CastFrom
9822 << SubExpr->getType();
9823 } else
9824 CCEDiag(E, diag::note_constexpr_invalid_cast)
9825 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9826 << Info.Ctx.getLangOpts().CPlusPlus;
9827 Result.Designator.setInvalid();
9828 }
9829 }
9830 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9831 ZeroInitialization(E);
9832 return true;
9833
9834 case CK_DerivedToBase:
9835 case CK_UncheckedDerivedToBase:
9836 if (!evaluatePointer(E->getSubExpr(), Result))
9837 return false;
9838 if (!Result.Base && Result.Offset.isZero())
9839 return true;
9840
9841 // Now figure out the necessary offset to add to the base LV to get from
9842 // the derived class to the base class.
9843 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9844 castAs<PointerType>()->getPointeeType(),
9845 Result);
9846
9847 case CK_BaseToDerived:
9848 if (!Visit(E->getSubExpr()))
9849 return false;
9850 if (!Result.Base && Result.Offset.isZero())
9851 return true;
9852 return HandleBaseToDerivedCast(Info, E, Result);
9853
9854 case CK_Dynamic:
9855 if (!Visit(E->getSubExpr()))
9856 return false;
9857 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9858
9859 case CK_NullToPointer:
9860 VisitIgnoredValue(E->getSubExpr());
9861 return ZeroInitialization(E);
9862
9863 case CK_IntegralToPointer: {
9864 CCEDiag(E, diag::note_constexpr_invalid_cast)
9865 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9866 << Info.Ctx.getLangOpts().CPlusPlus;
9867
9868 APValue Value;
9869 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9870 break;
9871
9872 if (Value.isInt()) {
9873 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9874 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9875 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
9876 Result.setNull(Info.Ctx, E->getType());
9877 } else {
9878 Result.Base = (Expr *)nullptr;
9879 Result.InvalidBase = false;
9880 Result.Offset = CharUnits::fromQuantity(N);
9881 Result.Designator.setInvalid();
9882 Result.IsNullPtr = false;
9883 }
9884 return true;
9885 } else {
9886 // In rare instances, the value isn't an lvalue.
9887 // For example, when the value is the difference between the addresses of
9888 // two labels. We reject that as a constant expression because we can't
9889 // compute a valid offset to convert into a pointer.
9890 if (!Value.isLValue())
9891 return false;
9892
9893 // Cast is of an lvalue, no need to change value.
9894 Result.setFrom(Info.Ctx, Value);
9895 return true;
9896 }
9897 }
9898
9899 case CK_ArrayToPointerDecay: {
9900 if (SubExpr->isGLValue()) {
9901 if (!evaluateLValue(SubExpr, Result))
9902 return false;
9903 } else {
9904 APValue &Value = Info.CurrentCall->createTemporary(
9905 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9906 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9907 return false;
9908 }
9909 // The result is a pointer to the first element of the array.
9910 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9911 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9912 Result.addArray(Info, E, CAT);
9913 else
9914 Result.addUnsizedArray(Info, E, AT->getElementType());
9915 return true;
9916 }
9917
9918 case CK_FunctionToPointerDecay:
9919 return evaluateLValue(SubExpr, Result);
9920
9921 case CK_LValueToRValue: {
9922 LValue LVal;
9923 if (!evaluateLValue(E->getSubExpr(), LVal))
9924 return false;
9925
9926 APValue RVal;
9927 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9928 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9929 LVal, RVal))
9930 return InvalidBaseOK &&
9931 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9932 return Success(RVal, E);
9933 }
9934 }
9935
9936 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9937}
9938
9940 UnaryExprOrTypeTrait ExprKind) {
9941 // C++ [expr.alignof]p3:
9942 // When alignof is applied to a reference type, the result is the
9943 // alignment of the referenced type.
9944 T = T.getNonReferenceType();
9945
9946 if (T.getQualifiers().hasUnaligned())
9947 return CharUnits::One();
9948
9949 const bool AlignOfReturnsPreferred =
9950 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9951
9952 // __alignof is defined to return the preferred alignment.
9953 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9954 // as well.
9955 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9956 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9957 // alignof and _Alignof are defined to return the ABI alignment.
9958 else if (ExprKind == UETT_AlignOf)
9959 return Ctx.getTypeAlignInChars(T.getTypePtr());
9960 else
9961 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9962}
9963
9965 UnaryExprOrTypeTrait ExprKind) {
9966 E = E->IgnoreParens();
9967
9968 // The kinds of expressions that we have special-case logic here for
9969 // should be kept up to date with the special checks for those
9970 // expressions in Sema.
9971
9972 // alignof decl is always accepted, even if it doesn't make sense: we default
9973 // to 1 in those cases.
9974 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9975 return Ctx.getDeclAlign(DRE->getDecl(),
9976 /*RefAsPointee*/ true);
9977
9978 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9979 return Ctx.getDeclAlign(ME->getMemberDecl(),
9980 /*RefAsPointee*/ true);
9981
9982 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9983}
9984
9985static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9986 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9987 return Info.Ctx.getDeclAlign(VD);
9988 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9989 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9990 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9991}
9992
9993/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9994/// __builtin_is_aligned and __builtin_assume_aligned.
9995static bool getAlignmentArgument(const Expr *E, QualType ForType,
9996 EvalInfo &Info, APSInt &Alignment) {
9997 if (!EvaluateInteger(E, Alignment, Info))
9998 return false;
9999 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10000 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10001 return false;
10002 }
10003 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10004 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10005 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10006 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10007 << MaxValue << ForType << Alignment;
10008 return false;
10009 }
10010 // Ensure both alignment and source value have the same bit width so that we
10011 // don't assert when computing the resulting value.
10012 APSInt ExtAlignment =
10013 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10014 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10015 "Alignment should not be changed by ext/trunc");
10016 Alignment = ExtAlignment;
10017 assert(Alignment.getBitWidth() == SrcWidth);
10018 return true;
10019}
10020
10021// To be clear: this happily visits unsupported builtins. Better name welcomed.
10022bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10023 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10024 return true;
10025
10026 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10027 return false;
10028
10029 Result.setInvalid(E);
10030 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10031 Result.addUnsizedArray(Info, E, PointeeTy);
10032 return true;
10033}
10034
10035bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10036 if (!IsConstantEvaluatedBuiltinCall(E))
10037 return visitNonBuiltinCallExpr(E);
10038 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10039}
10040
10041// Determine if T is a character type for which we guarantee that
10042// sizeof(T) == 1.
10044 return T->isCharType() || T->isChar8Type();
10045}
10046
10047bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10048 unsigned BuiltinOp) {
10050 return Success(E);
10051
10052 switch (BuiltinOp) {
10053 case Builtin::BIaddressof:
10054 case Builtin::BI__addressof:
10055 case Builtin::BI__builtin_addressof:
10056 return evaluateLValue(E->getArg(0), Result);
10057 case Builtin::BI__builtin_assume_aligned: {
10058 // We need to be very careful here because: if the pointer does not have the
10059 // asserted alignment, then the behavior is undefined, and undefined
10060 // behavior is non-constant.
10061 if (!evaluatePointer(E->getArg(0), Result))
10062 return false;
10063
10064 LValue OffsetResult(Result);
10065 APSInt Alignment;
10066 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10067 Alignment))
10068 return false;
10069 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10070
10071 if (E->getNumArgs() > 2) {
10072 APSInt Offset;
10073 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10074 return false;
10075
10076 int64_t AdditionalOffset = -Offset.getZExtValue();
10077 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10078 }
10079
10080 // If there is a base object, then it must have the correct alignment.
10081 if (OffsetResult.Base) {
10082 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10083
10084 if (BaseAlignment < Align) {
10085 Result.Designator.setInvalid();
10086 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10087 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10088 return false;
10089 }
10090 }
10091
10092 // The offset must also have the correct alignment.
10093 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10094 Result.Designator.setInvalid();
10095
10096 (OffsetResult.Base
10097 ? CCEDiag(E->getArg(0),
10098 diag::note_constexpr_baa_insufficient_alignment)
10099 << 1
10100 : CCEDiag(E->getArg(0),
10101 diag::note_constexpr_baa_value_insufficient_alignment))
10102 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10103 return false;
10104 }
10105
10106 return true;
10107 }
10108 case Builtin::BI__builtin_align_up:
10109 case Builtin::BI__builtin_align_down: {
10110 if (!evaluatePointer(E->getArg(0), Result))
10111 return false;
10112 APSInt Alignment;
10113 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10114 Alignment))
10115 return false;
10116 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10117 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10118 // For align_up/align_down, we can return the same value if the alignment
10119 // is known to be greater or equal to the requested value.
10120 if (PtrAlign.getQuantity() >= Alignment)
10121 return true;
10122
10123 // The alignment could be greater than the minimum at run-time, so we cannot
10124 // infer much about the resulting pointer value. One case is possible:
10125 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10126 // can infer the correct index if the requested alignment is smaller than
10127 // the base alignment so we can perform the computation on the offset.
10128 if (BaseAlignment.getQuantity() >= Alignment) {
10129 assert(Alignment.getBitWidth() <= 64 &&
10130 "Cannot handle > 64-bit address-space");
10131 uint64_t Alignment64 = Alignment.getZExtValue();
10133 BuiltinOp == Builtin::BI__builtin_align_down
10134 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10135 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10136 Result.adjustOffset(NewOffset - Result.Offset);
10137 // TODO: diagnose out-of-bounds values/only allow for arrays?
10138 return true;
10139 }
10140 // Otherwise, we cannot constant-evaluate the result.
10141 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10142 << Alignment;
10143 return false;
10144 }
10145 case Builtin::BI__builtin_operator_new:
10146 return HandleOperatorNewCall(Info, E, Result);
10147 case Builtin::BI__builtin_launder:
10148 return evaluatePointer(E->getArg(0), Result);
10149 case Builtin::BIstrchr:
10150 case Builtin::BIwcschr:
10151 case Builtin::BImemchr:
10152 case Builtin::BIwmemchr:
10153 if (Info.getLangOpts().CPlusPlus11)
10154 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10155 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10156 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10157 else
10158 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10159 [[fallthrough]];
10160 case Builtin::BI__builtin_strchr:
10161 case Builtin::BI__builtin_wcschr:
10162 case Builtin::BI__builtin_memchr:
10163 case Builtin::BI__builtin_char_memchr:
10164 case Builtin::BI__builtin_wmemchr: {
10165 if (!Visit(E->getArg(0)))
10166 return false;
10167 APSInt Desired;
10168 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10169 return false;
10170 uint64_t MaxLength = uint64_t(-1);
10171 if (BuiltinOp != Builtin::BIstrchr &&
10172 BuiltinOp != Builtin::BIwcschr &&
10173 BuiltinOp != Builtin::BI__builtin_strchr &&
10174 BuiltinOp != Builtin::BI__builtin_wcschr) {
10175 APSInt N;
10176 if (!EvaluateInteger(E->getArg(2), N, Info))
10177 return false;
10178 MaxLength = N.getZExtValue();
10179 }
10180 // We cannot find the value if there are no candidates to match against.
10181 if (MaxLength == 0u)
10182 return ZeroInitialization(E);
10183 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10184 Result.Designator.Invalid)
10185 return false;
10186 QualType CharTy = Result.Designator.getType(Info.Ctx);
10187 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10188 BuiltinOp == Builtin::BI__builtin_memchr;
10189 assert(IsRawByte ||
10190 Info.Ctx.hasSameUnqualifiedType(
10191 CharTy, E->getArg(0)->getType()->getPointeeType()));
10192 // Pointers to const void may point to objects of incomplete type.
10193 if (IsRawByte && CharTy->isIncompleteType()) {
10194 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10195 return false;
10196 }
10197 // Give up on byte-oriented matching against multibyte elements.
10198 // FIXME: We can compare the bytes in the correct order.
10199 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10200 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10201 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10202 return false;
10203 }
10204 // Figure out what value we're actually looking for (after converting to
10205 // the corresponding unsigned type if necessary).
10206 uint64_t DesiredVal;
10207 bool StopAtNull = false;
10208 switch (BuiltinOp) {
10209 case Builtin::BIstrchr:
10210 case Builtin::BI__builtin_strchr:
10211 // strchr compares directly to the passed integer, and therefore
10212 // always fails if given an int that is not a char.
10213 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10214 E->getArg(1)->getType(),
10215 Desired),
10216 Desired))
10217 return ZeroInitialization(E);
10218 StopAtNull = true;
10219 [[fallthrough]];
10220 case Builtin::BImemchr:
10221 case Builtin::BI__builtin_memchr:
10222 case Builtin::BI__builtin_char_memchr:
10223 // memchr compares by converting both sides to unsigned char. That's also
10224 // correct for strchr if we get this far (to cope with plain char being
10225 // unsigned in the strchr case).
10226 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10227 break;
10228
10229 case Builtin::BIwcschr:
10230 case Builtin::BI__builtin_wcschr:
10231 StopAtNull = true;
10232 [[fallthrough]];
10233 case Builtin::BIwmemchr:
10234 case Builtin::BI__builtin_wmemchr:
10235 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10236 DesiredVal = Desired.getZExtValue();
10237 break;
10238 }
10239
10240 for (; MaxLength; --MaxLength) {
10241 APValue Char;
10242 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10243 !Char.isInt())
10244 return false;
10245 if (Char.getInt().getZExtValue() == DesiredVal)
10246 return true;
10247 if (StopAtNull && !Char.getInt())
10248 break;
10249 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10250 return false;
10251 }
10252 // Not found: return nullptr.
10253 return ZeroInitialization(E);
10254 }
10255
10256 case Builtin::BImemcpy:
10257 case Builtin::BImemmove:
10258 case Builtin::BIwmemcpy:
10259 case Builtin::BIwmemmove:
10260 if (Info.getLangOpts().CPlusPlus11)
10261 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10262 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10263 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10264 else
10265 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10266 [[fallthrough]];
10267 case Builtin::BI__builtin_memcpy:
10268 case Builtin::BI__builtin_memmove:
10269 case Builtin::BI__builtin_wmemcpy:
10270 case Builtin::BI__builtin_wmemmove: {
10271 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10272 BuiltinOp == Builtin::BIwmemmove ||
10273 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10274 BuiltinOp == Builtin::BI__builtin_wmemmove;
10275 bool Move = BuiltinOp == Builtin::BImemmove ||
10276 BuiltinOp == Builtin::BIwmemmove ||
10277 BuiltinOp == Builtin::BI__builtin_memmove ||
10278 BuiltinOp == Builtin::BI__builtin_wmemmove;
10279
10280 // The result of mem* is the first argument.
10281 if (!Visit(E->getArg(0)))
10282 return false;
10283 LValue Dest = Result;
10284
10285 LValue Src;
10286 if (!EvaluatePointer(E->getArg(1), Src, Info))
10287 return false;
10288
10289 APSInt N;
10290 if (!EvaluateInteger(E->getArg(2), N, Info))
10291 return false;
10292 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10293
10294 // If the size is zero, we treat this as always being a valid no-op.
10295 // (Even if one of the src and dest pointers is null.)
10296 if (!N)
10297 return true;
10298
10299 // Otherwise, if either of the operands is null, we can't proceed. Don't
10300 // try to determine the type of the copied objects, because there aren't
10301 // any.
10302 if (!Src.Base || !Dest.Base) {
10303 APValue Val;
10304 (!Src.Base ? Src : Dest).moveInto(Val);
10305 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10306 << Move << WChar << !!Src.Base
10307 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10308 return false;
10309 }
10310 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10311 return false;
10312
10313 // We require that Src and Dest are both pointers to arrays of
10314 // trivially-copyable type. (For the wide version, the designator will be
10315 // invalid if the designated object is not a wchar_t.)
10316 QualType T = Dest.Designator.getType(Info.Ctx);
10317 QualType SrcT = Src.Designator.getType(Info.Ctx);
10318 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10319 // FIXME: Consider using our bit_cast implementation to support this.
10320 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10321 return false;
10322 }
10323 if (T->isIncompleteType()) {
10324 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10325 return false;
10326 }
10327 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10328 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10329 return false;
10330 }
10331
10332 // Figure out how many T's we're copying.
10333 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10334 if (TSize == 0)
10335 return false;
10336 if (!WChar) {
10337 uint64_t Remainder;
10338 llvm::APInt OrigN = N;
10339 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10340 if (Remainder) {
10341 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10342 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10343 << (unsigned)TSize;
10344 return false;
10345 }
10346 }
10347
10348 // Check that the copying will remain within the arrays, just so that we
10349 // can give a more meaningful diagnostic. This implicitly also checks that
10350 // N fits into 64 bits.
10351 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10352 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10353 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10354 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10355 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10356 << toString(N, 10, /*Signed*/false);
10357 return false;
10358 }
10359 uint64_t NElems = N.getZExtValue();
10360 uint64_t NBytes = NElems * TSize;
10361
10362 // Check for overlap.
10363 int Direction = 1;
10364 if (HasSameBase(Src, Dest)) {
10365 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10366 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10367 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10368 // Dest is inside the source region.
10369 if (!Move) {
10370 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10371 return false;
10372 }
10373 // For memmove and friends, copy backwards.
10374 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10375 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10376 return false;
10377 Direction = -1;
10378 } else if (!Move && SrcOffset >= DestOffset &&
10379 SrcOffset - DestOffset < NBytes) {
10380 // Src is inside the destination region for memcpy: invalid.
10381 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10382 return false;
10383 }
10384 }
10385
10386 while (true) {
10387 APValue Val;
10388 // FIXME: Set WantObjectRepresentation to true if we're copying a
10389 // char-like type?
10390 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10391 !handleAssignment(Info, E, Dest, T, Val))
10392 return false;
10393 // Do not iterate past the last element; if we're copying backwards, that
10394 // might take us off the start of the array.
10395 if (--NElems == 0)
10396 return true;
10397 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10398 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10399 return false;
10400 }
10401 }
10402
10403 default:
10404 return false;
10405 }
10406}
10407
10408static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10409 APValue &Result, const InitListExpr *ILE,
10410 QualType AllocType);
10411static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10412 APValue &Result,
10413 const CXXConstructExpr *CCE,
10414 QualType AllocType);
10415
10416bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10417 if (!Info.getLangOpts().CPlusPlus20)
10418 Info.CCEDiag(E, diag::note_constexpr_new);
10419
10420 // We cannot speculatively evaluate a delete expression.
10421 if (Info.SpeculativeEvaluationDepth)
10422 return false;
10423
10424 FunctionDecl *OperatorNew = E->getOperatorNew();
10425 QualType AllocType = E->getAllocatedType();
10426 QualType TargetType = AllocType;
10427
10428 bool IsNothrow = false;
10429 bool IsPlacement = false;
10430
10431 if (E->getNumPlacementArgs() == 1 &&
10432 E->getPlacementArg(0)->getType()->isNothrowT()) {
10433 // The only new-placement list we support is of the form (std::nothrow).
10434 //
10435 // FIXME: There is no restriction on this, but it's not clear that any
10436 // other form makes any sense. We get here for cases such as:
10437 //
10438 // new (std::align_val_t{N}) X(int)
10439 //
10440 // (which should presumably be valid only if N is a multiple of
10441 // alignof(int), and in any case can't be deallocated unless N is
10442 // alignof(X) and X has new-extended alignment).
10443 LValue Nothrow;
10444 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10445 return false;
10446 IsNothrow = true;
10447 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10448 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10449 (Info.CurrentCall->CanEvalMSConstexpr &&
10450 OperatorNew->hasAttr<MSConstexprAttr>())) {
10451 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10452 return false;
10453 if (Result.Designator.Invalid)
10454 return false;
10455 TargetType = E->getPlacementArg(0)->getType();
10456 IsPlacement = true;
10457 } else {
10458 Info.FFDiag(E, diag::note_constexpr_new_placement)
10459 << /*C++26 feature*/ 1 << E->getSourceRange();
10460 return false;
10461 }
10462 } else if (E->getNumPlacementArgs()) {
10463 Info.FFDiag(E, diag::note_constexpr_new_placement)
10464 << /*Unsupported*/ 0 << E->getSourceRange();
10465 return false;
10466 } else if (!OperatorNew
10467 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10468 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10469 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10470 return false;
10471 }
10472
10473 const Expr *Init = E->getInitializer();
10474 const InitListExpr *ResizedArrayILE = nullptr;
10475 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10476 bool ValueInit = false;
10477
10478 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10479 const Expr *Stripped = *ArraySize;
10480 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10481 Stripped = ICE->getSubExpr())
10482 if (ICE->getCastKind() != CK_NoOp &&
10483 ICE->getCastKind() != CK_IntegralCast)
10484 break;
10485
10486 llvm::APSInt ArrayBound;
10487 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10488 return false;
10489
10490 // C++ [expr.new]p9:
10491 // The expression is erroneous if:
10492 // -- [...] its value before converting to size_t [or] applying the
10493 // second standard conversion sequence is less than zero
10494 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10495 if (IsNothrow)
10496 return ZeroInitialization(E);
10497
10498 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10499 << ArrayBound << (*ArraySize)->getSourceRange();
10500 return false;
10501 }
10502
10503 // -- its value is such that the size of the allocated object would
10504 // exceed the implementation-defined limit
10505 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10507 Info.Ctx, AllocType, ArrayBound),
10508 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10509 if (IsNothrow)
10510 return ZeroInitialization(E);
10511 return false;
10512 }
10513
10514 // -- the new-initializer is a braced-init-list and the number of
10515 // array elements for which initializers are provided [...]
10516 // exceeds the number of elements to initialize
10517 if (!Init) {
10518 // No initialization is performed.
10519 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10520 isa<ImplicitValueInitExpr>(Init)) {
10521 ValueInit = true;
10522 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10523 ResizedArrayCCE = CCE;
10524 } else {
10525 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10526 assert(CAT && "unexpected type for array initializer");
10527
10528 unsigned Bits =
10529 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10530 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10531 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10532 if (InitBound.ugt(AllocBound)) {
10533 if (IsNothrow)
10534 return ZeroInitialization(E);
10535
10536 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10537 << toString(AllocBound, 10, /*Signed=*/false)
10538 << toString(InitBound, 10, /*Signed=*/false)
10539 << (*ArraySize)->getSourceRange();
10540 return false;
10541 }
10542
10543 // If the sizes differ, we must have an initializer list, and we need
10544 // special handling for this case when we initialize.
10545 if (InitBound != AllocBound)
10546 ResizedArrayILE = cast<InitListExpr>(Init);
10547 }
10548
10549 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10550 ArraySizeModifier::Normal, 0);
10551 } else {
10552 assert(!AllocType->isArrayType() &&
10553 "array allocation with non-array new");
10554 }
10555
10556 APValue *Val;
10557 if (IsPlacement) {
10559 struct FindObjectHandler {
10560 EvalInfo &Info;
10561 const Expr *E;
10562 QualType AllocType;
10563 const AccessKinds AccessKind;
10564 APValue *Value;
10565
10566 typedef bool result_type;
10567 bool failed() { return false; }
10568 bool checkConst(QualType QT) {
10569 if (QT.isConstQualified()) {
10570 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10571 return false;
10572 }
10573 return true;
10574 }
10575 bool found(APValue &Subobj, QualType SubobjType) {
10576 if (!checkConst(SubobjType))
10577 return false;
10578 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10579 // old name of the object to be used to name the new object.
10580 unsigned SubobjectSize = 1;
10581 unsigned AllocSize = 1;
10582 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10583 AllocSize = CAT->getZExtSize();
10584 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10585 SubobjectSize = CAT->getZExtSize();
10586 if (SubobjectSize < AllocSize ||
10587 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10588 Info.Ctx.getBaseElementType(AllocType))) {
10589 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10590 << SubobjType << AllocType;
10591 return false;
10592 }
10593 Value = &Subobj;
10594 return true;
10595 }
10596 bool found(APSInt &Value, QualType SubobjType) {
10597 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10598 return false;
10599 }
10600 bool found(APFloat &Value, QualType SubobjType) {
10601 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10602 return false;
10603 }
10604 } Handler = {Info, E, AllocType, AK, nullptr};
10605
10606 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10607 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10608 return false;
10609
10610 Val = Handler.Value;
10611
10612 // [basic.life]p1:
10613 // The lifetime of an object o of type T ends when [...] the storage
10614 // which the object occupies is [...] reused by an object that is not
10615 // nested within o (6.6.2).
10616 *Val = APValue();
10617 } else {
10618 // Perform the allocation and obtain a pointer to the resulting object.
10619 Val = Info.createHeapAlloc(E, AllocType, Result);
10620 if (!Val)
10621 return false;
10622 }
10623
10624 if (ValueInit) {
10625 ImplicitValueInitExpr VIE(AllocType);
10626 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10627 return false;
10628 } else if (ResizedArrayILE) {
10629 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10630 AllocType))
10631 return false;
10632 } else if (ResizedArrayCCE) {
10633 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10634 AllocType))
10635 return false;
10636 } else if (Init) {
10637 if (!EvaluateInPlace(*Val, Info, Result, Init))
10638 return false;
10639 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10640 return false;
10641 }
10642
10643 // Array new returns a pointer to the first element, not a pointer to the
10644 // array.
10645 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10646 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10647
10648 return true;
10649}
10650//===----------------------------------------------------------------------===//
10651// Member Pointer Evaluation
10652//===----------------------------------------------------------------------===//
10653
10654namespace {
10655class MemberPointerExprEvaluator
10656 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10657 MemberPtr &Result;
10658
10659 bool Success(const ValueDecl *D) {
10660 Result = MemberPtr(D);
10661 return true;
10662 }
10663public:
10664
10665 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10666 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10667
10668 bool Success(const APValue &V, const Expr *E) {
10669 Result.setFrom(V);
10670 return true;
10671 }
10672 bool ZeroInitialization(const Expr *E) {
10673 return Success((const ValueDecl*)nullptr);
10674 }
10675
10676 bool VisitCastExpr(const CastExpr *E);
10677 bool VisitUnaryAddrOf(const UnaryOperator *E);
10678};
10679} // end anonymous namespace
10680
10681static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10682 EvalInfo &Info) {
10683 assert(!E->isValueDependent());
10684 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10685 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10686}
10687
10688bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10689 switch (E->getCastKind()) {
10690 default:
10691 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10692
10693 case CK_NullToMemberPointer:
10694 VisitIgnoredValue(E->getSubExpr());
10695 return ZeroInitialization(E);
10696
10697 case CK_BaseToDerivedMemberPointer: {
10698 if (!Visit(E->getSubExpr()))
10699 return false;
10700 if (E->path_empty())
10701 return true;
10702 // Base-to-derived member pointer casts store the path in derived-to-base
10703 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10704 // the wrong end of the derived->base arc, so stagger the path by one class.
10705 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10706 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10707 PathI != PathE; ++PathI) {
10708 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10709 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10710 if (!Result.castToDerived(Derived))
10711 return Error(E);
10712 }
10713 if (!Result.castToDerived(E->getType()
10716 return Error(E);
10717 return true;
10718 }
10719
10720 case CK_DerivedToBaseMemberPointer:
10721 if (!Visit(E->getSubExpr()))
10722 return false;
10723 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10724 PathE = E->path_end(); PathI != PathE; ++PathI) {
10725 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10726 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10727 if (!Result.castToBase(Base))
10728 return Error(E);
10729 }
10730 return true;
10731 }
10732}
10733
10734bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10735 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10736 // member can be formed.
10737 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10738}
10739
10740//===----------------------------------------------------------------------===//
10741// Record Evaluation
10742//===----------------------------------------------------------------------===//
10743
10744namespace {
10745 class RecordExprEvaluator
10746 : public ExprEvaluatorBase<RecordExprEvaluator> {
10747 const LValue &This;
10748 APValue &Result;
10749 public:
10750
10751 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10752 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10753
10754 bool Success(const APValue &V, const Expr *E) {
10755 Result = V;
10756 return true;
10757 }
10758 bool ZeroInitialization(const Expr *E) {
10759 return ZeroInitialization(E, E->getType());
10760 }
10761 bool ZeroInitialization(const Expr *E, QualType T);
10762
10763 bool VisitCallExpr(const CallExpr *E) {
10764 return handleCallExpr(E, Result, &This);
10765 }
10766 bool VisitCastExpr(const CastExpr *E);
10767 bool VisitInitListExpr(const InitListExpr *E);
10768 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10769 return VisitCXXConstructExpr(E, E->getType());
10770 }
10771 bool VisitLambdaExpr(const LambdaExpr *E);
10772 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10773 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10774 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10775 bool VisitBinCmp(const BinaryOperator *E);
10776 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10777 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10778 ArrayRef<Expr *> Args);
10779 };
10780}
10781
10782/// Perform zero-initialization on an object of non-union class type.
10783/// C++11 [dcl.init]p5:
10784/// To zero-initialize an object or reference of type T means:
10785/// [...]
10786/// -- if T is a (possibly cv-qualified) non-union class type,
10787/// each non-static data member and each base-class subobject is
10788/// zero-initialized
10789static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10790 const RecordDecl *RD,
10791 const LValue &This, APValue &Result) {
10792 assert(!RD->isUnion() && "Expected non-union class type");
10793 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10794 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10795 std::distance(RD->field_begin(), RD->field_end()));
10796
10797 if (RD->isInvalidDecl()) return false;
10798 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10799
10800 if (CD) {
10801 unsigned Index = 0;
10803 End = CD->bases_end(); I != End; ++I, ++Index) {
10804 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10805 LValue Subobject = This;
10806 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10807 return false;
10808 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10809 Result.getStructBase(Index)))
10810 return false;
10811 }
10812 }
10813
10814 for (const auto *I : RD->fields()) {
10815 // -- if T is a reference type, no initialization is performed.
10816 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10817 continue;
10818
10819 LValue Subobject = This;
10820 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10821 return false;
10822
10823 ImplicitValueInitExpr VIE(I->getType());
10824 if (!EvaluateInPlace(
10825 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10826 return false;
10827 }
10828
10829 return true;
10830}
10831
10832bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10833 const auto *RD = T->castAsRecordDecl();
10834 if (RD->isInvalidDecl()) return false;
10835 if (RD->isUnion()) {
10836 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10837 // object's first non-static named data member is zero-initialized
10839 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10840 ++I;
10841 if (I == RD->field_end()) {
10842 Result = APValue((const FieldDecl*)nullptr);
10843 return true;
10844 }
10845
10846 LValue Subobject = This;
10847 if (!HandleLValueMember(Info, E, Subobject, *I))
10848 return false;
10849 Result = APValue(*I);
10850 ImplicitValueInitExpr VIE(I->getType());
10851 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10852 }
10853
10854 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10855 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10856 return false;
10857 }
10858
10859 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10860}
10861
10862bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10863 switch (E->getCastKind()) {
10864 default:
10865 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10866
10867 case CK_ConstructorConversion:
10868 return Visit(E->getSubExpr());
10869
10870 case CK_DerivedToBase:
10871 case CK_UncheckedDerivedToBase: {
10872 APValue DerivedObject;
10873 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10874 return false;
10875 if (!DerivedObject.isStruct())
10876 return Error(E->getSubExpr());
10877
10878 // Derived-to-base rvalue conversion: just slice off the derived part.
10879 APValue *Value = &DerivedObject;
10880 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10881 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10882 PathE = E->path_end(); PathI != PathE; ++PathI) {
10883 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10884 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10885 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10886 RD = Base;
10887 }
10888 Result = *Value;
10889 return true;
10890 }
10891 }
10892}
10893
10894bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10895 if (E->isTransparent())
10896 return Visit(E->getInit(0));
10897 return VisitCXXParenListOrInitListExpr(E, E->inits());
10898}
10899
10900bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10901 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10902 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
10903 if (RD->isInvalidDecl()) return false;
10904 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10905 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10906
10907 EvalInfo::EvaluatingConstructorRAII EvalObj(
10908 Info,
10909 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10910 CXXRD && CXXRD->getNumBases());
10911
10912 if (RD->isUnion()) {
10913 const FieldDecl *Field;
10914 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10915 Field = ILE->getInitializedFieldInUnion();
10916 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10917 Field = PLIE->getInitializedFieldInUnion();
10918 } else {
10919 llvm_unreachable(
10920 "Expression is neither an init list nor a C++ paren list");
10921 }
10922
10923 Result = APValue(Field);
10924 if (!Field)
10925 return true;
10926
10927 // If the initializer list for a union does not contain any elements, the
10928 // first element of the union is value-initialized.
10929 // FIXME: The element should be initialized from an initializer list.
10930 // Is this difference ever observable for initializer lists which
10931 // we don't build?
10932 ImplicitValueInitExpr VIE(Field->getType());
10933 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10934
10935 LValue Subobject = This;
10936 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10937 return false;
10938
10939 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10940 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10941 isa<CXXDefaultInitExpr>(InitExpr));
10942
10943 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10944 if (Field->isBitField())
10945 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10946 Field);
10947 return true;
10948 }
10949
10950 return false;
10951 }
10952
10953 if (!Result.hasValue())
10954 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10955 std::distance(RD->field_begin(), RD->field_end()));
10956 unsigned ElementNo = 0;
10957 bool Success = true;
10958
10959 // Initialize base classes.
10960 if (CXXRD && CXXRD->getNumBases()) {
10961 for (const auto &Base : CXXRD->bases()) {
10962 assert(ElementNo < Args.size() && "missing init for base class");
10963 const Expr *Init = Args[ElementNo];
10964
10965 LValue Subobject = This;
10966 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10967 return false;
10968
10969 APValue &FieldVal = Result.getStructBase(ElementNo);
10970 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10971 if (!Info.noteFailure())
10972 return false;
10973 Success = false;
10974 }
10975 ++ElementNo;
10976 }
10977
10978 EvalObj.finishedConstructingBases();
10979 }
10980
10981 // Initialize members.
10982 for (const auto *Field : RD->fields()) {
10983 // Anonymous bit-fields are not considered members of the class for
10984 // purposes of aggregate initialization.
10985 if (Field->isUnnamedBitField())
10986 continue;
10987
10988 LValue Subobject = This;
10989
10990 bool HaveInit = ElementNo < Args.size();
10991
10992 // FIXME: Diagnostics here should point to the end of the initializer
10993 // list, not the start.
10994 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10995 Subobject, Field, &Layout))
10996 return false;
10997
10998 // Perform an implicit value-initialization for members beyond the end of
10999 // the initializer list.
11000 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11001 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11002
11003 if (Field->getType()->isIncompleteArrayType()) {
11004 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11005 if (!CAT->isZeroSize()) {
11006 // Bail out for now. This might sort of "work", but the rest of the
11007 // code isn't really prepared to handle it.
11008 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11009 return false;
11010 }
11011 }
11012 }
11013
11014 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11015 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11016 isa<CXXDefaultInitExpr>(Init));
11017
11018 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11019 if (Field->getType()->isReferenceType()) {
11020 LValue Result;
11021 if (!EvaluateInitForDeclOfReferenceType(Info, Field, Init, Result,
11022 FieldVal)) {
11023 if (!Info.noteFailure())
11024 return false;
11025 Success = false;
11026 }
11027 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11028 (Field->isBitField() &&
11029 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11030 if (!Info.noteFailure())
11031 return false;
11032 Success = false;
11033 }
11034 }
11035
11036 EvalObj.finishedConstructingFields();
11037
11038 return Success;
11039}
11040
11041bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11042 QualType T) {
11043 // Note that E's type is not necessarily the type of our class here; we might
11044 // be initializing an array element instead.
11045 const CXXConstructorDecl *FD = E->getConstructor();
11046 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11047
11048 bool ZeroInit = E->requiresZeroInitialization();
11049 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11050 if (ZeroInit)
11051 return ZeroInitialization(E, T);
11052
11053 return handleDefaultInitValue(T, Result);
11054 }
11055
11056 const FunctionDecl *Definition = nullptr;
11057 auto Body = FD->getBody(Definition);
11058
11059 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11060 return false;
11061
11062 // Avoid materializing a temporary for an elidable copy/move constructor.
11063 if (E->isElidable() && !ZeroInit) {
11064 // FIXME: This only handles the simplest case, where the source object
11065 // is passed directly as the first argument to the constructor.
11066 // This should also handle stepping though implicit casts and
11067 // and conversion sequences which involve two steps, with a
11068 // conversion operator followed by a converting constructor.
11069 const Expr *SrcObj = E->getArg(0);
11070 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11071 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11072 if (const MaterializeTemporaryExpr *ME =
11073 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11074 return Visit(ME->getSubExpr());
11075 }
11076
11077 if (ZeroInit && !ZeroInitialization(E, T))
11078 return false;
11079
11080 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11081 return HandleConstructorCall(E, This, Args,
11082 cast<CXXConstructorDecl>(Definition), Info,
11083 Result);
11084}
11085
11086bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11087 const CXXInheritedCtorInitExpr *E) {
11088 if (!Info.CurrentCall) {
11089 assert(Info.checkingPotentialConstantExpression());
11090 return false;
11091 }
11092
11093 const CXXConstructorDecl *FD = E->getConstructor();
11094 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11095 return false;
11096
11097 const FunctionDecl *Definition = nullptr;
11098 auto Body = FD->getBody(Definition);
11099
11100 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11101 return false;
11102
11103 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11104 cast<CXXConstructorDecl>(Definition), Info,
11105 Result);
11106}
11107
11108bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11111 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11112
11113 LValue Array;
11114 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11115 return false;
11116
11117 assert(ArrayType && "unexpected type for array initializer");
11118
11119 // Get a pointer to the first element of the array.
11120 Array.addArray(Info, E, ArrayType);
11121
11122 // FIXME: What if the initializer_list type has base classes, etc?
11123 Result = APValue(APValue::UninitStruct(), 0, 2);
11124 Array.moveInto(Result.getStructField(0));
11125
11126 auto *Record = E->getType()->castAsRecordDecl();
11127 RecordDecl::field_iterator Field = Record->field_begin();
11128 assert(Field != Record->field_end() &&
11129 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11131 "Expected std::initializer_list first field to be const E *");
11132 ++Field;
11133 assert(Field != Record->field_end() &&
11134 "Expected std::initializer_list to have two fields");
11135
11136 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11137 // Length.
11138 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11139 } else {
11140 // End pointer.
11141 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11143 "Expected std::initializer_list second field to be const E *");
11144 if (!HandleLValueArrayAdjustment(Info, E, Array,
11146 ArrayType->getZExtSize()))
11147 return false;
11148 Array.moveInto(Result.getStructField(1));
11149 }
11150
11151 assert(++Field == Record->field_end() &&
11152 "Expected std::initializer_list to only have two fields");
11153
11154 return true;
11155}
11156
11157bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11158 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11159 if (ClosureClass->isInvalidDecl())
11160 return false;
11161
11162 const size_t NumFields =
11163 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11164
11165 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11166 E->capture_init_end()) &&
11167 "The number of lambda capture initializers should equal the number of "
11168 "fields within the closure type");
11169
11170 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11171 // Iterate through all the lambda's closure object's fields and initialize
11172 // them.
11173 auto *CaptureInitIt = E->capture_init_begin();
11174 bool Success = true;
11175 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11176 for (const auto *Field : ClosureClass->fields()) {
11177 assert(CaptureInitIt != E->capture_init_end());
11178 // Get the initializer for this field
11179 Expr *const CurFieldInit = *CaptureInitIt++;
11180
11181 // If there is no initializer, either this is a VLA or an error has
11182 // occurred.
11183 if (!CurFieldInit || CurFieldInit->containsErrors())
11184 return Error(E);
11185
11186 LValue Subobject = This;
11187
11188 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11189 return false;
11190
11191 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11192 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11193 if (!Info.keepEvaluatingAfterFailure())
11194 return false;
11195 Success = false;
11196 }
11197 }
11198 return Success;
11199}
11200
11201static bool EvaluateRecord(const Expr *E, const LValue &This,
11202 APValue &Result, EvalInfo &Info) {
11203 assert(!E->isValueDependent());
11204 assert(E->isPRValue() && E->getType()->isRecordType() &&
11205 "can't evaluate expression as a record rvalue");
11206 return RecordExprEvaluator(Info, This, Result).Visit(E);
11207}
11208
11209//===----------------------------------------------------------------------===//
11210// Temporary Evaluation
11211//
11212// Temporaries are represented in the AST as rvalues, but generally behave like
11213// lvalues. The full-object of which the temporary is a subobject is implicitly
11214// materialized so that a reference can bind to it.
11215//===----------------------------------------------------------------------===//
11216namespace {
11217class TemporaryExprEvaluator
11218 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11219public:
11220 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11221 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11222
11223 /// Visit an expression which constructs the value of this temporary.
11224 bool VisitConstructExpr(const Expr *E) {
11225 APValue &Value = Info.CurrentCall->createTemporary(
11226 E, E->getType(), ScopeKind::FullExpression, Result);
11227 return EvaluateInPlace(Value, Info, Result, E);
11228 }
11229
11230 bool VisitCastExpr(const CastExpr *E) {
11231 switch (E->getCastKind()) {
11232 default:
11233 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11234
11235 case CK_ConstructorConversion:
11236 return VisitConstructExpr(E->getSubExpr());
11237 }
11238 }
11239 bool VisitInitListExpr(const InitListExpr *E) {
11240 return VisitConstructExpr(E);
11241 }
11242 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11243 return VisitConstructExpr(E);
11244 }
11245 bool VisitCallExpr(const CallExpr *E) {
11246 return VisitConstructExpr(E);
11247 }
11248 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11249 return VisitConstructExpr(E);
11250 }
11251 bool VisitLambdaExpr(const LambdaExpr *E) {
11252 return VisitConstructExpr(E);
11253 }
11254};
11255} // end anonymous namespace
11256
11257/// Evaluate an expression of record type as a temporary.
11258static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11259 assert(!E->isValueDependent());
11260 assert(E->isPRValue() && E->getType()->isRecordType());
11261 return TemporaryExprEvaluator(Info, Result).Visit(E);
11262}
11263
11264//===----------------------------------------------------------------------===//
11265// Vector Evaluation
11266//===----------------------------------------------------------------------===//
11267
11268namespace {
11269 class VectorExprEvaluator
11270 : public ExprEvaluatorBase<VectorExprEvaluator> {
11271 APValue &Result;
11272 public:
11273
11274 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11275 : ExprEvaluatorBaseTy(info), Result(Result) {}
11276
11277 bool Success(ArrayRef<APValue> V, const Expr *E) {
11278 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11279 // FIXME: remove this APValue copy.
11280 Result = APValue(V.data(), V.size());
11281 return true;
11282 }
11283 bool Success(const APValue &V, const Expr *E) {
11284 assert(V.isVector());
11285 Result = V;
11286 return true;
11287 }
11288 bool ZeroInitialization(const Expr *E);
11289
11290 bool VisitUnaryReal(const UnaryOperator *E)
11291 { return Visit(E->getSubExpr()); }
11292 bool VisitCastExpr(const CastExpr* E);
11293 bool VisitInitListExpr(const InitListExpr *E);
11294 bool VisitUnaryImag(const UnaryOperator *E);
11295 bool VisitBinaryOperator(const BinaryOperator *E);
11296 bool VisitUnaryOperator(const UnaryOperator *E);
11297 bool VisitCallExpr(const CallExpr *E);
11298 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11299 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11300
11301 // FIXME: Missing: conditional operator (for GNU
11302 // conditional select), ExtVectorElementExpr
11303 };
11304} // end anonymous namespace
11305
11306static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11307 assert(E->isPRValue() && E->getType()->isVectorType() &&
11308 "not a vector prvalue");
11309 return VectorExprEvaluator(Info, Result).Visit(E);
11310}
11311
11312static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11313 assert(Val.isVector() && "expected vector APValue");
11314 unsigned NumElts = Val.getVectorLength();
11315
11316 // Each element is one bit, so create an integer with NumElts bits.
11317 llvm::APInt Result(NumElts, 0);
11318
11319 for (unsigned I = 0; I < NumElts; ++I) {
11320 const APValue &Elt = Val.getVectorElt(I);
11321 assert(Elt.isInt() && "expected integer element in bool vector");
11322
11323 if (Elt.getInt().getBoolValue())
11324 Result.setBit(I);
11325 }
11326
11327 return Result;
11328}
11329
11330bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11331 const VectorType *VTy = E->getType()->castAs<VectorType>();
11332 unsigned NElts = VTy->getNumElements();
11333
11334 const Expr *SE = E->getSubExpr();
11335 QualType SETy = SE->getType();
11336
11337 switch (E->getCastKind()) {
11338 case CK_VectorSplat: {
11339 APValue Val = APValue();
11340 if (SETy->isIntegerType()) {
11341 APSInt IntResult;
11342 if (!EvaluateInteger(SE, IntResult, Info))
11343 return false;
11344 Val = APValue(std::move(IntResult));
11345 } else if (SETy->isRealFloatingType()) {
11346 APFloat FloatResult(0.0);
11347 if (!EvaluateFloat(SE, FloatResult, Info))
11348 return false;
11349 Val = APValue(std::move(FloatResult));
11350 } else {
11351 return Error(E);
11352 }
11353
11354 // Splat and create vector APValue.
11355 SmallVector<APValue, 4> Elts(NElts, Val);
11356 return Success(Elts, E);
11357 }
11358 case CK_BitCast: {
11359 APValue SVal;
11360 if (!Evaluate(SVal, Info, SE))
11361 return false;
11362
11363 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11364 // Give up if the input isn't an int, float, or vector. For example, we
11365 // reject "(v4i16)(intptr_t)&a".
11366 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11367 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11368 << Info.Ctx.getLangOpts().CPlusPlus;
11369 return false;
11370 }
11371
11372 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11373 return false;
11374
11375 return true;
11376 }
11377 case CK_HLSLVectorTruncation: {
11378 APValue Val;
11379 SmallVector<APValue, 4> Elements;
11380 if (!EvaluateVector(SE, Val, Info))
11381 return Error(E);
11382 for (unsigned I = 0; I < NElts; I++)
11383 Elements.push_back(Val.getVectorElt(I));
11384 return Success(Elements, E);
11385 }
11386 default:
11387 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11388 }
11389}
11390
11391bool
11392VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11393 const VectorType *VT = E->getType()->castAs<VectorType>();
11394 unsigned NumInits = E->getNumInits();
11395 unsigned NumElements = VT->getNumElements();
11396
11397 QualType EltTy = VT->getElementType();
11398 SmallVector<APValue, 4> Elements;
11399
11400 // MFloat8 type doesn't have constants and thus constant folding
11401 // is impossible.
11402 if (EltTy->isMFloat8Type())
11403 return false;
11404
11405 // The number of initializers can be less than the number of
11406 // vector elements. For OpenCL, this can be due to nested vector
11407 // initialization. For GCC compatibility, missing trailing elements
11408 // should be initialized with zeroes.
11409 unsigned CountInits = 0, CountElts = 0;
11410 while (CountElts < NumElements) {
11411 // Handle nested vector initialization.
11412 if (CountInits < NumInits
11413 && E->getInit(CountInits)->getType()->isVectorType()) {
11414 APValue v;
11415 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11416 return Error(E);
11417 unsigned vlen = v.getVectorLength();
11418 for (unsigned j = 0; j < vlen; j++)
11419 Elements.push_back(v.getVectorElt(j));
11420 CountElts += vlen;
11421 } else if (EltTy->isIntegerType()) {
11422 llvm::APSInt sInt(32);
11423 if (CountInits < NumInits) {
11424 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11425 return false;
11426 } else // trailing integer zero.
11427 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11428 Elements.push_back(APValue(sInt));
11429 CountElts++;
11430 } else {
11431 llvm::APFloat f(0.0);
11432 if (CountInits < NumInits) {
11433 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11434 return false;
11435 } else // trailing float zero.
11436 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11437 Elements.push_back(APValue(f));
11438 CountElts++;
11439 }
11440 CountInits++;
11441 }
11442 return Success(Elements, E);
11443}
11444
11445bool
11446VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11447 const auto *VT = E->getType()->castAs<VectorType>();
11448 QualType EltTy = VT->getElementType();
11449 APValue ZeroElement;
11450 if (EltTy->isIntegerType())
11451 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11452 else
11453 ZeroElement =
11454 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11455
11456 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11457 return Success(Elements, E);
11458}
11459
11460bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11461 VisitIgnoredValue(E->getSubExpr());
11462 return ZeroInitialization(E);
11463}
11464
11465bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11466 BinaryOperatorKind Op = E->getOpcode();
11467 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11468 "Operation not supported on vector types");
11469
11470 if (Op == BO_Comma)
11471 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11472
11473 Expr *LHS = E->getLHS();
11474 Expr *RHS = E->getRHS();
11475
11476 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11477 "Must both be vector types");
11478 // Checking JUST the types are the same would be fine, except shifts don't
11479 // need to have their types be the same (since you always shift by an int).
11480 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11482 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11484 "All operands must be the same size.");
11485
11486 APValue LHSValue;
11487 APValue RHSValue;
11488 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11489 if (!LHSOK && !Info.noteFailure())
11490 return false;
11491 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11492 return false;
11493
11494 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11495 return false;
11496
11497 return Success(LHSValue, E);
11498}
11499
11500static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11501 QualType ResultTy,
11503 APValue Elt) {
11504 switch (Op) {
11505 case UO_Plus:
11506 // Nothing to do here.
11507 return Elt;
11508 case UO_Minus:
11509 if (Elt.getKind() == APValue::Int) {
11510 Elt.getInt().negate();
11511 } else {
11512 assert(Elt.getKind() == APValue::Float &&
11513 "Vector can only be int or float type");
11514 Elt.getFloat().changeSign();
11515 }
11516 return Elt;
11517 case UO_Not:
11518 // This is only valid for integral types anyway, so we don't have to handle
11519 // float here.
11520 assert(Elt.getKind() == APValue::Int &&
11521 "Vector operator ~ can only be int");
11522 Elt.getInt().flipAllBits();
11523 return Elt;
11524 case UO_LNot: {
11525 if (Elt.getKind() == APValue::Int) {
11526 Elt.getInt() = !Elt.getInt();
11527 // operator ! on vectors returns -1 for 'truth', so negate it.
11528 Elt.getInt().negate();
11529 return Elt;
11530 }
11531 assert(Elt.getKind() == APValue::Float &&
11532 "Vector can only be int or float type");
11533 // Float types result in an int of the same size, but -1 for true, or 0 for
11534 // false.
11535 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11536 ResultTy->isUnsignedIntegerType()};
11537 if (Elt.getFloat().isZero())
11538 EltResult.setAllBits();
11539 else
11540 EltResult.clearAllBits();
11541
11542 return APValue{EltResult};
11543 }
11544 default:
11545 // FIXME: Implement the rest of the unary operators.
11546 return std::nullopt;
11547 }
11548}
11549
11550bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11551 Expr *SubExpr = E->getSubExpr();
11552 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11553 // This result element type differs in the case of negating a floating point
11554 // vector, since the result type is the a vector of the equivilant sized
11555 // integer.
11556 const QualType ResultEltTy = VD->getElementType();
11557 UnaryOperatorKind Op = E->getOpcode();
11558
11559 APValue SubExprValue;
11560 if (!Evaluate(SubExprValue, Info, SubExpr))
11561 return false;
11562
11563 // FIXME: This vector evaluator someday needs to be changed to be LValue
11564 // aware/keep LValue information around, rather than dealing with just vector
11565 // types directly. Until then, we cannot handle cases where the operand to
11566 // these unary operators is an LValue. The only case I've been able to see
11567 // cause this is operator++ assigning to a member expression (only valid in
11568 // altivec compilations) in C mode, so this shouldn't limit us too much.
11569 if (SubExprValue.isLValue())
11570 return false;
11571
11572 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11573 "Vector length doesn't match type?");
11574
11575 SmallVector<APValue, 4> ResultElements;
11576 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11577 std::optional<APValue> Elt = handleVectorUnaryOperator(
11578 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11579 if (!Elt)
11580 return false;
11581 ResultElements.push_back(*Elt);
11582 }
11583 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11584}
11585
11586static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11587 const Expr *E, QualType SourceTy,
11588 QualType DestTy, APValue const &Original,
11589 APValue &Result) {
11590 if (SourceTy->isIntegerType()) {
11591 if (DestTy->isRealFloatingType()) {
11592 Result = APValue(APFloat(0.0));
11593 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11594 DestTy, Result.getFloat());
11595 }
11596 if (DestTy->isIntegerType()) {
11597 Result = APValue(
11598 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11599 return true;
11600 }
11601 } else if (SourceTy->isRealFloatingType()) {
11602 if (DestTy->isRealFloatingType()) {
11603 Result = Original;
11604 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11605 Result.getFloat());
11606 }
11607 if (DestTy->isIntegerType()) {
11608 Result = APValue(APSInt());
11609 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11610 DestTy, Result.getInt());
11611 }
11612 }
11613
11614 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11615 << SourceTy << DestTy;
11616 return false;
11617}
11618
11619bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11620 if (!IsConstantEvaluatedBuiltinCall(E))
11621 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11622
11623 switch (E->getBuiltinCallee()) {
11624 default:
11625 return false;
11626 case Builtin::BI__builtin_elementwise_popcount:
11627 case Builtin::BI__builtin_elementwise_bitreverse: {
11628 APValue Source;
11629 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11630 return false;
11631
11632 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11633 unsigned SourceLen = Source.getVectorLength();
11634 SmallVector<APValue, 4> ResultElements;
11635 ResultElements.reserve(SourceLen);
11636
11637 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11638 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11639 switch (E->getBuiltinCallee()) {
11640 case Builtin::BI__builtin_elementwise_popcount:
11641 ResultElements.push_back(APValue(
11642 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11643 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11644 break;
11645 case Builtin::BI__builtin_elementwise_bitreverse:
11646 ResultElements.push_back(
11647 APValue(APSInt(Elt.reverseBits(),
11648 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11649 break;
11650 }
11651 }
11652
11653 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11654 }
11655 case Builtin::BI__builtin_elementwise_abs: {
11656 APValue Source;
11657 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11658 return false;
11659
11660 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11661 unsigned SourceLen = Source.getVectorLength();
11662 SmallVector<APValue, 4> ResultElements;
11663 ResultElements.reserve(SourceLen);
11664
11665 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11666 APValue CurrentEle = Source.getVectorElt(EltNum);
11667 APValue Val = DestEltTy->isFloatingType()
11668 ? APValue(llvm::abs(CurrentEle.getFloat()))
11669 : APValue(APSInt(
11670 CurrentEle.getInt().abs(),
11671 DestEltTy->isUnsignedIntegerOrEnumerationType()));
11672 ResultElements.push_back(Val);
11673 }
11674
11675 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11676 }
11677
11678 case Builtin::BI__builtin_elementwise_add_sat:
11679 case Builtin::BI__builtin_elementwise_sub_sat:
11680 case clang::X86::BI__builtin_ia32_pmulhuw128:
11681 case clang::X86::BI__builtin_ia32_pmulhuw256:
11682 case clang::X86::BI__builtin_ia32_pmulhuw512:
11683 case clang::X86::BI__builtin_ia32_pmulhw128:
11684 case clang::X86::BI__builtin_ia32_pmulhw256:
11685 case clang::X86::BI__builtin_ia32_pmulhw512:
11686 case clang::X86::BI__builtin_ia32_psllv2di:
11687 case clang::X86::BI__builtin_ia32_psllv4di:
11688 case clang::X86::BI__builtin_ia32_psllv4si:
11689 case clang::X86::BI__builtin_ia32_psllv8si:
11690 case clang::X86::BI__builtin_ia32_psrav4si:
11691 case clang::X86::BI__builtin_ia32_psrav8si:
11692 case clang::X86::BI__builtin_ia32_psrlv2di:
11693 case clang::X86::BI__builtin_ia32_psrlv4di:
11694 case clang::X86::BI__builtin_ia32_psrlv4si:
11695 case clang::X86::BI__builtin_ia32_psrlv8si:
11696
11697 case clang::X86::BI__builtin_ia32_psllwi128:
11698 case clang::X86::BI__builtin_ia32_pslldi128:
11699 case clang::X86::BI__builtin_ia32_psllqi128:
11700 case clang::X86::BI__builtin_ia32_psllwi256:
11701 case clang::X86::BI__builtin_ia32_pslldi256:
11702 case clang::X86::BI__builtin_ia32_psllqi256:
11703 case clang::X86::BI__builtin_ia32_psllwi512:
11704 case clang::X86::BI__builtin_ia32_pslldi512:
11705 case clang::X86::BI__builtin_ia32_psllqi512:
11706
11707 case clang::X86::BI__builtin_ia32_psrlwi128:
11708 case clang::X86::BI__builtin_ia32_psrldi128:
11709 case clang::X86::BI__builtin_ia32_psrlqi128:
11710 case clang::X86::BI__builtin_ia32_psrlwi256:
11711 case clang::X86::BI__builtin_ia32_psrldi256:
11712 case clang::X86::BI__builtin_ia32_psrlqi256:
11713 case clang::X86::BI__builtin_ia32_psrlwi512:
11714 case clang::X86::BI__builtin_ia32_psrldi512:
11715 case clang::X86::BI__builtin_ia32_psrlqi512:
11716
11717 case clang::X86::BI__builtin_ia32_psrawi128:
11718 case clang::X86::BI__builtin_ia32_psradi128:
11719 case clang::X86::BI__builtin_ia32_psraqi128:
11720 case clang::X86::BI__builtin_ia32_psrawi256:
11721 case clang::X86::BI__builtin_ia32_psradi256:
11722 case clang::X86::BI__builtin_ia32_psraqi256:
11723 case clang::X86::BI__builtin_ia32_psrawi512:
11724 case clang::X86::BI__builtin_ia32_psradi512:
11725 case clang::X86::BI__builtin_ia32_psraqi512: {
11726
11727 APValue SourceLHS, SourceRHS;
11728 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11729 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11730 return false;
11731
11732 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11733 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11734 unsigned SourceLen = SourceLHS.getVectorLength();
11735 SmallVector<APValue, 4> ResultElements;
11736 ResultElements.reserve(SourceLen);
11737
11738 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11739 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11740
11741 if (SourceRHS.isInt()) {
11742 const unsigned LaneBitWidth = LHS.getBitWidth();
11743 const unsigned ShiftAmount = SourceRHS.getInt().getZExtValue();
11744
11745 switch (E->getBuiltinCallee()) {
11746 case clang::X86::BI__builtin_ia32_psllwi128:
11747 case clang::X86::BI__builtin_ia32_psllwi256:
11748 case clang::X86::BI__builtin_ia32_psllwi512:
11749 case clang::X86::BI__builtin_ia32_pslldi128:
11750 case clang::X86::BI__builtin_ia32_pslldi256:
11751 case clang::X86::BI__builtin_ia32_pslldi512:
11752 case clang::X86::BI__builtin_ia32_psllqi128:
11753 case clang::X86::BI__builtin_ia32_psllqi256:
11754 case clang::X86::BI__builtin_ia32_psllqi512:
11755 if (ShiftAmount >= LaneBitWidth) {
11756 ResultElements.push_back(
11757 APValue(APSInt(APInt::getZero(LaneBitWidth), DestUnsigned)));
11758 } else {
11759 ResultElements.push_back(
11760 APValue(APSInt(LHS.shl(ShiftAmount), DestUnsigned)));
11761 }
11762 break;
11763 case clang::X86::BI__builtin_ia32_psrlwi128:
11764 case clang::X86::BI__builtin_ia32_psrlwi256:
11765 case clang::X86::BI__builtin_ia32_psrlwi512:
11766 case clang::X86::BI__builtin_ia32_psrldi128:
11767 case clang::X86::BI__builtin_ia32_psrldi256:
11768 case clang::X86::BI__builtin_ia32_psrldi512:
11769 case clang::X86::BI__builtin_ia32_psrlqi128:
11770 case clang::X86::BI__builtin_ia32_psrlqi256:
11771 case clang::X86::BI__builtin_ia32_psrlqi512:
11772 if (ShiftAmount >= LaneBitWidth) {
11773 ResultElements.push_back(
11774 APValue(APSInt(APInt::getZero(LaneBitWidth), DestUnsigned)));
11775 } else {
11776 ResultElements.push_back(
11777 APValue(APSInt(LHS.lshr(ShiftAmount), DestUnsigned)));
11778 }
11779 break;
11780 case clang::X86::BI__builtin_ia32_psrawi128:
11781 case clang::X86::BI__builtin_ia32_psrawi256:
11782 case clang::X86::BI__builtin_ia32_psrawi512:
11783 case clang::X86::BI__builtin_ia32_psradi128:
11784 case clang::X86::BI__builtin_ia32_psradi256:
11785 case clang::X86::BI__builtin_ia32_psradi512:
11786 case clang::X86::BI__builtin_ia32_psraqi128:
11787 case clang::X86::BI__builtin_ia32_psraqi256:
11788 case clang::X86::BI__builtin_ia32_psraqi512:
11789 ResultElements.push_back(
11790 APValue(APSInt(LHS.ashr(std::min(ShiftAmount, LaneBitWidth - 1)),
11791 DestUnsigned)));
11792 break;
11793 default:
11794 llvm_unreachable("Unexpected builtin callee");
11795 }
11796 continue;
11797 }
11798 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11799 switch (E->getBuiltinCallee()) {
11800 case Builtin::BI__builtin_elementwise_add_sat:
11801 ResultElements.push_back(APValue(
11802 APSInt(LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS),
11803 DestUnsigned)));
11804 break;
11805 case Builtin::BI__builtin_elementwise_sub_sat:
11806 ResultElements.push_back(APValue(
11807 APSInt(LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS),
11808 DestUnsigned)));
11809 break;
11810 case clang::X86::BI__builtin_ia32_pmulhuw128:
11811 case clang::X86::BI__builtin_ia32_pmulhuw256:
11812 case clang::X86::BI__builtin_ia32_pmulhuw512:
11813 ResultElements.push_back(APValue(APSInt(llvm::APIntOps::mulhu(LHS, RHS),
11814 /*isUnsigned=*/true)));
11815 break;
11816 case clang::X86::BI__builtin_ia32_pmulhw128:
11817 case clang::X86::BI__builtin_ia32_pmulhw256:
11818 case clang::X86::BI__builtin_ia32_pmulhw512:
11819 ResultElements.push_back(APValue(APSInt(llvm::APIntOps::mulhs(LHS, RHS),
11820 /*isUnsigned=*/false)));
11821 break;
11822 case clang::X86::BI__builtin_ia32_psllv2di:
11823 case clang::X86::BI__builtin_ia32_psllv4di:
11824 case clang::X86::BI__builtin_ia32_psllv4si:
11825 case clang::X86::BI__builtin_ia32_psllv8si:
11826 if (RHS.uge(RHS.getBitWidth())) {
11827 ResultElements.push_back(
11828 APValue(APSInt(APInt::getZero(RHS.getBitWidth()), DestUnsigned)));
11829 break;
11830 }
11831 ResultElements.push_back(
11832 APValue(APSInt(LHS.shl(RHS.getZExtValue()), DestUnsigned)));
11833 break;
11834 case clang::X86::BI__builtin_ia32_psrav4si:
11835 case clang::X86::BI__builtin_ia32_psrav8si:
11836 if (RHS.uge(RHS.getBitWidth())) {
11837 ResultElements.push_back(
11838 APValue(APSInt(LHS.ashr(RHS.getBitWidth() - 1), DestUnsigned)));
11839 break;
11840 }
11841 ResultElements.push_back(
11842 APValue(APSInt(LHS.ashr(RHS.getZExtValue()), DestUnsigned)));
11843 break;
11844 case clang::X86::BI__builtin_ia32_psrlv2di:
11845 case clang::X86::BI__builtin_ia32_psrlv4di:
11846 case clang::X86::BI__builtin_ia32_psrlv4si:
11847 case clang::X86::BI__builtin_ia32_psrlv8si:
11848 if (RHS.uge(RHS.getBitWidth())) {
11849 ResultElements.push_back(
11850 APValue(APSInt(APInt::getZero(RHS.getBitWidth()), DestUnsigned)));
11851 break;
11852 }
11853 ResultElements.push_back(
11854 APValue(APSInt(LHS.lshr(RHS.getZExtValue()), DestUnsigned)));
11855 break;
11856 }
11857 }
11858
11859 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11860 }
11861 case clang::X86::BI__builtin_ia32_pmuldq128:
11862 case clang::X86::BI__builtin_ia32_pmuldq256:
11863 case clang::X86::BI__builtin_ia32_pmuldq512:
11864 case clang::X86::BI__builtin_ia32_pmuludq128:
11865 case clang::X86::BI__builtin_ia32_pmuludq256:
11866 case clang::X86::BI__builtin_ia32_pmuludq512: {
11867 APValue SourceLHS, SourceRHS;
11868 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11869 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11870 return false;
11871
11872 unsigned SourceLen = SourceLHS.getVectorLength();
11873 SmallVector<APValue, 4> ResultElements;
11874 ResultElements.reserve(SourceLen / 2);
11875
11876 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
11877 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11878 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11879
11880 switch (E->getBuiltinCallee()) {
11881 case clang::X86::BI__builtin_ia32_pmuludq128:
11882 case clang::X86::BI__builtin_ia32_pmuludq256:
11883 case clang::X86::BI__builtin_ia32_pmuludq512:
11884 ResultElements.push_back(
11885 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
11886 break;
11887 case clang::X86::BI__builtin_ia32_pmuldq128:
11888 case clang::X86::BI__builtin_ia32_pmuldq256:
11889 case clang::X86::BI__builtin_ia32_pmuldq512:
11890 ResultElements.push_back(
11891 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
11892 break;
11893 }
11894 }
11895
11896 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11897 }
11898 case clang::X86::BI__builtin_ia32_vprotbi:
11899 case clang::X86::BI__builtin_ia32_vprotdi:
11900 case clang::X86::BI__builtin_ia32_vprotqi:
11901 case clang::X86::BI__builtin_ia32_vprotwi:
11902 case clang::X86::BI__builtin_ia32_prold128:
11903 case clang::X86::BI__builtin_ia32_prold256:
11904 case clang::X86::BI__builtin_ia32_prold512:
11905 case clang::X86::BI__builtin_ia32_prolq128:
11906 case clang::X86::BI__builtin_ia32_prolq256:
11907 case clang::X86::BI__builtin_ia32_prolq512: {
11908 APValue SourceLHS, SourceRHS;
11909 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11910 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11911 return false;
11912
11913 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11914 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11915 unsigned SourceLen = SourceLHS.getVectorLength();
11916 SmallVector<APValue, 4> ResultElements;
11917 ResultElements.reserve(SourceLen);
11918
11919 APSInt RHS = SourceRHS.getInt();
11920
11921 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11922 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11923 ResultElements.push_back(APValue(APSInt(LHS.rotl(RHS), DestUnsigned)));
11924 }
11925
11926 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11927 }
11928 case clang::X86::BI__builtin_ia32_prord128:
11929 case clang::X86::BI__builtin_ia32_prord256:
11930 case clang::X86::BI__builtin_ia32_prord512:
11931 case clang::X86::BI__builtin_ia32_prorq128:
11932 case clang::X86::BI__builtin_ia32_prorq256:
11933 case clang::X86::BI__builtin_ia32_prorq512: {
11934 APValue SourceLHS, SourceRHS;
11935 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11936 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11937 return false;
11938
11939 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11940 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11941 unsigned SourceLen = SourceLHS.getVectorLength();
11942 SmallVector<APValue, 4> ResultElements;
11943 ResultElements.reserve(SourceLen);
11944
11945 APSInt RHS = SourceRHS.getInt();
11946
11947 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11948 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11949 ResultElements.push_back(APValue(APSInt(LHS.rotr(RHS), DestUnsigned)));
11950 }
11951
11952 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11953 }
11954 case Builtin::BI__builtin_elementwise_max:
11955 case Builtin::BI__builtin_elementwise_min: {
11956 APValue SourceLHS, SourceRHS;
11957 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11958 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11959 return false;
11960
11961 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11962
11963 if (!DestEltTy->isIntegerType())
11964 return false;
11965
11966 unsigned SourceLen = SourceLHS.getVectorLength();
11967 SmallVector<APValue, 4> ResultElements;
11968 ResultElements.reserve(SourceLen);
11969
11970 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11971 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11972 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11973 switch (E->getBuiltinCallee()) {
11974 case Builtin::BI__builtin_elementwise_max:
11975 ResultElements.push_back(
11976 APValue(APSInt(std::max(LHS, RHS),
11977 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11978 break;
11979 case Builtin::BI__builtin_elementwise_min:
11980 ResultElements.push_back(
11981 APValue(APSInt(std::min(LHS, RHS),
11982 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11983 break;
11984 }
11985 }
11986
11987 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11988 }
11989 case X86::BI__builtin_ia32_selectb_128:
11990 case X86::BI__builtin_ia32_selectb_256:
11991 case X86::BI__builtin_ia32_selectb_512:
11992 case X86::BI__builtin_ia32_selectw_128:
11993 case X86::BI__builtin_ia32_selectw_256:
11994 case X86::BI__builtin_ia32_selectw_512:
11995 case X86::BI__builtin_ia32_selectd_128:
11996 case X86::BI__builtin_ia32_selectd_256:
11997 case X86::BI__builtin_ia32_selectd_512:
11998 case X86::BI__builtin_ia32_selectq_128:
11999 case X86::BI__builtin_ia32_selectq_256:
12000 case X86::BI__builtin_ia32_selectq_512:
12001 case X86::BI__builtin_ia32_selectph_128:
12002 case X86::BI__builtin_ia32_selectph_256:
12003 case X86::BI__builtin_ia32_selectph_512:
12004 case X86::BI__builtin_ia32_selectpbf_128:
12005 case X86::BI__builtin_ia32_selectpbf_256:
12006 case X86::BI__builtin_ia32_selectpbf_512:
12007 case X86::BI__builtin_ia32_selectps_128:
12008 case X86::BI__builtin_ia32_selectps_256:
12009 case X86::BI__builtin_ia32_selectps_512:
12010 case X86::BI__builtin_ia32_selectpd_128:
12011 case X86::BI__builtin_ia32_selectpd_256:
12012 case X86::BI__builtin_ia32_selectpd_512: {
12013 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
12014 APValue SourceMask, SourceLHS, SourceRHS;
12015 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
12016 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
12017 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
12018 return false;
12019
12020 APSInt Mask = SourceMask.getInt();
12021 unsigned SourceLen = SourceLHS.getVectorLength();
12022 SmallVector<APValue, 4> ResultElements;
12023 ResultElements.reserve(SourceLen);
12024
12025 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12026 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
12027 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
12028 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
12029 }
12030
12031 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12032 }
12033 case Builtin::BI__builtin_elementwise_ctlz:
12034 case Builtin::BI__builtin_elementwise_cttz: {
12035 APValue SourceLHS;
12036 std::optional<APValue> Fallback;
12037 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
12038 return false;
12039 if (E->getNumArgs() > 1) {
12040 APValue FallbackTmp;
12041 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
12042 return false;
12043 Fallback = FallbackTmp;
12044 }
12045
12046 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12047 unsigned SourceLen = SourceLHS.getVectorLength();
12048 SmallVector<APValue, 4> ResultElements;
12049 ResultElements.reserve(SourceLen);
12050
12051 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12052 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12053 if (!LHS) {
12054 // Without a fallback, a zero element is undefined
12055 if (!Fallback) {
12056 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
12057 << /*IsTrailing=*/(E->getBuiltinCallee() ==
12058 Builtin::BI__builtin_elementwise_cttz);
12059 return false;
12060 }
12061 ResultElements.push_back(Fallback->getVectorElt(EltNum));
12062 continue;
12063 }
12064 switch (E->getBuiltinCallee()) {
12065 case Builtin::BI__builtin_elementwise_ctlz:
12066 ResultElements.push_back(APValue(
12067 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
12068 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12069 break;
12070 case Builtin::BI__builtin_elementwise_cttz:
12071 ResultElements.push_back(APValue(
12072 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
12073 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12074 break;
12075 }
12076 }
12077
12078 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12079 }
12080
12081 case Builtin::BI__builtin_elementwise_fma: {
12082 APValue SourceX, SourceY, SourceZ;
12083 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
12084 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
12085 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
12086 return false;
12087
12088 unsigned SourceLen = SourceX.getVectorLength();
12089 SmallVector<APValue> ResultElements;
12090 ResultElements.reserve(SourceLen);
12091 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
12092 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12093 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
12094 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
12095 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
12096 APFloat Result(X);
12097 (void)Result.fusedMultiplyAdd(Y, Z, RM);
12098 ResultElements.push_back(APValue(Result));
12099 }
12100 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12101 }
12102 }
12103}
12104
12105bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
12106 APValue Source;
12107 QualType SourceVecType = E->getSrcExpr()->getType();
12108 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
12109 return false;
12110
12111 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
12112 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
12113
12114 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12115
12116 auto SourceLen = Source.getVectorLength();
12117 SmallVector<APValue, 4> ResultElements;
12118 ResultElements.reserve(SourceLen);
12119 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12120 APValue Elt;
12121 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
12122 Source.getVectorElt(EltNum), Elt))
12123 return false;
12124 ResultElements.push_back(std::move(Elt));
12125 }
12126
12127 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12128}
12129
12130static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
12131 QualType ElemType, APValue const &VecVal1,
12132 APValue const &VecVal2, unsigned EltNum,
12133 APValue &Result) {
12134 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
12135 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
12136
12137 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
12138 int64_t index = IndexVal.getExtValue();
12139 // The spec says that -1 should be treated as undef for optimizations,
12140 // but in constexpr we'd have to produce an APValue::Indeterminate,
12141 // which is prohibited from being a top-level constant value. Emit a
12142 // diagnostic instead.
12143 if (index == -1) {
12144 Info.FFDiag(
12145 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
12146 << EltNum;
12147 return false;
12148 }
12149
12150 if (index < 0 ||
12151 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
12152 llvm_unreachable("Out of bounds shuffle index");
12153
12154 if (index >= TotalElementsInInputVector1)
12155 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
12156 else
12157 Result = VecVal1.getVectorElt(index);
12158 return true;
12159}
12160
12161bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
12162 APValue VecVal1;
12163 const Expr *Vec1 = E->getExpr(0);
12164 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
12165 return false;
12166 APValue VecVal2;
12167 const Expr *Vec2 = E->getExpr(1);
12168 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
12169 return false;
12170
12171 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
12172 QualType DestElTy = DestVecTy->getElementType();
12173
12174 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
12175
12176 SmallVector<APValue, 4> ResultElements;
12177 ResultElements.reserve(TotalElementsInOutputVector);
12178 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
12179 APValue Elt;
12180 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
12181 return false;
12182 ResultElements.push_back(std::move(Elt));
12183 }
12184
12185 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12186}
12187
12188//===----------------------------------------------------------------------===//
12189// Array Evaluation
12190//===----------------------------------------------------------------------===//
12191
12192namespace {
12193 class ArrayExprEvaluator
12194 : public ExprEvaluatorBase<ArrayExprEvaluator> {
12195 const LValue &This;
12196 APValue &Result;
12197 public:
12198
12199 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
12200 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12201
12202 bool Success(const APValue &V, const Expr *E) {
12203 assert(V.isArray() && "expected array");
12204 Result = V;
12205 return true;
12206 }
12207
12208 bool ZeroInitialization(const Expr *E) {
12209 const ConstantArrayType *CAT =
12210 Info.Ctx.getAsConstantArrayType(E->getType());
12211 if (!CAT) {
12212 if (E->getType()->isIncompleteArrayType()) {
12213 // We can be asked to zero-initialize a flexible array member; this
12214 // is represented as an ImplicitValueInitExpr of incomplete array
12215 // type. In this case, the array has zero elements.
12216 Result = APValue(APValue::UninitArray(), 0, 0);
12217 return true;
12218 }
12219 // FIXME: We could handle VLAs here.
12220 return Error(E);
12221 }
12222
12223 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
12224 if (!Result.hasArrayFiller())
12225 return true;
12226
12227 // Zero-initialize all elements.
12228 LValue Subobject = This;
12229 Subobject.addArray(Info, E, CAT);
12231 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
12232 }
12233
12234 bool VisitCallExpr(const CallExpr *E) {
12235 return handleCallExpr(E, Result, &This);
12236 }
12237 bool VisitInitListExpr(const InitListExpr *E,
12238 QualType AllocType = QualType());
12239 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
12240 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
12241 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
12242 const LValue &Subobject,
12244 bool VisitStringLiteral(const StringLiteral *E,
12245 QualType AllocType = QualType()) {
12246 expandStringLiteral(Info, E, Result, AllocType);
12247 return true;
12248 }
12249 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
12250 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
12251 ArrayRef<Expr *> Args,
12252 const Expr *ArrayFiller,
12253 QualType AllocType = QualType());
12254 };
12255} // end anonymous namespace
12256
12257static bool EvaluateArray(const Expr *E, const LValue &This,
12258 APValue &Result, EvalInfo &Info) {
12259 assert(!E->isValueDependent());
12260 assert(E->isPRValue() && E->getType()->isArrayType() &&
12261 "not an array prvalue");
12262 return ArrayExprEvaluator(Info, This, Result).Visit(E);
12263}
12264
12265static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
12266 APValue &Result, const InitListExpr *ILE,
12267 QualType AllocType) {
12268 assert(!ILE->isValueDependent());
12269 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
12270 "not an array prvalue");
12271 return ArrayExprEvaluator(Info, This, Result)
12272 .VisitInitListExpr(ILE, AllocType);
12273}
12274
12275static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
12276 APValue &Result,
12277 const CXXConstructExpr *CCE,
12278 QualType AllocType) {
12279 assert(!CCE->isValueDependent());
12280 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
12281 "not an array prvalue");
12282 return ArrayExprEvaluator(Info, This, Result)
12283 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
12284}
12285
12286// Return true iff the given array filler may depend on the element index.
12287static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
12288 // For now, just allow non-class value-initialization and initialization
12289 // lists comprised of them.
12290 if (isa<ImplicitValueInitExpr>(FillerExpr))
12291 return false;
12292 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
12293 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
12294 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
12295 return true;
12296 }
12297
12298 if (ILE->hasArrayFiller() &&
12299 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
12300 return true;
12301
12302 return false;
12303 }
12304 return true;
12305}
12306
12307bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
12308 QualType AllocType) {
12309 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12310 AllocType.isNull() ? E->getType() : AllocType);
12311 if (!CAT)
12312 return Error(E);
12313
12314 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
12315 // an appropriately-typed string literal enclosed in braces.
12316 if (E->isStringLiteralInit()) {
12317 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
12318 // FIXME: Support ObjCEncodeExpr here once we support it in
12319 // ArrayExprEvaluator generally.
12320 if (!SL)
12321 return Error(E);
12322 return VisitStringLiteral(SL, AllocType);
12323 }
12324 // Any other transparent list init will need proper handling of the
12325 // AllocType; we can't just recurse to the inner initializer.
12326 assert(!E->isTransparent() &&
12327 "transparent array list initialization is not string literal init?");
12328
12329 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
12330 AllocType);
12331}
12332
12333bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
12334 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
12335 QualType AllocType) {
12336 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12337 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
12338
12339 bool Success = true;
12340
12341 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
12342 "zero-initialized array shouldn't have any initialized elts");
12343 APValue Filler;
12344 if (Result.isArray() && Result.hasArrayFiller())
12345 Filler = Result.getArrayFiller();
12346
12347 unsigned NumEltsToInit = Args.size();
12348 unsigned NumElts = CAT->getZExtSize();
12349
12350 // If the initializer might depend on the array index, run it for each
12351 // array element.
12352 if (NumEltsToInit != NumElts &&
12353 MaybeElementDependentArrayFiller(ArrayFiller)) {
12354 NumEltsToInit = NumElts;
12355 } else {
12356 for (auto *Init : Args) {
12357 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
12358 NumEltsToInit += EmbedS->getDataElementCount() - 1;
12359 }
12360 if (NumEltsToInit > NumElts)
12361 NumEltsToInit = NumElts;
12362 }
12363
12364 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
12365 << NumEltsToInit << ".\n");
12366
12367 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
12368
12369 // If the array was previously zero-initialized, preserve the
12370 // zero-initialized values.
12371 if (Filler.hasValue()) {
12372 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
12373 Result.getArrayInitializedElt(I) = Filler;
12374 if (Result.hasArrayFiller())
12375 Result.getArrayFiller() = Filler;
12376 }
12377
12378 LValue Subobject = This;
12379 Subobject.addArray(Info, ExprToVisit, CAT);
12380 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
12381 if (Init->isValueDependent())
12382 return EvaluateDependentExpr(Init, Info);
12383
12384 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
12385 Subobject, Init) ||
12386 !HandleLValueArrayAdjustment(Info, Init, Subobject,
12387 CAT->getElementType(), 1)) {
12388 if (!Info.noteFailure())
12389 return false;
12390 Success = false;
12391 }
12392 return true;
12393 };
12394 unsigned ArrayIndex = 0;
12395 QualType DestTy = CAT->getElementType();
12396 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
12397 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
12398 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
12399 if (ArrayIndex >= NumEltsToInit)
12400 break;
12401 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
12402 StringLiteral *SL = EmbedS->getDataStringLiteral();
12403 for (unsigned I = EmbedS->getStartingElementPos(),
12404 N = EmbedS->getDataElementCount();
12405 I != EmbedS->getStartingElementPos() + N; ++I) {
12406 Value = SL->getCodeUnit(I);
12407 if (DestTy->isIntegerType()) {
12408 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
12409 } else {
12410 assert(DestTy->isFloatingType() && "unexpected type");
12411 const FPOptions FPO =
12412 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12413 APFloat FValue(0.0);
12414 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
12415 DestTy, FValue))
12416 return false;
12417 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
12418 }
12419 ArrayIndex++;
12420 }
12421 } else {
12422 if (!Eval(Init, ArrayIndex))
12423 return false;
12424 ++ArrayIndex;
12425 }
12426 }
12427
12428 if (!Result.hasArrayFiller())
12429 return Success;
12430
12431 // If we get here, we have a trivial filler, which we can just evaluate
12432 // once and splat over the rest of the array elements.
12433 assert(ArrayFiller && "no array filler for incomplete init list");
12434 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
12435 ArrayFiller) &&
12436 Success;
12437}
12438
12439bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
12440 LValue CommonLV;
12441 if (E->getCommonExpr() &&
12442 !Evaluate(Info.CurrentCall->createTemporary(
12443 E->getCommonExpr(),
12444 getStorageType(Info.Ctx, E->getCommonExpr()),
12445 ScopeKind::FullExpression, CommonLV),
12446 Info, E->getCommonExpr()->getSourceExpr()))
12447 return false;
12448
12449 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
12450
12451 uint64_t Elements = CAT->getZExtSize();
12452 Result = APValue(APValue::UninitArray(), Elements, Elements);
12453
12454 LValue Subobject = This;
12455 Subobject.addArray(Info, E, CAT);
12456
12457 bool Success = true;
12458 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
12459 // C++ [class.temporary]/5
12460 // There are four contexts in which temporaries are destroyed at a different
12461 // point than the end of the full-expression. [...] The second context is
12462 // when a copy constructor is called to copy an element of an array while
12463 // the entire array is copied [...]. In either case, if the constructor has
12464 // one or more default arguments, the destruction of every temporary created
12465 // in a default argument is sequenced before the construction of the next
12466 // array element, if any.
12467 FullExpressionRAII Scope(Info);
12468
12469 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
12470 Info, Subobject, E->getSubExpr()) ||
12471 !HandleLValueArrayAdjustment(Info, E, Subobject,
12472 CAT->getElementType(), 1)) {
12473 if (!Info.noteFailure())
12474 return false;
12475 Success = false;
12476 }
12477
12478 // Make sure we run the destructors too.
12479 Scope.destroy();
12480 }
12481
12482 return Success;
12483}
12484
12485bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
12486 return VisitCXXConstructExpr(E, This, &Result, E->getType());
12487}
12488
12489bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
12490 const LValue &Subobject,
12491 APValue *Value,
12492 QualType Type) {
12493 bool HadZeroInit = Value->hasValue();
12494
12495 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
12496 unsigned FinalSize = CAT->getZExtSize();
12497
12498 // Preserve the array filler if we had prior zero-initialization.
12499 APValue Filler =
12500 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
12501 : APValue();
12502
12503 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
12504 if (FinalSize == 0)
12505 return true;
12506
12507 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
12508 Info, E->getExprLoc(), E->getConstructor(),
12509 E->requiresZeroInitialization());
12510 LValue ArrayElt = Subobject;
12511 ArrayElt.addArray(Info, E, CAT);
12512 // We do the whole initialization in two passes, first for just one element,
12513 // then for the whole array. It's possible we may find out we can't do const
12514 // init in the first pass, in which case we avoid allocating a potentially
12515 // large array. We don't do more passes because expanding array requires
12516 // copying the data, which is wasteful.
12517 for (const unsigned N : {1u, FinalSize}) {
12518 unsigned OldElts = Value->getArrayInitializedElts();
12519 if (OldElts == N)
12520 break;
12521
12522 // Expand the array to appropriate size.
12523 APValue NewValue(APValue::UninitArray(), N, FinalSize);
12524 for (unsigned I = 0; I < OldElts; ++I)
12525 NewValue.getArrayInitializedElt(I).swap(
12526 Value->getArrayInitializedElt(I));
12527 Value->swap(NewValue);
12528
12529 if (HadZeroInit)
12530 for (unsigned I = OldElts; I < N; ++I)
12531 Value->getArrayInitializedElt(I) = Filler;
12532
12533 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
12534 // If we have a trivial constructor, only evaluate it once and copy
12535 // the result into all the array elements.
12536 APValue &FirstResult = Value->getArrayInitializedElt(0);
12537 for (unsigned I = OldElts; I < FinalSize; ++I)
12538 Value->getArrayInitializedElt(I) = FirstResult;
12539 } else {
12540 for (unsigned I = OldElts; I < N; ++I) {
12541 if (!VisitCXXConstructExpr(E, ArrayElt,
12542 &Value->getArrayInitializedElt(I),
12543 CAT->getElementType()) ||
12544 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
12545 CAT->getElementType(), 1))
12546 return false;
12547 // When checking for const initilization any diagnostic is considered
12548 // an error.
12549 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
12550 !Info.keepEvaluatingAfterFailure())
12551 return false;
12552 }
12553 }
12554 }
12555
12556 return true;
12557 }
12558
12559 if (!Type->isRecordType())
12560 return Error(E);
12561
12562 return RecordExprEvaluator(Info, Subobject, *Value)
12563 .VisitCXXConstructExpr(E, Type);
12564}
12565
12566bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
12567 const CXXParenListInitExpr *E) {
12568 assert(E->getType()->isConstantArrayType() &&
12569 "Expression result is not a constant array type");
12570
12571 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
12572 E->getArrayFiller());
12573}
12574
12575//===----------------------------------------------------------------------===//
12576// Integer Evaluation
12577//
12578// As a GNU extension, we support casting pointers to sufficiently-wide integer
12579// types and back in constant folding. Integer values are thus represented
12580// either as an integer-valued APValue, or as an lvalue-valued APValue.
12581//===----------------------------------------------------------------------===//
12582
12583namespace {
12584class IntExprEvaluator
12585 : public ExprEvaluatorBase<IntExprEvaluator> {
12586 APValue &Result;
12587public:
12588 IntExprEvaluator(EvalInfo &info, APValue &result)
12589 : ExprEvaluatorBaseTy(info), Result(result) {}
12590
12591 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
12592 assert(E->getType()->isIntegralOrEnumerationType() &&
12593 "Invalid evaluation result.");
12594 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
12595 "Invalid evaluation result.");
12596 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12597 "Invalid evaluation result.");
12598 Result = APValue(SI);
12599 return true;
12600 }
12601 bool Success(const llvm::APSInt &SI, const Expr *E) {
12602 return Success(SI, E, Result);
12603 }
12604
12605 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
12606 assert(E->getType()->isIntegralOrEnumerationType() &&
12607 "Invalid evaluation result.");
12608 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12609 "Invalid evaluation result.");
12610 Result = APValue(APSInt(I));
12611 Result.getInt().setIsUnsigned(
12613 return true;
12614 }
12615 bool Success(const llvm::APInt &I, const Expr *E) {
12616 return Success(I, E, Result);
12617 }
12618
12619 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12620 assert(E->getType()->isIntegralOrEnumerationType() &&
12621 "Invalid evaluation result.");
12622 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
12623 return true;
12624 }
12625 bool Success(uint64_t Value, const Expr *E) {
12626 return Success(Value, E, Result);
12627 }
12628
12629 bool Success(CharUnits Size, const Expr *E) {
12630 return Success(Size.getQuantity(), E);
12631 }
12632
12633 bool Success(const APValue &V, const Expr *E) {
12634 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
12635 // pointer allow further evaluation of the value.
12636 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
12637 V.allowConstexprUnknown()) {
12638 Result = V;
12639 return true;
12640 }
12641 return Success(V.getInt(), E);
12642 }
12643
12644 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
12645
12646 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
12647 const CallExpr *);
12648
12649 //===--------------------------------------------------------------------===//
12650 // Visitor Methods
12651 //===--------------------------------------------------------------------===//
12652
12653 bool VisitIntegerLiteral(const IntegerLiteral *E) {
12654 return Success(E->getValue(), E);
12655 }
12656 bool VisitCharacterLiteral(const CharacterLiteral *E) {
12657 return Success(E->getValue(), E);
12658 }
12659
12660 bool CheckReferencedDecl(const Expr *E, const Decl *D);
12661 bool VisitDeclRefExpr(const DeclRefExpr *E) {
12662 if (CheckReferencedDecl(E, E->getDecl()))
12663 return true;
12664
12665 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
12666 }
12667 bool VisitMemberExpr(const MemberExpr *E) {
12668 if (CheckReferencedDecl(E, E->getMemberDecl())) {
12669 VisitIgnoredBaseExpression(E->getBase());
12670 return true;
12671 }
12672
12673 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
12674 }
12675
12676 bool VisitCallExpr(const CallExpr *E);
12677 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
12678 bool VisitBinaryOperator(const BinaryOperator *E);
12679 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
12680 bool VisitUnaryOperator(const UnaryOperator *E);
12681
12682 bool VisitCastExpr(const CastExpr* E);
12683 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
12684
12685 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
12686 return Success(E->getValue(), E);
12687 }
12688
12689 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
12690 return Success(E->getValue(), E);
12691 }
12692
12693 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
12694 if (Info.ArrayInitIndex == uint64_t(-1)) {
12695 // We were asked to evaluate this subexpression independent of the
12696 // enclosing ArrayInitLoopExpr. We can't do that.
12697 Info.FFDiag(E);
12698 return false;
12699 }
12700 return Success(Info.ArrayInitIndex, E);
12701 }
12702
12703 // Note, GNU defines __null as an integer, not a pointer.
12704 bool VisitGNUNullExpr(const GNUNullExpr *E) {
12705 return ZeroInitialization(E);
12706 }
12707
12708 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
12709 if (E->isStoredAsBoolean())
12710 return Success(E->getBoolValue(), E);
12711 if (E->getAPValue().isAbsent())
12712 return false;
12713 assert(E->getAPValue().isInt() && "APValue type not supported");
12714 return Success(E->getAPValue().getInt(), E);
12715 }
12716
12717 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
12718 return Success(E->getValue(), E);
12719 }
12720
12721 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
12722 return Success(E->getValue(), E);
12723 }
12724
12725 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
12726 // This should not be evaluated during constant expr evaluation, as it
12727 // should always be in an unevaluated context (the args list of a 'gang' or
12728 // 'tile' clause).
12729 return Error(E);
12730 }
12731
12732 bool VisitUnaryReal(const UnaryOperator *E);
12733 bool VisitUnaryImag(const UnaryOperator *E);
12734
12735 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
12736 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
12737 bool VisitSourceLocExpr(const SourceLocExpr *E);
12738 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
12739 bool VisitRequiresExpr(const RequiresExpr *E);
12740 // FIXME: Missing: array subscript of vector, member of vector
12741};
12742
12743class FixedPointExprEvaluator
12744 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
12745 APValue &Result;
12746
12747 public:
12748 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
12749 : ExprEvaluatorBaseTy(info), Result(result) {}
12750
12751 bool Success(const llvm::APInt &I, const Expr *E) {
12752 return Success(
12753 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12754 }
12755
12756 bool Success(uint64_t Value, const Expr *E) {
12757 return Success(
12758 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12759 }
12760
12761 bool Success(const APValue &V, const Expr *E) {
12762 return Success(V.getFixedPoint(), E);
12763 }
12764
12765 bool Success(const APFixedPoint &V, const Expr *E) {
12766 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12767 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12768 "Invalid evaluation result.");
12769 Result = APValue(V);
12770 return true;
12771 }
12772
12773 bool ZeroInitialization(const Expr *E) {
12774 return Success(0, E);
12775 }
12776
12777 //===--------------------------------------------------------------------===//
12778 // Visitor Methods
12779 //===--------------------------------------------------------------------===//
12780
12781 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12782 return Success(E->getValue(), E);
12783 }
12784
12785 bool VisitCastExpr(const CastExpr *E);
12786 bool VisitUnaryOperator(const UnaryOperator *E);
12787 bool VisitBinaryOperator(const BinaryOperator *E);
12788};
12789} // end anonymous namespace
12790
12791/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12792/// produce either the integer value or a pointer.
12793///
12794/// GCC has a heinous extension which folds casts between pointer types and
12795/// pointer-sized integral types. We support this by allowing the evaluation of
12796/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12797/// Some simple arithmetic on such values is supported (they are treated much
12798/// like char*).
12799static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12800 EvalInfo &Info) {
12801 assert(!E->isValueDependent());
12802 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12803 return IntExprEvaluator(Info, Result).Visit(E);
12804}
12805
12806static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12807 assert(!E->isValueDependent());
12808 APValue Val;
12809 if (!EvaluateIntegerOrLValue(E, Val, Info))
12810 return false;
12811 if (!Val.isInt()) {
12812 // FIXME: It would be better to produce the diagnostic for casting
12813 // a pointer to an integer.
12814 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12815 return false;
12816 }
12817 Result = Val.getInt();
12818 return true;
12819}
12820
12821bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12822 APValue Evaluated = E->EvaluateInContext(
12823 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12824 return Success(Evaluated, E);
12825}
12826
12827static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12828 EvalInfo &Info) {
12829 assert(!E->isValueDependent());
12830 if (E->getType()->isFixedPointType()) {
12831 APValue Val;
12832 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12833 return false;
12834 if (!Val.isFixedPoint())
12835 return false;
12836
12837 Result = Val.getFixedPoint();
12838 return true;
12839 }
12840 return false;
12841}
12842
12843static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12844 EvalInfo &Info) {
12845 assert(!E->isValueDependent());
12846 if (E->getType()->isIntegerType()) {
12847 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12848 APSInt Val;
12849 if (!EvaluateInteger(E, Val, Info))
12850 return false;
12851 Result = APFixedPoint(Val, FXSema);
12852 return true;
12853 } else if (E->getType()->isFixedPointType()) {
12854 return EvaluateFixedPoint(E, Result, Info);
12855 }
12856 return false;
12857}
12858
12859/// Check whether the given declaration can be directly converted to an integral
12860/// rvalue. If not, no diagnostic is produced; there are other things we can
12861/// try.
12862bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12863 // Enums are integer constant exprs.
12864 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12865 // Check for signedness/width mismatches between E type and ECD value.
12866 bool SameSign = (ECD->getInitVal().isSigned()
12868 bool SameWidth = (ECD->getInitVal().getBitWidth()
12869 == Info.Ctx.getIntWidth(E->getType()));
12870 if (SameSign && SameWidth)
12871 return Success(ECD->getInitVal(), E);
12872 else {
12873 // Get rid of mismatch (otherwise Success assertions will fail)
12874 // by computing a new value matching the type of E.
12875 llvm::APSInt Val = ECD->getInitVal();
12876 if (!SameSign)
12877 Val.setIsSigned(!ECD->getInitVal().isSigned());
12878 if (!SameWidth)
12879 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12880 return Success(Val, E);
12881 }
12882 }
12883 return false;
12884}
12885
12886/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12887/// as GCC.
12889 const LangOptions &LangOpts) {
12890 assert(!T->isDependentType() && "unexpected dependent type");
12891
12892 QualType CanTy = T.getCanonicalType();
12893
12894 switch (CanTy->getTypeClass()) {
12895#define TYPE(ID, BASE)
12896#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12897#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12898#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12899#include "clang/AST/TypeNodes.inc"
12900 case Type::Auto:
12901 case Type::DeducedTemplateSpecialization:
12902 llvm_unreachable("unexpected non-canonical or dependent type");
12903
12904 case Type::Builtin:
12905 switch (cast<BuiltinType>(CanTy)->getKind()) {
12906#define BUILTIN_TYPE(ID, SINGLETON_ID)
12907#define SIGNED_TYPE(ID, SINGLETON_ID) \
12908 case BuiltinType::ID: return GCCTypeClass::Integer;
12909#define FLOATING_TYPE(ID, SINGLETON_ID) \
12910 case BuiltinType::ID: return GCCTypeClass::RealFloat;
12911#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12912 case BuiltinType::ID: break;
12913#include "clang/AST/BuiltinTypes.def"
12914 case BuiltinType::Void:
12915 return GCCTypeClass::Void;
12916
12917 case BuiltinType::Bool:
12918 return GCCTypeClass::Bool;
12919
12920 case BuiltinType::Char_U:
12921 case BuiltinType::UChar:
12922 case BuiltinType::WChar_U:
12923 case BuiltinType::Char8:
12924 case BuiltinType::Char16:
12925 case BuiltinType::Char32:
12926 case BuiltinType::UShort:
12927 case BuiltinType::UInt:
12928 case BuiltinType::ULong:
12929 case BuiltinType::ULongLong:
12930 case BuiltinType::UInt128:
12931 return GCCTypeClass::Integer;
12932
12933 case BuiltinType::UShortAccum:
12934 case BuiltinType::UAccum:
12935 case BuiltinType::ULongAccum:
12936 case BuiltinType::UShortFract:
12937 case BuiltinType::UFract:
12938 case BuiltinType::ULongFract:
12939 case BuiltinType::SatUShortAccum:
12940 case BuiltinType::SatUAccum:
12941 case BuiltinType::SatULongAccum:
12942 case BuiltinType::SatUShortFract:
12943 case BuiltinType::SatUFract:
12944 case BuiltinType::SatULongFract:
12945 return GCCTypeClass::None;
12946
12947 case BuiltinType::NullPtr:
12948
12949 case BuiltinType::ObjCId:
12950 case BuiltinType::ObjCClass:
12951 case BuiltinType::ObjCSel:
12952#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
12953 case BuiltinType::Id:
12954#include "clang/Basic/OpenCLImageTypes.def"
12955#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
12956 case BuiltinType::Id:
12957#include "clang/Basic/OpenCLExtensionTypes.def"
12958 case BuiltinType::OCLSampler:
12959 case BuiltinType::OCLEvent:
12960 case BuiltinType::OCLClkEvent:
12961 case BuiltinType::OCLQueue:
12962 case BuiltinType::OCLReserveID:
12963#define SVE_TYPE(Name, Id, SingletonId) \
12964 case BuiltinType::Id:
12965#include "clang/Basic/AArch64ACLETypes.def"
12966#define PPC_VECTOR_TYPE(Name, Id, Size) \
12967 case BuiltinType::Id:
12968#include "clang/Basic/PPCTypes.def"
12969#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12970#include "clang/Basic/RISCVVTypes.def"
12971#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12972#include "clang/Basic/WebAssemblyReferenceTypes.def"
12973#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
12974#include "clang/Basic/AMDGPUTypes.def"
12975#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12976#include "clang/Basic/HLSLIntangibleTypes.def"
12977 return GCCTypeClass::None;
12978
12979 case BuiltinType::Dependent:
12980 llvm_unreachable("unexpected dependent type");
12981 };
12982 llvm_unreachable("unexpected placeholder type");
12983
12984 case Type::Enum:
12985 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
12986
12987 case Type::Pointer:
12988 case Type::ConstantArray:
12989 case Type::VariableArray:
12990 case Type::IncompleteArray:
12991 case Type::FunctionNoProto:
12992 case Type::FunctionProto:
12993 case Type::ArrayParameter:
12994 return GCCTypeClass::Pointer;
12995
12996 case Type::MemberPointer:
12997 return CanTy->isMemberDataPointerType()
12998 ? GCCTypeClass::PointerToDataMember
12999 : GCCTypeClass::PointerToMemberFunction;
13000
13001 case Type::Complex:
13002 return GCCTypeClass::Complex;
13003
13004 case Type::Record:
13005 return CanTy->isUnionType() ? GCCTypeClass::Union
13006 : GCCTypeClass::ClassOrStruct;
13007
13008 case Type::Atomic:
13009 // GCC classifies _Atomic T the same as T.
13011 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
13012
13013 case Type::Vector:
13014 case Type::ExtVector:
13015 return GCCTypeClass::Vector;
13016
13017 case Type::BlockPointer:
13018 case Type::ConstantMatrix:
13019 case Type::ObjCObject:
13020 case Type::ObjCInterface:
13021 case Type::ObjCObjectPointer:
13022 case Type::Pipe:
13023 case Type::HLSLAttributedResource:
13024 case Type::HLSLInlineSpirv:
13025 // Classify all other types that don't fit into the regular
13026 // classification the same way.
13027 return GCCTypeClass::None;
13028
13029 case Type::BitInt:
13030 return GCCTypeClass::BitInt;
13031
13032 case Type::LValueReference:
13033 case Type::RValueReference:
13034 llvm_unreachable("invalid type for expression");
13035 }
13036
13037 llvm_unreachable("unexpected type class");
13038}
13039
13040/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
13041/// as GCC.
13042static GCCTypeClass
13044 // If no argument was supplied, default to None. This isn't
13045 // ideal, however it is what gcc does.
13046 if (E->getNumArgs() == 0)
13047 return GCCTypeClass::None;
13048
13049 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
13050 // being an ICE, but still folds it to a constant using the type of the first
13051 // argument.
13052 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
13053}
13054
13055/// EvaluateBuiltinConstantPForLValue - Determine the result of
13056/// __builtin_constant_p when applied to the given pointer.
13057///
13058/// A pointer is only "constant" if it is null (or a pointer cast to integer)
13059/// or it points to the first character of a string literal.
13062 if (Base.isNull()) {
13063 // A null base is acceptable.
13064 return true;
13065 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
13066 if (!isa<StringLiteral>(E))
13067 return false;
13068 return LV.getLValueOffset().isZero();
13069 } else if (Base.is<TypeInfoLValue>()) {
13070 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
13071 // evaluate to true.
13072 return true;
13073 } else {
13074 // Any other base is not constant enough for GCC.
13075 return false;
13076 }
13077}
13078
13079/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
13080/// GCC as we can manage.
13081static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
13082 // This evaluation is not permitted to have side-effects, so evaluate it in
13083 // a speculative evaluation context.
13084 SpeculativeEvaluationRAII SpeculativeEval(Info);
13085
13086 // Constant-folding is always enabled for the operand of __builtin_constant_p
13087 // (even when the enclosing evaluation context otherwise requires a strict
13088 // language-specific constant expression).
13089 FoldConstant Fold(Info, true);
13090
13091 QualType ArgType = Arg->getType();
13092
13093 // __builtin_constant_p always has one operand. The rules which gcc follows
13094 // are not precisely documented, but are as follows:
13095 //
13096 // - If the operand is of integral, floating, complex or enumeration type,
13097 // and can be folded to a known value of that type, it returns 1.
13098 // - If the operand can be folded to a pointer to the first character
13099 // of a string literal (or such a pointer cast to an integral type)
13100 // or to a null pointer or an integer cast to a pointer, it returns 1.
13101 //
13102 // Otherwise, it returns 0.
13103 //
13104 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
13105 // its support for this did not work prior to GCC 9 and is not yet well
13106 // understood.
13107 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
13108 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
13109 ArgType->isNullPtrType()) {
13110 APValue V;
13111 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
13112 Fold.keepDiagnostics();
13113 return false;
13114 }
13115
13116 // For a pointer (possibly cast to integer), there are special rules.
13117 if (V.getKind() == APValue::LValue)
13119
13120 // Otherwise, any constant value is good enough.
13121 return V.hasValue();
13122 }
13123
13124 // Anything else isn't considered to be sufficiently constant.
13125 return false;
13126}
13127
13128/// Retrieves the "underlying object type" of the given expression,
13129/// as used by __builtin_object_size.
13131 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
13132 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
13133 return VD->getType();
13134 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
13135 if (isa<CompoundLiteralExpr>(E))
13136 return E->getType();
13137 } else if (B.is<TypeInfoLValue>()) {
13138 return B.getTypeInfoType();
13139 } else if (B.is<DynamicAllocLValue>()) {
13140 return B.getDynamicAllocType();
13141 }
13142
13143 return QualType();
13144}
13145
13146/// A more selective version of E->IgnoreParenCasts for
13147/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
13148/// to change the type of E.
13149/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
13150///
13151/// Always returns an RValue with a pointer representation.
13153 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
13154
13155 const Expr *NoParens = E->IgnoreParens();
13156 const auto *Cast = dyn_cast<CastExpr>(NoParens);
13157 if (Cast == nullptr)
13158 return NoParens;
13159
13160 // We only conservatively allow a few kinds of casts, because this code is
13161 // inherently a simple solution that seeks to support the common case.
13162 auto CastKind = Cast->getCastKind();
13163 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
13164 CastKind != CK_AddressSpaceConversion)
13165 return NoParens;
13166
13167 const auto *SubExpr = Cast->getSubExpr();
13168 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
13169 return NoParens;
13170 return ignorePointerCastsAndParens(SubExpr);
13171}
13172
13173/// Checks to see if the given LValue's Designator is at the end of the LValue's
13174/// record layout. e.g.
13175/// struct { struct { int a, b; } fst, snd; } obj;
13176/// obj.fst // no
13177/// obj.snd // yes
13178/// obj.fst.a // no
13179/// obj.fst.b // no
13180/// obj.snd.a // no
13181/// obj.snd.b // yes
13182///
13183/// Please note: this function is specialized for how __builtin_object_size
13184/// views "objects".
13185///
13186/// If this encounters an invalid RecordDecl or otherwise cannot determine the
13187/// correct result, it will always return true.
13188static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
13189 assert(!LVal.Designator.Invalid);
13190
13191 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
13192 const RecordDecl *Parent = FD->getParent();
13193 if (Parent->isInvalidDecl() || Parent->isUnion())
13194 return true;
13195 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
13196 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
13197 };
13198
13199 auto &Base = LVal.getLValueBase();
13200 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
13201 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
13202 if (!IsLastOrInvalidFieldDecl(FD))
13203 return false;
13204 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
13205 for (auto *FD : IFD->chain()) {
13206 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
13207 return false;
13208 }
13209 }
13210 }
13211
13212 unsigned I = 0;
13213 QualType BaseType = getType(Base);
13214 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
13215 // If we don't know the array bound, conservatively assume we're looking at
13216 // the final array element.
13217 ++I;
13218 if (BaseType->isIncompleteArrayType())
13219 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
13220 else
13221 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
13222 }
13223
13224 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
13225 const auto &Entry = LVal.Designator.Entries[I];
13226 if (BaseType->isArrayType()) {
13227 // Because __builtin_object_size treats arrays as objects, we can ignore
13228 // the index iff this is the last array in the Designator.
13229 if (I + 1 == E)
13230 return true;
13231 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
13232 uint64_t Index = Entry.getAsArrayIndex();
13233 if (Index + 1 != CAT->getZExtSize())
13234 return false;
13235 BaseType = CAT->getElementType();
13236 } else if (BaseType->isAnyComplexType()) {
13237 const auto *CT = BaseType->castAs<ComplexType>();
13238 uint64_t Index = Entry.getAsArrayIndex();
13239 if (Index != 1)
13240 return false;
13241 BaseType = CT->getElementType();
13242 } else if (auto *FD = getAsField(Entry)) {
13243 if (!IsLastOrInvalidFieldDecl(FD))
13244 return false;
13245 BaseType = FD->getType();
13246 } else {
13247 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
13248 return false;
13249 }
13250 }
13251 return true;
13252}
13253
13254/// Tests to see if the LValue has a user-specified designator (that isn't
13255/// necessarily valid). Note that this always returns 'true' if the LValue has
13256/// an unsized array as its first designator entry, because there's currently no
13257/// way to tell if the user typed *foo or foo[0].
13258static bool refersToCompleteObject(const LValue &LVal) {
13259 if (LVal.Designator.Invalid)
13260 return false;
13261
13262 if (!LVal.Designator.Entries.empty())
13263 return LVal.Designator.isMostDerivedAnUnsizedArray();
13264
13265 if (!LVal.InvalidBase)
13266 return true;
13267
13268 // If `E` is a MemberExpr, then the first part of the designator is hiding in
13269 // the LValueBase.
13270 const auto *E = LVal.Base.dyn_cast<const Expr *>();
13271 return !E || !isa<MemberExpr>(E);
13272}
13273
13274/// Attempts to detect a user writing into a piece of memory that's impossible
13275/// to figure out the size of by just using types.
13276static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
13277 const SubobjectDesignator &Designator = LVal.Designator;
13278 // Notes:
13279 // - Users can only write off of the end when we have an invalid base. Invalid
13280 // bases imply we don't know where the memory came from.
13281 // - We used to be a bit more aggressive here; we'd only be conservative if
13282 // the array at the end was flexible, or if it had 0 or 1 elements. This
13283 // broke some common standard library extensions (PR30346), but was
13284 // otherwise seemingly fine. It may be useful to reintroduce this behavior
13285 // with some sort of list. OTOH, it seems that GCC is always
13286 // conservative with the last element in structs (if it's an array), so our
13287 // current behavior is more compatible than an explicit list approach would
13288 // be.
13289 auto isFlexibleArrayMember = [&] {
13291 FAMKind StrictFlexArraysLevel =
13292 Ctx.getLangOpts().getStrictFlexArraysLevel();
13293
13294 if (Designator.isMostDerivedAnUnsizedArray())
13295 return true;
13296
13297 if (StrictFlexArraysLevel == FAMKind::Default)
13298 return true;
13299
13300 if (Designator.getMostDerivedArraySize() == 0 &&
13301 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
13302 return true;
13303
13304 if (Designator.getMostDerivedArraySize() == 1 &&
13305 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
13306 return true;
13307
13308 return false;
13309 };
13310
13311 return LVal.InvalidBase &&
13312 Designator.Entries.size() == Designator.MostDerivedPathLength &&
13313 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
13314 isDesignatorAtObjectEnd(Ctx, LVal);
13315}
13316
13317/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
13318/// Fails if the conversion would cause loss of precision.
13319static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
13320 CharUnits &Result) {
13321 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
13322 if (Int.ugt(CharUnitsMax))
13323 return false;
13324 Result = CharUnits::fromQuantity(Int.getZExtValue());
13325 return true;
13326}
13327
13328/// If we're evaluating the object size of an instance of a struct that
13329/// contains a flexible array member, add the size of the initializer.
13330static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
13331 const LValue &LV, CharUnits &Size) {
13332 if (!T.isNull() && T->isStructureType() &&
13334 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
13335 if (const auto *VD = dyn_cast<VarDecl>(V))
13336 if (VD->hasInit())
13337 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
13338}
13339
13340/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
13341/// determine how many bytes exist from the beginning of the object to either
13342/// the end of the current subobject, or the end of the object itself, depending
13343/// on what the LValue looks like + the value of Type.
13344///
13345/// If this returns false, the value of Result is undefined.
13346static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
13347 unsigned Type, const LValue &LVal,
13348 CharUnits &EndOffset) {
13349 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
13350
13351 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
13352 if (Ty.isNull())
13353 return false;
13354
13355 Ty = Ty.getNonReferenceType();
13356
13357 if (Ty->isIncompleteType() || Ty->isFunctionType())
13358 return false;
13359
13360 return HandleSizeof(Info, ExprLoc, Ty, Result);
13361 };
13362
13363 // We want to evaluate the size of the entire object. This is a valid fallback
13364 // for when Type=1 and the designator is invalid, because we're asked for an
13365 // upper-bound.
13366 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
13367 // Type=3 wants a lower bound, so we can't fall back to this.
13368 if (Type == 3 && !DetermineForCompleteObject)
13369 return false;
13370
13371 llvm::APInt APEndOffset;
13372 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13373 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13374 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13375
13376 if (LVal.InvalidBase)
13377 return false;
13378
13379 QualType BaseTy = getObjectType(LVal.getLValueBase());
13380 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
13381 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
13382 return Ret;
13383 }
13384
13385 // We want to evaluate the size of a subobject.
13386 const SubobjectDesignator &Designator = LVal.Designator;
13387
13388 // The following is a moderately common idiom in C:
13389 //
13390 // struct Foo { int a; char c[1]; };
13391 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
13392 // strcpy(&F->c[0], Bar);
13393 //
13394 // In order to not break too much legacy code, we need to support it.
13395 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
13396 // If we can resolve this to an alloc_size call, we can hand that back,
13397 // because we know for certain how many bytes there are to write to.
13398 llvm::APInt APEndOffset;
13399 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13400 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13401 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13402
13403 // If we cannot determine the size of the initial allocation, then we can't
13404 // given an accurate upper-bound. However, we are still able to give
13405 // conservative lower-bounds for Type=3.
13406 if (Type == 1)
13407 return false;
13408 }
13409
13410 CharUnits BytesPerElem;
13411 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
13412 return false;
13413
13414 // According to the GCC documentation, we want the size of the subobject
13415 // denoted by the pointer. But that's not quite right -- what we actually
13416 // want is the size of the immediately-enclosing array, if there is one.
13417 int64_t ElemsRemaining;
13418 if (Designator.MostDerivedIsArrayElement &&
13419 Designator.Entries.size() == Designator.MostDerivedPathLength) {
13420 uint64_t ArraySize = Designator.getMostDerivedArraySize();
13421 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
13422 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
13423 } else {
13424 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
13425 }
13426
13427 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
13428 return true;
13429}
13430
13431/// Tries to evaluate the __builtin_object_size for @p E. If successful,
13432/// returns true and stores the result in @p Size.
13433///
13434/// If @p WasError is non-null, this will report whether the failure to evaluate
13435/// is to be treated as an Error in IntExprEvaluator.
13436static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
13437 EvalInfo &Info, uint64_t &Size) {
13438 // Determine the denoted object.
13439 LValue LVal;
13440 {
13441 // The operand of __builtin_object_size is never evaluated for side-effects.
13442 // If there are any, but we can determine the pointed-to object anyway, then
13443 // ignore the side-effects.
13444 SpeculativeEvaluationRAII SpeculativeEval(Info);
13445 IgnoreSideEffectsRAII Fold(Info);
13446
13447 if (E->isGLValue()) {
13448 // It's possible for us to be given GLValues if we're called via
13449 // Expr::tryEvaluateObjectSize.
13450 APValue RVal;
13451 if (!EvaluateAsRValue(Info, E, RVal))
13452 return false;
13453 LVal.setFrom(Info.Ctx, RVal);
13454 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
13455 /*InvalidBaseOK=*/true))
13456 return false;
13457 }
13458
13459 // If we point to before the start of the object, there are no accessible
13460 // bytes.
13461 if (LVal.getLValueOffset().isNegative()) {
13462 Size = 0;
13463 return true;
13464 }
13465
13466 CharUnits EndOffset;
13467 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
13468 return false;
13469
13470 // If we've fallen outside of the end offset, just pretend there's nothing to
13471 // write to/read from.
13472 if (EndOffset <= LVal.getLValueOffset())
13473 Size = 0;
13474 else
13475 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
13476 return true;
13477}
13478
13479bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
13480 if (!IsConstantEvaluatedBuiltinCall(E))
13481 return ExprEvaluatorBaseTy::VisitCallExpr(E);
13482 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
13483}
13484
13485static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
13486 APValue &Val, APSInt &Alignment) {
13487 QualType SrcTy = E->getArg(0)->getType();
13488 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
13489 return false;
13490 // Even though we are evaluating integer expressions we could get a pointer
13491 // argument for the __builtin_is_aligned() case.
13492 if (SrcTy->isPointerType()) {
13493 LValue Ptr;
13494 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
13495 return false;
13496 Ptr.moveInto(Val);
13497 } else if (!SrcTy->isIntegralOrEnumerationType()) {
13498 Info.FFDiag(E->getArg(0));
13499 return false;
13500 } else {
13501 APSInt SrcInt;
13502 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
13503 return false;
13504 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
13505 "Bit widths must be the same");
13506 Val = APValue(SrcInt);
13507 }
13508 assert(Val.hasValue());
13509 return true;
13510}
13511
13512bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
13513 unsigned BuiltinOp) {
13514 switch (BuiltinOp) {
13515 default:
13516 return false;
13517
13518 case Builtin::BI__builtin_dynamic_object_size:
13519 case Builtin::BI__builtin_object_size: {
13520 // The type was checked when we built the expression.
13521 unsigned Type =
13522 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13523 assert(Type <= 3 && "unexpected type");
13524
13525 uint64_t Size;
13526 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
13527 return Success(Size, E);
13528
13529 if (E->getArg(0)->HasSideEffects(Info.Ctx))
13530 return Success((Type & 2) ? 0 : -1, E);
13531
13532 // Expression had no side effects, but we couldn't statically determine the
13533 // size of the referenced object.
13534 switch (Info.EvalMode) {
13535 case EvalInfo::EM_ConstantExpression:
13536 case EvalInfo::EM_ConstantFold:
13537 case EvalInfo::EM_IgnoreSideEffects:
13538 // Leave it to IR generation.
13539 return Error(E);
13540 case EvalInfo::EM_ConstantExpressionUnevaluated:
13541 // Reduce it to a constant now.
13542 return Success((Type & 2) ? 0 : -1, E);
13543 }
13544
13545 llvm_unreachable("unexpected EvalMode");
13546 }
13547
13548 case Builtin::BI__builtin_os_log_format_buffer_size: {
13551 return Success(Layout.size().getQuantity(), E);
13552 }
13553
13554 case Builtin::BI__builtin_is_aligned: {
13555 APValue Src;
13556 APSInt Alignment;
13557 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13558 return false;
13559 if (Src.isLValue()) {
13560 // If we evaluated a pointer, check the minimum known alignment.
13561 LValue Ptr;
13562 Ptr.setFrom(Info.Ctx, Src);
13563 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
13564 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
13565 // We can return true if the known alignment at the computed offset is
13566 // greater than the requested alignment.
13567 assert(PtrAlign.isPowerOfTwo());
13568 assert(Alignment.isPowerOf2());
13569 if (PtrAlign.getQuantity() >= Alignment)
13570 return Success(1, E);
13571 // If the alignment is not known to be sufficient, some cases could still
13572 // be aligned at run time. However, if the requested alignment is less or
13573 // equal to the base alignment and the offset is not aligned, we know that
13574 // the run-time value can never be aligned.
13575 if (BaseAlignment.getQuantity() >= Alignment &&
13576 PtrAlign.getQuantity() < Alignment)
13577 return Success(0, E);
13578 // Otherwise we can't infer whether the value is sufficiently aligned.
13579 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
13580 // in cases where we can't fully evaluate the pointer.
13581 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
13582 << Alignment;
13583 return false;
13584 }
13585 assert(Src.isInt());
13586 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
13587 }
13588 case Builtin::BI__builtin_align_up: {
13589 APValue Src;
13590 APSInt Alignment;
13591 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13592 return false;
13593 if (!Src.isInt())
13594 return Error(E);
13595 APSInt AlignedVal =
13596 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
13597 Src.getInt().isUnsigned());
13598 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13599 return Success(AlignedVal, E);
13600 }
13601 case Builtin::BI__builtin_align_down: {
13602 APValue Src;
13603 APSInt Alignment;
13604 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13605 return false;
13606 if (!Src.isInt())
13607 return Error(E);
13608 APSInt AlignedVal =
13609 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
13610 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13611 return Success(AlignedVal, E);
13612 }
13613
13614 case Builtin::BI__builtin_bitreverse8:
13615 case Builtin::BI__builtin_bitreverse16:
13616 case Builtin::BI__builtin_bitreverse32:
13617 case Builtin::BI__builtin_bitreverse64:
13618 case Builtin::BI__builtin_elementwise_bitreverse: {
13619 APSInt Val;
13620 if (!EvaluateInteger(E->getArg(0), Val, Info))
13621 return false;
13622
13623 return Success(Val.reverseBits(), E);
13624 }
13625
13626 case Builtin::BI__builtin_bswap16:
13627 case Builtin::BI__builtin_bswap32:
13628 case Builtin::BI__builtin_bswap64: {
13629 APSInt Val;
13630 if (!EvaluateInteger(E->getArg(0), Val, Info))
13631 return false;
13632
13633 return Success(Val.byteSwap(), E);
13634 }
13635
13636 case Builtin::BI__builtin_classify_type:
13637 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
13638
13639 case Builtin::BI__builtin_clrsb:
13640 case Builtin::BI__builtin_clrsbl:
13641 case Builtin::BI__builtin_clrsbll: {
13642 APSInt Val;
13643 if (!EvaluateInteger(E->getArg(0), Val, Info))
13644 return false;
13645
13646 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
13647 }
13648
13649 case Builtin::BI__builtin_clz:
13650 case Builtin::BI__builtin_clzl:
13651 case Builtin::BI__builtin_clzll:
13652 case Builtin::BI__builtin_clzs:
13653 case Builtin::BI__builtin_clzg:
13654 case Builtin::BI__builtin_elementwise_ctlz:
13655 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
13656 case Builtin::BI__lzcnt:
13657 case Builtin::BI__lzcnt64: {
13658 APSInt Val;
13659 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13660 APValue Vec;
13661 if (!EvaluateVector(E->getArg(0), Vec, Info))
13662 return false;
13663 Val = ConvertBoolVectorToInt(Vec);
13664 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13665 return false;
13666 }
13667
13668 std::optional<APSInt> Fallback;
13669 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
13670 BuiltinOp == Builtin::BI__builtin_elementwise_ctlz) &&
13671 E->getNumArgs() > 1) {
13672 APSInt FallbackTemp;
13673 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13674 return false;
13675 Fallback = FallbackTemp;
13676 }
13677
13678 if (!Val) {
13679 if (Fallback)
13680 return Success(*Fallback, E);
13681
13682 // When the argument is 0, the result of GCC builtins is undefined,
13683 // whereas for Microsoft intrinsics, the result is the bit-width of the
13684 // argument.
13685 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
13686 BuiltinOp != Builtin::BI__lzcnt &&
13687 BuiltinOp != Builtin::BI__lzcnt64;
13688
13689 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctlz) {
13690 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13691 << /*IsTrailing=*/false;
13692 }
13693
13694 if (ZeroIsUndefined)
13695 return Error(E);
13696 }
13697
13698 return Success(Val.countl_zero(), E);
13699 }
13700
13701 case Builtin::BI__builtin_constant_p: {
13702 const Expr *Arg = E->getArg(0);
13703 if (EvaluateBuiltinConstantP(Info, Arg))
13704 return Success(true, E);
13705 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
13706 // Outside a constant context, eagerly evaluate to false in the presence
13707 // of side-effects in order to avoid -Wunsequenced false-positives in
13708 // a branch on __builtin_constant_p(expr).
13709 return Success(false, E);
13710 }
13711 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13712 return false;
13713 }
13714
13715 case Builtin::BI__noop:
13716 // __noop always evaluates successfully and returns 0.
13717 return Success(0, E);
13718
13719 case Builtin::BI__builtin_is_constant_evaluated: {
13720 const auto *Callee = Info.CurrentCall->getCallee();
13721 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
13722 (Info.CallStackDepth == 1 ||
13723 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
13724 Callee->getIdentifier() &&
13725 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
13726 // FIXME: Find a better way to avoid duplicated diagnostics.
13727 if (Info.EvalStatus.Diag)
13728 Info.report((Info.CallStackDepth == 1)
13729 ? E->getExprLoc()
13730 : Info.CurrentCall->getCallRange().getBegin(),
13731 diag::warn_is_constant_evaluated_always_true_constexpr)
13732 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
13733 : "std::is_constant_evaluated");
13734 }
13735
13736 return Success(Info.InConstantContext, E);
13737 }
13738
13739 case Builtin::BI__builtin_is_within_lifetime:
13740 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
13741 return Success(*result, E);
13742 return false;
13743
13744 case Builtin::BI__builtin_ctz:
13745 case Builtin::BI__builtin_ctzl:
13746 case Builtin::BI__builtin_ctzll:
13747 case Builtin::BI__builtin_ctzs:
13748 case Builtin::BI__builtin_ctzg:
13749 case Builtin::BI__builtin_elementwise_cttz: {
13750 APSInt Val;
13751 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13752 APValue Vec;
13753 if (!EvaluateVector(E->getArg(0), Vec, Info))
13754 return false;
13755 Val = ConvertBoolVectorToInt(Vec);
13756 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13757 return false;
13758 }
13759
13760 std::optional<APSInt> Fallback;
13761 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
13762 BuiltinOp == Builtin::BI__builtin_elementwise_cttz) &&
13763 E->getNumArgs() > 1) {
13764 APSInt FallbackTemp;
13765 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13766 return false;
13767 Fallback = FallbackTemp;
13768 }
13769
13770 if (!Val) {
13771 if (Fallback)
13772 return Success(*Fallback, E);
13773
13774 if (BuiltinOp == Builtin::BI__builtin_elementwise_cttz) {
13775 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13776 << /*IsTrailing=*/true;
13777 }
13778 return Error(E);
13779 }
13780
13781 return Success(Val.countr_zero(), E);
13782 }
13783
13784 case Builtin::BI__builtin_eh_return_data_regno: {
13785 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13786 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13787 return Success(Operand, E);
13788 }
13789
13790 case Builtin::BI__builtin_elementwise_abs: {
13791 APSInt Val;
13792 if (!EvaluateInteger(E->getArg(0), Val, Info))
13793 return false;
13794
13795 return Success(Val.abs(), E);
13796 }
13797
13798 case Builtin::BI__builtin_expect:
13799 case Builtin::BI__builtin_expect_with_probability:
13800 return Visit(E->getArg(0));
13801
13802 case Builtin::BI__builtin_ptrauth_string_discriminator: {
13803 const auto *Literal =
13804 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
13805 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13806 return Success(Result, E);
13807 }
13808
13809 case Builtin::BI__builtin_ffs:
13810 case Builtin::BI__builtin_ffsl:
13811 case Builtin::BI__builtin_ffsll: {
13812 APSInt Val;
13813 if (!EvaluateInteger(E->getArg(0), Val, Info))
13814 return false;
13815
13816 unsigned N = Val.countr_zero();
13817 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13818 }
13819
13820 case Builtin::BI__builtin_fpclassify: {
13821 APFloat Val(0.0);
13822 if (!EvaluateFloat(E->getArg(5), Val, Info))
13823 return false;
13824 unsigned Arg;
13825 switch (Val.getCategory()) {
13826 case APFloat::fcNaN: Arg = 0; break;
13827 case APFloat::fcInfinity: Arg = 1; break;
13828 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13829 case APFloat::fcZero: Arg = 4; break;
13830 }
13831 return Visit(E->getArg(Arg));
13832 }
13833
13834 case Builtin::BI__builtin_isinf_sign: {
13835 APFloat Val(0.0);
13836 return EvaluateFloat(E->getArg(0), Val, Info) &&
13837 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13838 }
13839
13840 case Builtin::BI__builtin_isinf: {
13841 APFloat Val(0.0);
13842 return EvaluateFloat(E->getArg(0), Val, Info) &&
13843 Success(Val.isInfinity() ? 1 : 0, E);
13844 }
13845
13846 case Builtin::BI__builtin_isfinite: {
13847 APFloat Val(0.0);
13848 return EvaluateFloat(E->getArg(0), Val, Info) &&
13849 Success(Val.isFinite() ? 1 : 0, E);
13850 }
13851
13852 case Builtin::BI__builtin_isnan: {
13853 APFloat Val(0.0);
13854 return EvaluateFloat(E->getArg(0), Val, Info) &&
13855 Success(Val.isNaN() ? 1 : 0, E);
13856 }
13857
13858 case Builtin::BI__builtin_isnormal: {
13859 APFloat Val(0.0);
13860 return EvaluateFloat(E->getArg(0), Val, Info) &&
13861 Success(Val.isNormal() ? 1 : 0, E);
13862 }
13863
13864 case Builtin::BI__builtin_issubnormal: {
13865 APFloat Val(0.0);
13866 return EvaluateFloat(E->getArg(0), Val, Info) &&
13867 Success(Val.isDenormal() ? 1 : 0, E);
13868 }
13869
13870 case Builtin::BI__builtin_iszero: {
13871 APFloat Val(0.0);
13872 return EvaluateFloat(E->getArg(0), Val, Info) &&
13873 Success(Val.isZero() ? 1 : 0, E);
13874 }
13875
13876 case Builtin::BI__builtin_signbit:
13877 case Builtin::BI__builtin_signbitf:
13878 case Builtin::BI__builtin_signbitl: {
13879 APFloat Val(0.0);
13880 return EvaluateFloat(E->getArg(0), Val, Info) &&
13881 Success(Val.isNegative() ? 1 : 0, E);
13882 }
13883
13884 case Builtin::BI__builtin_isgreater:
13885 case Builtin::BI__builtin_isgreaterequal:
13886 case Builtin::BI__builtin_isless:
13887 case Builtin::BI__builtin_islessequal:
13888 case Builtin::BI__builtin_islessgreater:
13889 case Builtin::BI__builtin_isunordered: {
13890 APFloat LHS(0.0);
13891 APFloat RHS(0.0);
13892 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13893 !EvaluateFloat(E->getArg(1), RHS, Info))
13894 return false;
13895
13896 return Success(
13897 [&] {
13898 switch (BuiltinOp) {
13899 case Builtin::BI__builtin_isgreater:
13900 return LHS > RHS;
13901 case Builtin::BI__builtin_isgreaterequal:
13902 return LHS >= RHS;
13903 case Builtin::BI__builtin_isless:
13904 return LHS < RHS;
13905 case Builtin::BI__builtin_islessequal:
13906 return LHS <= RHS;
13907 case Builtin::BI__builtin_islessgreater: {
13908 APFloat::cmpResult cmp = LHS.compare(RHS);
13909 return cmp == APFloat::cmpResult::cmpLessThan ||
13910 cmp == APFloat::cmpResult::cmpGreaterThan;
13911 }
13912 case Builtin::BI__builtin_isunordered:
13913 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13914 default:
13915 llvm_unreachable("Unexpected builtin ID: Should be a floating "
13916 "point comparison function");
13917 }
13918 }()
13919 ? 1
13920 : 0,
13921 E);
13922 }
13923
13924 case Builtin::BI__builtin_issignaling: {
13925 APFloat Val(0.0);
13926 return EvaluateFloat(E->getArg(0), Val, Info) &&
13927 Success(Val.isSignaling() ? 1 : 0, E);
13928 }
13929
13930 case Builtin::BI__builtin_isfpclass: {
13931 APSInt MaskVal;
13932 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
13933 return false;
13934 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
13935 APFloat Val(0.0);
13936 return EvaluateFloat(E->getArg(0), Val, Info) &&
13937 Success((Val.classify() & Test) ? 1 : 0, E);
13938 }
13939
13940 case Builtin::BI__builtin_parity:
13941 case Builtin::BI__builtin_parityl:
13942 case Builtin::BI__builtin_parityll: {
13943 APSInt Val;
13944 if (!EvaluateInteger(E->getArg(0), Val, Info))
13945 return false;
13946
13947 return Success(Val.popcount() % 2, E);
13948 }
13949
13950 case Builtin::BI__builtin_abs:
13951 case Builtin::BI__builtin_labs:
13952 case Builtin::BI__builtin_llabs: {
13953 APSInt Val;
13954 if (!EvaluateInteger(E->getArg(0), Val, Info))
13955 return false;
13956 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
13957 /*IsUnsigned=*/false))
13958 return false;
13959 if (Val.isNegative())
13960 Val.negate();
13961 return Success(Val, E);
13962 }
13963
13964 case Builtin::BI__builtin_popcount:
13965 case Builtin::BI__builtin_popcountl:
13966 case Builtin::BI__builtin_popcountll:
13967 case Builtin::BI__builtin_popcountg:
13968 case Builtin::BI__builtin_elementwise_popcount:
13969 case Builtin::BI__popcnt16: // Microsoft variants of popcount
13970 case Builtin::BI__popcnt:
13971 case Builtin::BI__popcnt64: {
13972 APSInt Val;
13973 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13974 APValue Vec;
13975 if (!EvaluateVector(E->getArg(0), Vec, Info))
13976 return false;
13977 Val = ConvertBoolVectorToInt(Vec);
13978 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13979 return false;
13980 }
13981
13982 return Success(Val.popcount(), E);
13983 }
13984
13985 case Builtin::BI__builtin_rotateleft8:
13986 case Builtin::BI__builtin_rotateleft16:
13987 case Builtin::BI__builtin_rotateleft32:
13988 case Builtin::BI__builtin_rotateleft64:
13989 case Builtin::BI_rotl8: // Microsoft variants of rotate right
13990 case Builtin::BI_rotl16:
13991 case Builtin::BI_rotl:
13992 case Builtin::BI_lrotl:
13993 case Builtin::BI_rotl64: {
13994 APSInt Val, Amt;
13995 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13996 !EvaluateInteger(E->getArg(1), Amt, Info))
13997 return false;
13998
13999 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
14000 }
14001
14002 case Builtin::BI__builtin_rotateright8:
14003 case Builtin::BI__builtin_rotateright16:
14004 case Builtin::BI__builtin_rotateright32:
14005 case Builtin::BI__builtin_rotateright64:
14006 case Builtin::BI_rotr8: // Microsoft variants of rotate right
14007 case Builtin::BI_rotr16:
14008 case Builtin::BI_rotr:
14009 case Builtin::BI_lrotr:
14010 case Builtin::BI_rotr64: {
14011 APSInt Val, Amt;
14012 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14013 !EvaluateInteger(E->getArg(1), Amt, Info))
14014 return false;
14015
14016 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
14017 }
14018
14019 case Builtin::BI__builtin_elementwise_add_sat: {
14020 APSInt LHS, RHS;
14021 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14022 !EvaluateInteger(E->getArg(1), RHS, Info))
14023 return false;
14024
14025 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
14026 return Success(APSInt(Result, !LHS.isSigned()), E);
14027 }
14028 case Builtin::BI__builtin_elementwise_sub_sat: {
14029 APSInt LHS, RHS;
14030 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14031 !EvaluateInteger(E->getArg(1), RHS, Info))
14032 return false;
14033
14034 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
14035 return Success(APSInt(Result, !LHS.isSigned()), E);
14036 }
14037 case Builtin::BI__builtin_elementwise_max: {
14038 APSInt LHS, RHS;
14039 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14040 !EvaluateInteger(E->getArg(1), RHS, Info))
14041 return false;
14042
14043 APInt Result = std::max(LHS, RHS);
14044 return Success(APSInt(Result, !LHS.isSigned()), E);
14045 }
14046 case Builtin::BI__builtin_elementwise_min: {
14047 APSInt LHS, RHS;
14048 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14049 !EvaluateInteger(E->getArg(1), RHS, Info))
14050 return false;
14051
14052 APInt Result = std::min(LHS, RHS);
14053 return Success(APSInt(Result, !LHS.isSigned()), E);
14054 }
14055 case Builtin::BIstrlen:
14056 case Builtin::BIwcslen:
14057 // A call to strlen is not a constant expression.
14058 if (Info.getLangOpts().CPlusPlus11)
14059 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
14060 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
14061 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
14062 else
14063 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
14064 [[fallthrough]];
14065 case Builtin::BI__builtin_strlen:
14066 case Builtin::BI__builtin_wcslen: {
14067 // As an extension, we support __builtin_strlen() as a constant expression,
14068 // and support folding strlen() to a constant.
14069 uint64_t StrLen;
14070 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
14071 return Success(StrLen, E);
14072 return false;
14073 }
14074
14075 case Builtin::BIstrcmp:
14076 case Builtin::BIwcscmp:
14077 case Builtin::BIstrncmp:
14078 case Builtin::BIwcsncmp:
14079 case Builtin::BImemcmp:
14080 case Builtin::BIbcmp:
14081 case Builtin::BIwmemcmp:
14082 // A call to strlen is not a constant expression.
14083 if (Info.getLangOpts().CPlusPlus11)
14084 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
14085 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
14086 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
14087 else
14088 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
14089 [[fallthrough]];
14090 case Builtin::BI__builtin_strcmp:
14091 case Builtin::BI__builtin_wcscmp:
14092 case Builtin::BI__builtin_strncmp:
14093 case Builtin::BI__builtin_wcsncmp:
14094 case Builtin::BI__builtin_memcmp:
14095 case Builtin::BI__builtin_bcmp:
14096 case Builtin::BI__builtin_wmemcmp: {
14097 LValue String1, String2;
14098 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
14099 !EvaluatePointer(E->getArg(1), String2, Info))
14100 return false;
14101
14102 uint64_t MaxLength = uint64_t(-1);
14103 if (BuiltinOp != Builtin::BIstrcmp &&
14104 BuiltinOp != Builtin::BIwcscmp &&
14105 BuiltinOp != Builtin::BI__builtin_strcmp &&
14106 BuiltinOp != Builtin::BI__builtin_wcscmp) {
14107 APSInt N;
14108 if (!EvaluateInteger(E->getArg(2), N, Info))
14109 return false;
14110 MaxLength = N.getZExtValue();
14111 }
14112
14113 // Empty substrings compare equal by definition.
14114 if (MaxLength == 0u)
14115 return Success(0, E);
14116
14117 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14118 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14119 String1.Designator.Invalid || String2.Designator.Invalid)
14120 return false;
14121
14122 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
14123 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
14124
14125 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
14126 BuiltinOp == Builtin::BIbcmp ||
14127 BuiltinOp == Builtin::BI__builtin_memcmp ||
14128 BuiltinOp == Builtin::BI__builtin_bcmp;
14129
14130 assert(IsRawByte ||
14131 (Info.Ctx.hasSameUnqualifiedType(
14132 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
14133 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
14134
14135 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
14136 // 'char8_t', but no other types.
14137 if (IsRawByte &&
14138 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
14139 // FIXME: Consider using our bit_cast implementation to support this.
14140 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
14141 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
14142 << CharTy2;
14143 return false;
14144 }
14145
14146 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
14147 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
14148 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
14149 Char1.isInt() && Char2.isInt();
14150 };
14151 const auto &AdvanceElems = [&] {
14152 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
14153 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
14154 };
14155
14156 bool StopAtNull =
14157 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
14158 BuiltinOp != Builtin::BIwmemcmp &&
14159 BuiltinOp != Builtin::BI__builtin_memcmp &&
14160 BuiltinOp != Builtin::BI__builtin_bcmp &&
14161 BuiltinOp != Builtin::BI__builtin_wmemcmp);
14162 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
14163 BuiltinOp == Builtin::BIwcsncmp ||
14164 BuiltinOp == Builtin::BIwmemcmp ||
14165 BuiltinOp == Builtin::BI__builtin_wcscmp ||
14166 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
14167 BuiltinOp == Builtin::BI__builtin_wmemcmp;
14168
14169 for (; MaxLength; --MaxLength) {
14170 APValue Char1, Char2;
14171 if (!ReadCurElems(Char1, Char2))
14172 return false;
14173 if (Char1.getInt().ne(Char2.getInt())) {
14174 if (IsWide) // wmemcmp compares with wchar_t signedness.
14175 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
14176 // memcmp always compares unsigned chars.
14177 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
14178 }
14179 if (StopAtNull && !Char1.getInt())
14180 return Success(0, E);
14181 assert(!(StopAtNull && !Char2.getInt()));
14182 if (!AdvanceElems())
14183 return false;
14184 }
14185 // We hit the strncmp / memcmp limit.
14186 return Success(0, E);
14187 }
14188
14189 case Builtin::BI__atomic_always_lock_free:
14190 case Builtin::BI__atomic_is_lock_free:
14191 case Builtin::BI__c11_atomic_is_lock_free: {
14192 APSInt SizeVal;
14193 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
14194 return false;
14195
14196 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
14197 // of two less than or equal to the maximum inline atomic width, we know it
14198 // is lock-free. If the size isn't a power of two, or greater than the
14199 // maximum alignment where we promote atomics, we know it is not lock-free
14200 // (at least not in the sense of atomic_is_lock_free). Otherwise,
14201 // the answer can only be determined at runtime; for example, 16-byte
14202 // atomics have lock-free implementations on some, but not all,
14203 // x86-64 processors.
14204
14205 // Check power-of-two.
14206 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
14207 if (Size.isPowerOfTwo()) {
14208 // Check against inlining width.
14209 unsigned InlineWidthBits =
14210 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
14211 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
14212 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
14213 Size == CharUnits::One())
14214 return Success(1, E);
14215
14216 // If the pointer argument can be evaluated to a compile-time constant
14217 // integer (or nullptr), check if that value is appropriately aligned.
14218 const Expr *PtrArg = E->getArg(1);
14220 APSInt IntResult;
14221 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
14222 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
14223 Info.Ctx) &&
14224 IntResult.isAligned(Size.getAsAlign()))
14225 return Success(1, E);
14226
14227 // Otherwise, check if the type's alignment against Size.
14228 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
14229 // Drop the potential implicit-cast to 'const volatile void*', getting
14230 // the underlying type.
14231 if (ICE->getCastKind() == CK_BitCast)
14232 PtrArg = ICE->getSubExpr();
14233 }
14234
14235 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
14236 QualType PointeeType = PtrTy->getPointeeType();
14237 if (!PointeeType->isIncompleteType() &&
14238 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
14239 // OK, we will inline operations on this object.
14240 return Success(1, E);
14241 }
14242 }
14243 }
14244 }
14245
14246 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
14247 Success(0, E) : Error(E);
14248 }
14249 case Builtin::BI__builtin_addcb:
14250 case Builtin::BI__builtin_addcs:
14251 case Builtin::BI__builtin_addc:
14252 case Builtin::BI__builtin_addcl:
14253 case Builtin::BI__builtin_addcll:
14254 case Builtin::BI__builtin_subcb:
14255 case Builtin::BI__builtin_subcs:
14256 case Builtin::BI__builtin_subc:
14257 case Builtin::BI__builtin_subcl:
14258 case Builtin::BI__builtin_subcll: {
14259 LValue CarryOutLValue;
14260 APSInt LHS, RHS, CarryIn, CarryOut, Result;
14261 QualType ResultType = E->getArg(0)->getType();
14262 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14263 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14264 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
14265 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
14266 return false;
14267 // Copy the number of bits and sign.
14268 Result = LHS;
14269 CarryOut = LHS;
14270
14271 bool FirstOverflowed = false;
14272 bool SecondOverflowed = false;
14273 switch (BuiltinOp) {
14274 default:
14275 llvm_unreachable("Invalid value for BuiltinOp");
14276 case Builtin::BI__builtin_addcb:
14277 case Builtin::BI__builtin_addcs:
14278 case Builtin::BI__builtin_addc:
14279 case Builtin::BI__builtin_addcl:
14280 case Builtin::BI__builtin_addcll:
14281 Result =
14282 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
14283 break;
14284 case Builtin::BI__builtin_subcb:
14285 case Builtin::BI__builtin_subcs:
14286 case Builtin::BI__builtin_subc:
14287 case Builtin::BI__builtin_subcl:
14288 case Builtin::BI__builtin_subcll:
14289 Result =
14290 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
14291 break;
14292 }
14293
14294 // It is possible for both overflows to happen but CGBuiltin uses an OR so
14295 // this is consistent.
14296 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
14297 APValue APV{CarryOut};
14298 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
14299 return false;
14300 return Success(Result, E);
14301 }
14302 case Builtin::BI__builtin_add_overflow:
14303 case Builtin::BI__builtin_sub_overflow:
14304 case Builtin::BI__builtin_mul_overflow:
14305 case Builtin::BI__builtin_sadd_overflow:
14306 case Builtin::BI__builtin_uadd_overflow:
14307 case Builtin::BI__builtin_uaddl_overflow:
14308 case Builtin::BI__builtin_uaddll_overflow:
14309 case Builtin::BI__builtin_usub_overflow:
14310 case Builtin::BI__builtin_usubl_overflow:
14311 case Builtin::BI__builtin_usubll_overflow:
14312 case Builtin::BI__builtin_umul_overflow:
14313 case Builtin::BI__builtin_umull_overflow:
14314 case Builtin::BI__builtin_umulll_overflow:
14315 case Builtin::BI__builtin_saddl_overflow:
14316 case Builtin::BI__builtin_saddll_overflow:
14317 case Builtin::BI__builtin_ssub_overflow:
14318 case Builtin::BI__builtin_ssubl_overflow:
14319 case Builtin::BI__builtin_ssubll_overflow:
14320 case Builtin::BI__builtin_smul_overflow:
14321 case Builtin::BI__builtin_smull_overflow:
14322 case Builtin::BI__builtin_smulll_overflow: {
14323 LValue ResultLValue;
14324 APSInt LHS, RHS;
14325
14326 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
14327 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14328 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14329 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
14330 return false;
14331
14332 APSInt Result;
14333 bool DidOverflow = false;
14334
14335 // If the types don't have to match, enlarge all 3 to the largest of them.
14336 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14337 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14338 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14339 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
14341 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
14343 uint64_t LHSSize = LHS.getBitWidth();
14344 uint64_t RHSSize = RHS.getBitWidth();
14345 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
14346 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
14347
14348 // Add an additional bit if the signedness isn't uniformly agreed to. We
14349 // could do this ONLY if there is a signed and an unsigned that both have
14350 // MaxBits, but the code to check that is pretty nasty. The issue will be
14351 // caught in the shrink-to-result later anyway.
14352 if (IsSigned && !AllSigned)
14353 ++MaxBits;
14354
14355 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
14356 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
14357 Result = APSInt(MaxBits, !IsSigned);
14358 }
14359
14360 // Find largest int.
14361 switch (BuiltinOp) {
14362 default:
14363 llvm_unreachable("Invalid value for BuiltinOp");
14364 case Builtin::BI__builtin_add_overflow:
14365 case Builtin::BI__builtin_sadd_overflow:
14366 case Builtin::BI__builtin_saddl_overflow:
14367 case Builtin::BI__builtin_saddll_overflow:
14368 case Builtin::BI__builtin_uadd_overflow:
14369 case Builtin::BI__builtin_uaddl_overflow:
14370 case Builtin::BI__builtin_uaddll_overflow:
14371 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
14372 : LHS.uadd_ov(RHS, DidOverflow);
14373 break;
14374 case Builtin::BI__builtin_sub_overflow:
14375 case Builtin::BI__builtin_ssub_overflow:
14376 case Builtin::BI__builtin_ssubl_overflow:
14377 case Builtin::BI__builtin_ssubll_overflow:
14378 case Builtin::BI__builtin_usub_overflow:
14379 case Builtin::BI__builtin_usubl_overflow:
14380 case Builtin::BI__builtin_usubll_overflow:
14381 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
14382 : LHS.usub_ov(RHS, DidOverflow);
14383 break;
14384 case Builtin::BI__builtin_mul_overflow:
14385 case Builtin::BI__builtin_smul_overflow:
14386 case Builtin::BI__builtin_smull_overflow:
14387 case Builtin::BI__builtin_smulll_overflow:
14388 case Builtin::BI__builtin_umul_overflow:
14389 case Builtin::BI__builtin_umull_overflow:
14390 case Builtin::BI__builtin_umulll_overflow:
14391 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
14392 : LHS.umul_ov(RHS, DidOverflow);
14393 break;
14394 }
14395
14396 // In the case where multiple sizes are allowed, truncate and see if
14397 // the values are the same.
14398 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14399 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14400 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14401 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
14402 // since it will give us the behavior of a TruncOrSelf in the case where
14403 // its parameter <= its size. We previously set Result to be at least the
14404 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
14405 // will work exactly like TruncOrSelf.
14406 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
14407 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
14408
14409 if (!APSInt::isSameValue(Temp, Result))
14410 DidOverflow = true;
14411 Result = Temp;
14412 }
14413
14414 APValue APV{Result};
14415 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14416 return false;
14417 return Success(DidOverflow, E);
14418 }
14419
14420 case Builtin::BI__builtin_reduce_add:
14421 case Builtin::BI__builtin_reduce_mul:
14422 case Builtin::BI__builtin_reduce_and:
14423 case Builtin::BI__builtin_reduce_or:
14424 case Builtin::BI__builtin_reduce_xor:
14425 case Builtin::BI__builtin_reduce_min:
14426 case Builtin::BI__builtin_reduce_max: {
14427 APValue Source;
14428 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
14429 return false;
14430
14431 unsigned SourceLen = Source.getVectorLength();
14432 APSInt Reduced = Source.getVectorElt(0).getInt();
14433 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
14434 switch (BuiltinOp) {
14435 default:
14436 return false;
14437 case Builtin::BI__builtin_reduce_add: {
14439 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14440 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
14441 return false;
14442 break;
14443 }
14444 case Builtin::BI__builtin_reduce_mul: {
14446 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14447 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
14448 return false;
14449 break;
14450 }
14451 case Builtin::BI__builtin_reduce_and: {
14452 Reduced &= Source.getVectorElt(EltNum).getInt();
14453 break;
14454 }
14455 case Builtin::BI__builtin_reduce_or: {
14456 Reduced |= Source.getVectorElt(EltNum).getInt();
14457 break;
14458 }
14459 case Builtin::BI__builtin_reduce_xor: {
14460 Reduced ^= Source.getVectorElt(EltNum).getInt();
14461 break;
14462 }
14463 case Builtin::BI__builtin_reduce_min: {
14464 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
14465 break;
14466 }
14467 case Builtin::BI__builtin_reduce_max: {
14468 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
14469 break;
14470 }
14471 }
14472 }
14473
14474 return Success(Reduced, E);
14475 }
14476
14477 case clang::X86::BI__builtin_ia32_addcarryx_u32:
14478 case clang::X86::BI__builtin_ia32_addcarryx_u64:
14479 case clang::X86::BI__builtin_ia32_subborrow_u32:
14480 case clang::X86::BI__builtin_ia32_subborrow_u64: {
14481 LValue ResultLValue;
14482 APSInt CarryIn, LHS, RHS;
14483 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
14484 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
14485 !EvaluateInteger(E->getArg(1), LHS, Info) ||
14486 !EvaluateInteger(E->getArg(2), RHS, Info) ||
14487 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
14488 return false;
14489
14490 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
14491 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
14492
14493 unsigned BitWidth = LHS.getBitWidth();
14494 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
14495 APInt ExResult =
14496 IsAdd
14497 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
14498 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
14499
14500 APInt Result = ExResult.extractBits(BitWidth, 0);
14501 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
14502
14503 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
14504 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14505 return false;
14506 return Success(CarryOut, E);
14507 }
14508
14509 case clang::X86::BI__builtin_ia32_bextr_u32:
14510 case clang::X86::BI__builtin_ia32_bextr_u64:
14511 case clang::X86::BI__builtin_ia32_bextri_u32:
14512 case clang::X86::BI__builtin_ia32_bextri_u64: {
14513 APSInt Val, Idx;
14514 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14515 !EvaluateInteger(E->getArg(1), Idx, Info))
14516 return false;
14517
14518 unsigned BitWidth = Val.getBitWidth();
14519 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
14520 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
14521 Length = Length > BitWidth ? BitWidth : Length;
14522
14523 // Handle out of bounds cases.
14524 if (Length == 0 || Shift >= BitWidth)
14525 return Success(0, E);
14526
14527 uint64_t Result = Val.getZExtValue() >> Shift;
14528 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
14529 return Success(Result, E);
14530 }
14531
14532 case clang::X86::BI__builtin_ia32_bzhi_si:
14533 case clang::X86::BI__builtin_ia32_bzhi_di: {
14534 APSInt Val, Idx;
14535 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14536 !EvaluateInteger(E->getArg(1), Idx, Info))
14537 return false;
14538
14539 unsigned BitWidth = Val.getBitWidth();
14540 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
14541 if (Index < BitWidth)
14542 Val.clearHighBits(BitWidth - Index);
14543 return Success(Val, E);
14544 }
14545
14546 case clang::X86::BI__builtin_ia32_lzcnt_u16:
14547 case clang::X86::BI__builtin_ia32_lzcnt_u32:
14548 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
14549 APSInt Val;
14550 if (!EvaluateInteger(E->getArg(0), Val, Info))
14551 return false;
14552 return Success(Val.countLeadingZeros(), E);
14553 }
14554
14555 case clang::X86::BI__builtin_ia32_tzcnt_u16:
14556 case clang::X86::BI__builtin_ia32_tzcnt_u32:
14557 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
14558 APSInt Val;
14559 if (!EvaluateInteger(E->getArg(0), Val, Info))
14560 return false;
14561 return Success(Val.countTrailingZeros(), E);
14562 }
14563
14564 case clang::X86::BI__builtin_ia32_pdep_si:
14565 case clang::X86::BI__builtin_ia32_pdep_di: {
14566 APSInt Val, Msk;
14567 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14568 !EvaluateInteger(E->getArg(1), Msk, Info))
14569 return false;
14570
14571 unsigned BitWidth = Val.getBitWidth();
14572 APInt Result = APInt::getZero(BitWidth);
14573 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
14574 if (Msk[I])
14575 Result.setBitVal(I, Val[P++]);
14576 return Success(Result, E);
14577 }
14578
14579 case clang::X86::BI__builtin_ia32_pext_si:
14580 case clang::X86::BI__builtin_ia32_pext_di: {
14581 APSInt Val, Msk;
14582 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14583 !EvaluateInteger(E->getArg(1), Msk, Info))
14584 return false;
14585
14586 unsigned BitWidth = Val.getBitWidth();
14587 APInt Result = APInt::getZero(BitWidth);
14588 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
14589 if (Msk[I])
14590 Result.setBitVal(P++, Val[I]);
14591 return Success(Result, E);
14592 }
14593 }
14594}
14595
14596/// Determine whether this is a pointer past the end of the complete
14597/// object referred to by the lvalue.
14599 const LValue &LV) {
14600 // A null pointer can be viewed as being "past the end" but we don't
14601 // choose to look at it that way here.
14602 if (!LV.getLValueBase())
14603 return false;
14604
14605 // If the designator is valid and refers to a subobject, we're not pointing
14606 // past the end.
14607 if (!LV.getLValueDesignator().Invalid &&
14608 !LV.getLValueDesignator().isOnePastTheEnd())
14609 return false;
14610
14611 // A pointer to an incomplete type might be past-the-end if the type's size is
14612 // zero. We cannot tell because the type is incomplete.
14613 QualType Ty = getType(LV.getLValueBase());
14614 if (Ty->isIncompleteType())
14615 return true;
14616
14617 // Can't be past the end of an invalid object.
14618 if (LV.getLValueDesignator().Invalid)
14619 return false;
14620
14621 // We're a past-the-end pointer if we point to the byte after the object,
14622 // no matter what our type or path is.
14623 auto Size = Ctx.getTypeSizeInChars(Ty);
14624 return LV.getLValueOffset() == Size;
14625}
14626
14627namespace {
14628
14629/// Data recursive integer evaluator of certain binary operators.
14630///
14631/// We use a data recursive algorithm for binary operators so that we are able
14632/// to handle extreme cases of chained binary operators without causing stack
14633/// overflow.
14634class DataRecursiveIntBinOpEvaluator {
14635 struct EvalResult {
14636 APValue Val;
14637 bool Failed = false;
14638
14639 EvalResult() = default;
14640
14641 void swap(EvalResult &RHS) {
14642 Val.swap(RHS.Val);
14643 Failed = RHS.Failed;
14644 RHS.Failed = false;
14645 }
14646 };
14647
14648 struct Job {
14649 const Expr *E;
14650 EvalResult LHSResult; // meaningful only for binary operator expression.
14651 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
14652
14653 Job() = default;
14654 Job(Job &&) = default;
14655
14656 void startSpeculativeEval(EvalInfo &Info) {
14657 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
14658 }
14659
14660 private:
14661 SpeculativeEvaluationRAII SpecEvalRAII;
14662 };
14663
14665
14666 IntExprEvaluator &IntEval;
14667 EvalInfo &Info;
14668 APValue &FinalResult;
14669
14670public:
14671 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
14672 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
14673
14674 /// True if \param E is a binary operator that we are going to handle
14675 /// data recursively.
14676 /// We handle binary operators that are comma, logical, or that have operands
14677 /// with integral or enumeration type.
14678 static bool shouldEnqueue(const BinaryOperator *E) {
14679 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
14681 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14682 E->getRHS()->getType()->isIntegralOrEnumerationType());
14683 }
14684
14685 bool Traverse(const BinaryOperator *E) {
14686 enqueue(E);
14687 EvalResult PrevResult;
14688 while (!Queue.empty())
14689 process(PrevResult);
14690
14691 if (PrevResult.Failed) return false;
14692
14693 FinalResult.swap(PrevResult.Val);
14694 return true;
14695 }
14696
14697private:
14698 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
14699 return IntEval.Success(Value, E, Result);
14700 }
14701 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
14702 return IntEval.Success(Value, E, Result);
14703 }
14704 bool Error(const Expr *E) {
14705 return IntEval.Error(E);
14706 }
14707 bool Error(const Expr *E, diag::kind D) {
14708 return IntEval.Error(E, D);
14709 }
14710
14711 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
14712 return Info.CCEDiag(E, D);
14713 }
14714
14715 // Returns true if visiting the RHS is necessary, false otherwise.
14716 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14717 bool &SuppressRHSDiags);
14718
14719 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14720 const BinaryOperator *E, APValue &Result);
14721
14722 void EvaluateExpr(const Expr *E, EvalResult &Result) {
14723 Result.Failed = !Evaluate(Result.Val, Info, E);
14724 if (Result.Failed)
14725 Result.Val = APValue();
14726 }
14727
14728 void process(EvalResult &Result);
14729
14730 void enqueue(const Expr *E) {
14731 E = E->IgnoreParens();
14732 Queue.resize(Queue.size()+1);
14733 Queue.back().E = E;
14734 Queue.back().Kind = Job::AnyExprKind;
14735 }
14736};
14737
14738}
14739
14740bool DataRecursiveIntBinOpEvaluator::
14741 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14742 bool &SuppressRHSDiags) {
14743 if (E->getOpcode() == BO_Comma) {
14744 // Ignore LHS but note if we could not evaluate it.
14745 if (LHSResult.Failed)
14746 return Info.noteSideEffect();
14747 return true;
14748 }
14749
14750 if (E->isLogicalOp()) {
14751 bool LHSAsBool;
14752 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
14753 // We were able to evaluate the LHS, see if we can get away with not
14754 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
14755 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
14756 Success(LHSAsBool, E, LHSResult.Val);
14757 return false; // Ignore RHS
14758 }
14759 } else {
14760 LHSResult.Failed = true;
14761
14762 // Since we weren't able to evaluate the left hand side, it
14763 // might have had side effects.
14764 if (!Info.noteSideEffect())
14765 return false;
14766
14767 // We can't evaluate the LHS; however, sometimes the result
14768 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14769 // Don't ignore RHS and suppress diagnostics from this arm.
14770 SuppressRHSDiags = true;
14771 }
14772
14773 return true;
14774 }
14775
14776 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14777 E->getRHS()->getType()->isIntegralOrEnumerationType());
14778
14779 if (LHSResult.Failed && !Info.noteFailure())
14780 return false; // Ignore RHS;
14781
14782 return true;
14783}
14784
14785static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
14786 bool IsSub) {
14787 // Compute the new offset in the appropriate width, wrapping at 64 bits.
14788 // FIXME: When compiling for a 32-bit target, we should use 32-bit
14789 // offsets.
14790 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
14791 CharUnits &Offset = LVal.getLValueOffset();
14792 uint64_t Offset64 = Offset.getQuantity();
14793 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
14794 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
14795 : Offset64 + Index64);
14796}
14797
14798bool DataRecursiveIntBinOpEvaluator::
14799 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14800 const BinaryOperator *E, APValue &Result) {
14801 if (E->getOpcode() == BO_Comma) {
14802 if (RHSResult.Failed)
14803 return false;
14804 Result = RHSResult.Val;
14805 return true;
14806 }
14807
14808 if (E->isLogicalOp()) {
14809 bool lhsResult, rhsResult;
14810 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
14811 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
14812
14813 if (LHSIsOK) {
14814 if (RHSIsOK) {
14815 if (E->getOpcode() == BO_LOr)
14816 return Success(lhsResult || rhsResult, E, Result);
14817 else
14818 return Success(lhsResult && rhsResult, E, Result);
14819 }
14820 } else {
14821 if (RHSIsOK) {
14822 // We can't evaluate the LHS; however, sometimes the result
14823 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14824 if (rhsResult == (E->getOpcode() == BO_LOr))
14825 return Success(rhsResult, E, Result);
14826 }
14827 }
14828
14829 return false;
14830 }
14831
14832 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14833 E->getRHS()->getType()->isIntegralOrEnumerationType());
14834
14835 if (LHSResult.Failed || RHSResult.Failed)
14836 return false;
14837
14838 const APValue &LHSVal = LHSResult.Val;
14839 const APValue &RHSVal = RHSResult.Val;
14840
14841 // Handle cases like (unsigned long)&a + 4.
14842 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
14843 Result = LHSVal;
14844 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
14845 return true;
14846 }
14847
14848 // Handle cases like 4 + (unsigned long)&a
14849 if (E->getOpcode() == BO_Add &&
14850 RHSVal.isLValue() && LHSVal.isInt()) {
14851 Result = RHSVal;
14852 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
14853 return true;
14854 }
14855
14856 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
14857 // Handle (intptr_t)&&A - (intptr_t)&&B.
14858 if (!LHSVal.getLValueOffset().isZero() ||
14859 !RHSVal.getLValueOffset().isZero())
14860 return false;
14861 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
14862 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
14863 if (!LHSExpr || !RHSExpr)
14864 return false;
14865 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14866 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14867 if (!LHSAddrExpr || !RHSAddrExpr)
14868 return false;
14869 // Make sure both labels come from the same function.
14870 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14871 RHSAddrExpr->getLabel()->getDeclContext())
14872 return false;
14873 Result = APValue(LHSAddrExpr, RHSAddrExpr);
14874 return true;
14875 }
14876
14877 // All the remaining cases expect both operands to be an integer
14878 if (!LHSVal.isInt() || !RHSVal.isInt())
14879 return Error(E);
14880
14881 // Set up the width and signedness manually, in case it can't be deduced
14882 // from the operation we're performing.
14883 // FIXME: Don't do this in the cases where we can deduce it.
14884 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
14886 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
14887 RHSVal.getInt(), Value))
14888 return false;
14889 return Success(Value, E, Result);
14890}
14891
14892void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
14893 Job &job = Queue.back();
14894
14895 switch (job.Kind) {
14896 case Job::AnyExprKind: {
14897 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
14898 if (shouldEnqueue(Bop)) {
14899 job.Kind = Job::BinOpKind;
14900 enqueue(Bop->getLHS());
14901 return;
14902 }
14903 }
14904
14905 EvaluateExpr(job.E, Result);
14906 Queue.pop_back();
14907 return;
14908 }
14909
14910 case Job::BinOpKind: {
14911 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14912 bool SuppressRHSDiags = false;
14913 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
14914 Queue.pop_back();
14915 return;
14916 }
14917 if (SuppressRHSDiags)
14918 job.startSpeculativeEval(Info);
14919 job.LHSResult.swap(Result);
14920 job.Kind = Job::BinOpVisitedLHSKind;
14921 enqueue(Bop->getRHS());
14922 return;
14923 }
14924
14925 case Job::BinOpVisitedLHSKind: {
14926 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14927 EvalResult RHS;
14928 RHS.swap(Result);
14929 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
14930 Queue.pop_back();
14931 return;
14932 }
14933 }
14934
14935 llvm_unreachable("Invalid Job::Kind!");
14936}
14937
14938namespace {
14939enum class CmpResult {
14940 Unequal,
14941 Less,
14942 Equal,
14943 Greater,
14944 Unordered,
14945};
14946}
14947
14948template <class SuccessCB, class AfterCB>
14949static bool
14951 SuccessCB &&Success, AfterCB &&DoAfter) {
14952 assert(!E->isValueDependent());
14953 assert(E->isComparisonOp() && "expected comparison operator");
14954 assert((E->getOpcode() == BO_Cmp ||
14956 "unsupported binary expression evaluation");
14957 auto Error = [&](const Expr *E) {
14958 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14959 return false;
14960 };
14961
14962 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
14963 bool IsEquality = E->isEqualityOp();
14964
14965 QualType LHSTy = E->getLHS()->getType();
14966 QualType RHSTy = E->getRHS()->getType();
14967
14968 if (LHSTy->isIntegralOrEnumerationType() &&
14969 RHSTy->isIntegralOrEnumerationType()) {
14970 APSInt LHS, RHS;
14971 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
14972 if (!LHSOK && !Info.noteFailure())
14973 return false;
14974 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
14975 return false;
14976 if (LHS < RHS)
14977 return Success(CmpResult::Less, E);
14978 if (LHS > RHS)
14979 return Success(CmpResult::Greater, E);
14980 return Success(CmpResult::Equal, E);
14981 }
14982
14983 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
14984 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
14985 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
14986
14987 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
14988 if (!LHSOK && !Info.noteFailure())
14989 return false;
14990 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
14991 return false;
14992 if (LHSFX < RHSFX)
14993 return Success(CmpResult::Less, E);
14994 if (LHSFX > RHSFX)
14995 return Success(CmpResult::Greater, E);
14996 return Success(CmpResult::Equal, E);
14997 }
14998
14999 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
15000 ComplexValue LHS, RHS;
15001 bool LHSOK;
15002 if (E->isAssignmentOp()) {
15003 LValue LV;
15004 EvaluateLValue(E->getLHS(), LV, Info);
15005 LHSOK = false;
15006 } else if (LHSTy->isRealFloatingType()) {
15007 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
15008 if (LHSOK) {
15009 LHS.makeComplexFloat();
15010 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
15011 }
15012 } else {
15013 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
15014 }
15015 if (!LHSOK && !Info.noteFailure())
15016 return false;
15017
15018 if (E->getRHS()->getType()->isRealFloatingType()) {
15019 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
15020 return false;
15021 RHS.makeComplexFloat();
15022 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
15023 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15024 return false;
15025
15026 if (LHS.isComplexFloat()) {
15027 APFloat::cmpResult CR_r =
15028 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
15029 APFloat::cmpResult CR_i =
15030 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
15031 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
15032 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
15033 } else {
15034 assert(IsEquality && "invalid complex comparison");
15035 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
15036 LHS.getComplexIntImag() == RHS.getComplexIntImag();
15037 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
15038 }
15039 }
15040
15041 if (LHSTy->isRealFloatingType() &&
15042 RHSTy->isRealFloatingType()) {
15043 APFloat RHS(0.0), LHS(0.0);
15044
15045 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
15046 if (!LHSOK && !Info.noteFailure())
15047 return false;
15048
15049 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
15050 return false;
15051
15052 assert(E->isComparisonOp() && "Invalid binary operator!");
15053 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
15054 if (!Info.InConstantContext &&
15055 APFloatCmpResult == APFloat::cmpUnordered &&
15056 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
15057 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
15058 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
15059 return false;
15060 }
15061 auto GetCmpRes = [&]() {
15062 switch (APFloatCmpResult) {
15063 case APFloat::cmpEqual:
15064 return CmpResult::Equal;
15065 case APFloat::cmpLessThan:
15066 return CmpResult::Less;
15067 case APFloat::cmpGreaterThan:
15068 return CmpResult::Greater;
15069 case APFloat::cmpUnordered:
15070 return CmpResult::Unordered;
15071 }
15072 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
15073 };
15074 return Success(GetCmpRes(), E);
15075 }
15076
15077 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
15078 LValue LHSValue, RHSValue;
15079
15080 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15081 if (!LHSOK && !Info.noteFailure())
15082 return false;
15083
15084 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15085 return false;
15086
15087 // Reject differing bases from the normal codepath; we special-case
15088 // comparisons to null.
15089 if (!HasSameBase(LHSValue, RHSValue)) {
15090 // Bail out early if we're checking potential constant expression.
15091 // Otherwise, prefer to diagnose other issues.
15092 if (Info.checkingPotentialConstantExpression() &&
15093 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
15094 return false;
15095 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
15096 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15097 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15098 Info.FFDiag(E, DiagID)
15099 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
15100 return false;
15101 };
15102 // Inequalities and subtractions between unrelated pointers have
15103 // unspecified or undefined behavior.
15104 if (!IsEquality)
15105 return DiagComparison(
15106 diag::note_constexpr_pointer_comparison_unspecified);
15107 // A constant address may compare equal to the address of a symbol.
15108 // The one exception is that address of an object cannot compare equal
15109 // to a null pointer constant.
15110 // TODO: Should we restrict this to actual null pointers, and exclude the
15111 // case of zero cast to pointer type?
15112 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
15113 (!RHSValue.Base && !RHSValue.Offset.isZero()))
15114 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
15115 !RHSValue.Base);
15116 // C++2c [intro.object]/10:
15117 // Two objects [...] may have the same address if [...] they are both
15118 // potentially non-unique objects.
15119 // C++2c [intro.object]/9:
15120 // An object is potentially non-unique if it is a string literal object,
15121 // the backing array of an initializer list, or a subobject thereof.
15122 //
15123 // This makes the comparison result unspecified, so it's not a constant
15124 // expression.
15125 //
15126 // TODO: Do we need to handle the initializer list case here?
15127 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15128 return DiagComparison(diag::note_constexpr_literal_comparison);
15129 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
15130 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
15131 !IsOpaqueConstantCall(LHSValue));
15132 // We can't tell whether weak symbols will end up pointing to the same
15133 // object.
15134 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
15135 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
15136 !IsWeakLValue(LHSValue));
15137 // We can't compare the address of the start of one object with the
15138 // past-the-end address of another object, per C++ DR1652.
15139 if (LHSValue.Base && LHSValue.Offset.isZero() &&
15140 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
15141 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15142 true);
15143 if (RHSValue.Base && RHSValue.Offset.isZero() &&
15144 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
15145 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15146 false);
15147 // We can't tell whether an object is at the same address as another
15148 // zero sized object.
15149 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
15150 (LHSValue.Base && isZeroSized(RHSValue)))
15151 return DiagComparison(
15152 diag::note_constexpr_pointer_comparison_zero_sized);
15153 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
15154 return DiagComparison(
15155 diag::note_constexpr_pointer_comparison_unspecified);
15156 // FIXME: Verify both variables are live.
15157 return Success(CmpResult::Unequal, E);
15158 }
15159
15160 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15161 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15162
15163 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15164 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15165
15166 // C++11 [expr.rel]p2:
15167 // - If two pointers point to non-static data members of the same object,
15168 // or to subobjects or array elements fo such members, recursively, the
15169 // pointer to the later declared member compares greater provided the
15170 // two members have the same access control and provided their class is
15171 // not a union.
15172 // [...]
15173 // - Otherwise pointer comparisons are unspecified.
15174 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
15175 bool WasArrayIndex;
15176 unsigned Mismatch = FindDesignatorMismatch(
15177 LHSValue.Base.isNull() ? QualType()
15178 : getType(LHSValue.Base).getNonReferenceType(),
15179 LHSDesignator, RHSDesignator, WasArrayIndex);
15180 // At the point where the designators diverge, the comparison has a
15181 // specified value if:
15182 // - we are comparing array indices
15183 // - we are comparing fields of a union, or fields with the same access
15184 // Otherwise, the result is unspecified and thus the comparison is not a
15185 // constant expression.
15186 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
15187 Mismatch < RHSDesignator.Entries.size()) {
15188 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
15189 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
15190 if (!LF && !RF)
15191 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
15192 else if (!LF)
15193 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15194 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
15195 << RF->getParent() << RF;
15196 else if (!RF)
15197 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15198 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
15199 << LF->getParent() << LF;
15200 else if (!LF->getParent()->isUnion() &&
15201 LF->getAccess() != RF->getAccess())
15202 Info.CCEDiag(E,
15203 diag::note_constexpr_pointer_comparison_differing_access)
15204 << LF << LF->getAccess() << RF << RF->getAccess()
15205 << LF->getParent();
15206 }
15207 }
15208
15209 // The comparison here must be unsigned, and performed with the same
15210 // width as the pointer.
15211 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
15212 uint64_t CompareLHS = LHSOffset.getQuantity();
15213 uint64_t CompareRHS = RHSOffset.getQuantity();
15214 assert(PtrSize <= 64 && "Unexpected pointer width");
15215 uint64_t Mask = ~0ULL >> (64 - PtrSize);
15216 CompareLHS &= Mask;
15217 CompareRHS &= Mask;
15218
15219 // If there is a base and this is a relational operator, we can only
15220 // compare pointers within the object in question; otherwise, the result
15221 // depends on where the object is located in memory.
15222 if (!LHSValue.Base.isNull() && IsRelational) {
15223 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
15224 if (BaseTy->isIncompleteType())
15225 return Error(E);
15226 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
15227 uint64_t OffsetLimit = Size.getQuantity();
15228 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
15229 return Error(E);
15230 }
15231
15232 if (CompareLHS < CompareRHS)
15233 return Success(CmpResult::Less, E);
15234 if (CompareLHS > CompareRHS)
15235 return Success(CmpResult::Greater, E);
15236 return Success(CmpResult::Equal, E);
15237 }
15238
15239 if (LHSTy->isMemberPointerType()) {
15240 assert(IsEquality && "unexpected member pointer operation");
15241 assert(RHSTy->isMemberPointerType() && "invalid comparison");
15242
15243 MemberPtr LHSValue, RHSValue;
15244
15245 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
15246 if (!LHSOK && !Info.noteFailure())
15247 return false;
15248
15249 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15250 return false;
15251
15252 // If either operand is a pointer to a weak function, the comparison is not
15253 // constant.
15254 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
15255 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15256 << LHSValue.getDecl();
15257 return false;
15258 }
15259 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
15260 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15261 << RHSValue.getDecl();
15262 return false;
15263 }
15264
15265 // C++11 [expr.eq]p2:
15266 // If both operands are null, they compare equal. Otherwise if only one is
15267 // null, they compare unequal.
15268 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
15269 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
15270 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15271 }
15272
15273 // Otherwise if either is a pointer to a virtual member function, the
15274 // result is unspecified.
15275 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
15276 if (MD->isVirtual())
15277 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15278 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
15279 if (MD->isVirtual())
15280 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15281
15282 // Otherwise they compare equal if and only if they would refer to the
15283 // same member of the same most derived object or the same subobject if
15284 // they were dereferenced with a hypothetical object of the associated
15285 // class type.
15286 bool Equal = LHSValue == RHSValue;
15287 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15288 }
15289
15290 if (LHSTy->isNullPtrType()) {
15291 assert(E->isComparisonOp() && "unexpected nullptr operation");
15292 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
15293 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
15294 // are compared, the result is true of the operator is <=, >= or ==, and
15295 // false otherwise.
15296 LValue Res;
15297 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
15298 !EvaluatePointer(E->getRHS(), Res, Info))
15299 return false;
15300 return Success(CmpResult::Equal, E);
15301 }
15302
15303 return DoAfter();
15304}
15305
15306bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
15307 if (!CheckLiteralType(Info, E))
15308 return false;
15309
15310 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15312 switch (CR) {
15313 case CmpResult::Unequal:
15314 llvm_unreachable("should never produce Unequal for three-way comparison");
15315 case CmpResult::Less:
15316 CCR = ComparisonCategoryResult::Less;
15317 break;
15318 case CmpResult::Equal:
15319 CCR = ComparisonCategoryResult::Equal;
15320 break;
15321 case CmpResult::Greater:
15322 CCR = ComparisonCategoryResult::Greater;
15323 break;
15324 case CmpResult::Unordered:
15325 CCR = ComparisonCategoryResult::Unordered;
15326 break;
15327 }
15328 // Evaluation succeeded. Lookup the information for the comparison category
15329 // type and fetch the VarDecl for the result.
15330 const ComparisonCategoryInfo &CmpInfo =
15332 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
15333 // Check and evaluate the result as a constant expression.
15334 LValue LV;
15335 LV.set(VD);
15336 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15337 return false;
15338 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15339 ConstantExprKind::Normal);
15340 };
15341 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15342 return ExprEvaluatorBaseTy::VisitBinCmp(E);
15343 });
15344}
15345
15346bool RecordExprEvaluator::VisitCXXParenListInitExpr(
15347 const CXXParenListInitExpr *E) {
15348 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
15349}
15350
15351bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15352 // We don't support assignment in C. C++ assignments don't get here because
15353 // assignment is an lvalue in C++.
15354 if (E->isAssignmentOp()) {
15355 Error(E);
15356 if (!Info.noteFailure())
15357 return false;
15358 }
15359
15360 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
15361 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
15362
15363 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
15364 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
15365 "DataRecursiveIntBinOpEvaluator should have handled integral types");
15366
15367 if (E->isComparisonOp()) {
15368 // Evaluate builtin binary comparisons by evaluating them as three-way
15369 // comparisons and then translating the result.
15370 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15371 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
15372 "should only produce Unequal for equality comparisons");
15373 bool IsEqual = CR == CmpResult::Equal,
15374 IsLess = CR == CmpResult::Less,
15375 IsGreater = CR == CmpResult::Greater;
15376 auto Op = E->getOpcode();
15377 switch (Op) {
15378 default:
15379 llvm_unreachable("unsupported binary operator");
15380 case BO_EQ:
15381 case BO_NE:
15382 return Success(IsEqual == (Op == BO_EQ), E);
15383 case BO_LT:
15384 return Success(IsLess, E);
15385 case BO_GT:
15386 return Success(IsGreater, E);
15387 case BO_LE:
15388 return Success(IsEqual || IsLess, E);
15389 case BO_GE:
15390 return Success(IsEqual || IsGreater, E);
15391 }
15392 };
15393 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15394 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15395 });
15396 }
15397
15398 QualType LHSTy = E->getLHS()->getType();
15399 QualType RHSTy = E->getRHS()->getType();
15400
15401 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
15402 E->getOpcode() == BO_Sub) {
15403 LValue LHSValue, RHSValue;
15404
15405 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15406 if (!LHSOK && !Info.noteFailure())
15407 return false;
15408
15409 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15410 return false;
15411
15412 // Reject differing bases from the normal codepath; we special-case
15413 // comparisons to null.
15414 if (!HasSameBase(LHSValue, RHSValue)) {
15415 if (Info.checkingPotentialConstantExpression() &&
15416 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
15417 return false;
15418
15419 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
15420 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
15421
15422 auto DiagArith = [&](unsigned DiagID) {
15423 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15424 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15425 Info.FFDiag(E, DiagID) << LHS << RHS;
15426 if (LHSExpr && LHSExpr == RHSExpr)
15427 Info.Note(LHSExpr->getExprLoc(),
15428 diag::note_constexpr_repeated_literal_eval)
15429 << LHSExpr->getSourceRange();
15430 return false;
15431 };
15432
15433 if (!LHSExpr || !RHSExpr)
15434 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
15435
15436 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15437 return DiagArith(diag::note_constexpr_literal_arith);
15438
15439 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
15440 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
15441 if (!LHSAddrExpr || !RHSAddrExpr)
15442 return Error(E);
15443 // Make sure both labels come from the same function.
15444 if (LHSAddrExpr->getLabel()->getDeclContext() !=
15445 RHSAddrExpr->getLabel()->getDeclContext())
15446 return Error(E);
15447 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
15448 }
15449 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15450 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15451
15452 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15453 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15454
15455 // C++11 [expr.add]p6:
15456 // Unless both pointers point to elements of the same array object, or
15457 // one past the last element of the array object, the behavior is
15458 // undefined.
15459 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
15460 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
15461 RHSDesignator))
15462 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
15463
15464 QualType Type = E->getLHS()->getType();
15465 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
15466
15467 CharUnits ElementSize;
15468 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
15469 return false;
15470
15471 // As an extension, a type may have zero size (empty struct or union in
15472 // C, array of zero length). Pointer subtraction in such cases has
15473 // undefined behavior, so is not constant.
15474 if (ElementSize.isZero()) {
15475 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
15476 << ElementType;
15477 return false;
15478 }
15479
15480 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
15481 // and produce incorrect results when it overflows. Such behavior
15482 // appears to be non-conforming, but is common, so perhaps we should
15483 // assume the standard intended for such cases to be undefined behavior
15484 // and check for them.
15485
15486 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
15487 // overflow in the final conversion to ptrdiff_t.
15488 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
15489 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
15490 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
15491 false);
15492 APSInt TrueResult = (LHS - RHS) / ElemSize;
15493 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
15494
15495 if (Result.extend(65) != TrueResult &&
15496 !HandleOverflow(Info, E, TrueResult, E->getType()))
15497 return false;
15498 return Success(Result, E);
15499 }
15500
15501 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15502}
15503
15504/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
15505/// a result as the expression's type.
15506bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
15507 const UnaryExprOrTypeTraitExpr *E) {
15508 switch(E->getKind()) {
15509 case UETT_PreferredAlignOf:
15510 case UETT_AlignOf: {
15511 if (E->isArgumentType())
15512 return Success(
15513 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
15514 else
15515 return Success(
15516 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
15517 }
15518
15519 case UETT_PtrAuthTypeDiscriminator: {
15520 if (E->getArgumentType()->isDependentType())
15521 return false;
15522 return Success(
15523 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
15524 }
15525 case UETT_VecStep: {
15526 QualType Ty = E->getTypeOfArgument();
15527
15528 if (Ty->isVectorType()) {
15529 unsigned n = Ty->castAs<VectorType>()->getNumElements();
15530
15531 // The vec_step built-in functions that take a 3-component
15532 // vector return 4. (OpenCL 1.1 spec 6.11.12)
15533 if (n == 3)
15534 n = 4;
15535
15536 return Success(n, E);
15537 } else
15538 return Success(1, E);
15539 }
15540
15541 case UETT_DataSizeOf:
15542 case UETT_SizeOf: {
15543 QualType SrcTy = E->getTypeOfArgument();
15544 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
15545 // the result is the size of the referenced type."
15546 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
15547 SrcTy = Ref->getPointeeType();
15548
15549 CharUnits Sizeof;
15550 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
15551 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
15552 : SizeOfType::SizeOf)) {
15553 return false;
15554 }
15555 return Success(Sizeof, E);
15556 }
15557 case UETT_OpenMPRequiredSimdAlign:
15558 assert(E->isArgumentType());
15559 return Success(
15560 Info.Ctx.toCharUnitsFromBits(
15561 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
15562 .getQuantity(),
15563 E);
15564 case UETT_VectorElements: {
15565 QualType Ty = E->getTypeOfArgument();
15566 // If the vector has a fixed size, we can determine the number of elements
15567 // at compile time.
15568 if (const auto *VT = Ty->getAs<VectorType>())
15569 return Success(VT->getNumElements(), E);
15570
15571 assert(Ty->isSizelessVectorType());
15572 if (Info.InConstantContext)
15573 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
15574 << E->getSourceRange();
15575
15576 return false;
15577 }
15578 case UETT_CountOf: {
15579 QualType Ty = E->getTypeOfArgument();
15580 assert(Ty->isArrayType());
15581
15582 // We don't need to worry about array element qualifiers, so getting the
15583 // unsafe array type is fine.
15584 if (const auto *CAT =
15585 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
15586 return Success(CAT->getSize(), E);
15587 }
15588
15589 assert(!Ty->isConstantSizeType());
15590
15591 // If it's a variable-length array type, we need to check whether it is a
15592 // multidimensional array. If so, we need to check the size expression of
15593 // the VLA to see if it's a constant size. If so, we can return that value.
15594 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
15595 assert(VAT);
15596 if (VAT->getElementType()->isArrayType()) {
15597 // Variable array size expression could be missing (e.g. int a[*][10]) In
15598 // that case, it can't be a constant expression.
15599 if (!VAT->getSizeExpr()) {
15600 Info.FFDiag(E->getBeginLoc());
15601 return false;
15602 }
15603
15604 std::optional<APSInt> Res =
15605 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
15606 if (Res) {
15607 // The resulting value always has type size_t, so we need to make the
15608 // returned APInt have the correct sign and bit-width.
15609 APInt Val{
15610 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
15611 Res->getZExtValue()};
15612 return Success(Val, E);
15613 }
15614 }
15615
15616 // Definitely a variable-length type, which is not an ICE.
15617 // FIXME: Better diagnostic.
15618 Info.FFDiag(E->getBeginLoc());
15619 return false;
15620 }
15621 }
15622
15623 llvm_unreachable("unknown expr/type trait");
15624}
15625
15626bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
15627 CharUnits Result;
15628 unsigned n = OOE->getNumComponents();
15629 if (n == 0)
15630 return Error(OOE);
15631 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
15632 for (unsigned i = 0; i != n; ++i) {
15633 OffsetOfNode ON = OOE->getComponent(i);
15634 switch (ON.getKind()) {
15635 case OffsetOfNode::Array: {
15636 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
15637 APSInt IdxResult;
15638 if (!EvaluateInteger(Idx, IdxResult, Info))
15639 return false;
15640 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
15641 if (!AT)
15642 return Error(OOE);
15643 CurrentType = AT->getElementType();
15644 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
15645 Result += IdxResult.getSExtValue() * ElementSize;
15646 break;
15647 }
15648
15649 case OffsetOfNode::Field: {
15650 FieldDecl *MemberDecl = ON.getField();
15651 const auto *RD = CurrentType->getAsRecordDecl();
15652 if (!RD)
15653 return Error(OOE);
15654 if (RD->isInvalidDecl()) return false;
15655 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15656 unsigned i = MemberDecl->getFieldIndex();
15657 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
15658 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
15659 CurrentType = MemberDecl->getType().getNonReferenceType();
15660 break;
15661 }
15662
15664 llvm_unreachable("dependent __builtin_offsetof");
15665
15666 case OffsetOfNode::Base: {
15667 CXXBaseSpecifier *BaseSpec = ON.getBase();
15668 if (BaseSpec->isVirtual())
15669 return Error(OOE);
15670
15671 // Find the layout of the class whose base we are looking into.
15672 const auto *RD = CurrentType->getAsCXXRecordDecl();
15673 if (!RD)
15674 return Error(OOE);
15675 if (RD->isInvalidDecl()) return false;
15676 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15677
15678 // Find the base class itself.
15679 CurrentType = BaseSpec->getType();
15680 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
15681 if (!BaseRD)
15682 return Error(OOE);
15683
15684 // Add the offset to the base.
15685 Result += RL.getBaseClassOffset(BaseRD);
15686 break;
15687 }
15688 }
15689 }
15690 return Success(Result, OOE);
15691}
15692
15693bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15694 switch (E->getOpcode()) {
15695 default:
15696 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
15697 // See C99 6.6p3.
15698 return Error(E);
15699 case UO_Extension:
15700 // FIXME: Should extension allow i-c-e extension expressions in its scope?
15701 // If so, we could clear the diagnostic ID.
15702 return Visit(E->getSubExpr());
15703 case UO_Plus:
15704 // The result is just the value.
15705 return Visit(E->getSubExpr());
15706 case UO_Minus: {
15707 if (!Visit(E->getSubExpr()))
15708 return false;
15709 if (!Result.isInt()) return Error(E);
15710 const APSInt &Value = Result.getInt();
15711 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
15712 if (Info.checkingForUndefinedBehavior())
15713 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15714 diag::warn_integer_constant_overflow)
15715 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
15716 /*UpperCase=*/true, /*InsertSeparators=*/true)
15717 << E->getType() << E->getSourceRange();
15718
15719 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
15720 E->getType()))
15721 return false;
15722 }
15723 return Success(-Value, E);
15724 }
15725 case UO_Not: {
15726 if (!Visit(E->getSubExpr()))
15727 return false;
15728 if (!Result.isInt()) return Error(E);
15729 return Success(~Result.getInt(), E);
15730 }
15731 case UO_LNot: {
15732 bool bres;
15733 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15734 return false;
15735 return Success(!bres, E);
15736 }
15737 }
15738}
15739
15740/// HandleCast - This is used to evaluate implicit or explicit casts where the
15741/// result type is integer.
15742bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
15743 const Expr *SubExpr = E->getSubExpr();
15744 QualType DestType = E->getType();
15745 QualType SrcType = SubExpr->getType();
15746
15747 switch (E->getCastKind()) {
15748 case CK_BaseToDerived:
15749 case CK_DerivedToBase:
15750 case CK_UncheckedDerivedToBase:
15751 case CK_Dynamic:
15752 case CK_ToUnion:
15753 case CK_ArrayToPointerDecay:
15754 case CK_FunctionToPointerDecay:
15755 case CK_NullToPointer:
15756 case CK_NullToMemberPointer:
15757 case CK_BaseToDerivedMemberPointer:
15758 case CK_DerivedToBaseMemberPointer:
15759 case CK_ReinterpretMemberPointer:
15760 case CK_ConstructorConversion:
15761 case CK_IntegralToPointer:
15762 case CK_ToVoid:
15763 case CK_VectorSplat:
15764 case CK_IntegralToFloating:
15765 case CK_FloatingCast:
15766 case CK_CPointerToObjCPointerCast:
15767 case CK_BlockPointerToObjCPointerCast:
15768 case CK_AnyPointerToBlockPointerCast:
15769 case CK_ObjCObjectLValueCast:
15770 case CK_FloatingRealToComplex:
15771 case CK_FloatingComplexToReal:
15772 case CK_FloatingComplexCast:
15773 case CK_FloatingComplexToIntegralComplex:
15774 case CK_IntegralRealToComplex:
15775 case CK_IntegralComplexCast:
15776 case CK_IntegralComplexToFloatingComplex:
15777 case CK_BuiltinFnToFnPtr:
15778 case CK_ZeroToOCLOpaqueType:
15779 case CK_NonAtomicToAtomic:
15780 case CK_AddressSpaceConversion:
15781 case CK_IntToOCLSampler:
15782 case CK_FloatingToFixedPoint:
15783 case CK_FixedPointToFloating:
15784 case CK_FixedPointCast:
15785 case CK_IntegralToFixedPoint:
15786 case CK_MatrixCast:
15787 case CK_HLSLAggregateSplatCast:
15788 llvm_unreachable("invalid cast kind for integral value");
15789
15790 case CK_BitCast:
15791 case CK_Dependent:
15792 case CK_LValueBitCast:
15793 case CK_ARCProduceObject:
15794 case CK_ARCConsumeObject:
15795 case CK_ARCReclaimReturnedObject:
15796 case CK_ARCExtendBlockObject:
15797 case CK_CopyAndAutoreleaseBlockObject:
15798 return Error(E);
15799
15800 case CK_UserDefinedConversion:
15801 case CK_LValueToRValue:
15802 case CK_AtomicToNonAtomic:
15803 case CK_NoOp:
15804 case CK_LValueToRValueBitCast:
15805 case CK_HLSLArrayRValue:
15806 case CK_HLSLElementwiseCast:
15807 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15808
15809 case CK_MemberPointerToBoolean:
15810 case CK_PointerToBoolean:
15811 case CK_IntegralToBoolean:
15812 case CK_FloatingToBoolean:
15813 case CK_BooleanToSignedIntegral:
15814 case CK_FloatingComplexToBoolean:
15815 case CK_IntegralComplexToBoolean: {
15816 bool BoolResult;
15817 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
15818 return false;
15819 uint64_t IntResult = BoolResult;
15820 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
15821 IntResult = (uint64_t)-1;
15822 return Success(IntResult, E);
15823 }
15824
15825 case CK_FixedPointToIntegral: {
15826 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
15827 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15828 return false;
15829 bool Overflowed;
15830 llvm::APSInt Result = Src.convertToInt(
15831 Info.Ctx.getIntWidth(DestType),
15832 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
15833 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
15834 return false;
15835 return Success(Result, E);
15836 }
15837
15838 case CK_FixedPointToBoolean: {
15839 // Unsigned padding does not affect this.
15840 APValue Val;
15841 if (!Evaluate(Val, Info, SubExpr))
15842 return false;
15843 return Success(Val.getFixedPoint().getBoolValue(), E);
15844 }
15845
15846 case CK_IntegralCast: {
15847 if (!Visit(SubExpr))
15848 return false;
15849
15850 if (!Result.isInt()) {
15851 // Allow casts of address-of-label differences if they are no-ops
15852 // or narrowing. (The narrowing case isn't actually guaranteed to
15853 // be constant-evaluatable except in some narrow cases which are hard
15854 // to detect here. We let it through on the assumption the user knows
15855 // what they are doing.)
15856 if (Result.isAddrLabelDiff())
15857 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
15858 // Only allow casts of lvalues if they are lossless.
15859 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
15860 }
15861
15862 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
15863 const auto *ED = DestType->getAsEnumDecl();
15864 // Check that the value is within the range of the enumeration values.
15865 //
15866 // This corressponds to [expr.static.cast]p10 which says:
15867 // A value of integral or enumeration type can be explicitly converted
15868 // to a complete enumeration type ... If the enumeration type does not
15869 // have a fixed underlying type, the value is unchanged if the original
15870 // value is within the range of the enumeration values ([dcl.enum]), and
15871 // otherwise, the behavior is undefined.
15872 //
15873 // This was resolved as part of DR2338 which has CD5 status.
15874 if (!ED->isFixed()) {
15875 llvm::APInt Min;
15876 llvm::APInt Max;
15877
15878 ED->getValueRange(Max, Min);
15879 --Max;
15880
15881 if (ED->getNumNegativeBits() &&
15882 (Max.slt(Result.getInt().getSExtValue()) ||
15883 Min.sgt(Result.getInt().getSExtValue())))
15884 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15885 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
15886 << Max.getSExtValue() << ED;
15887 else if (!ED->getNumNegativeBits() &&
15888 Max.ult(Result.getInt().getZExtValue()))
15889 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15890 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
15891 << Max.getZExtValue() << ED;
15892 }
15893 }
15894
15895 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
15896 Result.getInt()), E);
15897 }
15898
15899 case CK_PointerToIntegral: {
15900 CCEDiag(E, diag::note_constexpr_invalid_cast)
15901 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
15902 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
15903
15904 LValue LV;
15905 if (!EvaluatePointer(SubExpr, LV, Info))
15906 return false;
15907
15908 if (LV.getLValueBase()) {
15909 // Only allow based lvalue casts if they are lossless.
15910 // FIXME: Allow a larger integer size than the pointer size, and allow
15911 // narrowing back down to pointer width in subsequent integral casts.
15912 // FIXME: Check integer type's active bits, not its type size.
15913 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
15914 return Error(E);
15915
15916 LV.Designator.setInvalid();
15917 LV.moveInto(Result);
15918 return true;
15919 }
15920
15921 APSInt AsInt;
15922 APValue V;
15923 LV.moveInto(V);
15924 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
15925 llvm_unreachable("Can't cast this!");
15926
15927 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
15928 }
15929
15930 case CK_IntegralComplexToReal: {
15931 ComplexValue C;
15932 if (!EvaluateComplex(SubExpr, C, Info))
15933 return false;
15934 return Success(C.getComplexIntReal(), E);
15935 }
15936
15937 case CK_FloatingToIntegral: {
15938 APFloat F(0.0);
15939 if (!EvaluateFloat(SubExpr, F, Info))
15940 return false;
15941
15942 APSInt Value;
15943 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
15944 return false;
15945 return Success(Value, E);
15946 }
15947 case CK_HLSLVectorTruncation: {
15948 APValue Val;
15949 if (!EvaluateVector(SubExpr, Val, Info))
15950 return Error(E);
15951 return Success(Val.getVectorElt(0), E);
15952 }
15953 }
15954
15955 llvm_unreachable("unknown cast resulting in integral value");
15956}
15957
15958bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15959 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15960 ComplexValue LV;
15961 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15962 return false;
15963 if (!LV.isComplexInt())
15964 return Error(E);
15965 return Success(LV.getComplexIntReal(), E);
15966 }
15967
15968 return Visit(E->getSubExpr());
15969}
15970
15971bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15972 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
15973 ComplexValue LV;
15974 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15975 return false;
15976 if (!LV.isComplexInt())
15977 return Error(E);
15978 return Success(LV.getComplexIntImag(), E);
15979 }
15980
15981 VisitIgnoredValue(E->getSubExpr());
15982 return Success(0, E);
15983}
15984
15985bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
15986 return Success(E->getPackLength(), E);
15987}
15988
15989bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
15990 return Success(E->getValue(), E);
15991}
15992
15993bool IntExprEvaluator::VisitConceptSpecializationExpr(
15995 return Success(E->isSatisfied(), E);
15996}
15997
15998bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
15999 return Success(E->isSatisfied(), E);
16000}
16001
16002bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16003 switch (E->getOpcode()) {
16004 default:
16005 // Invalid unary operators
16006 return Error(E);
16007 case UO_Plus:
16008 // The result is just the value.
16009 return Visit(E->getSubExpr());
16010 case UO_Minus: {
16011 if (!Visit(E->getSubExpr())) return false;
16012 if (!Result.isFixedPoint())
16013 return Error(E);
16014 bool Overflowed;
16015 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
16016 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
16017 return false;
16018 return Success(Negated, E);
16019 }
16020 case UO_LNot: {
16021 bool bres;
16022 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
16023 return false;
16024 return Success(!bres, E);
16025 }
16026 }
16027}
16028
16029bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
16030 const Expr *SubExpr = E->getSubExpr();
16031 QualType DestType = E->getType();
16032 assert(DestType->isFixedPointType() &&
16033 "Expected destination type to be a fixed point type");
16034 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
16035
16036 switch (E->getCastKind()) {
16037 case CK_FixedPointCast: {
16038 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
16039 if (!EvaluateFixedPoint(SubExpr, Src, Info))
16040 return false;
16041 bool Overflowed;
16042 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
16043 if (Overflowed) {
16044 if (Info.checkingForUndefinedBehavior())
16045 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16046 diag::warn_fixedpoint_constant_overflow)
16047 << Result.toString() << E->getType();
16048 if (!HandleOverflow(Info, E, Result, E->getType()))
16049 return false;
16050 }
16051 return Success(Result, E);
16052 }
16053 case CK_IntegralToFixedPoint: {
16054 APSInt Src;
16055 if (!EvaluateInteger(SubExpr, Src, Info))
16056 return false;
16057
16058 bool Overflowed;
16059 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
16060 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
16061
16062 if (Overflowed) {
16063 if (Info.checkingForUndefinedBehavior())
16064 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16065 diag::warn_fixedpoint_constant_overflow)
16066 << IntResult.toString() << E->getType();
16067 if (!HandleOverflow(Info, E, IntResult, E->getType()))
16068 return false;
16069 }
16070
16071 return Success(IntResult, E);
16072 }
16073 case CK_FloatingToFixedPoint: {
16074 APFloat Src(0.0);
16075 if (!EvaluateFloat(SubExpr, Src, Info))
16076 return false;
16077
16078 bool Overflowed;
16079 APFixedPoint Result = APFixedPoint::getFromFloatValue(
16080 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
16081
16082 if (Overflowed) {
16083 if (Info.checkingForUndefinedBehavior())
16084 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16085 diag::warn_fixedpoint_constant_overflow)
16086 << Result.toString() << E->getType();
16087 if (!HandleOverflow(Info, E, Result, E->getType()))
16088 return false;
16089 }
16090
16091 return Success(Result, E);
16092 }
16093 case CK_NoOp:
16094 case CK_LValueToRValue:
16095 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16096 default:
16097 return Error(E);
16098 }
16099}
16100
16101bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16102 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16103 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16104
16105 const Expr *LHS = E->getLHS();
16106 const Expr *RHS = E->getRHS();
16107 FixedPointSemantics ResultFXSema =
16108 Info.Ctx.getFixedPointSemantics(E->getType());
16109
16110 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
16111 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
16112 return false;
16113 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
16114 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
16115 return false;
16116
16117 bool OpOverflow = false, ConversionOverflow = false;
16118 APFixedPoint Result(LHSFX.getSemantics());
16119 switch (E->getOpcode()) {
16120 case BO_Add: {
16121 Result = LHSFX.add(RHSFX, &OpOverflow)
16122 .convert(ResultFXSema, &ConversionOverflow);
16123 break;
16124 }
16125 case BO_Sub: {
16126 Result = LHSFX.sub(RHSFX, &OpOverflow)
16127 .convert(ResultFXSema, &ConversionOverflow);
16128 break;
16129 }
16130 case BO_Mul: {
16131 Result = LHSFX.mul(RHSFX, &OpOverflow)
16132 .convert(ResultFXSema, &ConversionOverflow);
16133 break;
16134 }
16135 case BO_Div: {
16136 if (RHSFX.getValue() == 0) {
16137 Info.FFDiag(E, diag::note_expr_divide_by_zero);
16138 return false;
16139 }
16140 Result = LHSFX.div(RHSFX, &OpOverflow)
16141 .convert(ResultFXSema, &ConversionOverflow);
16142 break;
16143 }
16144 case BO_Shl:
16145 case BO_Shr: {
16146 FixedPointSemantics LHSSema = LHSFX.getSemantics();
16147 llvm::APSInt RHSVal = RHSFX.getValue();
16148
16149 unsigned ShiftBW =
16150 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
16151 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
16152 // Embedded-C 4.1.6.2.2:
16153 // The right operand must be nonnegative and less than the total number
16154 // of (nonpadding) bits of the fixed-point operand ...
16155 if (RHSVal.isNegative())
16156 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
16157 else if (Amt != RHSVal)
16158 Info.CCEDiag(E, diag::note_constexpr_large_shift)
16159 << RHSVal << E->getType() << ShiftBW;
16160
16161 if (E->getOpcode() == BO_Shl)
16162 Result = LHSFX.shl(Amt, &OpOverflow);
16163 else
16164 Result = LHSFX.shr(Amt, &OpOverflow);
16165 break;
16166 }
16167 default:
16168 return false;
16169 }
16170 if (OpOverflow || ConversionOverflow) {
16171 if (Info.checkingForUndefinedBehavior())
16172 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16173 diag::warn_fixedpoint_constant_overflow)
16174 << Result.toString() << E->getType();
16175 if (!HandleOverflow(Info, E, Result, E->getType()))
16176 return false;
16177 }
16178 return Success(Result, E);
16179}
16180
16181//===----------------------------------------------------------------------===//
16182// Float Evaluation
16183//===----------------------------------------------------------------------===//
16184
16185namespace {
16186class FloatExprEvaluator
16187 : public ExprEvaluatorBase<FloatExprEvaluator> {
16188 APFloat &Result;
16189public:
16190 FloatExprEvaluator(EvalInfo &info, APFloat &result)
16191 : ExprEvaluatorBaseTy(info), Result(result) {}
16192
16193 bool Success(const APValue &V, const Expr *e) {
16194 Result = V.getFloat();
16195 return true;
16196 }
16197
16198 bool ZeroInitialization(const Expr *E) {
16199 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
16200 return true;
16201 }
16202
16203 bool VisitCallExpr(const CallExpr *E);
16204
16205 bool VisitUnaryOperator(const UnaryOperator *E);
16206 bool VisitBinaryOperator(const BinaryOperator *E);
16207 bool VisitFloatingLiteral(const FloatingLiteral *E);
16208 bool VisitCastExpr(const CastExpr *E);
16209
16210 bool VisitUnaryReal(const UnaryOperator *E);
16211 bool VisitUnaryImag(const UnaryOperator *E);
16212
16213 // FIXME: Missing: array subscript of vector, member of vector
16214};
16215} // end anonymous namespace
16216
16217static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
16218 assert(!E->isValueDependent());
16219 assert(E->isPRValue() && E->getType()->isRealFloatingType());
16220 return FloatExprEvaluator(Info, Result).Visit(E);
16221}
16222
16223static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
16224 QualType ResultTy,
16225 const Expr *Arg,
16226 bool SNaN,
16227 llvm::APFloat &Result) {
16228 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
16229 if (!S) return false;
16230
16231 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
16232
16233 llvm::APInt fill;
16234
16235 // Treat empty strings as if they were zero.
16236 if (S->getString().empty())
16237 fill = llvm::APInt(32, 0);
16238 else if (S->getString().getAsInteger(0, fill))
16239 return false;
16240
16241 if (Context.getTargetInfo().isNan2008()) {
16242 if (SNaN)
16243 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16244 else
16245 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16246 } else {
16247 // Prior to IEEE 754-2008, architectures were allowed to choose whether
16248 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
16249 // a different encoding to what became a standard in 2008, and for pre-
16250 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
16251 // sNaN. This is now known as "legacy NaN" encoding.
16252 if (SNaN)
16253 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16254 else
16255 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16256 }
16257
16258 return true;
16259}
16260
16261bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
16262 if (!IsConstantEvaluatedBuiltinCall(E))
16263 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16264
16265 switch (E->getBuiltinCallee()) {
16266 default:
16267 return false;
16268
16269 case Builtin::BI__builtin_huge_val:
16270 case Builtin::BI__builtin_huge_valf:
16271 case Builtin::BI__builtin_huge_vall:
16272 case Builtin::BI__builtin_huge_valf16:
16273 case Builtin::BI__builtin_huge_valf128:
16274 case Builtin::BI__builtin_inf:
16275 case Builtin::BI__builtin_inff:
16276 case Builtin::BI__builtin_infl:
16277 case Builtin::BI__builtin_inff16:
16278 case Builtin::BI__builtin_inff128: {
16279 const llvm::fltSemantics &Sem =
16280 Info.Ctx.getFloatTypeSemantics(E->getType());
16281 Result = llvm::APFloat::getInf(Sem);
16282 return true;
16283 }
16284
16285 case Builtin::BI__builtin_nans:
16286 case Builtin::BI__builtin_nansf:
16287 case Builtin::BI__builtin_nansl:
16288 case Builtin::BI__builtin_nansf16:
16289 case Builtin::BI__builtin_nansf128:
16290 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16291 true, Result))
16292 return Error(E);
16293 return true;
16294
16295 case Builtin::BI__builtin_nan:
16296 case Builtin::BI__builtin_nanf:
16297 case Builtin::BI__builtin_nanl:
16298 case Builtin::BI__builtin_nanf16:
16299 case Builtin::BI__builtin_nanf128:
16300 // If this is __builtin_nan() turn this into a nan, otherwise we
16301 // can't constant fold it.
16302 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16303 false, Result))
16304 return Error(E);
16305 return true;
16306
16307 case Builtin::BI__builtin_elementwise_abs:
16308 case Builtin::BI__builtin_fabs:
16309 case Builtin::BI__builtin_fabsf:
16310 case Builtin::BI__builtin_fabsl:
16311 case Builtin::BI__builtin_fabsf128:
16312 // The C standard says "fabs raises no floating-point exceptions,
16313 // even if x is a signaling NaN. The returned value is independent of
16314 // the current rounding direction mode." Therefore constant folding can
16315 // proceed without regard to the floating point settings.
16316 // Reference, WG14 N2478 F.10.4.3
16317 if (!EvaluateFloat(E->getArg(0), Result, Info))
16318 return false;
16319
16320 if (Result.isNegative())
16321 Result.changeSign();
16322 return true;
16323
16324 case Builtin::BI__arithmetic_fence:
16325 return EvaluateFloat(E->getArg(0), Result, Info);
16326
16327 // FIXME: Builtin::BI__builtin_powi
16328 // FIXME: Builtin::BI__builtin_powif
16329 // FIXME: Builtin::BI__builtin_powil
16330
16331 case Builtin::BI__builtin_copysign:
16332 case Builtin::BI__builtin_copysignf:
16333 case Builtin::BI__builtin_copysignl:
16334 case Builtin::BI__builtin_copysignf128: {
16335 APFloat RHS(0.);
16336 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16337 !EvaluateFloat(E->getArg(1), RHS, Info))
16338 return false;
16339 Result.copySign(RHS);
16340 return true;
16341 }
16342
16343 case Builtin::BI__builtin_fmax:
16344 case Builtin::BI__builtin_fmaxf:
16345 case Builtin::BI__builtin_fmaxl:
16346 case Builtin::BI__builtin_fmaxf16:
16347 case Builtin::BI__builtin_fmaxf128: {
16348 APFloat RHS(0.);
16349 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16350 !EvaluateFloat(E->getArg(1), RHS, Info))
16351 return false;
16352 Result = maxnum(Result, RHS);
16353 return true;
16354 }
16355
16356 case Builtin::BI__builtin_fmin:
16357 case Builtin::BI__builtin_fminf:
16358 case Builtin::BI__builtin_fminl:
16359 case Builtin::BI__builtin_fminf16:
16360 case Builtin::BI__builtin_fminf128: {
16361 APFloat RHS(0.);
16362 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16363 !EvaluateFloat(E->getArg(1), RHS, Info))
16364 return false;
16365 Result = minnum(Result, RHS);
16366 return true;
16367 }
16368
16369 case Builtin::BI__builtin_fmaximum_num:
16370 case Builtin::BI__builtin_fmaximum_numf:
16371 case Builtin::BI__builtin_fmaximum_numl:
16372 case Builtin::BI__builtin_fmaximum_numf16:
16373 case Builtin::BI__builtin_fmaximum_numf128: {
16374 APFloat RHS(0.);
16375 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16376 !EvaluateFloat(E->getArg(1), RHS, Info))
16377 return false;
16378 Result = maximumnum(Result, RHS);
16379 return true;
16380 }
16381
16382 case Builtin::BI__builtin_fminimum_num:
16383 case Builtin::BI__builtin_fminimum_numf:
16384 case Builtin::BI__builtin_fminimum_numl:
16385 case Builtin::BI__builtin_fminimum_numf16:
16386 case Builtin::BI__builtin_fminimum_numf128: {
16387 APFloat RHS(0.);
16388 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16389 !EvaluateFloat(E->getArg(1), RHS, Info))
16390 return false;
16391 Result = minimumnum(Result, RHS);
16392 return true;
16393 }
16394
16395 case Builtin::BI__builtin_elementwise_fma: {
16396 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
16397 !E->getArg(2)->isPRValue()) {
16398 return false;
16399 }
16400 APFloat SourceY(0.), SourceZ(0.);
16401 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16402 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
16403 !EvaluateFloat(E->getArg(2), SourceZ, Info))
16404 return false;
16405 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
16406 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
16407 return true;
16408 }
16409 }
16410}
16411
16412bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
16413 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16414 ComplexValue CV;
16415 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16416 return false;
16417 Result = CV.FloatReal;
16418 return true;
16419 }
16420
16421 return Visit(E->getSubExpr());
16422}
16423
16424bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
16425 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16426 ComplexValue CV;
16427 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16428 return false;
16429 Result = CV.FloatImag;
16430 return true;
16431 }
16432
16433 VisitIgnoredValue(E->getSubExpr());
16434 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
16435 Result = llvm::APFloat::getZero(Sem);
16436 return true;
16437}
16438
16439bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16440 switch (E->getOpcode()) {
16441 default: return Error(E);
16442 case UO_Plus:
16443 return EvaluateFloat(E->getSubExpr(), Result, Info);
16444 case UO_Minus:
16445 // In C standard, WG14 N2478 F.3 p4
16446 // "the unary - raises no floating point exceptions,
16447 // even if the operand is signalling."
16448 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
16449 return false;
16450 Result.changeSign();
16451 return true;
16452 }
16453}
16454
16455bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16456 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16457 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16458
16459 APFloat RHS(0.0);
16460 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
16461 if (!LHSOK && !Info.noteFailure())
16462 return false;
16463 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
16464 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
16465}
16466
16467bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
16468 Result = E->getValue();
16469 return true;
16470}
16471
16472bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
16473 const Expr* SubExpr = E->getSubExpr();
16474
16475 switch (E->getCastKind()) {
16476 default:
16477 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16478
16479 case CK_IntegralToFloating: {
16480 APSInt IntResult;
16481 const FPOptions FPO = E->getFPFeaturesInEffect(
16482 Info.Ctx.getLangOpts());
16483 return EvaluateInteger(SubExpr, IntResult, Info) &&
16484 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
16485 IntResult, E->getType(), Result);
16486 }
16487
16488 case CK_FixedPointToFloating: {
16489 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
16490 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
16491 return false;
16492 Result =
16493 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
16494 return true;
16495 }
16496
16497 case CK_FloatingCast: {
16498 if (!Visit(SubExpr))
16499 return false;
16500 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
16501 Result);
16502 }
16503
16504 case CK_FloatingComplexToReal: {
16505 ComplexValue V;
16506 if (!EvaluateComplex(SubExpr, V, Info))
16507 return false;
16508 Result = V.getComplexFloatReal();
16509 return true;
16510 }
16511 case CK_HLSLVectorTruncation: {
16512 APValue Val;
16513 if (!EvaluateVector(SubExpr, Val, Info))
16514 return Error(E);
16515 return Success(Val.getVectorElt(0), E);
16516 }
16517 }
16518}
16519
16520//===----------------------------------------------------------------------===//
16521// Complex Evaluation (for float and integer)
16522//===----------------------------------------------------------------------===//
16523
16524namespace {
16525class ComplexExprEvaluator
16526 : public ExprEvaluatorBase<ComplexExprEvaluator> {
16527 ComplexValue &Result;
16528
16529public:
16530 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
16531 : ExprEvaluatorBaseTy(info), Result(Result) {}
16532
16533 bool Success(const APValue &V, const Expr *e) {
16534 Result.setFrom(V);
16535 return true;
16536 }
16537
16538 bool ZeroInitialization(const Expr *E);
16539
16540 //===--------------------------------------------------------------------===//
16541 // Visitor Methods
16542 //===--------------------------------------------------------------------===//
16543
16544 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
16545 bool VisitCastExpr(const CastExpr *E);
16546 bool VisitBinaryOperator(const BinaryOperator *E);
16547 bool VisitUnaryOperator(const UnaryOperator *E);
16548 bool VisitInitListExpr(const InitListExpr *E);
16549 bool VisitCallExpr(const CallExpr *E);
16550};
16551} // end anonymous namespace
16552
16553static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
16554 EvalInfo &Info) {
16555 assert(!E->isValueDependent());
16556 assert(E->isPRValue() && E->getType()->isAnyComplexType());
16557 return ComplexExprEvaluator(Info, Result).Visit(E);
16558}
16559
16560bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
16561 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
16562 if (ElemTy->isRealFloatingType()) {
16563 Result.makeComplexFloat();
16564 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
16565 Result.FloatReal = Zero;
16566 Result.FloatImag = Zero;
16567 } else {
16568 Result.makeComplexInt();
16569 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
16570 Result.IntReal = Zero;
16571 Result.IntImag = Zero;
16572 }
16573 return true;
16574}
16575
16576bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
16577 const Expr* SubExpr = E->getSubExpr();
16578
16579 if (SubExpr->getType()->isRealFloatingType()) {
16580 Result.makeComplexFloat();
16581 APFloat &Imag = Result.FloatImag;
16582 if (!EvaluateFloat(SubExpr, Imag, Info))
16583 return false;
16584
16585 Result.FloatReal = APFloat(Imag.getSemantics());
16586 return true;
16587 } else {
16588 assert(SubExpr->getType()->isIntegerType() &&
16589 "Unexpected imaginary literal.");
16590
16591 Result.makeComplexInt();
16592 APSInt &Imag = Result.IntImag;
16593 if (!EvaluateInteger(SubExpr, Imag, Info))
16594 return false;
16595
16596 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
16597 return true;
16598 }
16599}
16600
16601bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
16602
16603 switch (E->getCastKind()) {
16604 case CK_BitCast:
16605 case CK_BaseToDerived:
16606 case CK_DerivedToBase:
16607 case CK_UncheckedDerivedToBase:
16608 case CK_Dynamic:
16609 case CK_ToUnion:
16610 case CK_ArrayToPointerDecay:
16611 case CK_FunctionToPointerDecay:
16612 case CK_NullToPointer:
16613 case CK_NullToMemberPointer:
16614 case CK_BaseToDerivedMemberPointer:
16615 case CK_DerivedToBaseMemberPointer:
16616 case CK_MemberPointerToBoolean:
16617 case CK_ReinterpretMemberPointer:
16618 case CK_ConstructorConversion:
16619 case CK_IntegralToPointer:
16620 case CK_PointerToIntegral:
16621 case CK_PointerToBoolean:
16622 case CK_ToVoid:
16623 case CK_VectorSplat:
16624 case CK_IntegralCast:
16625 case CK_BooleanToSignedIntegral:
16626 case CK_IntegralToBoolean:
16627 case CK_IntegralToFloating:
16628 case CK_FloatingToIntegral:
16629 case CK_FloatingToBoolean:
16630 case CK_FloatingCast:
16631 case CK_CPointerToObjCPointerCast:
16632 case CK_BlockPointerToObjCPointerCast:
16633 case CK_AnyPointerToBlockPointerCast:
16634 case CK_ObjCObjectLValueCast:
16635 case CK_FloatingComplexToReal:
16636 case CK_FloatingComplexToBoolean:
16637 case CK_IntegralComplexToReal:
16638 case CK_IntegralComplexToBoolean:
16639 case CK_ARCProduceObject:
16640 case CK_ARCConsumeObject:
16641 case CK_ARCReclaimReturnedObject:
16642 case CK_ARCExtendBlockObject:
16643 case CK_CopyAndAutoreleaseBlockObject:
16644 case CK_BuiltinFnToFnPtr:
16645 case CK_ZeroToOCLOpaqueType:
16646 case CK_NonAtomicToAtomic:
16647 case CK_AddressSpaceConversion:
16648 case CK_IntToOCLSampler:
16649 case CK_FloatingToFixedPoint:
16650 case CK_FixedPointToFloating:
16651 case CK_FixedPointCast:
16652 case CK_FixedPointToBoolean:
16653 case CK_FixedPointToIntegral:
16654 case CK_IntegralToFixedPoint:
16655 case CK_MatrixCast:
16656 case CK_HLSLVectorTruncation:
16657 case CK_HLSLElementwiseCast:
16658 case CK_HLSLAggregateSplatCast:
16659 llvm_unreachable("invalid cast kind for complex value");
16660
16661 case CK_LValueToRValue:
16662 case CK_AtomicToNonAtomic:
16663 case CK_NoOp:
16664 case CK_LValueToRValueBitCast:
16665 case CK_HLSLArrayRValue:
16666 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16667
16668 case CK_Dependent:
16669 case CK_LValueBitCast:
16670 case CK_UserDefinedConversion:
16671 return Error(E);
16672
16673 case CK_FloatingRealToComplex: {
16674 APFloat &Real = Result.FloatReal;
16675 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
16676 return false;
16677
16678 Result.makeComplexFloat();
16679 Result.FloatImag = APFloat(Real.getSemantics());
16680 return true;
16681 }
16682
16683 case CK_FloatingComplexCast: {
16684 if (!Visit(E->getSubExpr()))
16685 return false;
16686
16687 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16688 QualType From
16689 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16690
16691 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
16692 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
16693 }
16694
16695 case CK_FloatingComplexToIntegralComplex: {
16696 if (!Visit(E->getSubExpr()))
16697 return false;
16698
16699 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16700 QualType From
16701 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16702 Result.makeComplexInt();
16703 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
16704 To, Result.IntReal) &&
16705 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
16706 To, Result.IntImag);
16707 }
16708
16709 case CK_IntegralRealToComplex: {
16710 APSInt &Real = Result.IntReal;
16711 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
16712 return false;
16713
16714 Result.makeComplexInt();
16715 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
16716 return true;
16717 }
16718
16719 case CK_IntegralComplexCast: {
16720 if (!Visit(E->getSubExpr()))
16721 return false;
16722
16723 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16724 QualType From
16725 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16726
16727 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
16728 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
16729 return true;
16730 }
16731
16732 case CK_IntegralComplexToFloatingComplex: {
16733 if (!Visit(E->getSubExpr()))
16734 return false;
16735
16736 const FPOptions FPO = E->getFPFeaturesInEffect(
16737 Info.Ctx.getLangOpts());
16738 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16739 QualType From
16740 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16741 Result.makeComplexFloat();
16742 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
16743 To, Result.FloatReal) &&
16744 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
16745 To, Result.FloatImag);
16746 }
16747 }
16748
16749 llvm_unreachable("unknown cast resulting in complex value");
16750}
16751
16752void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
16753 APFloat &ResR, APFloat &ResI) {
16754 // This is an implementation of complex multiplication according to the
16755 // constraints laid out in C11 Annex G. The implementation uses the
16756 // following naming scheme:
16757 // (a + ib) * (c + id)
16758
16759 APFloat AC = A * C;
16760 APFloat BD = B * D;
16761 APFloat AD = A * D;
16762 APFloat BC = B * C;
16763 ResR = AC - BD;
16764 ResI = AD + BC;
16765 if (ResR.isNaN() && ResI.isNaN()) {
16766 bool Recalc = false;
16767 if (A.isInfinity() || B.isInfinity()) {
16768 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16769 A);
16770 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16771 B);
16772 if (C.isNaN())
16773 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16774 if (D.isNaN())
16775 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16776 Recalc = true;
16777 }
16778 if (C.isInfinity() || D.isInfinity()) {
16779 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16780 C);
16781 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16782 D);
16783 if (A.isNaN())
16784 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16785 if (B.isNaN())
16786 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16787 Recalc = true;
16788 }
16789 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
16790 BC.isInfinity())) {
16791 if (A.isNaN())
16792 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16793 if (B.isNaN())
16794 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16795 if (C.isNaN())
16796 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16797 if (D.isNaN())
16798 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16799 Recalc = true;
16800 }
16801 if (Recalc) {
16802 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
16803 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
16804 }
16805 }
16806}
16807
16808void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
16809 APFloat &ResR, APFloat &ResI) {
16810 // This is an implementation of complex division according to the
16811 // constraints laid out in C11 Annex G. The implementation uses the
16812 // following naming scheme:
16813 // (a + ib) / (c + id)
16814
16815 int DenomLogB = 0;
16816 APFloat MaxCD = maxnum(abs(C), abs(D));
16817 if (MaxCD.isFinite()) {
16818 DenomLogB = ilogb(MaxCD);
16819 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
16820 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
16821 }
16822 APFloat Denom = C * C + D * D;
16823 ResR =
16824 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16825 ResI =
16826 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16827 if (ResR.isNaN() && ResI.isNaN()) {
16828 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
16829 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
16830 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
16831 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
16832 D.isFinite()) {
16833 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16834 A);
16835 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16836 B);
16837 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
16838 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
16839 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
16840 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16841 C);
16842 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16843 D);
16844 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
16845 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
16846 }
16847 }
16848}
16849
16850bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16851 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16852 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16853
16854 // Track whether the LHS or RHS is real at the type system level. When this is
16855 // the case we can simplify our evaluation strategy.
16856 bool LHSReal = false, RHSReal = false;
16857
16858 bool LHSOK;
16859 if (E->getLHS()->getType()->isRealFloatingType()) {
16860 LHSReal = true;
16861 APFloat &Real = Result.FloatReal;
16862 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
16863 if (LHSOK) {
16864 Result.makeComplexFloat();
16865 Result.FloatImag = APFloat(Real.getSemantics());
16866 }
16867 } else {
16868 LHSOK = Visit(E->getLHS());
16869 }
16870 if (!LHSOK && !Info.noteFailure())
16871 return false;
16872
16873 ComplexValue RHS;
16874 if (E->getRHS()->getType()->isRealFloatingType()) {
16875 RHSReal = true;
16876 APFloat &Real = RHS.FloatReal;
16877 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
16878 return false;
16879 RHS.makeComplexFloat();
16880 RHS.FloatImag = APFloat(Real.getSemantics());
16881 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16882 return false;
16883
16884 assert(!(LHSReal && RHSReal) &&
16885 "Cannot have both operands of a complex operation be real.");
16886 switch (E->getOpcode()) {
16887 default: return Error(E);
16888 case BO_Add:
16889 if (Result.isComplexFloat()) {
16890 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
16891 APFloat::rmNearestTiesToEven);
16892 if (LHSReal)
16893 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16894 else if (!RHSReal)
16895 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
16896 APFloat::rmNearestTiesToEven);
16897 } else {
16898 Result.getComplexIntReal() += RHS.getComplexIntReal();
16899 Result.getComplexIntImag() += RHS.getComplexIntImag();
16900 }
16901 break;
16902 case BO_Sub:
16903 if (Result.isComplexFloat()) {
16904 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
16905 APFloat::rmNearestTiesToEven);
16906 if (LHSReal) {
16907 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16908 Result.getComplexFloatImag().changeSign();
16909 } else if (!RHSReal) {
16910 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
16911 APFloat::rmNearestTiesToEven);
16912 }
16913 } else {
16914 Result.getComplexIntReal() -= RHS.getComplexIntReal();
16915 Result.getComplexIntImag() -= RHS.getComplexIntImag();
16916 }
16917 break;
16918 case BO_Mul:
16919 if (Result.isComplexFloat()) {
16920 // This is an implementation of complex multiplication according to the
16921 // constraints laid out in C11 Annex G. The implementation uses the
16922 // following naming scheme:
16923 // (a + ib) * (c + id)
16924 ComplexValue LHS = Result;
16925 APFloat &A = LHS.getComplexFloatReal();
16926 APFloat &B = LHS.getComplexFloatImag();
16927 APFloat &C = RHS.getComplexFloatReal();
16928 APFloat &D = RHS.getComplexFloatImag();
16929 APFloat &ResR = Result.getComplexFloatReal();
16930 APFloat &ResI = Result.getComplexFloatImag();
16931 if (LHSReal) {
16932 assert(!RHSReal && "Cannot have two real operands for a complex op!");
16933 ResR = A;
16934 ResI = A;
16935 // ResR = A * C;
16936 // ResI = A * D;
16937 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
16938 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
16939 return false;
16940 } else if (RHSReal) {
16941 // ResR = C * A;
16942 // ResI = C * B;
16943 ResR = C;
16944 ResI = C;
16945 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
16946 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
16947 return false;
16948 } else {
16949 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
16950 }
16951 } else {
16952 ComplexValue LHS = Result;
16953 Result.getComplexIntReal() =
16954 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
16955 LHS.getComplexIntImag() * RHS.getComplexIntImag());
16956 Result.getComplexIntImag() =
16957 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
16958 LHS.getComplexIntImag() * RHS.getComplexIntReal());
16959 }
16960 break;
16961 case BO_Div:
16962 if (Result.isComplexFloat()) {
16963 // This is an implementation of complex division according to the
16964 // constraints laid out in C11 Annex G. The implementation uses the
16965 // following naming scheme:
16966 // (a + ib) / (c + id)
16967 ComplexValue LHS = Result;
16968 APFloat &A = LHS.getComplexFloatReal();
16969 APFloat &B = LHS.getComplexFloatImag();
16970 APFloat &C = RHS.getComplexFloatReal();
16971 APFloat &D = RHS.getComplexFloatImag();
16972 APFloat &ResR = Result.getComplexFloatReal();
16973 APFloat &ResI = Result.getComplexFloatImag();
16974 if (RHSReal) {
16975 ResR = A;
16976 ResI = B;
16977 // ResR = A / C;
16978 // ResI = B / C;
16979 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
16980 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
16981 return false;
16982 } else {
16983 if (LHSReal) {
16984 // No real optimizations we can do here, stub out with zero.
16985 B = APFloat::getZero(A.getSemantics());
16986 }
16987 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
16988 }
16989 } else {
16990 ComplexValue LHS = Result;
16991 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
16992 RHS.getComplexIntImag() * RHS.getComplexIntImag();
16993 if (Den.isZero())
16994 return Error(E, diag::note_expr_divide_by_zero);
16995
16996 Result.getComplexIntReal() =
16997 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
16998 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
16999 Result.getComplexIntImag() =
17000 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
17001 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
17002 }
17003 break;
17004 }
17005
17006 return true;
17007}
17008
17009bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17010 // Get the operand value into 'Result'.
17011 if (!Visit(E->getSubExpr()))
17012 return false;
17013
17014 switch (E->getOpcode()) {
17015 default:
17016 return Error(E);
17017 case UO_Extension:
17018 return true;
17019 case UO_Plus:
17020 // The result is always just the subexpr.
17021 return true;
17022 case UO_Minus:
17023 if (Result.isComplexFloat()) {
17024 Result.getComplexFloatReal().changeSign();
17025 Result.getComplexFloatImag().changeSign();
17026 }
17027 else {
17028 Result.getComplexIntReal() = -Result.getComplexIntReal();
17029 Result.getComplexIntImag() = -Result.getComplexIntImag();
17030 }
17031 return true;
17032 case UO_Not:
17033 if (Result.isComplexFloat())
17034 Result.getComplexFloatImag().changeSign();
17035 else
17036 Result.getComplexIntImag() = -Result.getComplexIntImag();
17037 return true;
17038 }
17039}
17040
17041bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
17042 if (E->getNumInits() == 2) {
17043 if (E->getType()->isComplexType()) {
17044 Result.makeComplexFloat();
17045 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
17046 return false;
17047 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
17048 return false;
17049 } else {
17050 Result.makeComplexInt();
17051 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
17052 return false;
17053 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
17054 return false;
17055 }
17056 return true;
17057 }
17058 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
17059}
17060
17061bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
17062 if (!IsConstantEvaluatedBuiltinCall(E))
17063 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17064
17065 switch (E->getBuiltinCallee()) {
17066 case Builtin::BI__builtin_complex:
17067 Result.makeComplexFloat();
17068 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
17069 return false;
17070 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
17071 return false;
17072 return true;
17073
17074 default:
17075 return false;
17076 }
17077}
17078
17079//===----------------------------------------------------------------------===//
17080// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
17081// implicit conversion.
17082//===----------------------------------------------------------------------===//
17083
17084namespace {
17085class AtomicExprEvaluator :
17086 public ExprEvaluatorBase<AtomicExprEvaluator> {
17087 const LValue *This;
17088 APValue &Result;
17089public:
17090 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
17091 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
17092
17093 bool Success(const APValue &V, const Expr *E) {
17094 Result = V;
17095 return true;
17096 }
17097
17098 bool ZeroInitialization(const Expr *E) {
17101 // For atomic-qualified class (and array) types in C++, initialize the
17102 // _Atomic-wrapped subobject directly, in-place.
17103 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
17104 : Evaluate(Result, Info, &VIE);
17105 }
17106
17107 bool VisitCastExpr(const CastExpr *E) {
17108 switch (E->getCastKind()) {
17109 default:
17110 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17111 case CK_NullToPointer:
17112 VisitIgnoredValue(E->getSubExpr());
17113 return ZeroInitialization(E);
17114 case CK_NonAtomicToAtomic:
17115 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
17116 : Evaluate(Result, Info, E->getSubExpr());
17117 }
17118 }
17119};
17120} // end anonymous namespace
17121
17122static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
17123 EvalInfo &Info) {
17124 assert(!E->isValueDependent());
17125 assert(E->isPRValue() && E->getType()->isAtomicType());
17126 return AtomicExprEvaluator(Info, This, Result).Visit(E);
17127}
17128
17129//===----------------------------------------------------------------------===//
17130// Void expression evaluation, primarily for a cast to void on the LHS of a
17131// comma operator
17132//===----------------------------------------------------------------------===//
17133
17134namespace {
17135class VoidExprEvaluator
17136 : public ExprEvaluatorBase<VoidExprEvaluator> {
17137public:
17138 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
17139
17140 bool Success(const APValue &V, const Expr *e) { return true; }
17141
17142 bool ZeroInitialization(const Expr *E) { return true; }
17143
17144 bool VisitCastExpr(const CastExpr *E) {
17145 switch (E->getCastKind()) {
17146 default:
17147 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17148 case CK_ToVoid:
17149 VisitIgnoredValue(E->getSubExpr());
17150 return true;
17151 }
17152 }
17153
17154 bool VisitCallExpr(const CallExpr *E) {
17155 if (!IsConstantEvaluatedBuiltinCall(E))
17156 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17157
17158 switch (E->getBuiltinCallee()) {
17159 case Builtin::BI__assume:
17160 case Builtin::BI__builtin_assume:
17161 // The argument is not evaluated!
17162 return true;
17163
17164 case Builtin::BI__builtin_operator_delete:
17165 return HandleOperatorDeleteCall(Info, E);
17166
17167 default:
17168 return false;
17169 }
17170 }
17171
17172 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
17173};
17174} // end anonymous namespace
17175
17176bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
17177 // We cannot speculatively evaluate a delete expression.
17178 if (Info.SpeculativeEvaluationDepth)
17179 return false;
17180
17181 FunctionDecl *OperatorDelete = E->getOperatorDelete();
17182 if (!OperatorDelete
17183 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17184 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17185 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
17186 return false;
17187 }
17188
17189 const Expr *Arg = E->getArgument();
17190
17191 LValue Pointer;
17192 if (!EvaluatePointer(Arg, Pointer, Info))
17193 return false;
17194 if (Pointer.Designator.Invalid)
17195 return false;
17196
17197 // Deleting a null pointer has no effect.
17198 if (Pointer.isNullPointer()) {
17199 // This is the only case where we need to produce an extension warning:
17200 // the only other way we can succeed is if we find a dynamic allocation,
17201 // and we will have warned when we allocated it in that case.
17202 if (!Info.getLangOpts().CPlusPlus20)
17203 Info.CCEDiag(E, diag::note_constexpr_new);
17204 return true;
17205 }
17206
17207 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
17208 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
17209 if (!Alloc)
17210 return false;
17211 QualType AllocType = Pointer.Base.getDynamicAllocType();
17212
17213 // For the non-array case, the designator must be empty if the static type
17214 // does not have a virtual destructor.
17215 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
17217 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
17218 << Arg->getType()->getPointeeType() << AllocType;
17219 return false;
17220 }
17221
17222 // For a class type with a virtual destructor, the selected operator delete
17223 // is the one looked up when building the destructor.
17224 if (!E->isArrayForm() && !E->isGlobalDelete()) {
17225 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
17226 if (VirtualDelete &&
17227 !VirtualDelete
17228 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17229 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17230 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
17231 return false;
17232 }
17233 }
17234
17235 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
17236 (*Alloc)->Value, AllocType))
17237 return false;
17238
17239 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
17240 // The element was already erased. This means the destructor call also
17241 // deleted the object.
17242 // FIXME: This probably results in undefined behavior before we get this
17243 // far, and should be diagnosed elsewhere first.
17244 Info.FFDiag(E, diag::note_constexpr_double_delete);
17245 return false;
17246 }
17247
17248 return true;
17249}
17250
17251static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
17252 assert(!E->isValueDependent());
17253 assert(E->isPRValue() && E->getType()->isVoidType());
17254 return VoidExprEvaluator(Info).Visit(E);
17255}
17256
17257//===----------------------------------------------------------------------===//
17258// Top level Expr::EvaluateAsRValue method.
17259//===----------------------------------------------------------------------===//
17260
17261static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
17262 assert(!E->isValueDependent());
17263 // In C, function designators are not lvalues, but we evaluate them as if they
17264 // are.
17265 QualType T = E->getType();
17266 if (E->isGLValue() || T->isFunctionType()) {
17267 LValue LV;
17268 if (!EvaluateLValue(E, LV, Info))
17269 return false;
17270 LV.moveInto(Result);
17271 } else if (T->isVectorType()) {
17272 if (!EvaluateVector(E, Result, Info))
17273 return false;
17274 } else if (T->isIntegralOrEnumerationType()) {
17275 if (!IntExprEvaluator(Info, Result).Visit(E))
17276 return false;
17277 } else if (T->hasPointerRepresentation()) {
17278 LValue LV;
17279 if (!EvaluatePointer(E, LV, Info))
17280 return false;
17281 LV.moveInto(Result);
17282 } else if (T->isRealFloatingType()) {
17283 llvm::APFloat F(0.0);
17284 if (!EvaluateFloat(E, F, Info))
17285 return false;
17286 Result = APValue(F);
17287 } else if (T->isAnyComplexType()) {
17288 ComplexValue C;
17289 if (!EvaluateComplex(E, C, Info))
17290 return false;
17291 C.moveInto(Result);
17292 } else if (T->isFixedPointType()) {
17293 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
17294 } else if (T->isMemberPointerType()) {
17295 MemberPtr P;
17296 if (!EvaluateMemberPointer(E, P, Info))
17297 return false;
17298 P.moveInto(Result);
17299 return true;
17300 } else if (T->isArrayType()) {
17301 LValue LV;
17302 APValue &Value =
17303 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17304 if (!EvaluateArray(E, LV, Value, Info))
17305 return false;
17306 Result = Value;
17307 } else if (T->isRecordType()) {
17308 LValue LV;
17309 APValue &Value =
17310 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17311 if (!EvaluateRecord(E, LV, Value, Info))
17312 return false;
17313 Result = Value;
17314 } else if (T->isVoidType()) {
17315 if (!Info.getLangOpts().CPlusPlus11)
17316 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
17317 << E->getType();
17318 if (!EvaluateVoid(E, Info))
17319 return false;
17320 } else if (T->isAtomicType()) {
17321 QualType Unqual = T.getAtomicUnqualifiedType();
17322 if (Unqual->isArrayType() || Unqual->isRecordType()) {
17323 LValue LV;
17324 APValue &Value = Info.CurrentCall->createTemporary(
17325 E, Unqual, ScopeKind::FullExpression, LV);
17326 if (!EvaluateAtomic(E, &LV, Value, Info))
17327 return false;
17328 Result = Value;
17329 } else {
17330 if (!EvaluateAtomic(E, nullptr, Result, Info))
17331 return false;
17332 }
17333 } else if (Info.getLangOpts().CPlusPlus11) {
17334 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
17335 return false;
17336 } else {
17337 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17338 return false;
17339 }
17340
17341 return true;
17342}
17343
17344/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
17345/// cases, the in-place evaluation is essential, since later initializers for
17346/// an object can indirectly refer to subobjects which were initialized earlier.
17347static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
17348 const Expr *E, bool AllowNonLiteralTypes) {
17349 assert(!E->isValueDependent());
17350
17351 // Normally expressions passed to EvaluateInPlace have a type, but not when
17352 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
17353 // replaced with a CXXConstructExpr. This can happen in LLDB.
17354 if (E->getType().isNull())
17355 return false;
17356
17357 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
17358 return false;
17359
17360 if (E->isPRValue()) {
17361 // Evaluate arrays and record types in-place, so that later initializers can
17362 // refer to earlier-initialized members of the object.
17363 QualType T = E->getType();
17364 if (T->isArrayType())
17365 return EvaluateArray(E, This, Result, Info);
17366 else if (T->isRecordType())
17367 return EvaluateRecord(E, This, Result, Info);
17368 else if (T->isAtomicType()) {
17369 QualType Unqual = T.getAtomicUnqualifiedType();
17370 if (Unqual->isArrayType() || Unqual->isRecordType())
17371 return EvaluateAtomic(E, &This, Result, Info);
17372 }
17373 }
17374
17375 // For any other type, in-place evaluation is unimportant.
17376 return Evaluate(Result, Info, E);
17377}
17378
17379/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
17380/// lvalue-to-rvalue cast if it is an lvalue.
17381static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
17382 assert(!E->isValueDependent());
17383
17384 if (E->getType().isNull())
17385 return false;
17386
17387 if (!CheckLiteralType(Info, E))
17388 return false;
17389
17390 if (Info.EnableNewConstInterp) {
17391 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
17392 return false;
17393 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17394 ConstantExprKind::Normal);
17395 }
17396
17397 if (!::Evaluate(Result, Info, E))
17398 return false;
17399
17400 // Implicit lvalue-to-rvalue cast.
17401 if (E->isGLValue()) {
17402 LValue LV;
17403 LV.setFrom(Info.Ctx, Result);
17404 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
17405 return false;
17406 }
17407
17408 // Check this core constant expression is a constant expression.
17409 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17410 ConstantExprKind::Normal) &&
17411 CheckMemoryLeaks(Info);
17412}
17413
17414static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
17415 const ASTContext &Ctx, bool &IsConst) {
17416 // Fast-path evaluations of integer literals, since we sometimes see files
17417 // containing vast quantities of these.
17418 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
17419 Result =
17420 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
17421 IsConst = true;
17422 return true;
17423 }
17424
17425 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
17426 Result = APValue(APSInt(APInt(1, L->getValue())));
17427 IsConst = true;
17428 return true;
17429 }
17430
17431 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
17432 Result = APValue(FL->getValue());
17433 IsConst = true;
17434 return true;
17435 }
17436
17437 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
17438 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
17439 IsConst = true;
17440 return true;
17441 }
17442
17443 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
17444 if (CE->hasAPValueResult()) {
17445 APValue APV = CE->getAPValueResult();
17446 if (!APV.isLValue()) {
17447 Result = std::move(APV);
17448 IsConst = true;
17449 return true;
17450 }
17451 }
17452
17453 // The SubExpr is usually just an IntegerLiteral.
17454 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
17455 }
17456
17457 // This case should be rare, but we need to check it before we check on
17458 // the type below.
17459 if (Exp->getType().isNull()) {
17460 IsConst = false;
17461 return true;
17462 }
17463
17464 return false;
17465}
17466
17469 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
17470 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
17471}
17472
17473static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
17474 const ASTContext &Ctx, EvalInfo &Info) {
17475 assert(!E->isValueDependent());
17476 bool IsConst;
17477 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
17478 return IsConst;
17479
17480 return EvaluateAsRValue(Info, E, Result.Val);
17481}
17482
17484 const ASTContext &Ctx,
17485 Expr::SideEffectsKind AllowSideEffects,
17486 EvalInfo &Info) {
17487 assert(!E->isValueDependent());
17489 return false;
17490
17491 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
17492 !ExprResult.Val.isInt() ||
17493 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17494 return false;
17495
17496 return true;
17497}
17498
17500 const ASTContext &Ctx,
17501 Expr::SideEffectsKind AllowSideEffects,
17502 EvalInfo &Info) {
17503 assert(!E->isValueDependent());
17504 if (!E->getType()->isFixedPointType())
17505 return false;
17506
17507 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
17508 return false;
17509
17510 if (!ExprResult.Val.isFixedPoint() ||
17511 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17512 return false;
17513
17514 return true;
17515}
17516
17517/// EvaluateAsRValue - Return true if this is a constant which we can fold using
17518/// any crazy technique (that has nothing to do with language standards) that
17519/// we want to. If this function returns true, it returns the folded constant
17520/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
17521/// will be applied to the result.
17523 bool InConstantContext) const {
17524 assert(!isValueDependent() &&
17525 "Expression evaluator can't be called on a dependent expression.");
17526 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
17527 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
17528 Info.InConstantContext = InConstantContext;
17529 return ::EvaluateAsRValue(this, Result, Ctx, Info);
17530}
17531
17532bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
17533 bool InConstantContext) const {
17534 assert(!isValueDependent() &&
17535 "Expression evaluator can't be called on a dependent expression.");
17536 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
17537 EvalResult Scratch;
17538 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
17539 HandleConversionToBool(Scratch.Val, Result);
17540}
17541
17543 SideEffectsKind AllowSideEffects,
17544 bool InConstantContext) const {
17545 assert(!isValueDependent() &&
17546 "Expression evaluator can't be called on a dependent expression.");
17547 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
17548 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
17549 Info.InConstantContext = InConstantContext;
17550 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
17551}
17552
17554 SideEffectsKind AllowSideEffects,
17555 bool InConstantContext) const {
17556 assert(!isValueDependent() &&
17557 "Expression evaluator can't be called on a dependent expression.");
17558 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
17559 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
17560 Info.InConstantContext = InConstantContext;
17561 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
17562}
17563
17564bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
17565 SideEffectsKind AllowSideEffects,
17566 bool InConstantContext) const {
17567 assert(!isValueDependent() &&
17568 "Expression evaluator can't be called on a dependent expression.");
17569
17570 if (!getType()->isRealFloatingType())
17571 return false;
17572
17573 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
17575 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
17576 !ExprResult.Val.isFloat() ||
17577 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17578 return false;
17579
17580 Result = ExprResult.Val.getFloat();
17581 return true;
17582}
17583
17585 bool InConstantContext) const {
17586 assert(!isValueDependent() &&
17587 "Expression evaluator can't be called on a dependent expression.");
17588
17589 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
17590 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
17591 Info.InConstantContext = InConstantContext;
17592 LValue LV;
17593 CheckedTemporaries CheckedTemps;
17594 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
17595 Result.HasSideEffects ||
17596 !CheckLValueConstantExpression(Info, getExprLoc(),
17597 Ctx.getLValueReferenceType(getType()), LV,
17598 ConstantExprKind::Normal, CheckedTemps))
17599 return false;
17600
17601 LV.moveInto(Result.Val);
17602 return true;
17603}
17604
17606 APValue DestroyedValue, QualType Type,
17608 bool IsConstantDestruction) {
17609 EvalInfo Info(Ctx, EStatus,
17610 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
17611 : EvalInfo::EM_ConstantFold);
17612 Info.setEvaluatingDecl(Base, DestroyedValue,
17613 EvalInfo::EvaluatingDeclKind::Dtor);
17614 Info.InConstantContext = IsConstantDestruction;
17615
17616 LValue LVal;
17617 LVal.set(Base);
17618
17619 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
17620 EStatus.HasSideEffects)
17621 return false;
17622
17623 if (!Info.discardCleanups())
17624 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17625
17626 return true;
17627}
17628
17630 ConstantExprKind Kind) const {
17631 assert(!isValueDependent() &&
17632 "Expression evaluator can't be called on a dependent expression.");
17633 bool IsConst;
17634 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
17635 Result.Val.hasValue())
17636 return true;
17637
17638 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
17639 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
17640 EvalInfo Info(Ctx, Result, EM);
17641 Info.InConstantContext = true;
17642
17643 if (Info.EnableNewConstInterp) {
17644 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
17645 return false;
17646 return CheckConstantExpression(Info, getExprLoc(),
17647 getStorageType(Ctx, this), Result.Val, Kind);
17648 }
17649
17650 // The type of the object we're initializing is 'const T' for a class NTTP.
17651 QualType T = getType();
17652 if (Kind == ConstantExprKind::ClassTemplateArgument)
17653 T.addConst();
17654
17655 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
17656 // represent the result of the evaluation. CheckConstantExpression ensures
17657 // this doesn't escape.
17658 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
17659 APValue::LValueBase Base(&BaseMTE);
17660 Info.setEvaluatingDecl(Base, Result.Val);
17661
17662 LValue LVal;
17663 LVal.set(Base);
17664 // C++23 [intro.execution]/p5
17665 // A full-expression is [...] a constant-expression
17666 // So we need to make sure temporary objects are destroyed after having
17667 // evaluating the expression (per C++23 [class.temporary]/p4).
17668 FullExpressionRAII Scope(Info);
17669 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
17670 Result.HasSideEffects || !Scope.destroy())
17671 return false;
17672
17673 if (!Info.discardCleanups())
17674 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17675
17676 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
17677 Result.Val, Kind))
17678 return false;
17679 if (!CheckMemoryLeaks(Info))
17680 return false;
17681
17682 // If this is a class template argument, it's required to have constant
17683 // destruction too.
17684 if (Kind == ConstantExprKind::ClassTemplateArgument &&
17685 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
17686 true) ||
17687 Result.HasSideEffects)) {
17688 // FIXME: Prefix a note to indicate that the problem is lack of constant
17689 // destruction.
17690 return false;
17691 }
17692
17693 return true;
17694}
17695
17697 const VarDecl *VD,
17699 bool IsConstantInitialization) const {
17700 assert(!isValueDependent() &&
17701 "Expression evaluator can't be called on a dependent expression.");
17702
17703 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
17704 std::string Name;
17705 llvm::raw_string_ostream OS(Name);
17706 VD->printQualifiedName(OS);
17707 return Name;
17708 });
17709
17710 Expr::EvalStatus EStatus;
17711 EStatus.Diag = &Notes;
17712
17713 EvalInfo Info(Ctx, EStatus,
17714 (IsConstantInitialization &&
17715 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
17716 ? EvalInfo::EM_ConstantExpression
17717 : EvalInfo::EM_ConstantFold);
17718 Info.setEvaluatingDecl(VD, Value);
17719 Info.InConstantContext = IsConstantInitialization;
17720
17721 SourceLocation DeclLoc = VD->getLocation();
17722 QualType DeclTy = VD->getType();
17723
17724 if (Info.EnableNewConstInterp) {
17725 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
17726 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
17727 return false;
17728
17729 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17730 ConstantExprKind::Normal);
17731 } else {
17732 LValue LVal;
17733 LVal.set(VD);
17734
17735 {
17736 // C++23 [intro.execution]/p5
17737 // A full-expression is ... an init-declarator ([dcl.decl]) or a
17738 // mem-initializer.
17739 // So we need to make sure temporary objects are destroyed after having
17740 // evaluated the expression (per C++23 [class.temporary]/p4).
17741 //
17742 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
17743 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
17744 // outermost FullExpr, such as ExprWithCleanups.
17745 FullExpressionRAII Scope(Info);
17746 if (!EvaluateInPlace(Value, Info, LVal, this,
17747 /*AllowNonLiteralTypes=*/true) ||
17748 EStatus.HasSideEffects)
17749 return false;
17750 }
17751
17752 // At this point, any lifetime-extended temporaries are completely
17753 // initialized.
17754 Info.performLifetimeExtension();
17755
17756 if (!Info.discardCleanups())
17757 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17758 }
17759
17760 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17761 ConstantExprKind::Normal) &&
17762 CheckMemoryLeaks(Info);
17763}
17764
17767 Expr::EvalStatus EStatus;
17768 EStatus.Diag = &Notes;
17769
17770 // Only treat the destruction as constant destruction if we formally have
17771 // constant initialization (or are usable in a constant expression).
17772 bool IsConstantDestruction = hasConstantInitialization();
17773
17774 // Make a copy of the value for the destructor to mutate, if we know it.
17775 // Otherwise, treat the value as default-initialized; if the destructor works
17776 // anyway, then the destruction is constant (and must be essentially empty).
17777 APValue DestroyedValue;
17778 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
17779 DestroyedValue = *getEvaluatedValue();
17780 else if (!handleDefaultInitValue(getType(), DestroyedValue))
17781 return false;
17782
17783 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
17784 getType(), getLocation(), EStatus,
17785 IsConstantDestruction) ||
17786 EStatus.HasSideEffects)
17787 return false;
17788
17789 ensureEvaluatedStmt()->HasConstantDestruction = true;
17790 return true;
17791}
17792
17793/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
17794/// constant folded, but discard the result.
17796 assert(!isValueDependent() &&
17797 "Expression evaluator can't be called on a dependent expression.");
17798
17799 EvalResult Result;
17800 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
17801 !hasUnacceptableSideEffect(Result, SEK);
17802}
17803
17806 assert(!isValueDependent() &&
17807 "Expression evaluator can't be called on a dependent expression.");
17808
17809 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
17810 EvalResult EVResult;
17811 EVResult.Diag = Diag;
17812 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17813 Info.InConstantContext = true;
17814
17815 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
17816 (void)Result;
17817 assert(Result && "Could not evaluate expression");
17818 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17819
17820 return EVResult.Val.getInt();
17821}
17822
17825 assert(!isValueDependent() &&
17826 "Expression evaluator can't be called on a dependent expression.");
17827
17828 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
17829 EvalResult EVResult;
17830 EVResult.Diag = Diag;
17831 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17832 Info.InConstantContext = true;
17833 Info.CheckingForUndefinedBehavior = true;
17834
17835 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
17836 (void)Result;
17837 assert(Result && "Could not evaluate expression");
17838 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17839
17840 return EVResult.Val.getInt();
17841}
17842
17844 assert(!isValueDependent() &&
17845 "Expression evaluator can't be called on a dependent expression.");
17846
17847 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
17848 bool IsConst;
17849 EvalResult EVResult;
17850 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
17851 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17852 Info.CheckingForUndefinedBehavior = true;
17853 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
17854 }
17855}
17856
17858 assert(Val.isLValue());
17859 return IsGlobalLValue(Val.getLValueBase());
17860}
17861
17862/// isIntegerConstantExpr - this recursive routine will test if an expression is
17863/// an integer constant expression.
17864
17865/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
17866/// comma, etc
17867
17868// CheckICE - This function does the fundamental ICE checking: the returned
17869// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
17870//
17871// Note that to reduce code duplication, this helper does no evaluation
17872// itself; the caller checks whether the expression is evaluatable, and
17873// in the rare cases where CheckICE actually cares about the evaluated
17874// value, it calls into Evaluate.
17875
17876namespace {
17877
17878enum ICEKind {
17879 /// This expression is an ICE.
17880 IK_ICE,
17881 /// This expression is not an ICE, but if it isn't evaluated, it's
17882 /// a legal subexpression for an ICE. This return value is used to handle
17883 /// the comma operator in C99 mode, and non-constant subexpressions.
17884 IK_ICEIfUnevaluated,
17885 /// This expression is not an ICE, and is not a legal subexpression for one.
17886 IK_NotICE
17887};
17888
17889struct ICEDiag {
17890 ICEKind Kind;
17892
17893 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
17894};
17895
17896}
17897
17898static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
17899
17900static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
17901
17902static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
17903 Expr::EvalResult EVResult;
17904 Expr::EvalStatus Status;
17905 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17906
17907 Info.InConstantContext = true;
17908 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
17909 !EVResult.Val.isInt())
17910 return ICEDiag(IK_NotICE, E->getBeginLoc());
17911
17912 return NoDiag();
17913}
17914
17915static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
17916 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
17918 return ICEDiag(IK_NotICE, E->getBeginLoc());
17919
17920 switch (E->getStmtClass()) {
17921#define ABSTRACT_STMT(Node)
17922#define STMT(Node, Base) case Expr::Node##Class:
17923#define EXPR(Node, Base)
17924#include "clang/AST/StmtNodes.inc"
17925 case Expr::PredefinedExprClass:
17926 case Expr::FloatingLiteralClass:
17927 case Expr::ImaginaryLiteralClass:
17928 case Expr::StringLiteralClass:
17929 case Expr::ArraySubscriptExprClass:
17930 case Expr::MatrixSubscriptExprClass:
17931 case Expr::ArraySectionExprClass:
17932 case Expr::OMPArrayShapingExprClass:
17933 case Expr::OMPIteratorExprClass:
17934 case Expr::MemberExprClass:
17935 case Expr::CompoundAssignOperatorClass:
17936 case Expr::CompoundLiteralExprClass:
17937 case Expr::ExtVectorElementExprClass:
17938 case Expr::DesignatedInitExprClass:
17939 case Expr::ArrayInitLoopExprClass:
17940 case Expr::ArrayInitIndexExprClass:
17941 case Expr::NoInitExprClass:
17942 case Expr::DesignatedInitUpdateExprClass:
17943 case Expr::ImplicitValueInitExprClass:
17944 case Expr::ParenListExprClass:
17945 case Expr::VAArgExprClass:
17946 case Expr::AddrLabelExprClass:
17947 case Expr::StmtExprClass:
17948 case Expr::CXXMemberCallExprClass:
17949 case Expr::CUDAKernelCallExprClass:
17950 case Expr::CXXAddrspaceCastExprClass:
17951 case Expr::CXXDynamicCastExprClass:
17952 case Expr::CXXTypeidExprClass:
17953 case Expr::CXXUuidofExprClass:
17954 case Expr::MSPropertyRefExprClass:
17955 case Expr::MSPropertySubscriptExprClass:
17956 case Expr::CXXNullPtrLiteralExprClass:
17957 case Expr::UserDefinedLiteralClass:
17958 case Expr::CXXThisExprClass:
17959 case Expr::CXXThrowExprClass:
17960 case Expr::CXXNewExprClass:
17961 case Expr::CXXDeleteExprClass:
17962 case Expr::CXXPseudoDestructorExprClass:
17963 case Expr::UnresolvedLookupExprClass:
17964 case Expr::RecoveryExprClass:
17965 case Expr::DependentScopeDeclRefExprClass:
17966 case Expr::CXXConstructExprClass:
17967 case Expr::CXXInheritedCtorInitExprClass:
17968 case Expr::CXXStdInitializerListExprClass:
17969 case Expr::CXXBindTemporaryExprClass:
17970 case Expr::ExprWithCleanupsClass:
17971 case Expr::CXXTemporaryObjectExprClass:
17972 case Expr::CXXUnresolvedConstructExprClass:
17973 case Expr::CXXDependentScopeMemberExprClass:
17974 case Expr::UnresolvedMemberExprClass:
17975 case Expr::ObjCStringLiteralClass:
17976 case Expr::ObjCBoxedExprClass:
17977 case Expr::ObjCArrayLiteralClass:
17978 case Expr::ObjCDictionaryLiteralClass:
17979 case Expr::ObjCEncodeExprClass:
17980 case Expr::ObjCMessageExprClass:
17981 case Expr::ObjCSelectorExprClass:
17982 case Expr::ObjCProtocolExprClass:
17983 case Expr::ObjCIvarRefExprClass:
17984 case Expr::ObjCPropertyRefExprClass:
17985 case Expr::ObjCSubscriptRefExprClass:
17986 case Expr::ObjCIsaExprClass:
17987 case Expr::ObjCAvailabilityCheckExprClass:
17988 case Expr::ShuffleVectorExprClass:
17989 case Expr::ConvertVectorExprClass:
17990 case Expr::BlockExprClass:
17991 case Expr::NoStmtClass:
17992 case Expr::OpaqueValueExprClass:
17993 case Expr::PackExpansionExprClass:
17994 case Expr::SubstNonTypeTemplateParmPackExprClass:
17995 case Expr::FunctionParmPackExprClass:
17996 case Expr::AsTypeExprClass:
17997 case Expr::ObjCIndirectCopyRestoreExprClass:
17998 case Expr::MaterializeTemporaryExprClass:
17999 case Expr::PseudoObjectExprClass:
18000 case Expr::AtomicExprClass:
18001 case Expr::LambdaExprClass:
18002 case Expr::CXXFoldExprClass:
18003 case Expr::CoawaitExprClass:
18004 case Expr::DependentCoawaitExprClass:
18005 case Expr::CoyieldExprClass:
18006 case Expr::SYCLUniqueStableNameExprClass:
18007 case Expr::CXXParenListInitExprClass:
18008 case Expr::HLSLOutArgExprClass:
18009 return ICEDiag(IK_NotICE, E->getBeginLoc());
18010
18011 case Expr::InitListExprClass: {
18012 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
18013 // form "T x = { a };" is equivalent to "T x = a;".
18014 // Unless we're initializing a reference, T is a scalar as it is known to be
18015 // of integral or enumeration type.
18016 if (E->isPRValue())
18017 if (cast<InitListExpr>(E)->getNumInits() == 1)
18018 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
18019 return ICEDiag(IK_NotICE, E->getBeginLoc());
18020 }
18021
18022 case Expr::SizeOfPackExprClass:
18023 case Expr::GNUNullExprClass:
18024 case Expr::SourceLocExprClass:
18025 case Expr::EmbedExprClass:
18026 case Expr::OpenACCAsteriskSizeExprClass:
18027 return NoDiag();
18028
18029 case Expr::PackIndexingExprClass:
18030 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
18031
18032 case Expr::SubstNonTypeTemplateParmExprClass:
18033 return
18034 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
18035
18036 case Expr::ConstantExprClass:
18037 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
18038
18039 case Expr::ParenExprClass:
18040 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
18041 case Expr::GenericSelectionExprClass:
18042 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
18043 case Expr::IntegerLiteralClass:
18044 case Expr::FixedPointLiteralClass:
18045 case Expr::CharacterLiteralClass:
18046 case Expr::ObjCBoolLiteralExprClass:
18047 case Expr::CXXBoolLiteralExprClass:
18048 case Expr::CXXScalarValueInitExprClass:
18049 case Expr::TypeTraitExprClass:
18050 case Expr::ConceptSpecializationExprClass:
18051 case Expr::RequiresExprClass:
18052 case Expr::ArrayTypeTraitExprClass:
18053 case Expr::ExpressionTraitExprClass:
18054 case Expr::CXXNoexceptExprClass:
18055 return NoDiag();
18056 case Expr::CallExprClass:
18057 case Expr::CXXOperatorCallExprClass: {
18058 // C99 6.6/3 allows function calls within unevaluated subexpressions of
18059 // constant expressions, but they can never be ICEs because an ICE cannot
18060 // contain an operand of (pointer to) function type.
18061 const CallExpr *CE = cast<CallExpr>(E);
18062 if (CE->getBuiltinCallee())
18063 return CheckEvalInICE(E, Ctx);
18064 return ICEDiag(IK_NotICE, E->getBeginLoc());
18065 }
18066 case Expr::CXXRewrittenBinaryOperatorClass:
18067 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
18068 Ctx);
18069 case Expr::DeclRefExprClass: {
18070 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
18071 if (isa<EnumConstantDecl>(D))
18072 return NoDiag();
18073
18074 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
18075 // integer variables in constant expressions:
18076 //
18077 // C++ 7.1.5.1p2
18078 // A variable of non-volatile const-qualified integral or enumeration
18079 // type initialized by an ICE can be used in ICEs.
18080 //
18081 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
18082 // that mode, use of reference variables should not be allowed.
18083 const VarDecl *VD = dyn_cast<VarDecl>(D);
18084 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
18085 !VD->getType()->isReferenceType())
18086 return NoDiag();
18087
18088 return ICEDiag(IK_NotICE, E->getBeginLoc());
18089 }
18090 case Expr::UnaryOperatorClass: {
18091 const UnaryOperator *Exp = cast<UnaryOperator>(E);
18092 switch (Exp->getOpcode()) {
18093 case UO_PostInc:
18094 case UO_PostDec:
18095 case UO_PreInc:
18096 case UO_PreDec:
18097 case UO_AddrOf:
18098 case UO_Deref:
18099 case UO_Coawait:
18100 // C99 6.6/3 allows increment and decrement within unevaluated
18101 // subexpressions of constant expressions, but they can never be ICEs
18102 // because an ICE cannot contain an lvalue operand.
18103 return ICEDiag(IK_NotICE, E->getBeginLoc());
18104 case UO_Extension:
18105 case UO_LNot:
18106 case UO_Plus:
18107 case UO_Minus:
18108 case UO_Not:
18109 case UO_Real:
18110 case UO_Imag:
18111 return CheckICE(Exp->getSubExpr(), Ctx);
18112 }
18113 llvm_unreachable("invalid unary operator class");
18114 }
18115 case Expr::OffsetOfExprClass: {
18116 // Note that per C99, offsetof must be an ICE. And AFAIK, using
18117 // EvaluateAsRValue matches the proposed gcc behavior for cases like
18118 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
18119 // compliance: we should warn earlier for offsetof expressions with
18120 // array subscripts that aren't ICEs, and if the array subscripts
18121 // are ICEs, the value of the offsetof must be an integer constant.
18122 return CheckEvalInICE(E, Ctx);
18123 }
18124 case Expr::UnaryExprOrTypeTraitExprClass: {
18125 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
18126 if ((Exp->getKind() == UETT_SizeOf) &&
18128 return ICEDiag(IK_NotICE, E->getBeginLoc());
18129 if (Exp->getKind() == UETT_CountOf) {
18130 QualType ArgTy = Exp->getTypeOfArgument();
18131 if (ArgTy->isVariableArrayType()) {
18132 // We need to look whether the array is multidimensional. If it is,
18133 // then we want to check the size expression manually to see whether
18134 // it is an ICE or not.
18135 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
18136 if (VAT->getElementType()->isArrayType())
18137 // Variable array size expression could be missing (e.g. int a[*][10])
18138 // In that case, it can't be a constant expression.
18139 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
18140 : ICEDiag(IK_NotICE, E->getBeginLoc());
18141
18142 // Otherwise, this is a regular VLA, which is definitely not an ICE.
18143 return ICEDiag(IK_NotICE, E->getBeginLoc());
18144 }
18145 }
18146 return NoDiag();
18147 }
18148 case Expr::BinaryOperatorClass: {
18149 const BinaryOperator *Exp = cast<BinaryOperator>(E);
18150 switch (Exp->getOpcode()) {
18151 case BO_PtrMemD:
18152 case BO_PtrMemI:
18153 case BO_Assign:
18154 case BO_MulAssign:
18155 case BO_DivAssign:
18156 case BO_RemAssign:
18157 case BO_AddAssign:
18158 case BO_SubAssign:
18159 case BO_ShlAssign:
18160 case BO_ShrAssign:
18161 case BO_AndAssign:
18162 case BO_XorAssign:
18163 case BO_OrAssign:
18164 // C99 6.6/3 allows assignments within unevaluated subexpressions of
18165 // constant expressions, but they can never be ICEs because an ICE cannot
18166 // contain an lvalue operand.
18167 return ICEDiag(IK_NotICE, E->getBeginLoc());
18168
18169 case BO_Mul:
18170 case BO_Div:
18171 case BO_Rem:
18172 case BO_Add:
18173 case BO_Sub:
18174 case BO_Shl:
18175 case BO_Shr:
18176 case BO_LT:
18177 case BO_GT:
18178 case BO_LE:
18179 case BO_GE:
18180 case BO_EQ:
18181 case BO_NE:
18182 case BO_And:
18183 case BO_Xor:
18184 case BO_Or:
18185 case BO_Comma:
18186 case BO_Cmp: {
18187 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18188 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18189 if (Exp->getOpcode() == BO_Div ||
18190 Exp->getOpcode() == BO_Rem) {
18191 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
18192 // we don't evaluate one.
18193 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
18194 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
18195 if (REval == 0)
18196 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18197 if (REval.isSigned() && REval.isAllOnes()) {
18198 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
18199 if (LEval.isMinSignedValue())
18200 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18201 }
18202 }
18203 }
18204 if (Exp->getOpcode() == BO_Comma) {
18205 if (Ctx.getLangOpts().C99) {
18206 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
18207 // if it isn't evaluated.
18208 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
18209 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18210 } else {
18211 // In both C89 and C++, commas in ICEs are illegal.
18212 return ICEDiag(IK_NotICE, E->getBeginLoc());
18213 }
18214 }
18215 return Worst(LHSResult, RHSResult);
18216 }
18217 case BO_LAnd:
18218 case BO_LOr: {
18219 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18220 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18221 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
18222 // Rare case where the RHS has a comma "side-effect"; we need
18223 // to actually check the condition to see whether the side
18224 // with the comma is evaluated.
18225 if ((Exp->getOpcode() == BO_LAnd) !=
18226 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
18227 return RHSResult;
18228 return NoDiag();
18229 }
18230
18231 return Worst(LHSResult, RHSResult);
18232 }
18233 }
18234 llvm_unreachable("invalid binary operator kind");
18235 }
18236 case Expr::ImplicitCastExprClass:
18237 case Expr::CStyleCastExprClass:
18238 case Expr::CXXFunctionalCastExprClass:
18239 case Expr::CXXStaticCastExprClass:
18240 case Expr::CXXReinterpretCastExprClass:
18241 case Expr::CXXConstCastExprClass:
18242 case Expr::ObjCBridgedCastExprClass: {
18243 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
18244 if (isa<ExplicitCastExpr>(E)) {
18245 if (const FloatingLiteral *FL
18246 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
18247 unsigned DestWidth = Ctx.getIntWidth(E->getType());
18248 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
18249 APSInt IgnoredVal(DestWidth, !DestSigned);
18250 bool Ignored;
18251 // If the value does not fit in the destination type, the behavior is
18252 // undefined, so we are not required to treat it as a constant
18253 // expression.
18254 if (FL->getValue().convertToInteger(IgnoredVal,
18255 llvm::APFloat::rmTowardZero,
18256 &Ignored) & APFloat::opInvalidOp)
18257 return ICEDiag(IK_NotICE, E->getBeginLoc());
18258 return NoDiag();
18259 }
18260 }
18261 switch (cast<CastExpr>(E)->getCastKind()) {
18262 case CK_LValueToRValue:
18263 case CK_AtomicToNonAtomic:
18264 case CK_NonAtomicToAtomic:
18265 case CK_NoOp:
18266 case CK_IntegralToBoolean:
18267 case CK_IntegralCast:
18268 return CheckICE(SubExpr, Ctx);
18269 default:
18270 return ICEDiag(IK_NotICE, E->getBeginLoc());
18271 }
18272 }
18273 case Expr::BinaryConditionalOperatorClass: {
18274 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
18275 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
18276 if (CommonResult.Kind == IK_NotICE) return CommonResult;
18277 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18278 if (FalseResult.Kind == IK_NotICE) return FalseResult;
18279 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
18280 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
18281 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
18282 return FalseResult;
18283 }
18284 case Expr::ConditionalOperatorClass: {
18285 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
18286 // If the condition (ignoring parens) is a __builtin_constant_p call,
18287 // then only the true side is actually considered in an integer constant
18288 // expression, and it is fully evaluated. This is an important GNU
18289 // extension. See GCC PR38377 for discussion.
18290 if (const CallExpr *CallCE
18291 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
18292 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
18293 return CheckEvalInICE(E, Ctx);
18294 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
18295 if (CondResult.Kind == IK_NotICE)
18296 return CondResult;
18297
18298 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
18299 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18300
18301 if (TrueResult.Kind == IK_NotICE)
18302 return TrueResult;
18303 if (FalseResult.Kind == IK_NotICE)
18304 return FalseResult;
18305 if (CondResult.Kind == IK_ICEIfUnevaluated)
18306 return CondResult;
18307 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
18308 return NoDiag();
18309 // Rare case where the diagnostics depend on which side is evaluated
18310 // Note that if we get here, CondResult is 0, and at least one of
18311 // TrueResult and FalseResult is non-zero.
18312 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
18313 return FalseResult;
18314 return TrueResult;
18315 }
18316 case Expr::CXXDefaultArgExprClass:
18317 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
18318 case Expr::CXXDefaultInitExprClass:
18319 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
18320 case Expr::ChooseExprClass: {
18321 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
18322 }
18323 case Expr::BuiltinBitCastExprClass: {
18324 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
18325 return ICEDiag(IK_NotICE, E->getBeginLoc());
18326 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
18327 }
18328 }
18329
18330 llvm_unreachable("Invalid StmtClass!");
18331}
18332
18333/// Evaluate an expression as a C++11 integral constant expression.
18335 const Expr *E,
18336 llvm::APSInt *Value) {
18338 return false;
18339
18340 APValue Result;
18341 if (!E->isCXX11ConstantExpr(Ctx, &Result))
18342 return false;
18343
18344 if (!Result.isInt())
18345 return false;
18346
18347 if (Value) *Value = Result.getInt();
18348 return true;
18349}
18350
18352 assert(!isValueDependent() &&
18353 "Expression evaluator can't be called on a dependent expression.");
18354
18355 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
18356
18357 if (Ctx.getLangOpts().CPlusPlus11)
18358 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
18359
18360 ICEDiag D = CheckICE(this, Ctx);
18361 if (D.Kind != IK_ICE)
18362 return false;
18363 return true;
18364}
18365
18366std::optional<llvm::APSInt>
18368 if (isValueDependent()) {
18369 // Expression evaluator can't succeed on a dependent expression.
18370 return std::nullopt;
18371 }
18372
18373 if (Ctx.getLangOpts().CPlusPlus11) {
18374 APSInt Value;
18376 return Value;
18377 return std::nullopt;
18378 }
18379
18380 if (!isIntegerConstantExpr(Ctx))
18381 return std::nullopt;
18382
18383 // The only possible side-effects here are due to UB discovered in the
18384 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
18385 // required to treat the expression as an ICE, so we produce the folded
18386 // value.
18388 Expr::EvalStatus Status;
18389 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
18390 Info.InConstantContext = true;
18391
18392 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
18393 llvm_unreachable("ICE cannot be evaluated!");
18394
18395 return ExprResult.Val.getInt();
18396}
18397
18399 assert(!isValueDependent() &&
18400 "Expression evaluator can't be called on a dependent expression.");
18401
18402 return CheckICE(this, Ctx).Kind == IK_ICE;
18403}
18404
18405bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result) const {
18406 assert(!isValueDependent() &&
18407 "Expression evaluator can't be called on a dependent expression.");
18408
18409 // We support this checking in C++98 mode in order to diagnose compatibility
18410 // issues.
18411 assert(Ctx.getLangOpts().CPlusPlus);
18412
18413 bool IsConst;
18414 APValue Scratch;
18415 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
18416 if (Result)
18417 *Result = Scratch;
18418 return true;
18419 }
18420
18421 // Build evaluation settings.
18422 Expr::EvalStatus Status;
18424 Status.Diag = &Diags;
18425 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
18426
18427 bool IsConstExpr =
18428 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
18429 // FIXME: We don't produce a diagnostic for this, but the callers that
18430 // call us on arbitrary full-expressions should generally not care.
18431 Info.discardCleanups() && !Status.HasSideEffects;
18432
18433 return IsConstExpr && Diags.empty();
18434}
18435
18437 const FunctionDecl *Callee,
18439 const Expr *This) const {
18440 assert(!isValueDependent() &&
18441 "Expression evaluator can't be called on a dependent expression.");
18442
18443 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
18444 std::string Name;
18445 llvm::raw_string_ostream OS(Name);
18446 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
18447 /*Qualified=*/true);
18448 return Name;
18449 });
18450
18451 Expr::EvalStatus Status;
18452 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
18453 Info.InConstantContext = true;
18454
18455 LValue ThisVal;
18456 const LValue *ThisPtr = nullptr;
18457 if (This) {
18458#ifndef NDEBUG
18459 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
18460 assert(MD && "Don't provide `this` for non-methods.");
18461 assert(MD->isImplicitObjectMemberFunction() &&
18462 "Don't provide `this` for methods without an implicit object.");
18463#endif
18464 if (!This->isValueDependent() &&
18465 EvaluateObjectArgument(Info, This, ThisVal) &&
18466 !Info.EvalStatus.HasSideEffects)
18467 ThisPtr = &ThisVal;
18468
18469 // Ignore any side-effects from a failed evaluation. This is safe because
18470 // they can't interfere with any other argument evaluation.
18471 Info.EvalStatus.HasSideEffects = false;
18472 }
18473
18474 CallRef Call = Info.CurrentCall->createCall(Callee);
18475 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
18476 I != E; ++I) {
18477 unsigned Idx = I - Args.begin();
18478 if (Idx >= Callee->getNumParams())
18479 break;
18480 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
18481 if ((*I)->isValueDependent() ||
18482 !EvaluateCallArg(PVD, *I, Call, Info) ||
18483 Info.EvalStatus.HasSideEffects) {
18484 // If evaluation fails, throw away the argument entirely.
18485 if (APValue *Slot = Info.getParamSlot(Call, PVD))
18486 *Slot = APValue();
18487 }
18488
18489 // Ignore any side-effects from a failed evaluation. This is safe because
18490 // they can't interfere with any other argument evaluation.
18491 Info.EvalStatus.HasSideEffects = false;
18492 }
18493
18494 // Parameter cleanups happen in the caller and are not part of this
18495 // evaluation.
18496 Info.discardCleanups();
18497 Info.EvalStatus.HasSideEffects = false;
18498
18499 // Build fake call to Callee.
18500 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
18501 Call);
18502 // FIXME: Missing ExprWithCleanups in enable_if conditions?
18503 FullExpressionRAII Scope(Info);
18504 return Evaluate(Value, Info, this) && Scope.destroy() &&
18505 !Info.EvalStatus.HasSideEffects;
18506}
18507
18510 PartialDiagnosticAt> &Diags) {
18511 // FIXME: It would be useful to check constexpr function templates, but at the
18512 // moment the constant expression evaluator cannot cope with the non-rigorous
18513 // ASTs which we build for dependent expressions.
18514 if (FD->isDependentContext())
18515 return true;
18516
18517 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
18518 std::string Name;
18519 llvm::raw_string_ostream OS(Name);
18521 /*Qualified=*/true);
18522 return Name;
18523 });
18524
18525 Expr::EvalStatus Status;
18526 Status.Diag = &Diags;
18527
18528 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
18529 Info.InConstantContext = true;
18530 Info.CheckingPotentialConstantExpression = true;
18531
18532 // The constexpr VM attempts to compile all methods to bytecode here.
18533 if (Info.EnableNewConstInterp) {
18534 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
18535 return Diags.empty();
18536 }
18537
18538 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
18539 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
18540
18541 // Fabricate an arbitrary expression on the stack and pretend that it
18542 // is a temporary being used as the 'this' pointer.
18543 LValue This;
18544 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
18545 : Info.Ctx.IntTy);
18546 This.set({&VIE, Info.CurrentCall->Index});
18547
18549
18550 APValue Scratch;
18551 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
18552 // Evaluate the call as a constant initializer, to allow the construction
18553 // of objects of non-literal types.
18554 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
18555 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
18556 } else {
18559 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
18560 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
18561 /*ResultSlot=*/nullptr);
18562 }
18563
18564 return Diags.empty();
18565}
18566
18568 const FunctionDecl *FD,
18570 PartialDiagnosticAt> &Diags) {
18571 assert(!E->isValueDependent() &&
18572 "Expression evaluator can't be called on a dependent expression.");
18573
18574 Expr::EvalStatus Status;
18575 Status.Diag = &Diags;
18576
18577 EvalInfo Info(FD->getASTContext(), Status,
18578 EvalInfo::EM_ConstantExpressionUnevaluated);
18579 Info.InConstantContext = true;
18580 Info.CheckingPotentialConstantExpression = true;
18581
18582 if (Info.EnableNewConstInterp) {
18583 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
18584 return Diags.empty();
18585 }
18586
18587 // Fabricate a call stack frame to give the arguments a plausible cover story.
18588 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
18589 /*CallExpr=*/nullptr, CallRef());
18590
18591 APValue ResultScratch;
18592 Evaluate(ResultScratch, Info, E);
18593 return Diags.empty();
18594}
18595
18596bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
18597 unsigned Type) const {
18598 if (!getType()->isPointerType())
18599 return false;
18600
18601 Expr::EvalStatus Status;
18602 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
18603 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
18604}
18605
18606static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
18607 EvalInfo &Info, std::string *StringResult) {
18608 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
18609 return false;
18610
18611 LValue String;
18612
18613 if (!EvaluatePointer(E, String, Info))
18614 return false;
18615
18616 QualType CharTy = E->getType()->getPointeeType();
18617
18618 // Fast path: if it's a string literal, search the string value.
18619 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
18620 String.getLValueBase().dyn_cast<const Expr *>())) {
18621 StringRef Str = S->getBytes();
18622 int64_t Off = String.Offset.getQuantity();
18623 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
18624 S->getCharByteWidth() == 1 &&
18625 // FIXME: Add fast-path for wchar_t too.
18626 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
18627 Str = Str.substr(Off);
18628
18629 StringRef::size_type Pos = Str.find(0);
18630 if (Pos != StringRef::npos)
18631 Str = Str.substr(0, Pos);
18632
18633 Result = Str.size();
18634 if (StringResult)
18635 *StringResult = Str;
18636 return true;
18637 }
18638
18639 // Fall through to slow path.
18640 }
18641
18642 // Slow path: scan the bytes of the string looking for the terminating 0.
18643 for (uint64_t Strlen = 0; /**/; ++Strlen) {
18644 APValue Char;
18645 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
18646 !Char.isInt())
18647 return false;
18648 if (!Char.getInt()) {
18649 Result = Strlen;
18650 return true;
18651 } else if (StringResult)
18652 StringResult->push_back(Char.getInt().getExtValue());
18653 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
18654 return false;
18655 }
18656}
18657
18658std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
18659 Expr::EvalStatus Status;
18660 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
18661 uint64_t Result;
18662 std::string StringResult;
18663
18664 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
18665 return StringResult;
18666 return {};
18667}
18668
18669template <typename T>
18670static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
18671 const Expr *SizeExpression,
18672 const Expr *PtrExpression,
18673 ASTContext &Ctx,
18674 Expr::EvalResult &Status) {
18675 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
18676 Info.InConstantContext = true;
18677
18678 if (Info.EnableNewConstInterp)
18679 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
18680 PtrExpression, Result);
18681
18682 LValue String;
18683 FullExpressionRAII Scope(Info);
18684 APSInt SizeValue;
18685 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
18686 return false;
18687
18688 uint64_t Size = SizeValue.getZExtValue();
18689
18690 // FIXME: better protect against invalid or excessive sizes
18691 if constexpr (std::is_same_v<APValue, T>)
18692 Result = APValue(APValue::UninitArray{}, Size, Size);
18693 else {
18694 if (Size < Result.max_size())
18695 Result.reserve(Size);
18696 }
18697 if (!::EvaluatePointer(PtrExpression, String, Info))
18698 return false;
18699
18700 QualType CharTy = PtrExpression->getType()->getPointeeType();
18701 for (uint64_t I = 0; I < Size; ++I) {
18702 APValue Char;
18703 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
18704 Char))
18705 return false;
18706
18707 if constexpr (std::is_same_v<APValue, T>) {
18708 Result.getArrayInitializedElt(I) = std::move(Char);
18709 } else {
18710 APSInt C = Char.getInt();
18711
18712 assert(C.getBitWidth() <= 8 &&
18713 "string element not representable in char");
18714
18715 Result.push_back(static_cast<char>(C.getExtValue()));
18716 }
18717
18718 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
18719 return false;
18720 }
18721
18722 return Scope.destroy() && CheckMemoryLeaks(Info);
18723}
18724
18725bool Expr::EvaluateCharRangeAsString(std::string &Result,
18726 const Expr *SizeExpression,
18727 const Expr *PtrExpression, ASTContext &Ctx,
18728 EvalResult &Status) const {
18729 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18730 PtrExpression, Ctx, Status);
18731}
18732
18734 const Expr *SizeExpression,
18735 const Expr *PtrExpression, ASTContext &Ctx,
18736 EvalResult &Status) const {
18737 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18738 PtrExpression, Ctx, Status);
18739}
18740
18741bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
18742 Expr::EvalStatus Status;
18743 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
18744
18745 if (Info.EnableNewConstInterp)
18746 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
18747
18748 return EvaluateBuiltinStrLen(this, Result, Info);
18749}
18750
18751namespace {
18752struct IsWithinLifetimeHandler {
18753 EvalInfo &Info;
18754 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
18755 using result_type = std::optional<bool>;
18756 std::optional<bool> failed() { return std::nullopt; }
18757 template <typename T>
18758 std::optional<bool> found(T &Subobj, QualType SubobjType) {
18759 return true;
18760 }
18761};
18762
18763std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
18764 const CallExpr *E) {
18765 EvalInfo &Info = IEE.Info;
18766 // Sometimes this is called during some sorts of constant folding / early
18767 // evaluation. These are meant for non-constant expressions and are not
18768 // necessary since this consteval builtin will never be evaluated at runtime.
18769 // Just fail to evaluate when not in a constant context.
18770 if (!Info.InConstantContext)
18771 return std::nullopt;
18772 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
18773 const Expr *Arg = E->getArg(0);
18774 if (Arg->isValueDependent())
18775 return std::nullopt;
18776 LValue Val;
18777 if (!EvaluatePointer(Arg, Val, Info))
18778 return std::nullopt;
18779
18780 if (Val.allowConstexprUnknown())
18781 return true;
18782
18783 auto Error = [&](int Diag) {
18784 bool CalledFromStd = false;
18785 const auto *Callee = Info.CurrentCall->getCallee();
18786 if (Callee && Callee->isInStdNamespace()) {
18787 const IdentifierInfo *Identifier = Callee->getIdentifier();
18788 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
18789 }
18790 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
18791 : E->getExprLoc(),
18792 diag::err_invalid_is_within_lifetime)
18793 << (CalledFromStd ? "std::is_within_lifetime"
18794 : "__builtin_is_within_lifetime")
18795 << Diag;
18796 return std::nullopt;
18797 };
18798 // C++2c [meta.const.eval]p4:
18799 // During the evaluation of an expression E as a core constant expression, a
18800 // call to this function is ill-formed unless p points to an object that is
18801 // usable in constant expressions or whose complete object's lifetime began
18802 // within E.
18803
18804 // Make sure it points to an object
18805 // nullptr does not point to an object
18806 if (Val.isNullPointer() || Val.getLValueBase().isNull())
18807 return Error(0);
18808 QualType T = Val.getLValueBase().getType();
18809 assert(!T->isFunctionType() &&
18810 "Pointers to functions should have been typed as function pointers "
18811 "which would have been rejected earlier");
18812 assert(T->isObjectType());
18813 // Hypothetical array element is not an object
18814 if (Val.getLValueDesignator().isOnePastTheEnd())
18815 return Error(1);
18816 assert(Val.getLValueDesignator().isValidSubobject() &&
18817 "Unchecked case for valid subobject");
18818 // All other ill-formed values should have failed EvaluatePointer, so the
18819 // object should be a pointer to an object that is usable in a constant
18820 // expression or whose complete lifetime began within the expression
18821 CompleteObject CO =
18822 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
18823 // The lifetime hasn't begun yet if we are still evaluating the
18824 // initializer ([basic.life]p(1.2))
18825 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
18826 return Error(2);
18827
18828 if (!CO)
18829 return false;
18830 IsWithinLifetimeHandler handler{Info};
18831 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
18832}
18833} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Expr * E
llvm::APSInt APSInt
Definition: Compiler.cpp:23
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1192
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, Expr::EvalResult &Status)
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize.
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type.
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class.
static bool hasVirtualDestructor(QualType T)
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value)
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid).
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool EvaluateDecompositionDeclInit(EvalInfo &Info, const DecompositionDecl *DD)
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value)
Evaluate an expression as a C++11 integral constant expression.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E.
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout.
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue.
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue.
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false, LValue *ObjectArg=nullptr)
Evaluate the arguments to a function call.
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const LValue &LVal, llvm::APInt &Result)
Convenience function.
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info, const ValueDecl *D, const Expr *Init, LValue &Result, APValue &Val)
Evaluates the initializer of a reference.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned.
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, const VarDecl *VD)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *ObjectArg, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
StringRef Identifier
Definition: Format.cpp:3185
const CFGBlock * Block
Definition: HTMLLogger.cpp:152
#define X(type, name)
Definition: Value.h:145
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
@ None
SourceLocation Loc
Definition: SemaObjC.cpp:754
bool Indirect
Definition: SemaObjC.cpp:755
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
__device__ int
a trap message and trap category.
QualType getType() const
Definition: APValue.cpp:63
QualType getDynamicAllocType() const
Definition: APValue.cpp:122
QualType getTypeInfoType() const
Definition: APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition: APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition: APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition: APValue.h:207
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition: APValue.h:215
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool hasArrayFiller() const
Definition: APValue.h:584
const LValueBase getLValueBase() const
Definition: APValue.cpp:983
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:576
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:474
APSInt & getInt()
Definition: APValue.h:489
APValue & getStructField(unsigned i)
Definition: APValue.h:617
const FieldDecl * getUnionField() const
Definition: APValue.h:629
bool isVector() const
Definition: APValue.h:473
APSInt & getComplexIntImag()
Definition: APValue.h:527
bool isAbsent() const
Definition: APValue.h:463
bool isComplexInt() const
Definition: APValue.h:470
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition: APValue.h:204
ValueKind getKind() const
Definition: APValue.h:461
unsigned getArrayInitializedElts() const
Definition: APValue.h:595
static APValue IndeterminateValue()
Definition: APValue.h:432
bool isFloat() const
Definition: APValue.h:468
APFixedPoint & getFixedPoint()
Definition: APValue.h:511
bool hasValue() const
Definition: APValue.h:465
bool hasLValuePath() const
Definition: APValue.cpp:998
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1066
APValue & getUnionValue()
Definition: APValue.h:633
CharUnits & getLValueOffset()
Definition: APValue.cpp:993
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:703
bool isComplexFloat() const
Definition: APValue.h:471
APValue & getVectorElt(unsigned I)
Definition: APValue.h:563
APValue & getArrayFiller()
Definition: APValue.h:587
unsigned getVectorLength() const
Definition: APValue.h:571
bool isLValue() const
Definition: APValue.h:472
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition: APValue.cpp:1059
bool isIndeterminate() const
Definition: APValue.h:464
bool isInt() const
Definition: APValue.h:467
unsigned getArraySize() const
Definition: APValue.h:599
bool allowConstexprUnknown() const
Definition: APValue.h:318
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:956
bool isFixedPoint() const
Definition: APValue.h:469
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
bool isStruct() const
Definition: APValue.h:475
APSInt & getComplexIntReal()
Definition: APValue.h:519
APFloat & getComplexFloatImag()
Definition: APValue.h:543
APFloat & getComplexFloatReal()
Definition: APValue.h:535
APFloat & getFloat()
Definition: APValue.h:503
APValue & getStructBase(unsigned i)
Definition: APValue.h:612
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
SourceManager & getSourceManager()
Definition: ASTContext.h:801
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2716
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2565
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:793
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2625
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
Definition: ASTContext.h:3310
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:3059
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2629
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:197
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:201
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:250
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:260
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4486
LabelDecl * getLabel() const
Definition: Expr.h:4509
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5957
Represents a loop initializing the elements of an array.
Definition: Expr.h:5904
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2723
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2990
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
QualType getElementType() const
Definition: TypeBase.h:3750
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: TypeBase.h:8142
Attr - This represents one attribute.
Definition: Attr.h:44
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4389
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition: Expr.h:4443
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:4424
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3974
Expr * getLHS() const
Definition: Expr.h:4024
bool isComparisonOp() const
Definition: Expr.h:4075
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:4121
bool isLogicalOp() const
Definition: Expr.h:4108
Expr * getRHS() const
Definition: Expr.h:4026
Opcode getOpcode() const
Definition: Expr.h:4019
A binding in a decomposition declaration.
Definition: DeclCXX.h:4179
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6560
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5470
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1494
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:723
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1549
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2604
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2999
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2690
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1271
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1378
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2620
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2869
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:481
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1753
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2255
bool isInstance() const
Definition: DeclCXX.h:2156
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2735
bool isStatic() const
Definition: DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2714
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition: DeclCXX.cpp:2845
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2349
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4303
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:768
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:5135
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition: DeclCXX.h:1233
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1673
base_class_iterator bases_end()
Definition: DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1366
base_class_range bases()
Definition: DeclCXX.h:608
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition: DeclCXX.cpp:1784
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:602
base_class_iterator bases_begin()
Definition: DeclCXX.h:615
capture_const_range captures() const
Definition: DeclCXX.h:1097
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1186
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2121
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1736
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:526
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:286
An expression "T()" which creates an rvalue of a non-class type T.
Definition: ExprCXX.h:2198
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:800
Represents the this expression in C++.
Definition: ExprCXX.h:1155
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:848
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1069
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1588
CaseStmt - Represent a case statement.
Definition: Stmt.h:1920
Expr * getLHS()
Definition: Stmt.h:2003
Expr * getRHS()
Definition: Stmt.h:2015
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3612
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3679
Expr * getSubExpr()
Definition: Expr.h:3662
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition: CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition: CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4784
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition: TypeBase.h:3293
QualType getElementType() const
Definition: TypeBase.h:3303
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4236
QualType getComputationLHSType() const
Definition: Expr.h:4270
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3541
bool isFileScope() const
Definition: Expr.h:3573
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1720
bool body_empty() const
Definition: Stmt.h:1764
Stmt *const * const_body_iterator
Definition: Stmt.h:1792
body_iterator body_end()
Definition: Stmt.h:1785
body_range body()
Definition: Stmt.h:1783
body_iterator body_begin()
Definition: Stmt.h:1784
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4327
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4350
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4354
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:196
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition: TypeBase.h:3839
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:214
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:254
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition: TypeBase.h:3865
bool isZeroSize() const
Return true if the size is zero.
Definition: TypeBase.h:3846
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: TypeBase.h:3872
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: TypeBase.h:3832
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: TypeBase.h:3852
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1084
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4655
Represents the current source location and context used to determine the value of the source location...
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2393
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1611
decl_range decls()
Definition: Stmt.h:1659
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:427
static void add(Kind k)
Definition: DeclBase.cpp:226
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:524
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:588
SourceLocation getLocation() const
Definition: DeclBase.h:439
DeclContext * getDeclContext()
Definition: DeclBase.h:448
AccessSpecifier getAccess() const
Definition: DeclBase.h:507
bool isAnyOperatorNew() const
A decomposition declaration.
Definition: DeclCXX.h:4243
auto flat_bindings() const
Definition: DeclCXX.h:4286
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2832
Stmt * getBody()
Definition: Stmt.h:2857
Expr * getCond()
Definition: Stmt.h:2850
Symbolic representation of a dynamic allocation.
Definition: APValue.h:65
static unsigned getMaxIndex()
Definition: APValue.h:85
Represents a reference to #emded data.
Definition: Expr.h:5062
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3420
EnumDecl * getDefinitionOrSelf() const
Definition: Decl.h:4111
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4168
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
EnumDecl * getOriginalDecl() const
Definition: TypeBase.h:6529
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3864
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3655
This represents one expression.
Definition: Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition: Expr.cpp:80
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition: Expr.h:287
SideEffectsKind
Definition: Expr.h:670
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:674
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition: Expr.h:672
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3078
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:177
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition: Expr.cpp:3922
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3073
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition: Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3069
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition: Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3624
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3207
ConstantExprKind
Definition: Expr.h:751
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:273
QualType getType() const
Definition: Expr.h:144
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
An expression trait intrinsic.
Definition: ExprCXX.h:3063
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6500
bool isFPConstrained() const
Definition: LangOptions.h:844
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:862
RoundingMode getRoundingMode() const
Definition: LangOptions.h:850
Represents a member of a struct/union/class.
Definition: Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4693
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3393
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3404
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:102
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2888
Represents a function declaration or definition.
Definition: Decl.h:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2794
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3271
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4146
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4134
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3806
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2376
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4270
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2780
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2469
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition: Decl.cpp:3414
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2384
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:3117
Declaration of a template function.
Definition: DeclTemplate.h:952
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4859
Represents a C11 generic selection.
Definition: Expr.h:6114
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2259
Stmt * getThen()
Definition: Stmt.h:2348
Stmt * getInit()
Definition: Stmt.h:2409
bool isNonNegatedConsteval() const
Definition: Stmt.h:2444
Expr * getCond()
Definition: Stmt.h:2336
Stmt * getElse()
Definition: Stmt.h:2357
bool isConsteval() const
Definition: Stmt.h:2439
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:1026
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1733
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5993
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3464
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3485
Describes an C or C++ initializer list.
Definition: Expr.h:5235
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1970
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
A global _GUID constant.
Definition: DeclCXX.h:4392
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4914
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3300
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition: Type.cpp:5502
This represents a decl that may have a name.
Definition: Decl.h:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1687
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:88
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:128
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:409
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:52
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2529
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2588
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2576
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2569
unsigned getNumComponents() const
Definition: Expr.h:2584
Helper class for OffsetOfExpr.
Definition: Expr.h:2423
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2481
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2487
@ Array
An index into an array.
Definition: Expr.h:2428
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2432
@ Field
A field.
Definition: Expr.h:2430
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2435
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2477
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2497
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
This expression type represents an asterisk in an OpenACC Size-Expr, used in the 'tile' and 'gang' cl...
Definition: Expr.h:2092
A partial diagnostic which we might know in advance that we are not going to emit.
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2184
Represents a parameter to a function.
Definition: Decl.h:1789
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1849
bool isExplicitObjectParameter() const
Definition: Decl.h:1877
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:2007
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6692
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: TypeBase.h:8427
QualType withConst() const
Definition: TypeBase.h:1159
void addConst()
Add the const type qualifier to this QualType.
Definition: TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
bool isConstant(const ASTContext &Ctx) const
Definition: TypeBase.h:1097
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: TypeBase.h:8528
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
void removeLocalVolatile()
Definition: TypeBase.h:8459
QualType withCVRQualifiers(unsigned CVR) const
Definition: TypeBase.h:1179
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: TypeBase.h:1164
void removeLocalConst()
Definition: TypeBase.h:8451
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: TypeBase.h:1545
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: TypeBase.h:8389
Represents a struct/union/class.
Definition: Decl.h:4309
bool hasFlexibleArrayMember() const
Definition: Decl.h:4342
field_iterator field_end() const
Definition: Decl.h:4515
field_range fields() const
Definition: Decl.h:4512
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4361
bool field_empty() const
Definition: Decl.h:4520
field_iterator field_begin() const
Definition: Decl.cpp:5154
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
Base for LValueReferenceType and RValueReferenceType.
Definition: TypeBase.h:3589
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:505
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4579
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4435
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4953
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4531
Stmt - This represents one statement.
Definition: Stmt.h:85
StmtClass getStmtClass() const
Definition: Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1801
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition: Expr.cpp:1184
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1884
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4658
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1893
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2509
Expr * getCond()
Definition: Stmt.h:2572
Stmt * getBody()
Definition: Stmt.h:2584
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:1144
Stmt * getInit()
Definition: Stmt.h:2589
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2640
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4840
bool isUnion() const
Definition: Decl.h:3919
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:1283
A template argument list.
Definition: DeclTemplate.h:250
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:286
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
A template parameter object.
Symbolic representation of typeid(T) for some type T.
Definition: APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition: TypeBase.h:8325
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2890
The base class of the type hierarchy.
Definition: TypeBase.h:1833
bool isStructureType() const
Definition: Type.cpp:678
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isFunctionReferenceType() const
Definition: TypeBase.h:8654
bool isMFloat8Type() const
Definition: TypeBase.h:8961
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2229
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition: Type.cpp:418
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2998
bool isIncompleteArrayType() const
Definition: TypeBase.h:8687
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2209
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:724
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: TypeBase.h:9235
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2277
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2119
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
bool isConstantArrayType() const
Definition: TypeBase.h:8683
bool isNothrowT() const
Definition: Type.cpp:3175
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.h:41
bool isVoidPointerType() const
Definition: Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2430
bool isArrayType() const
Definition: TypeBase.h:8679
bool isCharType() const
Definition: Type.cpp:2136
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isPointerType() const
Definition: TypeBase.h:8580
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: TypeBase.h:8980
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isVariableArrayType() const
Definition: TypeBase.h:8691
bool isChar8Type() const
Definition: Type.cpp:2152
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2612
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: TypeBase.h:9054
bool isExtVectorBoolType() const
Definition: TypeBase.h:8727
bool isMemberDataPointerType() const
Definition: TypeBase.h:8672
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: TypeBase.h:8905
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
RecordDecl * castAsRecordDecl() const
Definition: Type.h:48
bool isAnyComplexType() const
Definition: TypeBase.h:8715
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:8992
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: TypeBase.h:9109
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isAtomicType() const
Definition: TypeBase.h:8762
bool isComplexIntegerType() const
Definition: Type.cpp:730
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: TypeBase.h:9212
bool isObjectType() const
Determine whether this type is an object type.
Definition: TypeBase.h:2528
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition: Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2440
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isVectorType() const
Definition: TypeBase.h:8719
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2324
bool isFloatingType() const
Definition: Type.cpp:2308
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2257
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition: TypeBase.h:2946
bool isAnyPointerType() const
Definition: TypeBase.h:8588
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
bool isNullPtrType() const
Definition: TypeBase.h:8973
bool isRecordType() const
Definition: TypeBase.h:8707
bool isUnionType() const
Definition: Type.cpp:718
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2574
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: TypeBase.h:9100
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2627
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2696
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2659
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2246
Expr * getSubExpr() const
Definition: Expr.h:2287
Opcode getOpcode() const
Definition: Expr.h:2282
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2328
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4449
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
QualType getType() const
Definition: Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5449
QualType getType() const
Definition: Value.cpp:237
bool hasValue() const
Definition: Value.h:135
Represents a variable declaration or definition.
Definition: Decl.h:925
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1568
bool hasInit() const
Definition: Decl.cpp:2398
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2636
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1577
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2575
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2877
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2648
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2366
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2486
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1207
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1176
const Expr * getInit() const
Definition: Decl.h:1367
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition: Decl.cpp:2628
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1183
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2375
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1252
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2528
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1357
Expr * getSizeExpr() const
Definition: TypeBase.h:3996
Represents a GCC generic vector type.
Definition: TypeBase.h:4191
unsigned getNumElements() const
Definition: TypeBase.h:4206
QualType getElementType() const
Definition: TypeBase.h:4205
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2697
Expr * getCond()
Definition: Stmt.h:2749
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1205
Stmt * getBody()
Definition: Stmt.h:2761
Base class for stack frames, shared between VM and walker.
Definition: Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition: State.h:58
#define bool
Definition: gpuintrin.h:32
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition: limits.h:71
#define UINT_MAX
Definition: limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition: OSLog.cpp:192
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:4035
llvm::APFloat APFloat
Definition: Floating.h:27
llvm::APInt APInt
Definition: FixedPoint.h:19
bool Call(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition: Interp.cpp:1551
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1260
llvm::FixedPointSemantics FixedPointSemantics
Definition: Interp.h:41
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition: Interp.h:3464
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
@ NonNull
Values of this type can never be null.
@ Success
Annotation was successful.
BinaryOperatorKind
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition: CallGraph.h:204
@ AS_public
Definition: Specifiers.h:124
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:45
@ TSCS_unspecified
Definition: Specifiers.h:236
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition: State.h:42
@ CSK_ArrayToPointer
Definition: State.h:46
@ CSK_Derived
Definition: State.h:44
@ CSK_Base
Definition: State.h:43
@ CSK_Real
Definition: State.h:48
@ CSK_ArrayIndex
Definition: State.h:47
@ CSK_Imag
Definition: State.h:49
@ CSK_VectorElement
Definition: State.h:50
@ CSK_Field
Definition: State.h:45
@ SD_Static
Static storage duration.
Definition: Specifiers.h:343
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:340
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition: State.h:26
@ AK_TypeId
Definition: State.h:34
@ AK_Construct
Definition: State.h:35
@ AK_Increment
Definition: State.h:30
@ AK_DynamicCast
Definition: State.h:33
@ AK_Read
Definition: State.h:27
@ AK_Assign
Definition: State.h:29
@ AK_IsWithinLifetime
Definition: State.h:37
@ AK_MemberCall
Definition: State.h:32
@ AK_ReadObjectRepresentation
Definition: State.h:28
@ AK_Dereference
Definition: State.h:38
@ AK_Destroy
Definition: State.h:36
@ AK_Decrement
Definition: State.h:31
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:249
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1288
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ None
The alignment was not explicit in code.
@ ArrayBound
Array bound in array declarator or new-expression.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
#define false
Definition: stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:647
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition: Expr.h:609
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:633
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:617
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:612
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition: tgmath.h:851
#define scalbn(__x, __y)
Definition: tgmath.h:1165