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
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(const 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(const 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] {
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;
679 APValue::LValueBase Base;
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) {
694 SourceLocation Loc;
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 {
712 APValue::LValueBase Base;
713 ArrayRef<APValue::LValuePathEntry> Path;
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.
754 APValue Value;
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.
827 llvm::SmallVector<Cleanup, 16> CleanupStack;
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,
909 ArrayRef<APValue::LValuePathEntry> Path) {
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 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
930 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
931 CallStackDepth(0), NextCallIndex(1),
932 StepsLeft(C.getLangOpts().ConstexprStepLimit),
933 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
934 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
935 /*This=*/nullptr,
936 /*CallExpr=*/nullptr, CallRef()),
937 EvaluatingDecl((const ValueDecl *)nullptr),
938 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
939 HasFoldFailureDiagnostic(false) {
940 EvalMode = Mode;
941 }
942
943 ~EvalInfo() {
944 discardCleanups();
945 }
946
947 ASTContext &getASTContext() const override { return Ctx; }
948 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
949
950 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
951 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
952 EvaluatingDecl = Base;
953 IsEvaluatingDecl = EDK;
954 EvaluatingDeclValue = &Value;
955 }
956
957 bool CheckCallLimit(SourceLocation Loc) {
958 // Don't perform any constexpr calls (other than the call we're checking)
959 // when checking a potential constant expression.
960 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
961 return false;
962 if (NextCallIndex == 0) {
963 // NextCallIndex has wrapped around.
964 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
965 return false;
966 }
967 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
968 return true;
969 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
970 << getLangOpts().ConstexprCallDepth;
971 return false;
972 }
973
974 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
975 uint64_t ElemCount, bool Diag) {
976 // FIXME: GH63562
977 // APValue stores array extents as unsigned,
978 // so anything that is greater that unsigned would overflow when
979 // constructing the array, we catch this here.
980 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
981 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
982 if (Diag)
983 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
984 return false;
985 }
986
987 // FIXME: GH63562
988 // Arrays allocate an APValue per element.
989 // We use the number of constexpr steps as a proxy for the maximum size
990 // of arrays to avoid exhausting the system resources, as initialization
991 // of each element is likely to take some number of steps anyway.
992 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
993 if (ElemCount > Limit) {
994 if (Diag)
995 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
996 << ElemCount << Limit;
997 return false;
998 }
999 return true;
1000 }
1001
1002 std::pair<CallStackFrame *, unsigned>
1003 getCallFrameAndDepth(unsigned CallIndex) {
1004 assert(CallIndex && "no call index in getCallFrameAndDepth");
1005 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1006 // be null in this loop.
1007 unsigned Depth = CallStackDepth;
1008 CallStackFrame *Frame = CurrentCall;
1009 while (Frame->Index > CallIndex) {
1010 Frame = Frame->Caller;
1011 --Depth;
1012 }
1013 if (Frame->Index == CallIndex)
1014 return {Frame, Depth};
1015 return {nullptr, 0};
1016 }
1017
1018 bool nextStep(const Stmt *S) {
1019 if (!StepsLeft) {
1020 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1021 return false;
1022 }
1023 --StepsLeft;
1024 return true;
1025 }
1026
1027 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1028
1029 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1030 std::optional<DynAlloc *> Result;
1031 auto It = HeapAllocs.find(DA);
1032 if (It != HeapAllocs.end())
1033 Result = &It->second;
1034 return Result;
1035 }
1036
1037 /// Get the allocated storage for the given parameter of the given call.
1038 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1039 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1040 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1041 : nullptr;
1042 }
1043
1044 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1045 struct StdAllocatorCaller {
1046 unsigned FrameIndex;
1047 QualType ElemType;
1048 const Expr *Call;
1049 explicit operator bool() const { return FrameIndex != 0; };
1050 };
1051
1052 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1053 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1054 Call = Call->Caller) {
1055 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1056 if (!MD)
1057 continue;
1058 const IdentifierInfo *FnII = MD->getIdentifier();
1059 if (!FnII || !FnII->isStr(FnName))
1060 continue;
1061
1062 const auto *CTSD =
1063 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1064 if (!CTSD)
1065 continue;
1066
1067 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1068 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1069 if (CTSD->isInStdNamespace() && ClassII &&
1070 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1071 TAL[0].getKind() == TemplateArgument::Type)
1072 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1073 }
1074
1075 return {};
1076 }
1077
1078 void performLifetimeExtension() {
1079 // Disable the cleanups for lifetime-extended temporaries.
1080 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1081 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1082 });
1083 }
1084
1085 /// Throw away any remaining cleanups at the end of evaluation. If any
1086 /// cleanups would have had a side-effect, note that as an unmodeled
1087 /// side-effect and return false. Otherwise, return true.
1088 bool discardCleanups() {
1089 for (Cleanup &C : CleanupStack) {
1090 if (C.hasSideEffect() && !noteSideEffect()) {
1091 CleanupStack.clear();
1092 return false;
1093 }
1094 }
1095 CleanupStack.clear();
1096 return true;
1097 }
1098
1099 private:
1100 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1101 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1102
1103 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1104 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1105
1106 void setFoldFailureDiagnostic(bool Flag) override {
1107 HasFoldFailureDiagnostic = Flag;
1108 }
1109
1110 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1111
1112 // If we have a prior diagnostic, it will be noting that the expression
1113 // isn't a constant expression. This diagnostic is more important,
1114 // unless we require this evaluation to produce a constant expression.
1115 //
1116 // FIXME: We might want to show both diagnostics to the user in
1117 // EvaluationMode::ConstantFold mode.
1118 bool hasPriorDiagnostic() override {
1119 if (!EvalStatus.Diag->empty()) {
1120 switch (EvalMode) {
1121 case EvaluationMode::ConstantFold:
1122 case EvaluationMode::IgnoreSideEffects:
1123 if (!HasFoldFailureDiagnostic)
1124 break;
1125 // We've already failed to fold something. Keep that diagnostic.
1126 [[fallthrough]];
1127 case EvaluationMode::ConstantExpression:
1128 case EvaluationMode::ConstantExpressionUnevaluated:
1129 setActiveDiagnostic(false);
1130 return true;
1131 }
1132 }
1133 return false;
1134 }
1135
1136 unsigned getCallStackDepth() override { return CallStackDepth; }
1137
1138 public:
1139 /// Should we continue evaluation after encountering a side-effect that we
1140 /// couldn't model?
1141 bool keepEvaluatingAfterSideEffect() const override {
1142 switch (EvalMode) {
1143 case EvaluationMode::IgnoreSideEffects:
1144 return true;
1145
1146 case EvaluationMode::ConstantExpression:
1147 case EvaluationMode::ConstantExpressionUnevaluated:
1148 case EvaluationMode::ConstantFold:
1149 // By default, assume any side effect might be valid in some other
1150 // evaluation of this expression from a different context.
1151 return checkingPotentialConstantExpression() ||
1152 checkingForUndefinedBehavior();
1153 }
1154 llvm_unreachable("Missed EvalMode case");
1155 }
1156
1157 /// Note that we have had a side-effect, and determine whether we should
1158 /// keep evaluating.
1159 bool noteSideEffect() override {
1160 EvalStatus.HasSideEffects = true;
1161 return keepEvaluatingAfterSideEffect();
1162 }
1163
1164 /// Should we continue evaluation after encountering undefined behavior?
1165 bool keepEvaluatingAfterUndefinedBehavior() {
1166 switch (EvalMode) {
1167 case EvaluationMode::IgnoreSideEffects:
1168 case EvaluationMode::ConstantFold:
1169 return true;
1170
1171 case EvaluationMode::ConstantExpression:
1172 case EvaluationMode::ConstantExpressionUnevaluated:
1173 return checkingForUndefinedBehavior();
1174 }
1175 llvm_unreachable("Missed EvalMode case");
1176 }
1177
1178 /// Note that we hit something that was technically undefined behavior, but
1179 /// that we can evaluate past it (such as signed overflow or floating-point
1180 /// division by zero.)
1181 bool noteUndefinedBehavior() override {
1182 EvalStatus.HasUndefinedBehavior = true;
1183 return keepEvaluatingAfterUndefinedBehavior();
1184 }
1185
1186 /// Should we continue evaluation as much as possible after encountering a
1187 /// construct which can't be reduced to a value?
1188 bool keepEvaluatingAfterFailure() const override {
1189 if (!StepsLeft)
1190 return false;
1191
1192 switch (EvalMode) {
1193 case EvaluationMode::ConstantExpression:
1194 case EvaluationMode::ConstantExpressionUnevaluated:
1195 case EvaluationMode::ConstantFold:
1196 case EvaluationMode::IgnoreSideEffects:
1197 return checkingPotentialConstantExpression() ||
1198 checkingForUndefinedBehavior();
1199 }
1200 llvm_unreachable("Missed EvalMode case");
1201 }
1202
1203 /// Notes that we failed to evaluate an expression that other expressions
1204 /// directly depend on, and determine if we should keep evaluating. This
1205 /// should only be called if we actually intend to keep evaluating.
1206 ///
1207 /// Call noteSideEffect() instead if we may be able to ignore the value that
1208 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1209 ///
1210 /// (Foo(), 1) // use noteSideEffect
1211 /// (Foo() || true) // use noteSideEffect
1212 /// Foo() + 1 // use noteFailure
1213 [[nodiscard]] bool noteFailure() {
1214 // Failure when evaluating some expression often means there is some
1215 // subexpression whose evaluation was skipped. Therefore, (because we
1216 // don't track whether we skipped an expression when unwinding after an
1217 // evaluation failure) every evaluation failure that bubbles up from a
1218 // subexpression implies that a side-effect has potentially happened. We
1219 // skip setting the HasSideEffects flag to true until we decide to
1220 // continue evaluating after that point, which happens here.
1221 bool KeepGoing = keepEvaluatingAfterFailure();
1222 EvalStatus.HasSideEffects |= KeepGoing;
1223 return KeepGoing;
1224 }
1225
1226 class ArrayInitLoopIndex {
1227 EvalInfo &Info;
1228 uint64_t OuterIndex;
1229
1230 public:
1231 ArrayInitLoopIndex(EvalInfo &Info)
1232 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1233 Info.ArrayInitIndex = 0;
1234 }
1235 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1236
1237 operator uint64_t&() { return Info.ArrayInitIndex; }
1238 };
1239 };
1240
1241 /// Object used to treat all foldable expressions as constant expressions.
1242 struct FoldConstant {
1243 EvalInfo &Info;
1244 bool Enabled;
1245 bool HadNoPriorDiags;
1246 EvaluationMode OldMode;
1247
1248 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1249 : Info(Info),
1250 Enabled(Enabled),
1251 HadNoPriorDiags(Info.EvalStatus.Diag &&
1252 Info.EvalStatus.Diag->empty() &&
1253 !Info.EvalStatus.HasSideEffects),
1254 OldMode(Info.EvalMode) {
1255 if (Enabled)
1256 Info.EvalMode = EvaluationMode::ConstantFold;
1257 }
1258 void keepDiagnostics() { Enabled = false; }
1259 ~FoldConstant() {
1260 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1261 !Info.EvalStatus.HasSideEffects)
1262 Info.EvalStatus.Diag->clear();
1263 Info.EvalMode = OldMode;
1264 }
1265 };
1266
1267 /// RAII object used to set the current evaluation mode to ignore
1268 /// side-effects.
1269 struct IgnoreSideEffectsRAII {
1270 EvalInfo &Info;
1271 EvaluationMode OldMode;
1272 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1273 : Info(Info), OldMode(Info.EvalMode) {
1274 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1275 }
1276
1277 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1278 };
1279
1280 /// RAII object used to optionally suppress diagnostics and side-effects from
1281 /// a speculative evaluation.
1282 class SpeculativeEvaluationRAII {
1283 EvalInfo *Info = nullptr;
1284 Expr::EvalStatus OldStatus;
1285 unsigned OldSpeculativeEvaluationDepth = 0;
1286
1287 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1288 Info = Other.Info;
1289 OldStatus = Other.OldStatus;
1290 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1291 Other.Info = nullptr;
1292 }
1293
1294 void maybeRestoreState() {
1295 if (!Info)
1296 return;
1297
1298 Info->EvalStatus = OldStatus;
1299 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1300 }
1301
1302 public:
1303 SpeculativeEvaluationRAII() = default;
1304
1305 SpeculativeEvaluationRAII(
1306 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1307 : Info(&Info), OldStatus(Info.EvalStatus),
1308 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1309 Info.EvalStatus.Diag = NewDiag;
1310 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1311 }
1312
1313 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1314 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1315 moveFromAndCancel(std::move(Other));
1316 }
1317
1318 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1319 maybeRestoreState();
1320 moveFromAndCancel(std::move(Other));
1321 return *this;
1322 }
1323
1324 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1325 };
1326
1327 /// RAII object wrapping a full-expression or block scope, and handling
1328 /// the ending of the lifetime of temporaries created within it.
1329 template<ScopeKind Kind>
1330 class ScopeRAII {
1331 EvalInfo &Info;
1332 unsigned OldStackSize;
1333 public:
1334 ScopeRAII(EvalInfo &Info)
1335 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1336 // Push a new temporary version. This is needed to distinguish between
1337 // temporaries created in different iterations of a loop.
1338 Info.CurrentCall->pushTempVersion();
1339 }
1340 bool destroy(bool RunDestructors = true) {
1341 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1342 OldStackSize = std::numeric_limits<unsigned>::max();
1343 return OK;
1344 }
1345 ~ScopeRAII() {
1346 if (OldStackSize != std::numeric_limits<unsigned>::max())
1347 destroy(false);
1348 // Body moved to a static method to encourage the compiler to inline away
1349 // instances of this class.
1350 Info.CurrentCall->popTempVersion();
1351 }
1352 private:
1353 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1354 unsigned OldStackSize) {
1355 assert(OldStackSize <= Info.CleanupStack.size() &&
1356 "running cleanups out of order?");
1357
1358 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1359 // for a full-expression scope.
1360 bool Success = true;
1361 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1362 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1363 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1364 Success = false;
1365 break;
1366 }
1367 }
1368 }
1369
1370 // Compact any retained cleanups.
1371 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1372 if (Kind != ScopeKind::Block)
1373 NewEnd =
1374 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1375 return C.isDestroyedAtEndOf(Kind);
1376 });
1377 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1378 return Success;
1379 }
1380 };
1381 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1382 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1383 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1384}
1385
1386bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1387 CheckSubobjectKind CSK) {
1388 if (Invalid)
1389 return false;
1390 if (isOnePastTheEnd()) {
1391 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1392 << CSK;
1393 setInvalid();
1394 return false;
1395 }
1396 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1397 // must actually be at least one array element; even a VLA cannot have a
1398 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1399 return true;
1400}
1401
1402void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1403 const Expr *E) {
1404 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1405 // Do not set the designator as invalid: we can represent this situation,
1406 // and correct handling of __builtin_object_size requires us to do so.
1407}
1408
1409void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1410 const Expr *E,
1411 const APSInt &N) {
1412 // If we're complaining, we must be able to statically determine the size of
1413 // the most derived array.
1414 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1415 Info.CCEDiag(E, diag::note_constexpr_array_index)
1416 << N << /*array*/ 0
1417 << static_cast<unsigned>(getMostDerivedArraySize());
1418 else
1419 Info.CCEDiag(E, diag::note_constexpr_array_index)
1420 << N << /*non-array*/ 1;
1421 setInvalid();
1422}
1423
1424CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1425 const FunctionDecl *Callee, const LValue *This,
1426 const Expr *CallExpr, CallRef Call)
1427 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1428 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1429 Index(Info.NextCallIndex++) {
1430 Info.CurrentCall = this;
1431 ++Info.CallStackDepth;
1432}
1433
1434CallStackFrame::~CallStackFrame() {
1435 assert(Info.CurrentCall == this && "calls retired out of order");
1436 --Info.CallStackDepth;
1437 Info.CurrentCall = Caller;
1438}
1439
1440static bool isRead(AccessKinds AK) {
1441 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1442 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1443}
1444
1446 switch (AK) {
1447 case AK_Read:
1449 case AK_MemberCall:
1450 case AK_DynamicCast:
1451 case AK_TypeId:
1453 case AK_Dereference:
1454 return false;
1455 case AK_Assign:
1456 case AK_Increment:
1457 case AK_Decrement:
1458 case AK_Construct:
1459 case AK_Destroy:
1460 return true;
1461 }
1462 llvm_unreachable("unknown access kind");
1463}
1464
1465static bool isAnyAccess(AccessKinds AK) {
1466 return isRead(AK) || isModification(AK);
1467}
1468
1469/// Is this an access per the C++ definition?
1471 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1472 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1473}
1474
1475/// Is this kind of access valid on an indeterminate object value?
1477 switch (AK) {
1478 case AK_Read:
1479 case AK_Increment:
1480 case AK_Decrement:
1481 case AK_Dereference:
1482 // These need the object's value.
1483 return false;
1484
1487 case AK_Assign:
1488 case AK_Construct:
1489 case AK_Destroy:
1490 // Construction and destruction don't need the value.
1491 return true;
1492
1493 case AK_MemberCall:
1494 case AK_DynamicCast:
1495 case AK_TypeId:
1496 // These aren't really meaningful on scalars.
1497 return true;
1498 }
1499 llvm_unreachable("unknown access kind");
1500}
1501
1502namespace {
1503 struct ComplexValue {
1504 private:
1505 bool IsInt;
1506
1507 public:
1508 APSInt IntReal, IntImag;
1509 APFloat FloatReal, FloatImag;
1510
1511 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1512
1513 void makeComplexFloat() { IsInt = false; }
1514 bool isComplexFloat() const { return !IsInt; }
1515 APFloat &getComplexFloatReal() { return FloatReal; }
1516 APFloat &getComplexFloatImag() { return FloatImag; }
1517
1518 void makeComplexInt() { IsInt = true; }
1519 bool isComplexInt() const { return IsInt; }
1520 APSInt &getComplexIntReal() { return IntReal; }
1521 APSInt &getComplexIntImag() { return IntImag; }
1522
1523 void moveInto(APValue &v) const {
1524 if (isComplexFloat())
1525 v = APValue(FloatReal, FloatImag);
1526 else
1527 v = APValue(IntReal, IntImag);
1528 }
1529 void setFrom(const APValue &v) {
1530 assert(v.isComplexFloat() || v.isComplexInt());
1531 if (v.isComplexFloat()) {
1532 makeComplexFloat();
1533 FloatReal = v.getComplexFloatReal();
1534 FloatImag = v.getComplexFloatImag();
1535 } else {
1536 makeComplexInt();
1537 IntReal = v.getComplexIntReal();
1538 IntImag = v.getComplexIntImag();
1539 }
1540 }
1541 };
1542
1543 struct LValue {
1544 APValue::LValueBase Base;
1545 CharUnits Offset;
1546 SubobjectDesignator Designator;
1547 bool IsNullPtr : 1;
1548 bool InvalidBase : 1;
1549 // P2280R4 track if we have an unknown reference or pointer.
1550 bool AllowConstexprUnknown = false;
1551
1552 const APValue::LValueBase getLValueBase() const { return Base; }
1553 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1554 CharUnits &getLValueOffset() { return Offset; }
1555 const CharUnits &getLValueOffset() const { return Offset; }
1556 SubobjectDesignator &getLValueDesignator() { return Designator; }
1557 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1558 bool isNullPointer() const { return IsNullPtr;}
1559
1560 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1561 unsigned getLValueVersion() const { return Base.getVersion(); }
1562
1563 void moveInto(APValue &V) const {
1564 if (Designator.Invalid)
1565 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1566 else {
1567 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1568 V = APValue(Base, Offset, Designator.Entries,
1569 Designator.IsOnePastTheEnd, IsNullPtr);
1570 }
1571 if (AllowConstexprUnknown)
1572 V.setConstexprUnknown();
1573 }
1574 void setFrom(const ASTContext &Ctx, const APValue &V) {
1575 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1576 Base = V.getLValueBase();
1577 Offset = V.getLValueOffset();
1578 InvalidBase = false;
1579 Designator = SubobjectDesignator(Ctx, V);
1580 IsNullPtr = V.isNullPointer();
1581 AllowConstexprUnknown = V.allowConstexprUnknown();
1582 }
1583
1584 void set(APValue::LValueBase B, bool BInvalid = false) {
1585#ifndef NDEBUG
1586 // We only allow a few types of invalid bases. Enforce that here.
1587 if (BInvalid) {
1588 const auto *E = B.get<const Expr *>();
1589 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1590 "Unexpected type of invalid base");
1591 }
1592#endif
1593
1594 Base = B;
1595 Offset = CharUnits::fromQuantity(0);
1596 InvalidBase = BInvalid;
1597 Designator = SubobjectDesignator(getType(B));
1598 IsNullPtr = false;
1599 AllowConstexprUnknown = false;
1600 }
1601
1602 void setNull(ASTContext &Ctx, QualType PointerTy) {
1603 Base = (const ValueDecl *)nullptr;
1604 Offset =
1606 InvalidBase = false;
1607 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1608 IsNullPtr = true;
1609 AllowConstexprUnknown = false;
1610 }
1611
1612 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1613 set(B, true);
1614 }
1615
1616 std::string toString(ASTContext &Ctx, QualType T) const {
1617 APValue Printable;
1618 moveInto(Printable);
1619 return Printable.getAsString(Ctx, T);
1620 }
1621
1622 private:
1623 // Check that this LValue is not based on a null pointer. If it is, produce
1624 // a diagnostic and mark the designator as invalid.
1625 template <typename GenDiagType>
1626 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1627 if (Designator.Invalid)
1628 return false;
1629 if (IsNullPtr) {
1630 GenDiag();
1631 Designator.setInvalid();
1632 return false;
1633 }
1634 return true;
1635 }
1636
1637 public:
1638 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1639 CheckSubobjectKind CSK) {
1640 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1641 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1642 });
1643 }
1644
1645 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1646 AccessKinds AK) {
1647 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1648 if (AK == AccessKinds::AK_Dereference)
1649 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1650 else
1651 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1652 });
1653 }
1654
1655 // Check this LValue refers to an object. If not, set the designator to be
1656 // invalid and emit a diagnostic.
1657 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1658 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1659 Designator.checkSubobject(Info, E, CSK);
1660 }
1661
1662 void addDecl(EvalInfo &Info, const Expr *E,
1663 const Decl *D, bool Virtual = false) {
1664 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1665 Designator.addDeclUnchecked(D, Virtual);
1666 }
1667 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1668 if (!Designator.Entries.empty()) {
1669 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1670 Designator.setInvalid();
1671 return;
1672 }
1673 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1674 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1675 getType(Base).getNonReferenceType()->isArrayType());
1676 Designator.FirstEntryIsAnUnsizedArray = true;
1677 Designator.addUnsizedArrayUnchecked(ElemTy);
1678 }
1679 }
1680 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1681 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1682 Designator.addArrayUnchecked(CAT);
1683 }
1684 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1685 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1686 Designator.addComplexUnchecked(EltTy, Imag);
1687 }
1688 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1689 uint64_t Size, uint64_t Idx) {
1690 if (checkSubobject(Info, E, CSK_VectorElement))
1691 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1692 }
1693 void clearIsNullPointer() {
1694 IsNullPtr = false;
1695 }
1696 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1697 const APSInt &Index, CharUnits ElementSize) {
1698 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1699 // but we're not required to diagnose it and it's valid in C++.)
1700 if (!Index)
1701 return;
1702
1703 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1704 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1705 // offsets.
1706 uint64_t Offset64 = Offset.getQuantity();
1707 uint64_t ElemSize64 = ElementSize.getQuantity();
1708 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1709 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1710
1711 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1712 Designator.adjustIndex(Info, E, Index, *this);
1713 clearIsNullPointer();
1714 }
1715 void adjustOffset(CharUnits N) {
1716 Offset += N;
1717 if (N.getQuantity())
1718 clearIsNullPointer();
1719 }
1720 };
1721
1722 struct MemberPtr {
1723 MemberPtr() {}
1724 explicit MemberPtr(const ValueDecl *Decl)
1725 : DeclAndIsDerivedMember(Decl, false) {}
1726
1727 /// The member or (direct or indirect) field referred to by this member
1728 /// pointer, or 0 if this is a null member pointer.
1729 const ValueDecl *getDecl() const {
1730 return DeclAndIsDerivedMember.getPointer();
1731 }
1732 /// Is this actually a member of some type derived from the relevant class?
1733 bool isDerivedMember() const {
1734 return DeclAndIsDerivedMember.getInt();
1735 }
1736 /// Get the class which the declaration actually lives in.
1737 const CXXRecordDecl *getContainingRecord() const {
1738 return cast<CXXRecordDecl>(
1739 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1740 }
1741
1742 void moveInto(APValue &V) const {
1743 V = APValue(getDecl(), isDerivedMember(), Path);
1744 }
1745 void setFrom(const APValue &V) {
1746 assert(V.isMemberPointer());
1747 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1748 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1749 Path.clear();
1750 llvm::append_range(Path, V.getMemberPointerPath());
1751 }
1752
1753 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1754 /// whether the member is a member of some class derived from the class type
1755 /// of the member pointer.
1756 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1757 /// Path - The path of base/derived classes from the member declaration's
1758 /// class (exclusive) to the class type of the member pointer (inclusive).
1759 SmallVector<const CXXRecordDecl*, 4> Path;
1760
1761 /// Perform a cast towards the class of the Decl (either up or down the
1762 /// hierarchy).
1763 bool castBack(const CXXRecordDecl *Class) {
1764 assert(!Path.empty());
1765 const CXXRecordDecl *Expected;
1766 if (Path.size() >= 2)
1767 Expected = Path[Path.size() - 2];
1768 else
1769 Expected = getContainingRecord();
1770 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1771 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1772 // if B does not contain the original member and is not a base or
1773 // derived class of the class containing the original member, the result
1774 // of the cast is undefined.
1775 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1776 // (D::*). We consider that to be a language defect.
1777 return false;
1778 }
1779 Path.pop_back();
1780 return true;
1781 }
1782 /// Perform a base-to-derived member pointer cast.
1783 bool castToDerived(const CXXRecordDecl *Derived) {
1784 if (!getDecl())
1785 return true;
1786 if (!isDerivedMember()) {
1787 Path.push_back(Derived);
1788 return true;
1789 }
1790 if (!castBack(Derived))
1791 return false;
1792 if (Path.empty())
1793 DeclAndIsDerivedMember.setInt(false);
1794 return true;
1795 }
1796 /// Perform a derived-to-base member pointer cast.
1797 bool castToBase(const CXXRecordDecl *Base) {
1798 if (!getDecl())
1799 return true;
1800 if (Path.empty())
1801 DeclAndIsDerivedMember.setInt(true);
1802 if (isDerivedMember()) {
1803 Path.push_back(Base);
1804 return true;
1805 }
1806 return castBack(Base);
1807 }
1808 };
1809
1810 /// Compare two member pointers, which are assumed to be of the same type.
1811 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1812 if (!LHS.getDecl() || !RHS.getDecl())
1813 return !LHS.getDecl() && !RHS.getDecl();
1814 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1815 return false;
1816 return LHS.Path == RHS.Path;
1817 }
1818}
1819
1820void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1821 const LValue &LV) {
1822 if (Invalid || !N)
1823 return;
1824 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1825 if (isMostDerivedAnUnsizedArray()) {
1826 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1827 // Can't verify -- trust that the user is doing the right thing (or if
1828 // not, trust that the caller will catch the bad behavior).
1829 // FIXME: Should we reject if this overflows, at least?
1830 Entries.back() =
1831 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1832 return;
1833 }
1834
1835 // [expr.add]p4: For the purposes of these operators, a pointer to a
1836 // nonarray object behaves the same as a pointer to the first element of
1837 // an array of length one with the type of the object as its element type.
1838 bool IsArray =
1839 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1840 uint64_t ArrayIndex =
1841 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1842 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1843
1844 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1845 if (!Info.checkingPotentialConstantExpression() ||
1846 !LV.AllowConstexprUnknown) {
1847 // Calculate the actual index in a wide enough type, so we can include
1848 // it in the note.
1849 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1850 (llvm::APInt &)N += ArrayIndex;
1851 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1852 diagnosePointerArithmetic(Info, E, N);
1853 }
1854 setInvalid();
1855 return;
1856 }
1857
1858 ArrayIndex += TruncatedN;
1859 assert(ArrayIndex <= ArraySize &&
1860 "bounds check succeeded for out-of-bounds index");
1861
1862 if (IsArray)
1863 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1864 else
1865 IsOnePastTheEnd = (ArrayIndex != 0);
1866}
1867
1868static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1869static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1870 const LValue &This, const Expr *E,
1871 bool AllowNonLiteralTypes = false);
1872static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1873 bool InvalidBaseOK = false);
1874static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1875 bool InvalidBaseOK = false);
1876static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1877 EvalInfo &Info);
1878static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1879static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1880static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1881 EvalInfo &Info);
1882static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1883static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1884static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1885 EvalInfo &Info);
1886static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1887static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1888 EvalInfo &Info,
1889 std::string *StringResult = nullptr);
1890
1891/// Evaluate an integer or fixed point expression into an APResult.
1892static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1893 EvalInfo &Info);
1894
1895/// Evaluate only a fixed point expression into an APResult.
1896static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1897 EvalInfo &Info);
1898
1899//===----------------------------------------------------------------------===//
1900// Misc utilities
1901//===----------------------------------------------------------------------===//
1902
1903/// Negate an APSInt in place, converting it to a signed form if necessary, and
1904/// preserving its value (by extending by up to one bit as needed).
1905static void negateAsSigned(APSInt &Int) {
1906 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1907 Int = Int.extend(Int.getBitWidth() + 1);
1908 Int.setIsSigned(true);
1909 }
1910 Int = -Int;
1911}
1912
1913template<typename KeyT>
1914APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1915 ScopeKind Scope, LValue &LV) {
1916 unsigned Version = getTempVersion();
1917 APValue::LValueBase Base(Key, Index, Version);
1918 LV.set(Base);
1919 return createLocal(Base, Key, T, Scope);
1920}
1921
1922/// Allocate storage for a parameter of a function call made in this frame.
1923APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1924 LValue &LV) {
1925 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1926 APValue::LValueBase Base(PVD, Index, Args.Version);
1927 LV.set(Base);
1928 // We always destroy parameters at the end of the call, even if we'd allow
1929 // them to live to the end of the full-expression at runtime, in order to
1930 // give portable results and match other compilers.
1931 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1932}
1933
1934APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1935 QualType T, ScopeKind Scope) {
1936 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1937 unsigned Version = Base.getVersion();
1938 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1939 assert(Result.isAbsent() && "local created multiple times");
1940
1941 // If we're creating a local immediately in the operand of a speculative
1942 // evaluation, don't register a cleanup to be run outside the speculative
1943 // evaluation context, since we won't actually be able to initialize this
1944 // object.
1945 if (Index <= Info.SpeculativeEvaluationDepth) {
1946 if (T.isDestructedType())
1947 Info.noteSideEffect();
1948 } else {
1949 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1950 }
1951 return Result;
1952}
1953
1954APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1955 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1956 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1957 return nullptr;
1958 }
1959
1960 DynamicAllocLValue DA(NumHeapAllocs++);
1962 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1963 std::forward_as_tuple(DA), std::tuple<>());
1964 assert(Result.second && "reused a heap alloc index?");
1965 Result.first->second.AllocExpr = E;
1966 return &Result.first->second.Value;
1967}
1968
1969/// Produce a string describing the given constexpr call.
1970void CallStackFrame::describe(raw_ostream &Out) const {
1971 unsigned ArgIndex = 0;
1972 bool IsMemberCall =
1973 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1974 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1975
1976 if (!IsMemberCall)
1977 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1978 /*Qualified=*/false);
1979
1980 if (This && IsMemberCall) {
1981 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1982 const Expr *Object = MCE->getImplicitObjectArgument();
1983 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1984 /*Indentation=*/0);
1985 if (Object->getType()->isPointerType())
1986 Out << "->";
1987 else
1988 Out << ".";
1989 } else if (const auto *OCE =
1990 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1991 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1992 Info.Ctx.getPrintingPolicy(),
1993 /*Indentation=*/0);
1994 Out << ".";
1995 } else {
1996 APValue Val;
1997 This->moveInto(Val);
1998 Val.printPretty(
1999 Out, Info.Ctx,
2000 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2001 Out << ".";
2002 }
2003 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2004 /*Qualified=*/false);
2005 IsMemberCall = false;
2006 }
2007
2008 Out << '(';
2009
2010 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2011 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2012 if (ArgIndex > (unsigned)IsMemberCall)
2013 Out << ", ";
2014
2015 const ParmVarDecl *Param = *I;
2016 APValue *V = Info.getParamSlot(Arguments, Param);
2017 if (V)
2018 V->printPretty(Out, Info.Ctx, Param->getType());
2019 else
2020 Out << "<...>";
2021
2022 if (ArgIndex == 0 && IsMemberCall)
2023 Out << "->" << *Callee << '(';
2024 }
2025
2026 Out << ')';
2027}
2028
2029/// Evaluate an expression to see if it had side-effects, and discard its
2030/// result.
2031/// \return \c true if the caller should keep evaluating.
2032static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2033 assert(!E->isValueDependent());
2034 APValue Scratch;
2035 if (!Evaluate(Scratch, Info, E))
2036 // We don't need the value, but we might have skipped a side effect here.
2037 return Info.noteSideEffect();
2038 return true;
2039}
2040
2041/// Should this call expression be treated as forming an opaque constant?
2042static bool IsOpaqueConstantCall(const CallExpr *E) {
2043 unsigned Builtin = E->getBuiltinCallee();
2044 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2045 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2046 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2047 Builtin == Builtin::BI__builtin_function_start);
2048}
2049
2050static bool IsOpaqueConstantCall(const LValue &LVal) {
2051 const auto *BaseExpr =
2052 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2053 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2054}
2055
2057 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2058 // constant expression of pointer type that evaluates to...
2059
2060 // ... a null pointer value, or a prvalue core constant expression of type
2061 // std::nullptr_t.
2062 if (!B)
2063 return true;
2064
2065 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2066 // ... the address of an object with static storage duration,
2067 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2068 return VD->hasGlobalStorage();
2070 return true;
2071 // ... the address of a function,
2072 // ... the address of a GUID [MS extension],
2073 // ... the address of an unnamed global constant
2075 }
2076
2077 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2078 return true;
2079
2080 const Expr *E = B.get<const Expr*>();
2081 switch (E->getStmtClass()) {
2082 default:
2083 return false;
2084 case Expr::CompoundLiteralExprClass: {
2086 return CLE->isFileScope() && CLE->isLValue();
2087 }
2088 case Expr::MaterializeTemporaryExprClass:
2089 // A materialized temporary might have been lifetime-extended to static
2090 // storage duration.
2091 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2092 // A string literal has static storage duration.
2093 case Expr::StringLiteralClass:
2094 case Expr::PredefinedExprClass:
2095 case Expr::ObjCStringLiteralClass:
2096 case Expr::ObjCEncodeExprClass:
2097 return true;
2098 case Expr::ObjCBoxedExprClass:
2099 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2100 case Expr::CallExprClass:
2102 // For GCC compatibility, &&label has static storage duration.
2103 case Expr::AddrLabelExprClass:
2104 return true;
2105 // A Block literal expression may be used as the initialization value for
2106 // Block variables at global or local static scope.
2107 case Expr::BlockExprClass:
2108 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2109 // The APValue generated from a __builtin_source_location will be emitted as a
2110 // literal.
2111 case Expr::SourceLocExprClass:
2112 return true;
2113 case Expr::ImplicitValueInitExprClass:
2114 // FIXME:
2115 // We can never form an lvalue with an implicit value initialization as its
2116 // base through expression evaluation, so these only appear in one case: the
2117 // implicit variable declaration we invent when checking whether a constexpr
2118 // constructor can produce a constant expression. We must assume that such
2119 // an expression might be a global lvalue.
2120 return true;
2121 }
2122}
2123
2124static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2125 return LVal.Base.dyn_cast<const ValueDecl*>();
2126}
2127
2128// Information about an LValueBase that is some kind of string.
2131 StringRef Bytes;
2133};
2134
2135// Gets the lvalue base of LVal as a string.
2136static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2137 LValueBaseString &AsString) {
2138 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2139 if (!BaseExpr)
2140 return false;
2141
2142 // For ObjCEncodeExpr, we need to compute and store the string.
2143 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2144 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2145 AsString.ObjCEncodeStorage);
2146 AsString.Bytes = AsString.ObjCEncodeStorage;
2147 AsString.CharWidth = 1;
2148 return true;
2149 }
2150
2151 // Otherwise, we have a StringLiteral.
2152 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2153 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2154 Lit = PE->getFunctionName();
2155
2156 if (!Lit)
2157 return false;
2158
2159 AsString.Bytes = Lit->getBytes();
2160 AsString.CharWidth = Lit->getCharByteWidth();
2161 return true;
2162}
2163
2164// Determine whether two string literals potentially overlap. This will be the
2165// case if they agree on the values of all the bytes on the overlapping region
2166// between them.
2167//
2168// The overlapping region is the portion of the two string literals that must
2169// overlap in memory if the pointers actually point to the same address at
2170// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2171// the overlapping region is "cdef\0", which in this case does agree, so the
2172// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2173// "bazbar" + 3, the overlapping region contains all of both strings, so they
2174// are not potentially overlapping, even though they agree from the given
2175// addresses onwards.
2176//
2177// See open core issue CWG2765 which is discussing the desired rule here.
2178static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2179 const LValue &LHS,
2180 const LValue &RHS) {
2181 LValueBaseString LHSString, RHSString;
2182 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2183 !GetLValueBaseAsString(Info, RHS, RHSString))
2184 return false;
2185
2186 // This is the byte offset to the location of the first character of LHS
2187 // within RHS. We don't need to look at the characters of one string that
2188 // would appear before the start of the other string if they were merged.
2189 CharUnits Offset = RHS.Offset - LHS.Offset;
2190 if (Offset.isNegative()) {
2191 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2192 return false;
2193 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2194 } else {
2195 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2196 return false;
2197 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2198 }
2199
2200 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2201 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2202 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2203 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2204
2205 // The null terminator isn't included in the string data, so check for it
2206 // manually. If the longer string doesn't have a null terminator where the
2207 // shorter string ends, they aren't potentially overlapping.
2208 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2209 if (Shorter.size() + NullByte >= Longer.size())
2210 break;
2211 if (Longer[Shorter.size() + NullByte])
2212 return false;
2213 }
2214
2215 // Otherwise, they're potentially overlapping if and only if the overlapping
2216 // region is the same.
2217 return Shorter == Longer.take_front(Shorter.size());
2218}
2219
2220static bool IsWeakLValue(const LValue &Value) {
2222 return Decl && Decl->isWeak();
2223}
2224
2225static bool isZeroSized(const LValue &Value) {
2227 if (isa_and_nonnull<VarDecl>(Decl)) {
2228 QualType Ty = Decl->getType();
2229 if (Ty->isArrayType())
2230 return Ty->isIncompleteType() ||
2231 Decl->getASTContext().getTypeSize(Ty) == 0;
2232 }
2233 return false;
2234}
2235
2236static bool HasSameBase(const LValue &A, const LValue &B) {
2237 if (!A.getLValueBase())
2238 return !B.getLValueBase();
2239 if (!B.getLValueBase())
2240 return false;
2241
2242 if (A.getLValueBase().getOpaqueValue() !=
2243 B.getLValueBase().getOpaqueValue())
2244 return false;
2245
2246 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2247 A.getLValueVersion() == B.getLValueVersion();
2248}
2249
2250static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2251 assert(Base && "no location for a null lvalue");
2252 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2253
2254 // For a parameter, find the corresponding call stack frame (if it still
2255 // exists), and point at the parameter of the function definition we actually
2256 // invoked.
2257 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2258 unsigned Idx = PVD->getFunctionScopeIndex();
2259 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2260 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2261 F->Arguments.Version == Base.getVersion() && F->Callee &&
2262 Idx < F->Callee->getNumParams()) {
2263 VD = F->Callee->getParamDecl(Idx);
2264 break;
2265 }
2266 }
2267 }
2268
2269 if (VD)
2270 Info.Note(VD->getLocation(), diag::note_declared_at);
2271 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2272 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2273 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2274 // FIXME: Produce a note for dangling pointers too.
2275 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2276 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2277 diag::note_constexpr_dynamic_alloc_here);
2278 }
2279
2280 // We have no information to show for a typeid(T) object.
2281}
2282
2287
2288/// Materialized temporaries that we've already checked to determine if they're
2289/// initializsed by a constant expression.
2292
2294 EvalInfo &Info, SourceLocation DiagLoc,
2295 QualType Type, const APValue &Value,
2296 ConstantExprKind Kind,
2297 const FieldDecl *SubobjectDecl,
2298 CheckedTemporaries &CheckedTemps);
2299
2300/// Check that this reference or pointer core constant expression is a valid
2301/// value for an address or reference constant expression. Return true if we
2302/// can fold this expression, whether or not it's a constant expression.
2303static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2304 QualType Type, const LValue &LVal,
2305 ConstantExprKind Kind,
2306 CheckedTemporaries &CheckedTemps) {
2307 bool IsReferenceType = Type->isReferenceType();
2308
2309 APValue::LValueBase Base = LVal.getLValueBase();
2310 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2311
2312 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2313 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2314
2315 // Additional restrictions apply in a template argument. We only enforce the
2316 // C++20 restrictions here; additional syntactic and semantic restrictions
2317 // are applied elsewhere.
2318 if (isTemplateArgument(Kind)) {
2319 int InvalidBaseKind = -1;
2320 StringRef Ident;
2321 if (Base.is<TypeInfoLValue>())
2322 InvalidBaseKind = 0;
2323 else if (isa_and_nonnull<StringLiteral>(BaseE))
2324 InvalidBaseKind = 1;
2325 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2326 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2327 InvalidBaseKind = 2;
2328 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2329 InvalidBaseKind = 3;
2330 Ident = PE->getIdentKindName();
2331 }
2332
2333 if (InvalidBaseKind != -1) {
2334 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2335 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2336 << Ident;
2337 return false;
2338 }
2339 }
2340
2341 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2342 FD && FD->isImmediateFunction()) {
2343 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2344 << !Type->isAnyPointerType();
2345 Info.Note(FD->getLocation(), diag::note_declared_at);
2346 return false;
2347 }
2348
2349 // Check that the object is a global. Note that the fake 'this' object we
2350 // manufacture when checking potential constant expressions is conservatively
2351 // assumed to be global here.
2352 if (!IsGlobalLValue(Base)) {
2353 if (Info.getLangOpts().CPlusPlus11) {
2354 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2355 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2356 << BaseVD;
2357 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2358 if (VarD && VarD->isConstexpr()) {
2359 // Non-static local constexpr variables have unintuitive semantics:
2360 // constexpr int a = 1;
2361 // constexpr const int *p = &a;
2362 // ... is invalid because the address of 'a' is not constant. Suggest
2363 // adding a 'static' in this case.
2364 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2365 << VarD
2366 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2367 } else {
2368 NoteLValueLocation(Info, Base);
2369 }
2370 } else {
2371 Info.FFDiag(Loc);
2372 }
2373 // Don't allow references to temporaries to escape.
2374 return false;
2375 }
2376 assert((Info.checkingPotentialConstantExpression() ||
2377 LVal.getLValueCallIndex() == 0) &&
2378 "have call index for global lvalue");
2379
2380 if (LVal.allowConstexprUnknown()) {
2381 if (BaseVD) {
2382 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2383 NoteLValueLocation(Info, Base);
2384 } else {
2385 Info.FFDiag(Loc);
2386 }
2387 return false;
2388 }
2389
2390 if (Base.is<DynamicAllocLValue>()) {
2391 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2392 << IsReferenceType << !Designator.Entries.empty();
2393 NoteLValueLocation(Info, Base);
2394 return false;
2395 }
2396
2397 if (BaseVD) {
2398 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2399 // Check if this is a thread-local variable.
2400 if (Var->getTLSKind())
2401 // FIXME: Diagnostic!
2402 return false;
2403
2404 // A dllimport variable never acts like a constant, unless we're
2405 // evaluating a value for use only in name mangling.
2406 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2407 // FIXME: Diagnostic!
2408 return false;
2409
2410 // In CUDA/HIP device compilation, only device side variables have
2411 // constant addresses.
2412 if (Info.getASTContext().getLangOpts().CUDA &&
2413 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2414 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2415 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2416 !Var->hasAttr<CUDAConstantAttr>() &&
2417 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2418 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2419 Var->hasAttr<HIPManagedAttr>())
2420 return false;
2421 }
2422 }
2423 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2424 // __declspec(dllimport) must be handled very carefully:
2425 // We must never initialize an expression with the thunk in C++.
2426 // Doing otherwise would allow the same id-expression to yield
2427 // different addresses for the same function in different translation
2428 // units. However, this means that we must dynamically initialize the
2429 // expression with the contents of the import address table at runtime.
2430 //
2431 // The C language has no notion of ODR; furthermore, it has no notion of
2432 // dynamic initialization. This means that we are permitted to
2433 // perform initialization with the address of the thunk.
2434 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2435 FD->hasAttr<DLLImportAttr>())
2436 // FIXME: Diagnostic!
2437 return false;
2438 }
2439 } else if (const auto *MTE =
2440 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2441 if (CheckedTemps.insert(MTE).second) {
2442 QualType TempType = getType(Base);
2443 if (TempType.isDestructedType()) {
2444 Info.FFDiag(MTE->getExprLoc(),
2445 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2446 << TempType;
2447 return false;
2448 }
2449
2450 APValue *V = MTE->getOrCreateValue(false);
2451 assert(V && "evasluation result refers to uninitialised temporary");
2453 Info, MTE->getExprLoc(), TempType, *V, Kind,
2454 /*SubobjectDecl=*/nullptr, CheckedTemps))
2455 return false;
2456 }
2457 }
2458
2459 // Allow address constant expressions to be past-the-end pointers. This is
2460 // an extension: the standard requires them to point to an object.
2461 if (!IsReferenceType)
2462 return true;
2463
2464 // A reference constant expression must refer to an object.
2465 if (!Base) {
2466 // FIXME: diagnostic
2467 Info.CCEDiag(Loc);
2468 return true;
2469 }
2470
2471 // Does this refer one past the end of some object?
2472 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2473 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2474 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2475 NoteLValueLocation(Info, Base);
2476 }
2477
2478 return true;
2479}
2480
2481/// Member pointers are constant expressions unless they point to a
2482/// non-virtual dllimport member function.
2483static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2484 SourceLocation Loc,
2485 QualType Type,
2486 const APValue &Value,
2487 ConstantExprKind Kind) {
2488 const ValueDecl *Member = Value.getMemberPointerDecl();
2489 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2490 if (!FD)
2491 return true;
2492 if (FD->isImmediateFunction()) {
2493 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2494 Info.Note(FD->getLocation(), diag::note_declared_at);
2495 return false;
2496 }
2497 return isForManglingOnly(Kind) || FD->isVirtual() ||
2498 !FD->hasAttr<DLLImportAttr>();
2499}
2500
2501/// Check that this core constant expression is of literal type, and if not,
2502/// produce an appropriate diagnostic.
2503static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2504 const LValue *This = nullptr) {
2505 // The restriction to literal types does not exist in C++23 anymore.
2506 if (Info.getLangOpts().CPlusPlus23)
2507 return true;
2508
2509 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2510 return true;
2511
2512 // C++1y: A constant initializer for an object o [...] may also invoke
2513 // constexpr constructors for o and its subobjects even if those objects
2514 // are of non-literal class types.
2515 //
2516 // C++11 missed this detail for aggregates, so classes like this:
2517 // struct foo_t { union { int i; volatile int j; } u; };
2518 // are not (obviously) initializable like so:
2519 // __attribute__((__require_constant_initialization__))
2520 // static const foo_t x = {{0}};
2521 // because "i" is a subobject with non-literal initialization (due to the
2522 // volatile member of the union). See:
2523 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2524 // Therefore, we use the C++1y behavior.
2525 if (This && Info.EvaluatingDecl == This->getLValueBase())
2526 return true;
2527
2528 // Prvalue constant expressions must be of literal types.
2529 if (Info.getLangOpts().CPlusPlus11)
2530 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2531 << E->getType();
2532 else
2533 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2534 return false;
2535}
2536
2538 EvalInfo &Info, SourceLocation DiagLoc,
2539 QualType Type, const APValue &Value,
2540 ConstantExprKind Kind,
2541 const FieldDecl *SubobjectDecl,
2542 CheckedTemporaries &CheckedTemps) {
2543 if (!Value.hasValue()) {
2544 if (SubobjectDecl) {
2545 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2546 << /*(name)*/ 1 << SubobjectDecl;
2547 Info.Note(SubobjectDecl->getLocation(),
2548 diag::note_constexpr_subobject_declared_here);
2549 } else {
2550 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2551 << /*of type*/ 0 << Type;
2552 }
2553 return false;
2554 }
2555
2556 // We allow _Atomic(T) to be initialized from anything that T can be
2557 // initialized from.
2558 if (const AtomicType *AT = Type->getAs<AtomicType>())
2559 Type = AT->getValueType();
2560
2561 // Core issue 1454: For a literal constant expression of array or class type,
2562 // each subobject of its value shall have been initialized by a constant
2563 // expression.
2564 if (Value.isArray()) {
2566 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2567 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2568 Value.getArrayInitializedElt(I), Kind,
2569 SubobjectDecl, CheckedTemps))
2570 return false;
2571 }
2572 if (!Value.hasArrayFiller())
2573 return true;
2574 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2575 Value.getArrayFiller(), Kind, SubobjectDecl,
2576 CheckedTemps);
2577 }
2578 if (Value.isUnion() && Value.getUnionField()) {
2579 return CheckEvaluationResult(
2580 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2581 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2582 }
2583 if (Value.isStruct()) {
2584 auto *RD = Type->castAsRecordDecl();
2585 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2586 unsigned BaseIndex = 0;
2587 for (const CXXBaseSpecifier &BS : CD->bases()) {
2588 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2589 if (!BaseValue.hasValue()) {
2590 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2591 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2592 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2593 return false;
2594 }
2595 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2596 Kind, /*SubobjectDecl=*/nullptr,
2597 CheckedTemps))
2598 return false;
2599 ++BaseIndex;
2600 }
2601 }
2602 for (const auto *I : RD->fields()) {
2603 if (I->isUnnamedBitField())
2604 continue;
2605
2606 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2607 Value.getStructField(I->getFieldIndex()), Kind,
2608 I, CheckedTemps))
2609 return false;
2610 }
2611 }
2612
2613 if (Value.isLValue() &&
2615 LValue LVal;
2616 LVal.setFrom(Info.Ctx, Value);
2617 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2618 CheckedTemps);
2619 }
2620
2621 if (Value.isMemberPointer() &&
2623 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2624
2625 // Everything else is fine.
2626 return true;
2627}
2628
2629/// Check that this core constant expression value is a valid value for a
2630/// constant expression. If not, report an appropriate diagnostic. Does not
2631/// check that the expression is of literal type.
2632static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2633 QualType Type, const APValue &Value,
2634 ConstantExprKind Kind) {
2635 // Nothing to check for a constant expression of type 'cv void'.
2636 if (Type->isVoidType())
2637 return true;
2638
2639 CheckedTemporaries CheckedTemps;
2641 Info, DiagLoc, Type, Value, Kind,
2642 /*SubobjectDecl=*/nullptr, CheckedTemps);
2643}
2644
2645/// Check that this evaluated value is fully-initialized and can be loaded by
2646/// an lvalue-to-rvalue conversion.
2647static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2648 QualType Type, const APValue &Value) {
2649 CheckedTemporaries CheckedTemps;
2650 return CheckEvaluationResult(
2652 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2653}
2654
2655/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2656/// "the allocated storage is deallocated within the evaluation".
2657static bool CheckMemoryLeaks(EvalInfo &Info) {
2658 if (!Info.HeapAllocs.empty()) {
2659 // We can still fold to a constant despite a compile-time memory leak,
2660 // so long as the heap allocation isn't referenced in the result (we check
2661 // that in CheckConstantExpression).
2662 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2663 diag::note_constexpr_memory_leak)
2664 << unsigned(Info.HeapAllocs.size() - 1);
2665 }
2666 return true;
2667}
2668
2669static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2670 // A null base expression indicates a null pointer. These are always
2671 // evaluatable, and they are false unless the offset is zero.
2672 if (!Value.getLValueBase()) {
2673 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2674 Result = !Value.getLValueOffset().isZero();
2675 return true;
2676 }
2677
2678 // We have a non-null base. These are generally known to be true, but if it's
2679 // a weak declaration it can be null at runtime.
2680 Result = true;
2681 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2682 return !Decl || !Decl->isWeak();
2683}
2684
2685static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2686 // TODO: This function should produce notes if it fails.
2687 switch (Val.getKind()) {
2688 case APValue::None:
2690 return false;
2691 case APValue::Int:
2692 Result = Val.getInt().getBoolValue();
2693 return true;
2695 Result = Val.getFixedPoint().getBoolValue();
2696 return true;
2697 case APValue::Float:
2698 Result = !Val.getFloat().isZero();
2699 return true;
2701 Result = Val.getComplexIntReal().getBoolValue() ||
2702 Val.getComplexIntImag().getBoolValue();
2703 return true;
2705 Result = !Val.getComplexFloatReal().isZero() ||
2706 !Val.getComplexFloatImag().isZero();
2707 return true;
2708 case APValue::LValue:
2709 return EvalPointerValueAsBool(Val, Result);
2711 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2712 return false;
2713 }
2714 Result = Val.getMemberPointerDecl();
2715 return true;
2716 case APValue::Vector:
2717 case APValue::Array:
2718 case APValue::Struct:
2719 case APValue::Union:
2721 return false;
2722 }
2723
2724 llvm_unreachable("unknown APValue kind");
2725}
2726
2727static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2728 EvalInfo &Info) {
2729 assert(!E->isValueDependent());
2730 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2731 APValue Val;
2732 if (!Evaluate(Val, Info, E))
2733 return false;
2734 return HandleConversionToBool(Val, Result);
2735}
2736
2737template<typename T>
2738static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2739 const T &SrcValue, QualType DestType) {
2740 Info.CCEDiag(E, diag::note_constexpr_overflow)
2741 << SrcValue << DestType;
2742 return Info.noteUndefinedBehavior();
2743}
2744
2745static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2746 QualType SrcType, const APFloat &Value,
2747 QualType DestType, APSInt &Result) {
2748 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2749 // Determine whether we are converting to unsigned or signed.
2750 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2751
2752 Result = APSInt(DestWidth, !DestSigned);
2753 bool ignored;
2754 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2755 & APFloat::opInvalidOp)
2756 return HandleOverflow(Info, E, Value, DestType);
2757 return true;
2758}
2759
2760/// Get rounding mode to use in evaluation of the specified expression.
2761///
2762/// If rounding mode is unknown at compile time, still try to evaluate the
2763/// expression. If the result is exact, it does not depend on rounding mode.
2764/// So return "tonearest" mode instead of "dynamic".
2765static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2766 llvm::RoundingMode RM =
2768 if (RM == llvm::RoundingMode::Dynamic)
2769 RM = llvm::RoundingMode::NearestTiesToEven;
2770 return RM;
2771}
2772
2773/// Check if the given evaluation result is allowed for constant evaluation.
2774static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2775 APFloat::opStatus St) {
2776 // In a constant context, assume that any dynamic rounding mode or FP
2777 // exception state matches the default floating-point environment.
2778 if (Info.InConstantContext)
2779 return true;
2780
2781 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2782 if ((St & APFloat::opInexact) &&
2783 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2784 // Inexact result means that it depends on rounding mode. If the requested
2785 // mode is dynamic, the evaluation cannot be made in compile time.
2786 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2787 return false;
2788 }
2789
2790 if ((St != APFloat::opOK) &&
2791 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2793 FPO.getAllowFEnvAccess())) {
2794 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2795 return false;
2796 }
2797
2798 if ((St & APFloat::opStatus::opInvalidOp) &&
2800 // There is no usefully definable result.
2801 Info.FFDiag(E);
2802 return false;
2803 }
2804
2805 // FIXME: if:
2806 // - evaluation triggered other FP exception, and
2807 // - exception mode is not "ignore", and
2808 // - the expression being evaluated is not a part of global variable
2809 // initializer,
2810 // the evaluation probably need to be rejected.
2811 return true;
2812}
2813
2814static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2815 QualType SrcType, QualType DestType,
2816 APFloat &Result) {
2817 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2819 "HandleFloatToFloatCast has been checked with only CastExpr, "
2820 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2821 "the new expression or address the root cause of this usage.");
2822 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2823 APFloat::opStatus St;
2824 APFloat Value = Result;
2825 bool ignored;
2826 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2827 return checkFloatingPointResult(Info, E, St);
2828}
2829
2830static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2831 QualType DestType, QualType SrcType,
2832 const APSInt &Value) {
2833 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2834 // Figure out if this is a truncate, extend or noop cast.
2835 // If the input is signed, do a sign extend, noop, or truncate.
2836 APSInt Result = Value.extOrTrunc(DestWidth);
2837 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2838 if (DestType->isBooleanType())
2839 Result = Value.getBoolValue();
2840 return Result;
2841}
2842
2843static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2844 const FPOptions FPO,
2845 QualType SrcType, const APSInt &Value,
2846 QualType DestType, APFloat &Result) {
2847 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2848 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2849 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2850 return checkFloatingPointResult(Info, E, St);
2851}
2852
2853static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2854 APValue &Value, const FieldDecl *FD) {
2855 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2856
2857 if (!Value.isInt()) {
2858 // Trying to store a pointer-cast-to-integer into a bitfield.
2859 // FIXME: In this case, we should provide the diagnostic for casting
2860 // a pointer to an integer.
2861 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2862 Info.FFDiag(E);
2863 return false;
2864 }
2865
2866 APSInt &Int = Value.getInt();
2867 unsigned OldBitWidth = Int.getBitWidth();
2868 unsigned NewBitWidth = FD->getBitWidthValue();
2869 if (NewBitWidth < OldBitWidth)
2870 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2871 return true;
2872}
2873
2874/// Perform the given integer operation, which is known to need at most BitWidth
2875/// bits, and check for overflow in the original type (if that type was not an
2876/// unsigned type).
2877template<typename Operation>
2878static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2879 const APSInt &LHS, const APSInt &RHS,
2880 unsigned BitWidth, Operation Op,
2881 APSInt &Result) {
2882 if (LHS.isUnsigned()) {
2883 Result = Op(LHS, RHS);
2884 return true;
2885 }
2886
2887 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2888 Result = Value.trunc(LHS.getBitWidth());
2889 if (Result.extend(BitWidth) != Value) {
2890 if (Info.checkingForUndefinedBehavior())
2891 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2892 diag::warn_integer_constant_overflow)
2893 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2894 /*UpperCase=*/true, /*InsertSeparators=*/true)
2895 << E->getType() << E->getSourceRange();
2896 return HandleOverflow(Info, E, Value, E->getType());
2897 }
2898 return true;
2899}
2900
2901/// Perform the given binary integer operation.
2902static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2903 const APSInt &LHS, BinaryOperatorKind Opcode,
2904 APSInt RHS, APSInt &Result) {
2905 bool HandleOverflowResult = true;
2906 switch (Opcode) {
2907 default:
2908 Info.FFDiag(E);
2909 return false;
2910 case BO_Mul:
2911 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2912 std::multiplies<APSInt>(), Result);
2913 case BO_Add:
2914 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2915 std::plus<APSInt>(), Result);
2916 case BO_Sub:
2917 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2918 std::minus<APSInt>(), Result);
2919 case BO_And: Result = LHS & RHS; return true;
2920 case BO_Xor: Result = LHS ^ RHS; return true;
2921 case BO_Or: Result = LHS | RHS; return true;
2922 case BO_Div:
2923 case BO_Rem:
2924 if (RHS == 0) {
2925 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2926 << E->getRHS()->getSourceRange();
2927 return false;
2928 }
2929 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2930 // this operation and gives the two's complement result.
2931 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2932 LHS.isMinSignedValue())
2933 HandleOverflowResult = HandleOverflow(
2934 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2935 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2936 return HandleOverflowResult;
2937 case BO_Shl: {
2938 if (Info.getLangOpts().OpenCL)
2939 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2940 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2941 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2942 RHS.isUnsigned());
2943 else if (RHS.isSigned() && RHS.isNegative()) {
2944 // During constant-folding, a negative shift is an opposite shift. Such
2945 // a shift is not a constant expression.
2946 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2947 if (!Info.noteUndefinedBehavior())
2948 return false;
2949 RHS = -RHS;
2950 goto shift_right;
2951 }
2952 shift_left:
2953 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2954 // the shifted type.
2955 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2956 if (SA != RHS) {
2957 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2958 << RHS << E->getType() << LHS.getBitWidth();
2959 if (!Info.noteUndefinedBehavior())
2960 return false;
2961 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2962 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2963 // operand, and must not overflow the corresponding unsigned type.
2964 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2965 // E1 x 2^E2 module 2^N.
2966 if (LHS.isNegative()) {
2967 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2968 if (!Info.noteUndefinedBehavior())
2969 return false;
2970 } else if (LHS.countl_zero() < SA) {
2971 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2972 if (!Info.noteUndefinedBehavior())
2973 return false;
2974 }
2975 }
2976 Result = LHS << SA;
2977 return true;
2978 }
2979 case BO_Shr: {
2980 if (Info.getLangOpts().OpenCL)
2981 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2982 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2983 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2984 RHS.isUnsigned());
2985 else if (RHS.isSigned() && RHS.isNegative()) {
2986 // During constant-folding, a negative shift is an opposite shift. Such a
2987 // shift is not a constant expression.
2988 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2989 if (!Info.noteUndefinedBehavior())
2990 return false;
2991 RHS = -RHS;
2992 goto shift_left;
2993 }
2994 shift_right:
2995 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2996 // shifted type.
2997 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2998 if (SA != RHS) {
2999 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3000 << RHS << E->getType() << LHS.getBitWidth();
3001 if (!Info.noteUndefinedBehavior())
3002 return false;
3003 }
3004
3005 Result = LHS >> SA;
3006 return true;
3007 }
3008
3009 case BO_LT: Result = LHS < RHS; return true;
3010 case BO_GT: Result = LHS > RHS; return true;
3011 case BO_LE: Result = LHS <= RHS; return true;
3012 case BO_GE: Result = LHS >= RHS; return true;
3013 case BO_EQ: Result = LHS == RHS; return true;
3014 case BO_NE: Result = LHS != RHS; return true;
3015 case BO_Cmp:
3016 llvm_unreachable("BO_Cmp should be handled elsewhere");
3017 }
3018}
3019
3020/// Perform the given binary floating-point operation, in-place, on LHS.
3021static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3022 APFloat &LHS, BinaryOperatorKind Opcode,
3023 const APFloat &RHS) {
3024 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3025 APFloat::opStatus St;
3026 switch (Opcode) {
3027 default:
3028 Info.FFDiag(E);
3029 return false;
3030 case BO_Mul:
3031 St = LHS.multiply(RHS, RM);
3032 break;
3033 case BO_Add:
3034 St = LHS.add(RHS, RM);
3035 break;
3036 case BO_Sub:
3037 St = LHS.subtract(RHS, RM);
3038 break;
3039 case BO_Div:
3040 // [expr.mul]p4:
3041 // If the second operand of / or % is zero the behavior is undefined.
3042 if (RHS.isZero())
3043 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3044 St = LHS.divide(RHS, RM);
3045 break;
3046 }
3047
3048 // [expr.pre]p4:
3049 // If during the evaluation of an expression, the result is not
3050 // mathematically defined [...], the behavior is undefined.
3051 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3052 if (LHS.isNaN()) {
3053 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3054 return Info.noteUndefinedBehavior();
3055 }
3056
3057 return checkFloatingPointResult(Info, E, St);
3058}
3059
3060static bool handleLogicalOpForVector(const APInt &LHSValue,
3061 BinaryOperatorKind Opcode,
3062 const APInt &RHSValue, APInt &Result) {
3063 bool LHS = (LHSValue != 0);
3064 bool RHS = (RHSValue != 0);
3065
3066 if (Opcode == BO_LAnd)
3067 Result = LHS && RHS;
3068 else
3069 Result = LHS || RHS;
3070 return true;
3071}
3072static bool handleLogicalOpForVector(const APFloat &LHSValue,
3073 BinaryOperatorKind Opcode,
3074 const APFloat &RHSValue, APInt &Result) {
3075 bool LHS = !LHSValue.isZero();
3076 bool RHS = !RHSValue.isZero();
3077
3078 if (Opcode == BO_LAnd)
3079 Result = LHS && RHS;
3080 else
3081 Result = LHS || RHS;
3082 return true;
3083}
3084
3085static bool handleLogicalOpForVector(const APValue &LHSValue,
3086 BinaryOperatorKind Opcode,
3087 const APValue &RHSValue, APInt &Result) {
3088 // The result is always an int type, however operands match the first.
3089 if (LHSValue.getKind() == APValue::Int)
3090 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3091 RHSValue.getInt(), Result);
3092 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3093 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3094 RHSValue.getFloat(), Result);
3095}
3096
3097template <typename APTy>
3098static bool
3100 const APTy &RHSValue, APInt &Result) {
3101 switch (Opcode) {
3102 default:
3103 llvm_unreachable("unsupported binary operator");
3104 case BO_EQ:
3105 Result = (LHSValue == RHSValue);
3106 break;
3107 case BO_NE:
3108 Result = (LHSValue != RHSValue);
3109 break;
3110 case BO_LT:
3111 Result = (LHSValue < RHSValue);
3112 break;
3113 case BO_GT:
3114 Result = (LHSValue > RHSValue);
3115 break;
3116 case BO_LE:
3117 Result = (LHSValue <= RHSValue);
3118 break;
3119 case BO_GE:
3120 Result = (LHSValue >= RHSValue);
3121 break;
3122 }
3123
3124 // The boolean operations on these vector types use an instruction that
3125 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3126 // to -1 to make sure that we produce the correct value.
3127 Result.negate();
3128
3129 return true;
3130}
3131
3132static bool handleCompareOpForVector(const APValue &LHSValue,
3133 BinaryOperatorKind Opcode,
3134 const APValue &RHSValue, APInt &Result) {
3135 // The result is always an int type, however operands match the first.
3136 if (LHSValue.getKind() == APValue::Int)
3137 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3138 RHSValue.getInt(), Result);
3139 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3140 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3141 RHSValue.getFloat(), Result);
3142}
3143
3144// Perform binary operations for vector types, in place on the LHS.
3145static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3146 BinaryOperatorKind Opcode,
3147 APValue &LHSValue,
3148 const APValue &RHSValue) {
3149 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3150 "Operation not supported on vector types");
3151
3152 const auto *VT = E->getType()->castAs<VectorType>();
3153 unsigned NumElements = VT->getNumElements();
3154 QualType EltTy = VT->getElementType();
3155
3156 // In the cases (typically C as I've observed) where we aren't evaluating
3157 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3158 // just give up.
3159 if (!LHSValue.isVector()) {
3160 assert(LHSValue.isLValue() &&
3161 "A vector result that isn't a vector OR uncalculated LValue");
3162 Info.FFDiag(E);
3163 return false;
3164 }
3165
3166 assert(LHSValue.getVectorLength() == NumElements &&
3167 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3168
3169 SmallVector<APValue, 4> ResultElements;
3170
3171 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3172 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3173 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3174
3175 if (EltTy->isIntegerType()) {
3176 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3177 EltTy->isUnsignedIntegerType()};
3178 bool Success = true;
3179
3180 if (BinaryOperator::isLogicalOp(Opcode))
3181 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3182 else if (BinaryOperator::isComparisonOp(Opcode))
3183 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3184 else
3185 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3186 RHSElt.getInt(), EltResult);
3187
3188 if (!Success) {
3189 Info.FFDiag(E);
3190 return false;
3191 }
3192 ResultElements.emplace_back(EltResult);
3193
3194 } else if (EltTy->isFloatingType()) {
3195 assert(LHSElt.getKind() == APValue::Float &&
3196 RHSElt.getKind() == APValue::Float &&
3197 "Mismatched LHS/RHS/Result Type");
3198 APFloat LHSFloat = LHSElt.getFloat();
3199
3200 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3201 RHSElt.getFloat())) {
3202 Info.FFDiag(E);
3203 return false;
3204 }
3205
3206 ResultElements.emplace_back(LHSFloat);
3207 }
3208 }
3209
3210 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3211 return true;
3212}
3213
3214/// Cast an lvalue referring to a base subobject to a derived class, by
3215/// truncating the lvalue's path to the given length.
3216static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3217 const RecordDecl *TruncatedType,
3218 unsigned TruncatedElements) {
3219 SubobjectDesignator &D = Result.Designator;
3220
3221 // Check we actually point to a derived class object.
3222 if (TruncatedElements == D.Entries.size())
3223 return true;
3224 assert(TruncatedElements >= D.MostDerivedPathLength &&
3225 "not casting to a derived class");
3226 if (!Result.checkSubobject(Info, E, CSK_Derived))
3227 return false;
3228
3229 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3230 const RecordDecl *RD = TruncatedType;
3231 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3232 if (RD->isInvalidDecl()) return false;
3233 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3234 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3235 if (isVirtualBaseClass(D.Entries[I]))
3236 Result.Offset -= Layout.getVBaseClassOffset(Base);
3237 else
3238 Result.Offset -= Layout.getBaseClassOffset(Base);
3239 RD = Base;
3240 }
3241 D.Entries.resize(TruncatedElements);
3242 return true;
3243}
3244
3245static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3246 const CXXRecordDecl *Derived,
3247 const CXXRecordDecl *Base,
3248 const ASTRecordLayout *RL = nullptr) {
3249 if (!RL) {
3250 if (Derived->isInvalidDecl()) return false;
3251 RL = &Info.Ctx.getASTRecordLayout(Derived);
3252 }
3253
3254 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3255 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3256 return true;
3257}
3258
3259static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3260 const CXXRecordDecl *DerivedDecl,
3261 const CXXBaseSpecifier *Base) {
3262 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3263
3264 if (!Base->isVirtual())
3265 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3266
3267 SubobjectDesignator &D = Obj.Designator;
3268 if (D.Invalid)
3269 return false;
3270
3271 // Extract most-derived object and corresponding type.
3272 // FIXME: After implementing P2280R4 it became possible to get references
3273 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3274 // locations and if we see crashes in those locations in the future
3275 // it may make more sense to move this fix into Lvalue::set.
3276 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3277 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3278 return false;
3279
3280 // Find the virtual base class.
3281 if (DerivedDecl->isInvalidDecl()) return false;
3282 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3283 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3284 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3285 return true;
3286}
3287
3288static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3289 QualType Type, LValue &Result) {
3290 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3291 PathE = E->path_end();
3292 PathI != PathE; ++PathI) {
3293 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3294 *PathI))
3295 return false;
3296 Type = (*PathI)->getType();
3297 }
3298 return true;
3299}
3300
3301/// Cast an lvalue referring to a derived class to a known base subobject.
3302static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3303 const CXXRecordDecl *DerivedRD,
3304 const CXXRecordDecl *BaseRD) {
3305 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3306 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3307 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3308 llvm_unreachable("Class must be derived from the passed in base class!");
3309
3310 for (CXXBasePathElement &Elem : Paths.front())
3311 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3312 return false;
3313 return true;
3314}
3315
3316/// Update LVal to refer to the given field, which must be a member of the type
3317/// currently described by LVal.
3318static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3319 const FieldDecl *FD,
3320 const ASTRecordLayout *RL = nullptr) {
3321 if (!RL) {
3322 if (FD->getParent()->isInvalidDecl()) return false;
3323 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3324 }
3325
3326 unsigned I = FD->getFieldIndex();
3327 LVal.addDecl(Info, E, FD);
3328 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3329 return true;
3330}
3331
3332/// Update LVal to refer to the given indirect field.
3333static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3334 LValue &LVal,
3335 const IndirectFieldDecl *IFD) {
3336 for (const auto *C : IFD->chain())
3337 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3338 return false;
3339 return true;
3340}
3341
3346
3347/// Get the size of the given type in char units.
3348static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3350 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3351 // extension.
3352 if (Type->isVoidType() || Type->isFunctionType()) {
3353 Size = CharUnits::One();
3354 return true;
3355 }
3356
3357 if (Type->isDependentType()) {
3358 Info.FFDiag(Loc);
3359 return false;
3360 }
3361
3362 if (!Type->isConstantSizeType()) {
3363 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3364 // FIXME: Better diagnostic.
3365 Info.FFDiag(Loc);
3366 return false;
3367 }
3368
3369 if (SOT == SizeOfType::SizeOf)
3370 Size = Info.Ctx.getTypeSizeInChars(Type);
3371 else
3372 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3373 return true;
3374}
3375
3376/// Update a pointer value to model pointer arithmetic.
3377/// \param Info - Information about the ongoing evaluation.
3378/// \param E - The expression being evaluated, for diagnostic purposes.
3379/// \param LVal - The pointer value to be updated.
3380/// \param EltTy - The pointee type represented by LVal.
3381/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3382static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3383 LValue &LVal, QualType EltTy,
3384 APSInt Adjustment) {
3385 CharUnits SizeOfPointee;
3386 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3387 return false;
3388
3389 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3390 return true;
3391}
3392
3393static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3394 LValue &LVal, QualType EltTy,
3395 int64_t Adjustment) {
3396 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3397 APSInt::get(Adjustment));
3398}
3399
3400/// Update an lvalue to refer to a component of a complex number.
3401/// \param Info - Information about the ongoing evaluation.
3402/// \param LVal - The lvalue to be updated.
3403/// \param EltTy - The complex number's component type.
3404/// \param Imag - False for the real component, true for the imaginary.
3405static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3406 LValue &LVal, QualType EltTy,
3407 bool Imag) {
3408 if (Imag) {
3409 CharUnits SizeOfComponent;
3410 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3411 return false;
3412 LVal.Offset += SizeOfComponent;
3413 }
3414 LVal.addComplex(Info, E, EltTy, Imag);
3415 return true;
3416}
3417
3418static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3419 LValue &LVal, QualType EltTy,
3420 uint64_t Size, uint64_t Idx) {
3421 if (Idx) {
3422 CharUnits SizeOfElement;
3423 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3424 return false;
3425 LVal.Offset += SizeOfElement * Idx;
3426 }
3427 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3428 return true;
3429}
3430
3431/// Try to evaluate the initializer for a variable declaration.
3432///
3433/// \param Info Information about the ongoing evaluation.
3434/// \param E An expression to be used when printing diagnostics.
3435/// \param VD The variable whose initializer should be obtained.
3436/// \param Version The version of the variable within the frame.
3437/// \param Frame The frame in which the variable was created. Must be null
3438/// if this variable is not local to the evaluation.
3439/// \param Result Filled in with a pointer to the value of the variable.
3440static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3441 const VarDecl *VD, CallStackFrame *Frame,
3442 unsigned Version, APValue *&Result) {
3443 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3444 // and pointers.
3445 bool AllowConstexprUnknown =
3446 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3447
3448 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3449
3450 auto CheckUninitReference = [&](bool IsLocalVariable) {
3451 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3452 // C++23 [expr.const]p8
3453 // ... For such an object that is not usable in constant expressions, the
3454 // dynamic type of the object is constexpr-unknown. For such a reference
3455 // that is not usable in constant expressions, the reference is treated
3456 // as binding to an unspecified object of the referenced type whose
3457 // lifetime and that of all subobjects includes the entire constant
3458 // evaluation and whose dynamic type is constexpr-unknown.
3459 //
3460 // Variables that are part of the current evaluation are not
3461 // constexpr-unknown.
3462 if (!AllowConstexprUnknown || IsLocalVariable) {
3463 if (!Info.checkingPotentialConstantExpression())
3464 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3465 return false;
3466 }
3467 Result = nullptr;
3468 }
3469 return true;
3470 };
3471
3472 // If this is a local variable, dig out its value.
3473 if (Frame) {
3474 Result = Frame->getTemporary(VD, Version);
3475 if (Result)
3476 return CheckUninitReference(/*IsLocalVariable=*/true);
3477
3478 if (!isa<ParmVarDecl>(VD)) {
3479 // Assume variables referenced within a lambda's call operator that were
3480 // not declared within the call operator are captures and during checking
3481 // of a potential constant expression, assume they are unknown constant
3482 // expressions.
3483 assert(isLambdaCallOperator(Frame->Callee) &&
3484 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3485 "missing value for local variable");
3486 if (Info.checkingPotentialConstantExpression())
3487 return false;
3488 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3489 // still reachable at all?
3490 Info.FFDiag(E->getBeginLoc(),
3491 diag::note_unimplemented_constexpr_lambda_feature_ast)
3492 << "captures not currently allowed";
3493 return false;
3494 }
3495 }
3496
3497 // If we're currently evaluating the initializer of this declaration, use that
3498 // in-flight value.
3499 if (Info.EvaluatingDecl == Base) {
3500 Result = Info.EvaluatingDeclValue;
3501 return CheckUninitReference(/*IsLocalVariable=*/false);
3502 }
3503
3504 // P2280R4 struck the restriction that variable of reference type lifetime
3505 // should begin within the evaluation of E
3506 // Used to be C++20 [expr.const]p5.12.2:
3507 // ... its lifetime began within the evaluation of E;
3508 if (isa<ParmVarDecl>(VD)) {
3509 if (AllowConstexprUnknown) {
3510 Result = nullptr;
3511 return true;
3512 }
3513
3514 // Assume parameters of a potential constant expression are usable in
3515 // constant expressions.
3516 if (!Info.checkingPotentialConstantExpression() ||
3517 !Info.CurrentCall->Callee ||
3518 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3519 if (Info.getLangOpts().CPlusPlus11) {
3520 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3521 << VD;
3522 NoteLValueLocation(Info, Base);
3523 } else {
3524 Info.FFDiag(E);
3525 }
3526 }
3527 return false;
3528 }
3529
3530 if (E->isValueDependent())
3531 return false;
3532
3533 // Dig out the initializer, and use the declaration which it's attached to.
3534 // FIXME: We should eventually check whether the variable has a reachable
3535 // initializing declaration.
3536 const Expr *Init = VD->getAnyInitializer(VD);
3537 // P2280R4 struck the restriction that variable of reference type should have
3538 // a preceding initialization.
3539 // Used to be C++20 [expr.const]p5.12:
3540 // ... reference has a preceding initialization and either ...
3541 if (!Init && !AllowConstexprUnknown) {
3542 // Don't diagnose during potential constant expression checking; an
3543 // initializer might be added later.
3544 if (!Info.checkingPotentialConstantExpression()) {
3545 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3546 << VD;
3547 NoteLValueLocation(Info, Base);
3548 }
3549 return false;
3550 }
3551
3552 // P2280R4 struck the initialization requirement for variables of reference
3553 // type so we can no longer assume we have an Init.
3554 // Used to be C++20 [expr.const]p5.12:
3555 // ... reference has a preceding initialization and either ...
3556 if (Init && Init->isValueDependent()) {
3557 // The DeclRefExpr is not value-dependent, but the variable it refers to
3558 // has a value-dependent initializer. This should only happen in
3559 // constant-folding cases, where the variable is not actually of a suitable
3560 // type for use in a constant expression (otherwise the DeclRefExpr would
3561 // have been value-dependent too), so diagnose that.
3562 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3563 if (!Info.checkingPotentialConstantExpression()) {
3564 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3565 ? diag::note_constexpr_ltor_non_constexpr
3566 : diag::note_constexpr_ltor_non_integral, 1)
3567 << VD << VD->getType();
3568 NoteLValueLocation(Info, Base);
3569 }
3570 return false;
3571 }
3572
3573 // Check that we can fold the initializer. In C++, we will have already done
3574 // this in the cases where it matters for conformance.
3575 // P2280R4 struck the initialization requirement for variables of reference
3576 // type so we can no longer assume we have an Init.
3577 // Used to be C++20 [expr.const]p5.12:
3578 // ... reference has a preceding initialization and either ...
3579 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3580 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3581 NoteLValueLocation(Info, Base);
3582 return false;
3583 }
3584
3585 // Check that the variable is actually usable in constant expressions. For a
3586 // const integral variable or a reference, we might have a non-constant
3587 // initializer that we can nonetheless evaluate the initializer for. Such
3588 // variables are not usable in constant expressions. In C++98, the
3589 // initializer also syntactically needs to be an ICE.
3590 //
3591 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3592 // expressions here; doing so would regress diagnostics for things like
3593 // reading from a volatile constexpr variable.
3594 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3595 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3596 !AllowConstexprUnknown) ||
3597 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3598 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3599 if (Init) {
3600 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3601 NoteLValueLocation(Info, Base);
3602 } else {
3603 Info.CCEDiag(E);
3604 }
3605 }
3606
3607 // Never use the initializer of a weak variable, not even for constant
3608 // folding. We can't be sure that this is the definition that will be used.
3609 if (VD->isWeak()) {
3610 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3611 NoteLValueLocation(Info, Base);
3612 return false;
3613 }
3614
3615 Result = VD->getEvaluatedValue();
3616
3617 if (!Result && !AllowConstexprUnknown)
3618 return false;
3619
3620 return CheckUninitReference(/*IsLocalVariable=*/false);
3621}
3622
3623/// Get the base index of the given base class within an APValue representing
3624/// the given derived class.
3625static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3626 const CXXRecordDecl *Base) {
3627 Base = Base->getCanonicalDecl();
3628 unsigned Index = 0;
3630 E = Derived->bases_end(); I != E; ++I, ++Index) {
3631 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3632 return Index;
3633 }
3634
3635 llvm_unreachable("base class missing from derived class's bases list");
3636}
3637
3638/// Extract the value of a character from a string literal.
3639static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3640 uint64_t Index) {
3641 assert(!isa<SourceLocExpr>(Lit) &&
3642 "SourceLocExpr should have already been converted to a StringLiteral");
3643
3644 // FIXME: Support MakeStringConstant
3645 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3646 std::string Str;
3647 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3648 assert(Index <= Str.size() && "Index too large");
3649 return APSInt::getUnsigned(Str.c_str()[Index]);
3650 }
3651
3652 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3653 Lit = PE->getFunctionName();
3654 const StringLiteral *S = cast<StringLiteral>(Lit);
3655 const ConstantArrayType *CAT =
3656 Info.Ctx.getAsConstantArrayType(S->getType());
3657 assert(CAT && "string literal isn't an array");
3658 QualType CharType = CAT->getElementType();
3659 assert(CharType->isIntegerType() && "unexpected character type");
3660 APSInt Value(Info.Ctx.getTypeSize(CharType),
3661 CharType->isUnsignedIntegerType());
3662 if (Index < S->getLength())
3663 Value = S->getCodeUnit(Index);
3664 return Value;
3665}
3666
3667// Expand a string literal into an array of characters.
3668//
3669// FIXME: This is inefficient; we should probably introduce something similar
3670// to the LLVM ConstantDataArray to make this cheaper.
3671static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3672 APValue &Result,
3673 QualType AllocType = QualType()) {
3674 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3675 AllocType.isNull() ? S->getType() : AllocType);
3676 assert(CAT && "string literal isn't an array");
3677 QualType CharType = CAT->getElementType();
3678 assert(CharType->isIntegerType() && "unexpected character type");
3679
3680 unsigned Elts = CAT->getZExtSize();
3681 Result = APValue(APValue::UninitArray(),
3682 std::min(S->getLength(), Elts), Elts);
3683 APSInt Value(Info.Ctx.getTypeSize(CharType),
3684 CharType->isUnsignedIntegerType());
3685 if (Result.hasArrayFiller())
3686 Result.getArrayFiller() = APValue(Value);
3687 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3688 Value = S->getCodeUnit(I);
3689 Result.getArrayInitializedElt(I) = APValue(Value);
3690 }
3691}
3692
3693// Expand an array so that it has more than Index filled elements.
3694static void expandArray(APValue &Array, unsigned Index) {
3695 unsigned Size = Array.getArraySize();
3696 assert(Index < Size);
3697
3698 // Always at least double the number of elements for which we store a value.
3699 unsigned OldElts = Array.getArrayInitializedElts();
3700 unsigned NewElts = std::max(Index+1, OldElts * 2);
3701 NewElts = std::min(Size, std::max(NewElts, 8u));
3702
3703 // Copy the data across.
3704 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3705 for (unsigned I = 0; I != OldElts; ++I)
3706 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3707 for (unsigned I = OldElts; I != NewElts; ++I)
3708 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3709 if (NewValue.hasArrayFiller())
3710 NewValue.getArrayFiller() = Array.getArrayFiller();
3711 Array.swap(NewValue);
3712}
3713
3714/// Determine whether a type would actually be read by an lvalue-to-rvalue
3715/// conversion. If it's of class type, we may assume that the copy operation
3716/// is trivial. Note that this is never true for a union type with fields
3717/// (because the copy always "reads" the active member) and always true for
3718/// a non-class type.
3719static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3721 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3722 return !RD || isReadByLvalueToRvalueConversion(RD);
3723}
3725 // FIXME: A trivial copy of a union copies the object representation, even if
3726 // the union is empty.
3727 if (RD->isUnion())
3728 return !RD->field_empty();
3729 if (RD->isEmpty())
3730 return false;
3731
3732 for (auto *Field : RD->fields())
3733 if (!Field->isUnnamedBitField() &&
3734 isReadByLvalueToRvalueConversion(Field->getType()))
3735 return true;
3736
3737 for (auto &BaseSpec : RD->bases())
3738 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3739 return true;
3740
3741 return false;
3742}
3743
3744/// Diagnose an attempt to read from any unreadable field within the specified
3745/// type, which might be a class type.
3746static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3747 QualType T) {
3748 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3749 if (!RD)
3750 return false;
3751
3752 if (!RD->hasMutableFields())
3753 return false;
3754
3755 for (auto *Field : RD->fields()) {
3756 // If we're actually going to read this field in some way, then it can't
3757 // be mutable. If we're in a union, then assigning to a mutable field
3758 // (even an empty one) can change the active member, so that's not OK.
3759 // FIXME: Add core issue number for the union case.
3760 if (Field->isMutable() &&
3761 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3762 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3763 Info.Note(Field->getLocation(), diag::note_declared_at);
3764 return true;
3765 }
3766
3767 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3768 return true;
3769 }
3770
3771 for (auto &BaseSpec : RD->bases())
3772 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3773 return true;
3774
3775 // All mutable fields were empty, and thus not actually read.
3776 return false;
3777}
3778
3779static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3781 bool MutableSubobject = false) {
3782 // A temporary or transient heap allocation we created.
3783 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3784 return true;
3785
3786 switch (Info.IsEvaluatingDecl) {
3787 case EvalInfo::EvaluatingDeclKind::None:
3788 return false;
3789
3790 case EvalInfo::EvaluatingDeclKind::Ctor:
3791 // The variable whose initializer we're evaluating.
3792 if (Info.EvaluatingDecl == Base)
3793 return true;
3794
3795 // A temporary lifetime-extended by the variable whose initializer we're
3796 // evaluating.
3797 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3798 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3799 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3800 return false;
3801
3802 case EvalInfo::EvaluatingDeclKind::Dtor:
3803 // C++2a [expr.const]p6:
3804 // [during constant destruction] the lifetime of a and its non-mutable
3805 // subobjects (but not its mutable subobjects) [are] considered to start
3806 // within e.
3807 if (MutableSubobject || Base != Info.EvaluatingDecl)
3808 return false;
3809 // FIXME: We can meaningfully extend this to cover non-const objects, but
3810 // we will need special handling: we should be able to access only
3811 // subobjects of such objects that are themselves declared const.
3813 return T.isConstQualified() || T->isReferenceType();
3814 }
3815
3816 llvm_unreachable("unknown evaluating decl kind");
3817}
3818
3819static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3820 SourceLocation CallLoc = {}) {
3821 return Info.CheckArraySize(
3822 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3823 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3824 /*Diag=*/true);
3825}
3826
3827namespace {
3828/// A handle to a complete object (an object that is not a subobject of
3829/// another object).
3830struct CompleteObject {
3831 /// The identity of the object.
3832 APValue::LValueBase Base;
3833 /// The value of the complete object.
3834 APValue *Value;
3835 /// The type of the complete object.
3836 QualType Type;
3837
3838 CompleteObject() : Value(nullptr) {}
3839 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3840 : Base(Base), Value(Value), Type(Type) {}
3841
3842 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3843 // If this isn't a "real" access (eg, if it's just accessing the type
3844 // info), allow it. We assume the type doesn't change dynamically for
3845 // subobjects of constexpr objects (even though we'd hit UB here if it
3846 // did). FIXME: Is this right?
3847 if (!isAnyAccess(AK))
3848 return true;
3849
3850 // In C++14 onwards, it is permitted to read a mutable member whose
3851 // lifetime began within the evaluation.
3852 // FIXME: Should we also allow this in C++11?
3853 if (!Info.getLangOpts().CPlusPlus14 &&
3854 AK != AccessKinds::AK_IsWithinLifetime)
3855 return false;
3856 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3857 }
3858
3859 explicit operator bool() const { return !Type.isNull(); }
3860};
3861} // end anonymous namespace
3862
3863static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3864 bool IsMutable = false) {
3865 // C++ [basic.type.qualifier]p1:
3866 // - A const object is an object of type const T or a non-mutable subobject
3867 // of a const object.
3868 if (ObjType.isConstQualified() && !IsMutable)
3869 SubobjType.addConst();
3870 // - A volatile object is an object of type const T or a subobject of a
3871 // volatile object.
3872 if (ObjType.isVolatileQualified())
3873 SubobjType.addVolatile();
3874 return SubobjType;
3875}
3876
3877/// Find the designated sub-object of an rvalue.
3878template <typename SubobjectHandler>
3879static typename SubobjectHandler::result_type
3880findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3881 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3882 if (Sub.Invalid)
3883 // A diagnostic will have already been produced.
3884 return handler.failed();
3885 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3886 if (Info.getLangOpts().CPlusPlus11)
3887 Info.FFDiag(E, Sub.isOnePastTheEnd()
3888 ? diag::note_constexpr_access_past_end
3889 : diag::note_constexpr_access_unsized_array)
3890 << handler.AccessKind;
3891 else
3892 Info.FFDiag(E);
3893 return handler.failed();
3894 }
3895
3896 APValue *O = Obj.Value;
3897 QualType ObjType = Obj.Type;
3898 const FieldDecl *LastField = nullptr;
3899 const FieldDecl *VolatileField = nullptr;
3900
3901 // Walk the designator's path to find the subobject.
3902 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3903 // Reading an indeterminate value is undefined, but assigning over one is OK.
3904 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3905 (O->isIndeterminate() &&
3906 !isValidIndeterminateAccess(handler.AccessKind))) {
3907 // Object has ended lifetime.
3908 // If I is non-zero, some subobject (member or array element) of a
3909 // complete object has ended its lifetime, so this is valid for
3910 // IsWithinLifetime, resulting in false.
3911 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3912 return false;
3913 if (!Info.checkingPotentialConstantExpression())
3914 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3915 << handler.AccessKind << O->isIndeterminate()
3916 << E->getSourceRange();
3917 return handler.failed();
3918 }
3919
3920 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3921 // const and volatile semantics are not applied on an object under
3922 // {con,de}struction.
3923 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3924 ObjType->isRecordType() &&
3925 Info.isEvaluatingCtorDtor(
3926 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3927 ConstructionPhase::None) {
3928 ObjType = Info.Ctx.getCanonicalType(ObjType);
3929 ObjType.removeLocalConst();
3930 ObjType.removeLocalVolatile();
3931 }
3932
3933 // If this is our last pass, check that the final object type is OK.
3934 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3935 // Accesses to volatile objects are prohibited.
3936 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3937 if (Info.getLangOpts().CPlusPlus) {
3938 int DiagKind;
3939 SourceLocation Loc;
3940 const NamedDecl *Decl = nullptr;
3941 if (VolatileField) {
3942 DiagKind = 2;
3943 Loc = VolatileField->getLocation();
3944 Decl = VolatileField;
3945 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3946 DiagKind = 1;
3947 Loc = VD->getLocation();
3948 Decl = VD;
3949 } else {
3950 DiagKind = 0;
3951 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3952 Loc = E->getExprLoc();
3953 }
3954 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3955 << handler.AccessKind << DiagKind << Decl;
3956 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3957 } else {
3958 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3959 }
3960 return handler.failed();
3961 }
3962
3963 // If we are reading an object of class type, there may still be more
3964 // things we need to check: if there are any mutable subobjects, we
3965 // cannot perform this read. (This only happens when performing a trivial
3966 // copy or assignment.)
3967 if (ObjType->isRecordType() &&
3968 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3969 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3970 return handler.failed();
3971 }
3972
3973 if (I == N) {
3974 if (!handler.found(*O, ObjType))
3975 return false;
3976
3977 // If we modified a bit-field, truncate it to the right width.
3978 if (isModification(handler.AccessKind) &&
3979 LastField && LastField->isBitField() &&
3980 !truncateBitfieldValue(Info, E, *O, LastField))
3981 return false;
3982
3983 return true;
3984 }
3985
3986 LastField = nullptr;
3987 if (ObjType->isArrayType()) {
3988 // Next subobject is an array element.
3989 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
3991 "vla in literal type?");
3992 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3993 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3994 CAT && CAT->getSize().ule(Index)) {
3995 // Note, it should not be possible to form a pointer with a valid
3996 // designator which points more than one past the end of the array.
3997 if (Info.getLangOpts().CPlusPlus11)
3998 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3999 << handler.AccessKind;
4000 else
4001 Info.FFDiag(E);
4002 return handler.failed();
4003 }
4004
4005 ObjType = AT->getElementType();
4006
4007 if (O->getArrayInitializedElts() > Index)
4008 O = &O->getArrayInitializedElt(Index);
4009 else if (!isRead(handler.AccessKind)) {
4010 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4011 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4012 return handler.failed();
4013
4014 expandArray(*O, Index);
4015 O = &O->getArrayInitializedElt(Index);
4016 } else
4017 O = &O->getArrayFiller();
4018 } else if (ObjType->isAnyComplexType()) {
4019 // Next subobject is a complex number.
4020 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4021 if (Index > 1) {
4022 if (Info.getLangOpts().CPlusPlus11)
4023 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4024 << handler.AccessKind;
4025 else
4026 Info.FFDiag(E);
4027 return handler.failed();
4028 }
4029
4030 ObjType = getSubobjectType(
4031 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4032
4033 assert(I == N - 1 && "extracting subobject of scalar?");
4034 if (O->isComplexInt()) {
4035 return handler.found(Index ? O->getComplexIntImag()
4036 : O->getComplexIntReal(), ObjType);
4037 } else {
4038 assert(O->isComplexFloat());
4039 return handler.found(Index ? O->getComplexFloatImag()
4040 : O->getComplexFloatReal(), ObjType);
4041 }
4042 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4043 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4044 unsigned NumElements = VT->getNumElements();
4045 if (Index == NumElements) {
4046 if (Info.getLangOpts().CPlusPlus11)
4047 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4048 << handler.AccessKind;
4049 else
4050 Info.FFDiag(E);
4051 return handler.failed();
4052 }
4053
4054 if (Index > NumElements) {
4055 Info.CCEDiag(E, diag::note_constexpr_array_index)
4056 << Index << /*array*/ 0 << NumElements;
4057 return handler.failed();
4058 }
4059
4060 ObjType = VT->getElementType();
4061 assert(I == N - 1 && "extracting subobject of scalar?");
4062 return handler.found(O->getVectorElt(Index), ObjType);
4063 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4064 if (Field->isMutable() &&
4065 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4066 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4067 << handler.AccessKind << Field;
4068 Info.Note(Field->getLocation(), diag::note_declared_at);
4069 return handler.failed();
4070 }
4071
4072 // Next subobject is a class, struct or union field.
4073 RecordDecl *RD =
4074 ObjType->castAsCanonical<RecordType>()->getOriginalDecl();
4075 if (RD->isUnion()) {
4076 const FieldDecl *UnionField = O->getUnionField();
4077 if (!UnionField ||
4078 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4079 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4080 // Placement new onto an inactive union member makes it active.
4081 O->setUnion(Field, APValue());
4082 } else {
4083 // Pointer to/into inactive union member: Not within lifetime
4084 if (handler.AccessKind == AK_IsWithinLifetime)
4085 return false;
4086 // FIXME: If O->getUnionValue() is absent, report that there's no
4087 // active union member rather than reporting the prior active union
4088 // member. We'll need to fix nullptr_t to not use APValue() as its
4089 // representation first.
4090 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4091 << handler.AccessKind << Field << !UnionField << UnionField;
4092 return handler.failed();
4093 }
4094 }
4095 O = &O->getUnionValue();
4096 } else
4097 O = &O->getStructField(Field->getFieldIndex());
4098
4099 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4100 LastField = Field;
4101 if (Field->getType().isVolatileQualified())
4102 VolatileField = Field;
4103 } else {
4104 // Next subobject is a base class.
4105 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4106 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4107 O = &O->getStructBase(getBaseIndex(Derived, Base));
4108
4109 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4110 }
4111 }
4112}
4113
4114namespace {
4115struct ExtractSubobjectHandler {
4116 EvalInfo &Info;
4117 const Expr *E;
4118 APValue &Result;
4119 const AccessKinds AccessKind;
4120
4121 typedef bool result_type;
4122 bool failed() { return false; }
4123 bool found(APValue &Subobj, QualType SubobjType) {
4124 Result = Subobj;
4125 if (AccessKind == AK_ReadObjectRepresentation)
4126 return true;
4127 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4128 }
4129 bool found(APSInt &Value, QualType SubobjType) {
4130 Result = APValue(Value);
4131 return true;
4132 }
4133 bool found(APFloat &Value, QualType SubobjType) {
4134 Result = APValue(Value);
4135 return true;
4136 }
4137};
4138} // end anonymous namespace
4139
4140/// Extract the designated sub-object of an rvalue.
4141static bool extractSubobject(EvalInfo &Info, const Expr *E,
4142 const CompleteObject &Obj,
4143 const SubobjectDesignator &Sub, APValue &Result,
4144 AccessKinds AK = AK_Read) {
4145 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4146 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4147 return findSubobject(Info, E, Obj, Sub, Handler);
4148}
4149
4150namespace {
4151struct ModifySubobjectHandler {
4152 EvalInfo &Info;
4153 APValue &NewVal;
4154 const Expr *E;
4155
4156 typedef bool result_type;
4157 static const AccessKinds AccessKind = AK_Assign;
4158
4159 bool checkConst(QualType QT) {
4160 // Assigning to a const object has undefined behavior.
4161 if (QT.isConstQualified()) {
4162 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4163 return false;
4164 }
4165 return true;
4166 }
4167
4168 bool failed() { return false; }
4169 bool found(APValue &Subobj, QualType SubobjType) {
4170 if (!checkConst(SubobjType))
4171 return false;
4172 // We've been given ownership of NewVal, so just swap it in.
4173 Subobj.swap(NewVal);
4174 return true;
4175 }
4176 bool found(APSInt &Value, QualType SubobjType) {
4177 if (!checkConst(SubobjType))
4178 return false;
4179 if (!NewVal.isInt()) {
4180 // Maybe trying to write a cast pointer value into a complex?
4181 Info.FFDiag(E);
4182 return false;
4183 }
4184 Value = NewVal.getInt();
4185 return true;
4186 }
4187 bool found(APFloat &Value, QualType SubobjType) {
4188 if (!checkConst(SubobjType))
4189 return false;
4190 Value = NewVal.getFloat();
4191 return true;
4192 }
4193};
4194} // end anonymous namespace
4195
4196const AccessKinds ModifySubobjectHandler::AccessKind;
4197
4198/// Update the designated sub-object of an rvalue to the given value.
4199static bool modifySubobject(EvalInfo &Info, const Expr *E,
4200 const CompleteObject &Obj,
4201 const SubobjectDesignator &Sub,
4202 APValue &NewVal) {
4203 ModifySubobjectHandler Handler = { Info, NewVal, E };
4204 return findSubobject(Info, E, Obj, Sub, Handler);
4205}
4206
4207/// Find the position where two subobject designators diverge, or equivalently
4208/// the length of the common initial subsequence.
4209static unsigned FindDesignatorMismatch(QualType ObjType,
4210 const SubobjectDesignator &A,
4211 const SubobjectDesignator &B,
4212 bool &WasArrayIndex) {
4213 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4214 for (/**/; I != N; ++I) {
4215 if (!ObjType.isNull() &&
4216 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4217 // Next subobject is an array element.
4218 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4219 WasArrayIndex = true;
4220 return I;
4221 }
4222 if (ObjType->isAnyComplexType())
4223 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4224 else
4225 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4226 } else {
4227 if (A.Entries[I].getAsBaseOrMember() !=
4228 B.Entries[I].getAsBaseOrMember()) {
4229 WasArrayIndex = false;
4230 return I;
4231 }
4232 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4233 // Next subobject is a field.
4234 ObjType = FD->getType();
4235 else
4236 // Next subobject is a base class.
4237 ObjType = QualType();
4238 }
4239 }
4240 WasArrayIndex = false;
4241 return I;
4242}
4243
4244/// Determine whether the given subobject designators refer to elements of the
4245/// same array object.
4247 const SubobjectDesignator &A,
4248 const SubobjectDesignator &B) {
4249 if (A.Entries.size() != B.Entries.size())
4250 return false;
4251
4252 bool IsArray = A.MostDerivedIsArrayElement;
4253 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4254 // A is a subobject of the array element.
4255 return false;
4256
4257 // If A (and B) designates an array element, the last entry will be the array
4258 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4259 // of length 1' case, and the entire path must match.
4260 bool WasArrayIndex;
4261 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4262 return CommonLength >= A.Entries.size() - IsArray;
4263}
4264
4265/// Find the complete object to which an LValue refers.
4266static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4267 AccessKinds AK, const LValue &LVal,
4268 QualType LValType) {
4269 if (LVal.InvalidBase) {
4270 Info.FFDiag(E);
4271 return CompleteObject();
4272 }
4273
4274 if (!LVal.Base) {
4276 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4277 else
4278 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4279 return CompleteObject();
4280 }
4281
4282 CallStackFrame *Frame = nullptr;
4283 unsigned Depth = 0;
4284 if (LVal.getLValueCallIndex()) {
4285 std::tie(Frame, Depth) =
4286 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4287 if (!Frame) {
4288 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4289 << AK << LVal.Base.is<const ValueDecl*>();
4290 NoteLValueLocation(Info, LVal.Base);
4291 return CompleteObject();
4292 }
4293 }
4294
4295 bool IsAccess = isAnyAccess(AK);
4296
4297 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4298 // is not a constant expression (even if the object is non-volatile). We also
4299 // apply this rule to C++98, in order to conform to the expected 'volatile'
4300 // semantics.
4301 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4302 if (Info.getLangOpts().CPlusPlus)
4303 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4304 << AK << LValType;
4305 else
4306 Info.FFDiag(E);
4307 return CompleteObject();
4308 }
4309
4310 // Compute value storage location and type of base object.
4311 APValue *BaseVal = nullptr;
4312 QualType BaseType = getType(LVal.Base);
4313
4314 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4315 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4316 // This is the object whose initializer we're evaluating, so its lifetime
4317 // started in the current evaluation.
4318 BaseVal = Info.EvaluatingDeclValue;
4319 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4320 // Allow reading from a GUID declaration.
4321 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4322 if (isModification(AK)) {
4323 // All the remaining cases do not permit modification of the object.
4324 Info.FFDiag(E, diag::note_constexpr_modify_global);
4325 return CompleteObject();
4326 }
4327 APValue &V = GD->getAsAPValue();
4328 if (V.isAbsent()) {
4329 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4330 << GD->getType();
4331 return CompleteObject();
4332 }
4333 return CompleteObject(LVal.Base, &V, GD->getType());
4334 }
4335
4336 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4337 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4338 if (isModification(AK)) {
4339 Info.FFDiag(E, diag::note_constexpr_modify_global);
4340 return CompleteObject();
4341 }
4342 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4343 GCD->getType());
4344 }
4345
4346 // Allow reading from template parameter objects.
4347 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4348 if (isModification(AK)) {
4349 Info.FFDiag(E, diag::note_constexpr_modify_global);
4350 return CompleteObject();
4351 }
4352 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4353 TPO->getType());
4354 }
4355
4356 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4357 // In C++11, constexpr, non-volatile variables initialized with constant
4358 // expressions are constant expressions too. Inside constexpr functions,
4359 // parameters are constant expressions even if they're non-const.
4360 // In C++1y, objects local to a constant expression (those with a Frame) are
4361 // both readable and writable inside constant expressions.
4362 // In C, such things can also be folded, although they are not ICEs.
4363 const VarDecl *VD = dyn_cast<VarDecl>(D);
4364 if (VD) {
4365 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4366 VD = VDef;
4367 }
4368 if (!VD || VD->isInvalidDecl()) {
4369 Info.FFDiag(E);
4370 return CompleteObject();
4371 }
4372
4373 bool IsConstant = BaseType.isConstant(Info.Ctx);
4374 bool ConstexprVar = false;
4375 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4376 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4377 ConstexprVar = VD->isConstexpr();
4378
4379 // Unless we're looking at a local variable or argument in a constexpr call,
4380 // the variable we're reading must be const (unless we are binding to a
4381 // reference).
4382 if (AK != clang::AK_Dereference && !Frame) {
4383 if (IsAccess && isa<ParmVarDecl>(VD)) {
4384 // Access of a parameter that's not associated with a frame isn't going
4385 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4386 // suitable diagnostic.
4387 } else if (Info.getLangOpts().CPlusPlus14 &&
4388 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4389 // OK, we can read and modify an object if we're in the process of
4390 // evaluating its initializer, because its lifetime began in this
4391 // evaluation.
4392 } else if (isModification(AK)) {
4393 // All the remaining cases do not permit modification of the object.
4394 Info.FFDiag(E, diag::note_constexpr_modify_global);
4395 return CompleteObject();
4396 } else if (VD->isConstexpr()) {
4397 // OK, we can read this variable.
4398 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4399 Info.FFDiag(E);
4400 return CompleteObject();
4401 } else if (BaseType->isIntegralOrEnumerationType()) {
4402 if (!IsConstant) {
4403 if (!IsAccess)
4404 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4405 if (Info.getLangOpts().CPlusPlus) {
4406 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4407 Info.Note(VD->getLocation(), diag::note_declared_at);
4408 } else {
4409 Info.FFDiag(E);
4410 }
4411 return CompleteObject();
4412 }
4413 } else if (!IsAccess) {
4414 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4415 } else if ((IsConstant || BaseType->isReferenceType()) &&
4416 Info.checkingPotentialConstantExpression() &&
4417 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4418 // This variable might end up being constexpr. Don't diagnose it yet.
4419 } else if (IsConstant) {
4420 // Keep evaluating to see what we can do. In particular, we support
4421 // folding of const floating-point types, in order to make static const
4422 // data members of such types (supported as an extension) more useful.
4423 if (Info.getLangOpts().CPlusPlus) {
4424 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4425 ? diag::note_constexpr_ltor_non_constexpr
4426 : diag::note_constexpr_ltor_non_integral, 1)
4427 << VD << BaseType;
4428 Info.Note(VD->getLocation(), diag::note_declared_at);
4429 } else {
4430 Info.CCEDiag(E);
4431 }
4432 } else {
4433 // Never allow reading a non-const value.
4434 if (Info.getLangOpts().CPlusPlus) {
4435 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4436 ? diag::note_constexpr_ltor_non_constexpr
4437 : diag::note_constexpr_ltor_non_integral, 1)
4438 << VD << BaseType;
4439 Info.Note(VD->getLocation(), diag::note_declared_at);
4440 } else {
4441 Info.FFDiag(E);
4442 }
4443 return CompleteObject();
4444 }
4445 }
4446
4447 // When binding to a reference, the variable does not need to be constexpr
4448 // or have constant initalization.
4449 if (AK != clang::AK_Dereference &&
4450 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4451 BaseVal))
4452 return CompleteObject();
4453 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4454 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4455 // we can't access a constexpr-unknown object.
4456 if (AK != clang::AK_Dereference && !BaseVal) {
4457 if (!Info.checkingPotentialConstantExpression()) {
4458 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4459 << AK << VD;
4460 Info.Note(VD->getLocation(), diag::note_declared_at);
4461 }
4462 return CompleteObject();
4463 }
4464 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4465 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4466 if (!Alloc) {
4467 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4468 return CompleteObject();
4469 }
4470 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4471 LVal.Base.getDynamicAllocType());
4472 }
4473 // When binding to a reference, the variable does not need to be
4474 // within its lifetime.
4475 else if (AK != clang::AK_Dereference) {
4476 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4477
4478 if (!Frame) {
4479 if (const MaterializeTemporaryExpr *MTE =
4480 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4481 assert(MTE->getStorageDuration() == SD_Static &&
4482 "should have a frame for a non-global materialized temporary");
4483
4484 // C++20 [expr.const]p4: [DR2126]
4485 // An object or reference is usable in constant expressions if it is
4486 // - a temporary object of non-volatile const-qualified literal type
4487 // whose lifetime is extended to that of a variable that is usable
4488 // in constant expressions
4489 //
4490 // C++20 [expr.const]p5:
4491 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4492 // - a non-volatile glvalue that refers to an object that is usable
4493 // in constant expressions, or
4494 // - a non-volatile glvalue of literal type that refers to a
4495 // non-volatile object whose lifetime began within the evaluation
4496 // of E;
4497 //
4498 // C++11 misses the 'began within the evaluation of e' check and
4499 // instead allows all temporaries, including things like:
4500 // int &&r = 1;
4501 // int x = ++r;
4502 // constexpr int k = r;
4503 // Therefore we use the C++14-onwards rules in C++11 too.
4504 //
4505 // Note that temporaries whose lifetimes began while evaluating a
4506 // variable's constructor are not usable while evaluating the
4507 // corresponding destructor, not even if they're of const-qualified
4508 // types.
4509 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4510 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4511 if (!IsAccess)
4512 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4513 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4514 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4515 return CompleteObject();
4516 }
4517
4518 BaseVal = MTE->getOrCreateValue(false);
4519 assert(BaseVal && "got reference to unevaluated temporary");
4520 } else if (const CompoundLiteralExpr *CLE =
4521 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4522 // According to GCC info page:
4523 //
4524 // 6.28 Compound Literals
4525 //
4526 // As an optimization, G++ sometimes gives array compound literals
4527 // longer lifetimes: when the array either appears outside a function or
4528 // has a const-qualified type. If foo and its initializer had elements
4529 // of type char *const rather than char *, or if foo were a global
4530 // variable, the array would have static storage duration. But it is
4531 // probably safest just to avoid the use of array compound literals in
4532 // C++ code.
4533 //
4534 // Obey that rule by checking constness for converted array types.
4535 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4536 !LValType->isArrayType() &&
4537 !CLETy.isConstant(Info.Ctx)) {
4538 Info.FFDiag(E);
4539 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4540 return CompleteObject();
4541 }
4542
4543 BaseVal = &CLE->getStaticValue();
4544 } else {
4545 if (!IsAccess)
4546 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4547 APValue Val;
4548 LVal.moveInto(Val);
4549 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4550 << AK
4551 << Val.getAsString(Info.Ctx,
4552 Info.Ctx.getLValueReferenceType(LValType));
4553 NoteLValueLocation(Info, LVal.Base);
4554 return CompleteObject();
4555 }
4556 } else if (AK != clang::AK_Dereference) {
4557 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4558 assert(BaseVal && "missing value for temporary");
4559 }
4560 }
4561
4562 // In C++14, we can't safely access any mutable state when we might be
4563 // evaluating after an unmodeled side effect. Parameters are modeled as state
4564 // in the caller, but aren't visible once the call returns, so they can be
4565 // modified in a speculatively-evaluated call.
4566 //
4567 // FIXME: Not all local state is mutable. Allow local constant subobjects
4568 // to be read here (but take care with 'mutable' fields).
4569 unsigned VisibleDepth = Depth;
4570 if (llvm::isa_and_nonnull<ParmVarDecl>(
4571 LVal.Base.dyn_cast<const ValueDecl *>()))
4572 ++VisibleDepth;
4573 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4574 Info.EvalStatus.HasSideEffects) ||
4575 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4576 return CompleteObject();
4577
4578 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4579}
4580
4581/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4582/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4583/// glvalue referred to by an entity of reference type.
4584///
4585/// \param Info - Information about the ongoing evaluation.
4586/// \param Conv - The expression for which we are performing the conversion.
4587/// Used for diagnostics.
4588/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4589/// case of a non-class type).
4590/// \param LVal - The glvalue on which we are attempting to perform this action.
4591/// \param RVal - The produced value will be placed here.
4592/// \param WantObjectRepresentation - If true, we're looking for the object
4593/// representation rather than the value, and in particular,
4594/// there is no requirement that the result be fully initialized.
4595static bool
4597 const LValue &LVal, APValue &RVal,
4598 bool WantObjectRepresentation = false) {
4599 if (LVal.Designator.Invalid)
4600 return false;
4601
4602 // Check for special cases where there is no existing APValue to look at.
4603 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4604
4605 AccessKinds AK =
4606 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4607
4608 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4610 // Special-case character extraction so we don't have to construct an
4611 // APValue for the whole string.
4612 assert(LVal.Designator.Entries.size() <= 1 &&
4613 "Can only read characters from string literals");
4614 if (LVal.Designator.Entries.empty()) {
4615 // Fail for now for LValue to RValue conversion of an array.
4616 // (This shouldn't show up in C/C++, but it could be triggered by a
4617 // weird EvaluateAsRValue call from a tool.)
4618 Info.FFDiag(Conv);
4619 return false;
4620 }
4621 if (LVal.Designator.isOnePastTheEnd()) {
4622 if (Info.getLangOpts().CPlusPlus11)
4623 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4624 else
4625 Info.FFDiag(Conv);
4626 return false;
4627 }
4628 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4629 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4630 return true;
4631 }
4632 }
4633
4634 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4635 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4636}
4637
4638/// Perform an assignment of Val to LVal. Takes ownership of Val.
4639static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4640 QualType LValType, APValue &Val) {
4641 if (LVal.Designator.Invalid)
4642 return false;
4643
4644 if (!Info.getLangOpts().CPlusPlus14) {
4645 Info.FFDiag(E);
4646 return false;
4647 }
4648
4649 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4650 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4651}
4652
4653namespace {
4654struct CompoundAssignSubobjectHandler {
4655 EvalInfo &Info;
4656 const CompoundAssignOperator *E;
4657 QualType PromotedLHSType;
4659 const APValue &RHS;
4660
4661 static const AccessKinds AccessKind = AK_Assign;
4662
4663 typedef bool result_type;
4664
4665 bool checkConst(QualType QT) {
4666 // Assigning to a const object has undefined behavior.
4667 if (QT.isConstQualified()) {
4668 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4669 return false;
4670 }
4671 return true;
4672 }
4673
4674 bool failed() { return false; }
4675 bool found(APValue &Subobj, QualType SubobjType) {
4676 switch (Subobj.getKind()) {
4677 case APValue::Int:
4678 return found(Subobj.getInt(), SubobjType);
4679 case APValue::Float:
4680 return found(Subobj.getFloat(), SubobjType);
4683 // FIXME: Implement complex compound assignment.
4684 Info.FFDiag(E);
4685 return false;
4686 case APValue::LValue:
4687 return foundPointer(Subobj, SubobjType);
4688 case APValue::Vector:
4689 return foundVector(Subobj, SubobjType);
4691 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4692 << /*read of=*/0 << /*uninitialized object=*/1
4693 << E->getLHS()->getSourceRange();
4694 return false;
4695 default:
4696 // FIXME: can this happen?
4697 Info.FFDiag(E);
4698 return false;
4699 }
4700 }
4701
4702 bool foundVector(APValue &Value, QualType SubobjType) {
4703 if (!checkConst(SubobjType))
4704 return false;
4705
4706 if (!SubobjType->isVectorType()) {
4707 Info.FFDiag(E);
4708 return false;
4709 }
4710 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4711 }
4712
4713 bool found(APSInt &Value, QualType SubobjType) {
4714 if (!checkConst(SubobjType))
4715 return false;
4716
4717 if (!SubobjType->isIntegerType()) {
4718 // We don't support compound assignment on integer-cast-to-pointer
4719 // values.
4720 Info.FFDiag(E);
4721 return false;
4722 }
4723
4724 if (RHS.isInt()) {
4725 APSInt LHS =
4726 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4727 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4728 return false;
4729 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4730 return true;
4731 } else if (RHS.isFloat()) {
4732 const FPOptions FPO = E->getFPFeaturesInEffect(
4733 Info.Ctx.getLangOpts());
4734 APFloat FValue(0.0);
4735 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4736 PromotedLHSType, FValue) &&
4737 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4738 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4739 Value);
4740 }
4741
4742 Info.FFDiag(E);
4743 return false;
4744 }
4745 bool found(APFloat &Value, QualType SubobjType) {
4746 return checkConst(SubobjType) &&
4747 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4748 Value) &&
4749 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4750 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4751 }
4752 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4753 if (!checkConst(SubobjType))
4754 return false;
4755
4756 QualType PointeeType;
4757 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4758 PointeeType = PT->getPointeeType();
4759
4760 if (PointeeType.isNull() || !RHS.isInt() ||
4761 (Opcode != BO_Add && Opcode != BO_Sub)) {
4762 Info.FFDiag(E);
4763 return false;
4764 }
4765
4766 APSInt Offset = RHS.getInt();
4767 if (Opcode == BO_Sub)
4768 negateAsSigned(Offset);
4769
4770 LValue LVal;
4771 LVal.setFrom(Info.Ctx, Subobj);
4772 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4773 return false;
4774 LVal.moveInto(Subobj);
4775 return true;
4776 }
4777};
4778} // end anonymous namespace
4779
4780const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4781
4782/// Perform a compound assignment of LVal <op>= RVal.
4783static bool handleCompoundAssignment(EvalInfo &Info,
4784 const CompoundAssignOperator *E,
4785 const LValue &LVal, QualType LValType,
4786 QualType PromotedLValType,
4787 BinaryOperatorKind Opcode,
4788 const APValue &RVal) {
4789 if (LVal.Designator.Invalid)
4790 return false;
4791
4792 if (!Info.getLangOpts().CPlusPlus14) {
4793 Info.FFDiag(E);
4794 return false;
4795 }
4796
4797 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4798 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4799 RVal };
4800 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4801}
4802
4803namespace {
4804struct IncDecSubobjectHandler {
4805 EvalInfo &Info;
4806 const UnaryOperator *E;
4808 APValue *Old;
4809
4810 typedef bool result_type;
4811
4812 bool checkConst(QualType QT) {
4813 // Assigning to a const object has undefined behavior.
4814 if (QT.isConstQualified()) {
4815 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4816 return false;
4817 }
4818 return true;
4819 }
4820
4821 bool failed() { return false; }
4822 bool found(APValue &Subobj, QualType SubobjType) {
4823 // Stash the old value. Also clear Old, so we don't clobber it later
4824 // if we're post-incrementing a complex.
4825 if (Old) {
4826 *Old = Subobj;
4827 Old = nullptr;
4828 }
4829
4830 switch (Subobj.getKind()) {
4831 case APValue::Int:
4832 return found(Subobj.getInt(), SubobjType);
4833 case APValue::Float:
4834 return found(Subobj.getFloat(), SubobjType);
4836 return found(Subobj.getComplexIntReal(),
4837 SubobjType->castAs<ComplexType>()->getElementType()
4838 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4840 return found(Subobj.getComplexFloatReal(),
4841 SubobjType->castAs<ComplexType>()->getElementType()
4842 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4843 case APValue::LValue:
4844 return foundPointer(Subobj, SubobjType);
4845 default:
4846 // FIXME: can this happen?
4847 Info.FFDiag(E);
4848 return false;
4849 }
4850 }
4851 bool found(APSInt &Value, QualType SubobjType) {
4852 if (!checkConst(SubobjType))
4853 return false;
4854
4855 if (!SubobjType->isIntegerType()) {
4856 // We don't support increment / decrement on integer-cast-to-pointer
4857 // values.
4858 Info.FFDiag(E);
4859 return false;
4860 }
4861
4862 if (Old) *Old = APValue(Value);
4863
4864 // bool arithmetic promotes to int, and the conversion back to bool
4865 // doesn't reduce mod 2^n, so special-case it.
4866 if (SubobjType->isBooleanType()) {
4867 if (AccessKind == AK_Increment)
4868 Value = 1;
4869 else
4870 Value = !Value;
4871 return true;
4872 }
4873
4874 bool WasNegative = Value.isNegative();
4875 if (AccessKind == AK_Increment) {
4876 ++Value;
4877
4878 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4879 APSInt ActualValue(Value, /*IsUnsigned*/true);
4880 return HandleOverflow(Info, E, ActualValue, SubobjType);
4881 }
4882 } else {
4883 --Value;
4884
4885 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4886 unsigned BitWidth = Value.getBitWidth();
4887 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4888 ActualValue.setBit(BitWidth);
4889 return HandleOverflow(Info, E, ActualValue, SubobjType);
4890 }
4891 }
4892 return true;
4893 }
4894 bool found(APFloat &Value, QualType SubobjType) {
4895 if (!checkConst(SubobjType))
4896 return false;
4897
4898 if (Old) *Old = APValue(Value);
4899
4900 APFloat One(Value.getSemantics(), 1);
4901 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4902 APFloat::opStatus St;
4903 if (AccessKind == AK_Increment)
4904 St = Value.add(One, RM);
4905 else
4906 St = Value.subtract(One, RM);
4907 return checkFloatingPointResult(Info, E, St);
4908 }
4909 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4910 if (!checkConst(SubobjType))
4911 return false;
4912
4913 QualType PointeeType;
4914 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4915 PointeeType = PT->getPointeeType();
4916 else {
4917 Info.FFDiag(E);
4918 return false;
4919 }
4920
4921 LValue LVal;
4922 LVal.setFrom(Info.Ctx, Subobj);
4923 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4924 AccessKind == AK_Increment ? 1 : -1))
4925 return false;
4926 LVal.moveInto(Subobj);
4927 return true;
4928 }
4929};
4930} // end anonymous namespace
4931
4932/// Perform an increment or decrement on LVal.
4933static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4934 QualType LValType, bool IsIncrement, APValue *Old) {
4935 if (LVal.Designator.Invalid)
4936 return false;
4937
4938 if (!Info.getLangOpts().CPlusPlus14) {
4939 Info.FFDiag(E);
4940 return false;
4941 }
4942
4943 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4944 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4945 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4946 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4947}
4948
4949/// Build an lvalue for the object argument of a member function call.
4950static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4951 LValue &This) {
4952 if (Object->getType()->isPointerType() && Object->isPRValue())
4953 return EvaluatePointer(Object, This, Info);
4954
4955 if (Object->isGLValue())
4956 return EvaluateLValue(Object, This, Info);
4957
4958 if (Object->getType()->isLiteralType(Info.Ctx))
4959 return EvaluateTemporary(Object, This, Info);
4960
4961 if (Object->getType()->isRecordType() && Object->isPRValue())
4962 return EvaluateTemporary(Object, This, Info);
4963
4964 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4965 return false;
4966}
4967
4968/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4969/// lvalue referring to the result.
4970///
4971/// \param Info - Information about the ongoing evaluation.
4972/// \param LV - An lvalue referring to the base of the member pointer.
4973/// \param RHS - The member pointer expression.
4974/// \param IncludeMember - Specifies whether the member itself is included in
4975/// the resulting LValue subobject designator. This is not possible when
4976/// creating a bound member function.
4977/// \return The field or method declaration to which the member pointer refers,
4978/// or 0 if evaluation fails.
4979static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4980 QualType LVType,
4981 LValue &LV,
4982 const Expr *RHS,
4983 bool IncludeMember = true) {
4984 MemberPtr MemPtr;
4985 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4986 return nullptr;
4987
4988 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4989 // member value, the behavior is undefined.
4990 if (!MemPtr.getDecl()) {
4991 // FIXME: Specific diagnostic.
4992 Info.FFDiag(RHS);
4993 return nullptr;
4994 }
4995
4996 if (MemPtr.isDerivedMember()) {
4997 // This is a member of some derived class. Truncate LV appropriately.
4998 // The end of the derived-to-base path for the base object must match the
4999 // derived-to-base path for the member pointer.
5000 // C++23 [expr.mptr.oper]p4:
5001 // If the result of E1 is an object [...] whose most derived object does
5002 // not contain the member to which E2 refers, the behavior is undefined.
5003 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5004 LV.Designator.Entries.size()) {
5005 Info.FFDiag(RHS);
5006 return nullptr;
5007 }
5008 unsigned PathLengthToMember =
5009 LV.Designator.Entries.size() - MemPtr.Path.size();
5010 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5011 const CXXRecordDecl *LVDecl = getAsBaseClass(
5012 LV.Designator.Entries[PathLengthToMember + I]);
5013 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5014 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5015 Info.FFDiag(RHS);
5016 return nullptr;
5017 }
5018 }
5019 // MemPtr.Path only contains the base classes of the class directly
5020 // containing the member E2. It is still necessary to check that the class
5021 // directly containing the member E2 lies on the derived-to-base path of E1
5022 // to avoid incorrectly permitting member pointer access into a sibling
5023 // class of the class containing the member E2. If this class would
5024 // correspond to the most-derived class of E1, it either isn't contained in
5025 // LV.Designator.Entries or the corresponding entry refers to an array
5026 // element instead. Therefore get the most derived class directly in this
5027 // case. Otherwise the previous entry should correpond to this class.
5028 const CXXRecordDecl *LastLVDecl =
5029 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5030 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5031 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5032 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5033 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5034 Info.FFDiag(RHS);
5035 return nullptr;
5036 }
5037
5038 // Truncate the lvalue to the appropriate derived class.
5039 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5040 PathLengthToMember))
5041 return nullptr;
5042 } else if (!MemPtr.Path.empty()) {
5043 // Extend the LValue path with the member pointer's path.
5044 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5045 MemPtr.Path.size() + IncludeMember);
5046
5047 // Walk down to the appropriate base class.
5048 if (const PointerType *PT = LVType->getAs<PointerType>())
5049 LVType = PT->getPointeeType();
5050 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5051 assert(RD && "member pointer access on non-class-type expression");
5052 // The first class in the path is that of the lvalue.
5053 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5054 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5055 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5056 return nullptr;
5057 RD = Base;
5058 }
5059 // Finally cast to the class containing the member.
5060 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5061 MemPtr.getContainingRecord()))
5062 return nullptr;
5063 }
5064
5065 // Add the member. Note that we cannot build bound member functions here.
5066 if (IncludeMember) {
5067 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5068 if (!HandleLValueMember(Info, RHS, LV, FD))
5069 return nullptr;
5070 } else if (const IndirectFieldDecl *IFD =
5071 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5072 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5073 return nullptr;
5074 } else {
5075 llvm_unreachable("can't construct reference to bound member function");
5076 }
5077 }
5078
5079 return MemPtr.getDecl();
5080}
5081
5082static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5083 const BinaryOperator *BO,
5084 LValue &LV,
5085 bool IncludeMember = true) {
5086 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5087
5088 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5089 if (Info.noteFailure()) {
5090 MemberPtr MemPtr;
5091 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5092 }
5093 return nullptr;
5094 }
5095
5096 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5097 BO->getRHS(), IncludeMember);
5098}
5099
5100/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5101/// the provided lvalue, which currently refers to the base object.
5102static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5103 LValue &Result) {
5104 SubobjectDesignator &D = Result.Designator;
5105 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5106 return false;
5107
5108 QualType TargetQT = E->getType();
5109 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5110 TargetQT = PT->getPointeeType();
5111
5112 auto InvalidCast = [&]() {
5113 if (!Info.checkingPotentialConstantExpression() ||
5114 !Result.AllowConstexprUnknown) {
5115 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5116 << D.MostDerivedType << TargetQT;
5117 }
5118 return false;
5119 };
5120
5121 // Check this cast lands within the final derived-to-base subobject path.
5122 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5123 return InvalidCast();
5124
5125 // Check the type of the final cast. We don't need to check the path,
5126 // since a cast can only be formed if the path is unique.
5127 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5128 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5129 const CXXRecordDecl *FinalType;
5130 if (NewEntriesSize == D.MostDerivedPathLength)
5131 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5132 else
5133 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5134 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5135 return InvalidCast();
5136
5137 // Truncate the lvalue to the appropriate derived class.
5138 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5139}
5140
5141/// Get the value to use for a default-initialized object of type T.
5142/// Return false if it encounters something invalid.
5144 bool Success = true;
5145
5146 // If there is already a value present don't overwrite it.
5147 if (!Result.isAbsent())
5148 return true;
5149
5150 if (auto *RD = T->getAsCXXRecordDecl()) {
5151 if (RD->isInvalidDecl()) {
5152 Result = APValue();
5153 return false;
5154 }
5155 if (RD->isUnion()) {
5156 Result = APValue((const FieldDecl *)nullptr);
5157 return true;
5158 }
5159 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5160 std::distance(RD->field_begin(), RD->field_end()));
5161
5162 unsigned Index = 0;
5163 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5164 End = RD->bases_end();
5165 I != End; ++I, ++Index)
5166 Success &=
5167 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5168
5169 for (const auto *I : RD->fields()) {
5170 if (I->isUnnamedBitField())
5171 continue;
5173 I->getType(), Result.getStructField(I->getFieldIndex()));
5174 }
5175 return Success;
5176 }
5177
5178 if (auto *AT =
5179 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5180 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5181 if (Result.hasArrayFiller())
5182 Success &=
5183 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5184
5185 return Success;
5186 }
5187
5188 Result = APValue::IndeterminateValue();
5189 return true;
5190}
5191
5192namespace {
5193enum EvalStmtResult {
5194 /// Evaluation failed.
5195 ESR_Failed,
5196 /// Hit a 'return' statement.
5197 ESR_Returned,
5198 /// Evaluation succeeded.
5199 ESR_Succeeded,
5200 /// Hit a 'continue' statement.
5201 ESR_Continue,
5202 /// Hit a 'break' statement.
5203 ESR_Break,
5204 /// Still scanning for 'case' or 'default' statement.
5205 ESR_CaseNotFound
5206};
5207}
5208/// Evaluates the initializer of a reference.
5209static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5210 const ValueDecl *D,
5211 const Expr *Init, LValue &Result,
5212 APValue &Val) {
5213 assert(Init->isGLValue() && D->getType()->isReferenceType());
5214 // A reference is an lvalue.
5215 if (!EvaluateLValue(Init, Result, Info))
5216 return false;
5217 // [C++26][decl.ref]
5218 // The object designated by such a glvalue can be outside its lifetime
5219 // Because a null pointer value or a pointer past the end of an object
5220 // does not point to an object, a reference in a well-defined program cannot
5221 // refer to such things;
5222 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5223 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5224 return false;
5225 }
5226
5227 // Save the result.
5228 Result.moveInto(Val);
5229 return true;
5230}
5231
5232static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5233 if (VD->isInvalidDecl())
5234 return false;
5235 // We don't need to evaluate the initializer for a static local.
5236 if (!VD->hasLocalStorage())
5237 return true;
5238
5239 LValue Result;
5240 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5241 ScopeKind::Block, Result);
5242
5243 const Expr *InitE = VD->getInit();
5244 if (!InitE) {
5245 if (VD->getType()->isDependentType())
5246 return Info.noteSideEffect();
5247 return handleDefaultInitValue(VD->getType(), Val);
5248 }
5249 if (InitE->isValueDependent())
5250 return false;
5251
5252 // For references to objects, check they do not designate a one-past-the-end
5253 // object.
5254 if (VD->getType()->isReferenceType()) {
5255 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5256 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5257 // Wipe out any partially-computed value, to allow tracking that this
5258 // evaluation failed.
5259 Val = APValue();
5260 return false;
5261 }
5262
5263 return true;
5264}
5265
5266static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5267 const DecompositionDecl *DD);
5268
5269static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5270 bool EvaluateConditionDecl = false) {
5271 bool OK = true;
5272 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5273 OK &= EvaluateVarDecl(Info, VD);
5274
5275 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5276 EvaluateConditionDecl && DD)
5277 OK &= EvaluateDecompositionDeclInit(Info, DD);
5278
5279 return OK;
5280}
5281
5282static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5283 const DecompositionDecl *DD) {
5284 bool OK = true;
5285 for (auto *BD : DD->flat_bindings())
5286 if (auto *VD = BD->getHoldingVar())
5287 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5288
5289 return OK;
5290}
5291
5292static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5293 const VarDecl *VD) {
5294 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5295 if (!EvaluateDecompositionDeclInit(Info, DD))
5296 return false;
5297 }
5298 return true;
5299}
5300
5301static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5302 assert(E->isValueDependent());
5303 if (Info.noteSideEffect())
5304 return true;
5305 assert(E->containsErrors() && "valid value-dependent expression should never "
5306 "reach invalid code path.");
5307 return false;
5308}
5309
5310/// Evaluate a condition (either a variable declaration or an expression).
5311static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5312 const Expr *Cond, bool &Result) {
5313 if (Cond->isValueDependent())
5314 return false;
5315 FullExpressionRAII Scope(Info);
5316 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5317 return false;
5318 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5319 return false;
5320 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5321 return false;
5322 return Scope.destroy();
5323}
5324
5325namespace {
5326/// A location where the result (returned value) of evaluating a
5327/// statement should be stored.
5328struct StmtResult {
5329 /// The APValue that should be filled in with the returned value.
5330 APValue &Value;
5331 /// The location containing the result, if any (used to support RVO).
5332 const LValue *Slot;
5333};
5334
5335struct TempVersionRAII {
5336 CallStackFrame &Frame;
5337
5338 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5339 Frame.pushTempVersion();
5340 }
5341
5342 ~TempVersionRAII() {
5343 Frame.popTempVersion();
5344 }
5345};
5346
5347}
5348
5349static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5350 const Stmt *S,
5351 const SwitchCase *SC = nullptr);
5352
5353/// Helper to implement named break/continue. Returns 'true' if the evaluation
5354/// result should be propagated up. Otherwise, it sets the evaluation result
5355/// to either Continue to continue the current loop, or Succeeded to break it.
5356static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5357 const Stmt *LoopOrSwitch,
5359 EvalStmtResult &ESR) {
5360 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5361
5362 // For loops, map Succeeded to Continue so we don't have to check for both.
5363 if (!IsSwitch && ESR == ESR_Succeeded) {
5364 ESR = ESR_Continue;
5365 return false;
5366 }
5367
5368 if (ESR != ESR_Break && ESR != ESR_Continue)
5369 return false;
5370
5371 // Are we breaking out of or continuing this statement?
5372 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5373 const Stmt *StackTop = Info.BreakContinueStack.back();
5374 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5375 Info.BreakContinueStack.pop_back();
5376 if (ESR == ESR_Break)
5377 ESR = ESR_Succeeded;
5378 return false;
5379 }
5380
5381 // We're not. Propagate the result up.
5382 for (BlockScopeRAII *S : Scopes) {
5383 if (!S->destroy()) {
5384 ESR = ESR_Failed;
5385 break;
5386 }
5387 }
5388 return true;
5389}
5390
5391/// Evaluate the body of a loop, and translate the result as appropriate.
5392static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5393 const Stmt *Body,
5394 const SwitchCase *Case = nullptr) {
5395 BlockScopeRAII Scope(Info);
5396
5397 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5398 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5399 ESR = ESR_Failed;
5400
5401 return ESR;
5402}
5403
5404/// Evaluate a switch statement.
5405static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5406 const SwitchStmt *SS) {
5407 BlockScopeRAII Scope(Info);
5408
5409 // Evaluate the switch condition.
5410 APSInt Value;
5411 {
5412 if (const Stmt *Init = SS->getInit()) {
5413 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5414 if (ESR != ESR_Succeeded) {
5415 if (ESR != ESR_Failed && !Scope.destroy())
5416 ESR = ESR_Failed;
5417 return ESR;
5418 }
5419 }
5420
5421 FullExpressionRAII CondScope(Info);
5422 if (SS->getConditionVariable() &&
5423 !EvaluateDecl(Info, SS->getConditionVariable()))
5424 return ESR_Failed;
5425 if (SS->getCond()->isValueDependent()) {
5426 // We don't know what the value is, and which branch should jump to.
5427 EvaluateDependentExpr(SS->getCond(), Info);
5428 return ESR_Failed;
5429 }
5430 if (!EvaluateInteger(SS->getCond(), Value, Info))
5431 return ESR_Failed;
5432
5434 return ESR_Failed;
5435
5436 if (!CondScope.destroy())
5437 return ESR_Failed;
5438 }
5439
5440 // Find the switch case corresponding to the value of the condition.
5441 // FIXME: Cache this lookup.
5442 const SwitchCase *Found = nullptr;
5443 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5444 SC = SC->getNextSwitchCase()) {
5445 if (isa<DefaultStmt>(SC)) {
5446 Found = SC;
5447 continue;
5448 }
5449
5450 const CaseStmt *CS = cast<CaseStmt>(SC);
5451 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5452 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5453 : LHS;
5454 if (LHS <= Value && Value <= RHS) {
5455 Found = SC;
5456 break;
5457 }
5458 }
5459
5460 if (!Found)
5461 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5462
5463 // Search the switch body for the switch case and evaluate it from there.
5464 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5465 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5466 return ESR_Failed;
5467 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5468 return ESR;
5469
5470 switch (ESR) {
5471 case ESR_Break:
5472 llvm_unreachable("Should have been converted to Succeeded");
5473 case ESR_Succeeded:
5474 case ESR_Continue:
5475 case ESR_Failed:
5476 case ESR_Returned:
5477 return ESR;
5478 case ESR_CaseNotFound:
5479 // This can only happen if the switch case is nested within a statement
5480 // expression. We have no intention of supporting that.
5481 Info.FFDiag(Found->getBeginLoc(),
5482 diag::note_constexpr_stmt_expr_unsupported);
5483 return ESR_Failed;
5484 }
5485 llvm_unreachable("Invalid EvalStmtResult!");
5486}
5487
5488static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5489 // An expression E is a core constant expression unless the evaluation of E
5490 // would evaluate one of the following: [C++23] - a control flow that passes
5491 // through a declaration of a variable with static or thread storage duration
5492 // unless that variable is usable in constant expressions.
5493 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5494 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5495 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5496 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5497 return false;
5498 }
5499 return true;
5500}
5501
5502// Evaluate a statement.
5503static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5504 const Stmt *S, const SwitchCase *Case) {
5505 if (!Info.nextStep(S))
5506 return ESR_Failed;
5507
5508 // If we're hunting down a 'case' or 'default' label, recurse through
5509 // substatements until we hit the label.
5510 if (Case) {
5511 switch (S->getStmtClass()) {
5512 case Stmt::CompoundStmtClass:
5513 // FIXME: Precompute which substatement of a compound statement we
5514 // would jump to, and go straight there rather than performing a
5515 // linear scan each time.
5516 case Stmt::LabelStmtClass:
5517 case Stmt::AttributedStmtClass:
5518 case Stmt::DoStmtClass:
5519 break;
5520
5521 case Stmt::CaseStmtClass:
5522 case Stmt::DefaultStmtClass:
5523 if (Case == S)
5524 Case = nullptr;
5525 break;
5526
5527 case Stmt::IfStmtClass: {
5528 // FIXME: Precompute which side of an 'if' we would jump to, and go
5529 // straight there rather than scanning both sides.
5530 const IfStmt *IS = cast<IfStmt>(S);
5531
5532 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5533 // preceded by our switch label.
5534 BlockScopeRAII Scope(Info);
5535
5536 // Step into the init statement in case it brings an (uninitialized)
5537 // variable into scope.
5538 if (const Stmt *Init = IS->getInit()) {
5539 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5540 if (ESR != ESR_CaseNotFound) {
5541 assert(ESR != ESR_Succeeded);
5542 return ESR;
5543 }
5544 }
5545
5546 // Condition variable must be initialized if it exists.
5547 // FIXME: We can skip evaluating the body if there's a condition
5548 // variable, as there can't be any case labels within it.
5549 // (The same is true for 'for' statements.)
5550
5551 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5552 if (ESR == ESR_Failed)
5553 return ESR;
5554 if (ESR != ESR_CaseNotFound)
5555 return Scope.destroy() ? ESR : ESR_Failed;
5556 if (!IS->getElse())
5557 return ESR_CaseNotFound;
5558
5559 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5560 if (ESR == ESR_Failed)
5561 return ESR;
5562 if (ESR != ESR_CaseNotFound)
5563 return Scope.destroy() ? ESR : ESR_Failed;
5564 return ESR_CaseNotFound;
5565 }
5566
5567 case Stmt::WhileStmtClass: {
5568 EvalStmtResult ESR =
5569 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5570 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5571 return ESR;
5572 if (ESR != ESR_Continue)
5573 return ESR;
5574 break;
5575 }
5576
5577 case Stmt::ForStmtClass: {
5578 const ForStmt *FS = cast<ForStmt>(S);
5579 BlockScopeRAII Scope(Info);
5580
5581 // Step into the init statement in case it brings an (uninitialized)
5582 // variable into scope.
5583 if (const Stmt *Init = FS->getInit()) {
5584 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5585 if (ESR != ESR_CaseNotFound) {
5586 assert(ESR != ESR_Succeeded);
5587 return ESR;
5588 }
5589 }
5590
5591 EvalStmtResult ESR =
5592 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5593 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5594 return ESR;
5595 if (ESR != ESR_Continue)
5596 return ESR;
5597 if (const auto *Inc = FS->getInc()) {
5598 if (Inc->isValueDependent()) {
5599 if (!EvaluateDependentExpr(Inc, Info))
5600 return ESR_Failed;
5601 } else {
5602 FullExpressionRAII IncScope(Info);
5603 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5604 return ESR_Failed;
5605 }
5606 }
5607 break;
5608 }
5609
5610 case Stmt::DeclStmtClass: {
5611 // Start the lifetime of any uninitialized variables we encounter. They
5612 // might be used by the selected branch of the switch.
5613 const DeclStmt *DS = cast<DeclStmt>(S);
5614 for (const auto *D : DS->decls()) {
5615 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5616 if (!CheckLocalVariableDeclaration(Info, VD))
5617 return ESR_Failed;
5618 if (VD->hasLocalStorage() && !VD->getInit())
5619 if (!EvaluateVarDecl(Info, VD))
5620 return ESR_Failed;
5621 // FIXME: If the variable has initialization that can't be jumped
5622 // over, bail out of any immediately-surrounding compound-statement
5623 // too. There can't be any case labels here.
5624 }
5625 }
5626 return ESR_CaseNotFound;
5627 }
5628
5629 default:
5630 return ESR_CaseNotFound;
5631 }
5632 }
5633
5634 switch (S->getStmtClass()) {
5635 default:
5636 if (const Expr *E = dyn_cast<Expr>(S)) {
5637 if (E->isValueDependent()) {
5638 if (!EvaluateDependentExpr(E, Info))
5639 return ESR_Failed;
5640 } else {
5641 // Don't bother evaluating beyond an expression-statement which couldn't
5642 // be evaluated.
5643 // FIXME: Do we need the FullExpressionRAII object here?
5644 // VisitExprWithCleanups should create one when necessary.
5645 FullExpressionRAII Scope(Info);
5646 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5647 return ESR_Failed;
5648 }
5649 return ESR_Succeeded;
5650 }
5651
5652 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5653 return ESR_Failed;
5654
5655 case Stmt::NullStmtClass:
5656 return ESR_Succeeded;
5657
5658 case Stmt::DeclStmtClass: {
5659 const DeclStmt *DS = cast<DeclStmt>(S);
5660 for (const auto *D : DS->decls()) {
5661 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5662 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5663 return ESR_Failed;
5664 // Each declaration initialization is its own full-expression.
5665 FullExpressionRAII Scope(Info);
5666 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5667 !Info.noteFailure())
5668 return ESR_Failed;
5669 if (!Scope.destroy())
5670 return ESR_Failed;
5671 }
5672 return ESR_Succeeded;
5673 }
5674
5675 case Stmt::ReturnStmtClass: {
5676 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5677 FullExpressionRAII Scope(Info);
5678 if (RetExpr && RetExpr->isValueDependent()) {
5679 EvaluateDependentExpr(RetExpr, Info);
5680 // We know we returned, but we don't know what the value is.
5681 return ESR_Failed;
5682 }
5683 if (RetExpr &&
5684 !(Result.Slot
5685 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5686 : Evaluate(Result.Value, Info, RetExpr)))
5687 return ESR_Failed;
5688 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5689 }
5690
5691 case Stmt::CompoundStmtClass: {
5692 BlockScopeRAII Scope(Info);
5693
5694 const CompoundStmt *CS = cast<CompoundStmt>(S);
5695 for (const auto *BI : CS->body()) {
5696 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5697 if (ESR == ESR_Succeeded)
5698 Case = nullptr;
5699 else if (ESR != ESR_CaseNotFound) {
5700 if (ESR != ESR_Failed && !Scope.destroy())
5701 return ESR_Failed;
5702 return ESR;
5703 }
5704 }
5705 if (Case)
5706 return ESR_CaseNotFound;
5707 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5708 }
5709
5710 case Stmt::IfStmtClass: {
5711 const IfStmt *IS = cast<IfStmt>(S);
5712
5713 // Evaluate the condition, as either a var decl or as an expression.
5714 BlockScopeRAII Scope(Info);
5715 if (const Stmt *Init = IS->getInit()) {
5716 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5717 if (ESR != ESR_Succeeded) {
5718 if (ESR != ESR_Failed && !Scope.destroy())
5719 return ESR_Failed;
5720 return ESR;
5721 }
5722 }
5723 bool Cond;
5724 if (IS->isConsteval()) {
5726 // If we are not in a constant context, if consteval should not evaluate
5727 // to true.
5728 if (!Info.InConstantContext)
5729 Cond = !Cond;
5730 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5731 Cond))
5732 return ESR_Failed;
5733
5734 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5735 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5736 if (ESR != ESR_Succeeded) {
5737 if (ESR != ESR_Failed && !Scope.destroy())
5738 return ESR_Failed;
5739 return ESR;
5740 }
5741 }
5742 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5743 }
5744
5745 case Stmt::WhileStmtClass: {
5746 const WhileStmt *WS = cast<WhileStmt>(S);
5747 while (true) {
5748 BlockScopeRAII Scope(Info);
5749 bool Continue;
5750 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5751 Continue))
5752 return ESR_Failed;
5753 if (!Continue)
5754 break;
5755
5756 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5757 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
5758 return ESR;
5759
5760 if (ESR != ESR_Continue) {
5761 if (ESR != ESR_Failed && !Scope.destroy())
5762 return ESR_Failed;
5763 return ESR;
5764 }
5765 if (!Scope.destroy())
5766 return ESR_Failed;
5767 }
5768 return ESR_Succeeded;
5769 }
5770
5771 case Stmt::DoStmtClass: {
5772 const DoStmt *DS = cast<DoStmt>(S);
5773 bool Continue;
5774 do {
5775 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5776 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
5777 return ESR;
5778 if (ESR != ESR_Continue)
5779 return ESR;
5780 Case = nullptr;
5781
5782 if (DS->getCond()->isValueDependent()) {
5783 EvaluateDependentExpr(DS->getCond(), Info);
5784 // Bailout as we don't know whether to keep going or terminate the loop.
5785 return ESR_Failed;
5786 }
5787 FullExpressionRAII CondScope(Info);
5788 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5789 !CondScope.destroy())
5790 return ESR_Failed;
5791 } while (Continue);
5792 return ESR_Succeeded;
5793 }
5794
5795 case Stmt::ForStmtClass: {
5796 const ForStmt *FS = cast<ForStmt>(S);
5797 BlockScopeRAII ForScope(Info);
5798 if (FS->getInit()) {
5799 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5800 if (ESR != ESR_Succeeded) {
5801 if (ESR != ESR_Failed && !ForScope.destroy())
5802 return ESR_Failed;
5803 return ESR;
5804 }
5805 }
5806 while (true) {
5807 BlockScopeRAII IterScope(Info);
5808 bool Continue = true;
5809 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5810 FS->getCond(), Continue))
5811 return ESR_Failed;
5812
5813 if (!Continue) {
5814 if (!IterScope.destroy())
5815 return ESR_Failed;
5816 break;
5817 }
5818
5819 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5820 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
5821 return ESR;
5822 if (ESR != ESR_Continue) {
5823 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5824 return ESR_Failed;
5825 return ESR;
5826 }
5827
5828 if (const auto *Inc = FS->getInc()) {
5829 if (Inc->isValueDependent()) {
5830 if (!EvaluateDependentExpr(Inc, Info))
5831 return ESR_Failed;
5832 } else {
5833 FullExpressionRAII IncScope(Info);
5834 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5835 return ESR_Failed;
5836 }
5837 }
5838
5839 if (!IterScope.destroy())
5840 return ESR_Failed;
5841 }
5842 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5843 }
5844
5845 case Stmt::CXXForRangeStmtClass: {
5847 BlockScopeRAII Scope(Info);
5848
5849 // Evaluate the init-statement if present.
5850 if (FS->getInit()) {
5851 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5852 if (ESR != ESR_Succeeded) {
5853 if (ESR != ESR_Failed && !Scope.destroy())
5854 return ESR_Failed;
5855 return ESR;
5856 }
5857 }
5858
5859 // Initialize the __range variable.
5860 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5861 if (ESR != ESR_Succeeded) {
5862 if (ESR != ESR_Failed && !Scope.destroy())
5863 return ESR_Failed;
5864 return ESR;
5865 }
5866
5867 // In error-recovery cases it's possible to get here even if we failed to
5868 // synthesize the __begin and __end variables.
5869 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5870 return ESR_Failed;
5871
5872 // Create the __begin and __end iterators.
5873 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5874 if (ESR != ESR_Succeeded) {
5875 if (ESR != ESR_Failed && !Scope.destroy())
5876 return ESR_Failed;
5877 return ESR;
5878 }
5879 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5880 if (ESR != ESR_Succeeded) {
5881 if (ESR != ESR_Failed && !Scope.destroy())
5882 return ESR_Failed;
5883 return ESR;
5884 }
5885
5886 while (true) {
5887 // Condition: __begin != __end.
5888 {
5889 if (FS->getCond()->isValueDependent()) {
5890 EvaluateDependentExpr(FS->getCond(), Info);
5891 // We don't know whether to keep going or terminate the loop.
5892 return ESR_Failed;
5893 }
5894 bool Continue = true;
5895 FullExpressionRAII CondExpr(Info);
5896 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5897 return ESR_Failed;
5898 if (!Continue)
5899 break;
5900 }
5901
5902 // User's variable declaration, initialized by *__begin.
5903 BlockScopeRAII InnerScope(Info);
5904 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5905 if (ESR != ESR_Succeeded) {
5906 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5907 return ESR_Failed;
5908 return ESR;
5909 }
5910
5911 // Loop body.
5912 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5913 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
5914 return ESR;
5915 if (ESR != ESR_Continue) {
5916 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5917 return ESR_Failed;
5918 return ESR;
5919 }
5920 if (FS->getInc()->isValueDependent()) {
5921 if (!EvaluateDependentExpr(FS->getInc(), Info))
5922 return ESR_Failed;
5923 } else {
5924 // Increment: ++__begin
5925 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5926 return ESR_Failed;
5927 }
5928
5929 if (!InnerScope.destroy())
5930 return ESR_Failed;
5931 }
5932
5933 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5934 }
5935
5936 case Stmt::SwitchStmtClass:
5937 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5938
5939 case Stmt::ContinueStmtClass:
5940 case Stmt::BreakStmtClass: {
5941 auto *B = cast<LoopControlStmt>(S);
5942 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
5943 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
5944 }
5945
5946 case Stmt::LabelStmtClass:
5947 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5948
5949 case Stmt::AttributedStmtClass: {
5950 const auto *AS = cast<AttributedStmt>(S);
5951 const auto *SS = AS->getSubStmt();
5952 MSConstexprContextRAII ConstexprContext(
5953 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5954 isa<ReturnStmt>(SS));
5955
5956 auto LO = Info.getASTContext().getLangOpts();
5957 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5958 for (auto *Attr : AS->getAttrs()) {
5959 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5960 if (!AA)
5961 continue;
5962
5963 auto *Assumption = AA->getAssumption();
5964 if (Assumption->isValueDependent())
5965 return ESR_Failed;
5966
5967 if (Assumption->HasSideEffects(Info.getASTContext()))
5968 continue;
5969
5970 bool Value;
5971 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5972 return ESR_Failed;
5973 if (!Value) {
5974 Info.CCEDiag(Assumption->getExprLoc(),
5975 diag::note_constexpr_assumption_failed);
5976 return ESR_Failed;
5977 }
5978 }
5979 }
5980
5981 return EvaluateStmt(Result, Info, SS, Case);
5982 }
5983
5984 case Stmt::CaseStmtClass:
5985 case Stmt::DefaultStmtClass:
5986 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5987 case Stmt::CXXTryStmtClass:
5988 // Evaluate try blocks by evaluating all sub statements.
5989 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5990 }
5991}
5992
5993/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5994/// default constructor. If so, we'll fold it whether or not it's marked as
5995/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5996/// so we need special handling.
5997static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5998 const CXXConstructorDecl *CD,
5999 bool IsValueInitialization) {
6000 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6001 return false;
6002
6003 // Value-initialization does not call a trivial default constructor, so such a
6004 // call is a core constant expression whether or not the constructor is
6005 // constexpr.
6006 if (!CD->isConstexpr() && !IsValueInitialization) {
6007 if (Info.getLangOpts().CPlusPlus11) {
6008 // FIXME: If DiagDecl is an implicitly-declared special member function,
6009 // we should be much more explicit about why it's not constexpr.
6010 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6011 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6012 Info.Note(CD->getLocation(), diag::note_declared_at);
6013 } else {
6014 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6015 }
6016 }
6017 return true;
6018}
6019
6020/// CheckConstexprFunction - Check that a function can be called in a constant
6021/// expression.
6022static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6024 const FunctionDecl *Definition,
6025 const Stmt *Body) {
6026 // Potential constant expressions can contain calls to declared, but not yet
6027 // defined, constexpr functions.
6028 if (Info.checkingPotentialConstantExpression() && !Definition &&
6029 Declaration->isConstexpr())
6030 return false;
6031
6032 // Bail out if the function declaration itself is invalid. We will
6033 // have produced a relevant diagnostic while parsing it, so just
6034 // note the problematic sub-expression.
6035 if (Declaration->isInvalidDecl()) {
6036 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6037 return false;
6038 }
6039
6040 // DR1872: An instantiated virtual constexpr function can't be called in a
6041 // constant expression (prior to C++20). We can still constant-fold such a
6042 // call.
6043 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6044 cast<CXXMethodDecl>(Declaration)->isVirtual())
6045 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6046
6047 if (Definition && Definition->isInvalidDecl()) {
6048 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6049 return false;
6050 }
6051
6052 // Can we evaluate this function call?
6053 if (Definition && Body &&
6054 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6055 Definition->hasAttr<MSConstexprAttr>())))
6056 return true;
6057
6058 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6059 // Special note for the assert() macro, as the normal error message falsely
6060 // implies we cannot use an assertion during constant evaluation.
6061 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6062 // FIXME: Instead of checking for an implementation-defined function,
6063 // check and evaluate the assert() macro.
6064 StringRef Name = DiagDecl->getName();
6065 bool AssertFailed =
6066 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6067 if (AssertFailed) {
6068 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6069 return false;
6070 }
6071 }
6072
6073 if (Info.getLangOpts().CPlusPlus11) {
6074 // If this function is not constexpr because it is an inherited
6075 // non-constexpr constructor, diagnose that directly.
6076 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6077 if (CD && CD->isInheritingConstructor()) {
6078 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6079 if (!Inherited->isConstexpr())
6080 DiagDecl = CD = Inherited;
6081 }
6082
6083 // FIXME: If DiagDecl is an implicitly-declared special member function
6084 // or an inheriting constructor, we should be much more explicit about why
6085 // it's not constexpr.
6086 if (CD && CD->isInheritingConstructor())
6087 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6088 << CD->getInheritedConstructor().getConstructor()->getParent();
6089 else
6090 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6091 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6092 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6093 } else {
6094 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6095 }
6096 return false;
6097}
6098
6099namespace {
6100struct CheckDynamicTypeHandler {
6102 typedef bool result_type;
6103 bool failed() { return false; }
6104 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6105 bool found(APSInt &Value, QualType SubobjType) { return true; }
6106 bool found(APFloat &Value, QualType SubobjType) { return true; }
6107};
6108} // end anonymous namespace
6109
6110/// Check that we can access the notional vptr of an object / determine its
6111/// dynamic type.
6112static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6113 AccessKinds AK, bool Polymorphic) {
6114 if (This.Designator.Invalid)
6115 return false;
6116
6117 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6118
6119 if (!Obj)
6120 return false;
6121
6122 if (!Obj.Value) {
6123 // The object is not usable in constant expressions, so we can't inspect
6124 // its value to see if it's in-lifetime or what the active union members
6125 // are. We can still check for a one-past-the-end lvalue.
6126 if (This.Designator.isOnePastTheEnd() ||
6127 This.Designator.isMostDerivedAnUnsizedArray()) {
6128 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6129 ? diag::note_constexpr_access_past_end
6130 : diag::note_constexpr_access_unsized_array)
6131 << AK;
6132 return false;
6133 } else if (Polymorphic) {
6134 // Conservatively refuse to perform a polymorphic operation if we would
6135 // not be able to read a notional 'vptr' value.
6136 if (!Info.checkingPotentialConstantExpression() ||
6137 !This.AllowConstexprUnknown) {
6138 APValue Val;
6139 This.moveInto(Val);
6140 QualType StarThisType =
6141 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6142 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6143 << AK << Val.getAsString(Info.Ctx, StarThisType);
6144 }
6145 return false;
6146 }
6147 return true;
6148 }
6149
6150 CheckDynamicTypeHandler Handler{AK};
6151 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6152}
6153
6154/// Check that the pointee of the 'this' pointer in a member function call is
6155/// either within its lifetime or in its period of construction or destruction.
6156static bool
6158 const LValue &This,
6159 const CXXMethodDecl *NamedMember) {
6160 return checkDynamicType(
6161 Info, E, This,
6162 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6163}
6164
6166 /// The dynamic class type of the object.
6168 /// The corresponding path length in the lvalue.
6169 unsigned PathLength;
6170};
6171
6172static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6173 unsigned PathLength) {
6174 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6175 Designator.Entries.size() && "invalid path length");
6176 return (PathLength == Designator.MostDerivedPathLength)
6177 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6178 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6179}
6180
6181/// Determine the dynamic type of an object.
6182static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6183 const Expr *E,
6184 LValue &This,
6185 AccessKinds AK) {
6186 // If we don't have an lvalue denoting an object of class type, there is no
6187 // meaningful dynamic type. (We consider objects of non-class type to have no
6188 // dynamic type.)
6189 if (!checkDynamicType(Info, E, This, AK,
6190 AK != AK_TypeId || This.AllowConstexprUnknown))
6191 return std::nullopt;
6192
6193 if (This.Designator.Invalid)
6194 return std::nullopt;
6195
6196 // Refuse to compute a dynamic type in the presence of virtual bases. This
6197 // shouldn't happen other than in constant-folding situations, since literal
6198 // types can't have virtual bases.
6199 //
6200 // Note that consumers of DynamicType assume that the type has no virtual
6201 // bases, and will need modifications if this restriction is relaxed.
6202 const CXXRecordDecl *Class =
6203 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6204 if (!Class || Class->getNumVBases()) {
6205 Info.FFDiag(E);
6206 return std::nullopt;
6207 }
6208
6209 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6210 // binary search here instead. But the overwhelmingly common case is that
6211 // we're not in the middle of a constructor, so it probably doesn't matter
6212 // in practice.
6213 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6214 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6215 PathLength <= Path.size(); ++PathLength) {
6216 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6217 Path.slice(0, PathLength))) {
6218 case ConstructionPhase::Bases:
6219 case ConstructionPhase::DestroyingBases:
6220 // We're constructing or destroying a base class. This is not the dynamic
6221 // type.
6222 break;
6223
6224 case ConstructionPhase::None:
6225 case ConstructionPhase::AfterBases:
6226 case ConstructionPhase::AfterFields:
6227 case ConstructionPhase::Destroying:
6228 // We've finished constructing the base classes and not yet started
6229 // destroying them again, so this is the dynamic type.
6230 return DynamicType{getBaseClassType(This.Designator, PathLength),
6231 PathLength};
6232 }
6233 }
6234
6235 // CWG issue 1517: we're constructing a base class of the object described by
6236 // 'This', so that object has not yet begun its period of construction and
6237 // any polymorphic operation on it results in undefined behavior.
6238 Info.FFDiag(E);
6239 return std::nullopt;
6240}
6241
6242/// Perform virtual dispatch.
6244 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6245 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6246 std::optional<DynamicType> DynType = ComputeDynamicType(
6247 Info, E, This,
6249 if (!DynType)
6250 return nullptr;
6251
6252 // Find the final overrider. It must be declared in one of the classes on the
6253 // path from the dynamic type to the static type.
6254 // FIXME: If we ever allow literal types to have virtual base classes, that
6255 // won't be true.
6256 const CXXMethodDecl *Callee = Found;
6257 unsigned PathLength = DynType->PathLength;
6258 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6259 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6260 const CXXMethodDecl *Overrider =
6261 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6262 if (Overrider) {
6263 Callee = Overrider;
6264 break;
6265 }
6266 }
6267
6268 // C++2a [class.abstract]p6:
6269 // the effect of making a virtual call to a pure virtual function [...] is
6270 // undefined
6271 if (Callee->isPureVirtual()) {
6272 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6273 Info.Note(Callee->getLocation(), diag::note_declared_at);
6274 return nullptr;
6275 }
6276
6277 // If necessary, walk the rest of the path to determine the sequence of
6278 // covariant adjustment steps to apply.
6279 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6280 Found->getReturnType())) {
6281 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6282 for (unsigned CovariantPathLength = PathLength + 1;
6283 CovariantPathLength != This.Designator.Entries.size();
6284 ++CovariantPathLength) {
6285 const CXXRecordDecl *NextClass =
6286 getBaseClassType(This.Designator, CovariantPathLength);
6287 const CXXMethodDecl *Next =
6288 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6289 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6290 Next->getReturnType(), CovariantAdjustmentPath.back()))
6291 CovariantAdjustmentPath.push_back(Next->getReturnType());
6292 }
6293 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6294 CovariantAdjustmentPath.back()))
6295 CovariantAdjustmentPath.push_back(Found->getReturnType());
6296 }
6297
6298 // Perform 'this' adjustment.
6299 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6300 return nullptr;
6301
6302 return Callee;
6303}
6304
6305/// Perform the adjustment from a value returned by a virtual function to
6306/// a value of the statically expected type, which may be a pointer or
6307/// reference to a base class of the returned type.
6308static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6309 APValue &Result,
6310 ArrayRef<QualType> Path) {
6311 assert(Result.isLValue() &&
6312 "unexpected kind of APValue for covariant return");
6313 if (Result.isNullPointer())
6314 return true;
6315
6316 LValue LVal;
6317 LVal.setFrom(Info.Ctx, Result);
6318
6319 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6320 for (unsigned I = 1; I != Path.size(); ++I) {
6321 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6322 assert(OldClass && NewClass && "unexpected kind of covariant return");
6323 if (OldClass != NewClass &&
6324 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6325 return false;
6326 OldClass = NewClass;
6327 }
6328
6329 LVal.moveInto(Result);
6330 return true;
6331}
6332
6333/// Determine whether \p Base, which is known to be a direct base class of
6334/// \p Derived, is a public base class.
6335static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6336 const CXXRecordDecl *Base) {
6337 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6338 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6339 if (BaseClass && declaresSameEntity(BaseClass, Base))
6340 return BaseSpec.getAccessSpecifier() == AS_public;
6341 }
6342 llvm_unreachable("Base is not a direct base of Derived");
6343}
6344
6345/// Apply the given dynamic cast operation on the provided lvalue.
6346///
6347/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6348/// to find a suitable target subobject.
6349static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6350 LValue &Ptr) {
6351 // We can't do anything with a non-symbolic pointer value.
6352 SubobjectDesignator &D = Ptr.Designator;
6353 if (D.Invalid)
6354 return false;
6355
6356 // C++ [expr.dynamic.cast]p6:
6357 // If v is a null pointer value, the result is a null pointer value.
6358 if (Ptr.isNullPointer() && !E->isGLValue())
6359 return true;
6360
6361 // For all the other cases, we need the pointer to point to an object within
6362 // its lifetime / period of construction / destruction, and we need to know
6363 // its dynamic type.
6364 std::optional<DynamicType> DynType =
6365 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6366 if (!DynType)
6367 return false;
6368
6369 // C++ [expr.dynamic.cast]p7:
6370 // If T is "pointer to cv void", then the result is a pointer to the most
6371 // derived object
6372 if (E->getType()->isVoidPointerType())
6373 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6374
6376 assert(C && "dynamic_cast target is not void pointer nor class");
6377 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6378
6379 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6380 // C++ [expr.dynamic.cast]p9:
6381 if (!E->isGLValue()) {
6382 // The value of a failed cast to pointer type is the null pointer value
6383 // of the required result type.
6384 Ptr.setNull(Info.Ctx, E->getType());
6385 return true;
6386 }
6387
6388 // A failed cast to reference type throws [...] std::bad_cast.
6389 unsigned DiagKind;
6390 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6391 DynType->Type->isDerivedFrom(C)))
6392 DiagKind = 0;
6393 else if (!Paths || Paths->begin() == Paths->end())
6394 DiagKind = 1;
6395 else if (Paths->isAmbiguous(CQT))
6396 DiagKind = 2;
6397 else {
6398 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6399 DiagKind = 3;
6400 }
6401 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6402 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6403 << Info.Ctx.getCanonicalTagType(DynType->Type)
6404 << E->getType().getUnqualifiedType();
6405 return false;
6406 };
6407
6408 // Runtime check, phase 1:
6409 // Walk from the base subobject towards the derived object looking for the
6410 // target type.
6411 for (int PathLength = Ptr.Designator.Entries.size();
6412 PathLength >= (int)DynType->PathLength; --PathLength) {
6413 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6414 if (declaresSameEntity(Class, C))
6415 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6416 // We can only walk across public inheritance edges.
6417 if (PathLength > (int)DynType->PathLength &&
6418 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6419 Class))
6420 return RuntimeCheckFailed(nullptr);
6421 }
6422
6423 // Runtime check, phase 2:
6424 // Search the dynamic type for an unambiguous public base of type C.
6425 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6426 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6427 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6428 Paths.front().Access == AS_public) {
6429 // Downcast to the dynamic type...
6430 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6431 return false;
6432 // ... then upcast to the chosen base class subobject.
6433 for (CXXBasePathElement &Elem : Paths.front())
6434 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6435 return false;
6436 return true;
6437 }
6438
6439 // Otherwise, the runtime check fails.
6440 return RuntimeCheckFailed(&Paths);
6441}
6442
6443namespace {
6444struct StartLifetimeOfUnionMemberHandler {
6445 EvalInfo &Info;
6446 const Expr *LHSExpr;
6447 const FieldDecl *Field;
6448 bool DuringInit;
6449 bool Failed = false;
6450 static const AccessKinds AccessKind = AK_Assign;
6451
6452 typedef bool result_type;
6453 bool failed() { return Failed; }
6454 bool found(APValue &Subobj, QualType SubobjType) {
6455 // We are supposed to perform no initialization but begin the lifetime of
6456 // the object. We interpret that as meaning to do what default
6457 // initialization of the object would do if all constructors involved were
6458 // trivial:
6459 // * All base, non-variant member, and array element subobjects' lifetimes
6460 // begin
6461 // * No variant members' lifetimes begin
6462 // * All scalar subobjects whose lifetimes begin have indeterminate values
6463 assert(SubobjType->isUnionType());
6464 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6465 // This union member is already active. If it's also in-lifetime, there's
6466 // nothing to do.
6467 if (Subobj.getUnionValue().hasValue())
6468 return true;
6469 } else if (DuringInit) {
6470 // We're currently in the process of initializing a different union
6471 // member. If we carried on, that initialization would attempt to
6472 // store to an inactive union member, resulting in undefined behavior.
6473 Info.FFDiag(LHSExpr,
6474 diag::note_constexpr_union_member_change_during_init);
6475 return false;
6476 }
6478 Failed = !handleDefaultInitValue(Field->getType(), Result);
6479 Subobj.setUnion(Field, Result);
6480 return true;
6481 }
6482 bool found(APSInt &Value, QualType SubobjType) {
6483 llvm_unreachable("wrong value kind for union object");
6484 }
6485 bool found(APFloat &Value, QualType SubobjType) {
6486 llvm_unreachable("wrong value kind for union object");
6487 }
6488};
6489} // end anonymous namespace
6490
6491const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6492
6493/// Handle a builtin simple-assignment or a call to a trivial assignment
6494/// operator whose left-hand side might involve a union member access. If it
6495/// does, implicitly start the lifetime of any accessed union elements per
6496/// C++20 [class.union]5.
6497static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6498 const Expr *LHSExpr,
6499 const LValue &LHS) {
6500 if (LHS.InvalidBase || LHS.Designator.Invalid)
6501 return false;
6502
6504 // C++ [class.union]p5:
6505 // define the set S(E) of subexpressions of E as follows:
6506 unsigned PathLength = LHS.Designator.Entries.size();
6507 for (const Expr *E = LHSExpr; E != nullptr;) {
6508 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6509 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6510 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6511 // Note that we can't implicitly start the lifetime of a reference,
6512 // so we don't need to proceed any further if we reach one.
6513 if (!FD || FD->getType()->isReferenceType())
6514 break;
6515
6516 // ... and also contains A.B if B names a union member ...
6517 if (FD->getParent()->isUnion()) {
6518 // ... of a non-class, non-array type, or of a class type with a
6519 // trivial default constructor that is not deleted, or an array of
6520 // such types.
6521 auto *RD =
6522 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6523 if (!RD || RD->hasTrivialDefaultConstructor())
6524 UnionPathLengths.push_back({PathLength - 1, FD});
6525 }
6526
6527 E = ME->getBase();
6528 --PathLength;
6529 assert(declaresSameEntity(FD,
6530 LHS.Designator.Entries[PathLength]
6531 .getAsBaseOrMember().getPointer()));
6532
6533 // -- If E is of the form A[B] and is interpreted as a built-in array
6534 // subscripting operator, S(E) is [S(the array operand, if any)].
6535 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6536 // Step over an ArrayToPointerDecay implicit cast.
6537 auto *Base = ASE->getBase()->IgnoreImplicit();
6538 if (!Base->getType()->isArrayType())
6539 break;
6540
6541 E = Base;
6542 --PathLength;
6543
6544 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6545 // Step over a derived-to-base conversion.
6546 E = ICE->getSubExpr();
6547 if (ICE->getCastKind() == CK_NoOp)
6548 continue;
6549 if (ICE->getCastKind() != CK_DerivedToBase &&
6550 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6551 break;
6552 // Walk path backwards as we walk up from the base to the derived class.
6553 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6554 if (Elt->isVirtual()) {
6555 // A class with virtual base classes never has a trivial default
6556 // constructor, so S(E) is empty in this case.
6557 E = nullptr;
6558 break;
6559 }
6560
6561 --PathLength;
6562 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6563 LHS.Designator.Entries[PathLength]
6564 .getAsBaseOrMember().getPointer()));
6565 }
6566
6567 // -- Otherwise, S(E) is empty.
6568 } else {
6569 break;
6570 }
6571 }
6572
6573 // Common case: no unions' lifetimes are started.
6574 if (UnionPathLengths.empty())
6575 return true;
6576
6577 // if modification of X [would access an inactive union member], an object
6578 // of the type of X is implicitly created
6579 CompleteObject Obj =
6580 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6581 if (!Obj)
6582 return false;
6583 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6584 llvm::reverse(UnionPathLengths)) {
6585 // Form a designator for the union object.
6586 SubobjectDesignator D = LHS.Designator;
6587 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6588
6589 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6590 ConstructionPhase::AfterBases;
6591 StartLifetimeOfUnionMemberHandler StartLifetime{
6592 Info, LHSExpr, LengthAndField.second, DuringInit};
6593 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6594 return false;
6595 }
6596
6597 return true;
6598}
6599
6600static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6601 CallRef Call, EvalInfo &Info, bool NonNull = false,
6602 APValue **EvaluatedArg = nullptr) {
6603 LValue LV;
6604 // Create the parameter slot and register its destruction. For a vararg
6605 // argument, create a temporary.
6606 // FIXME: For calling conventions that destroy parameters in the callee,
6607 // should we consider performing destruction when the function returns
6608 // instead?
6609 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6610 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6611 ScopeKind::Call, LV);
6612 if (!EvaluateInPlace(V, Info, LV, Arg))
6613 return false;
6614
6615 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6616 // undefined behavior, so is non-constant.
6617 if (NonNull && V.isLValue() && V.isNullPointer()) {
6618 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6619 return false;
6620 }
6621
6622 if (EvaluatedArg)
6623 *EvaluatedArg = &V;
6624
6625 return true;
6626}
6627
6628/// Evaluate the arguments to a function call.
6629static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6630 EvalInfo &Info, const FunctionDecl *Callee,
6631 bool RightToLeft = false,
6632 LValue *ObjectArg = nullptr) {
6633 bool Success = true;
6634 llvm::SmallBitVector ForbiddenNullArgs;
6635 if (Callee->hasAttr<NonNullAttr>()) {
6636 ForbiddenNullArgs.resize(Args.size());
6637 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6638 if (!Attr->args_size()) {
6639 ForbiddenNullArgs.set();
6640 break;
6641 } else
6642 for (auto Idx : Attr->args()) {
6643 unsigned ASTIdx = Idx.getASTIndex();
6644 if (ASTIdx >= Args.size())
6645 continue;
6646 ForbiddenNullArgs[ASTIdx] = true;
6647 }
6648 }
6649 }
6650 for (unsigned I = 0; I < Args.size(); I++) {
6651 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6652 const ParmVarDecl *PVD =
6653 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6654 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6655 APValue *That = nullptr;
6656 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6657 // If we're checking for a potential constant expression, evaluate all
6658 // initializers even if some of them fail.
6659 if (!Info.noteFailure())
6660 return false;
6661 Success = false;
6662 }
6663 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6664 ObjectArg->setFrom(Info.Ctx, *That);
6665 }
6666 return Success;
6667}
6668
6669/// Perform a trivial copy from Param, which is the parameter of a copy or move
6670/// constructor or assignment operator.
6671static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6672 const Expr *E, APValue &Result,
6673 bool CopyObjectRepresentation) {
6674 // Find the reference argument.
6675 CallStackFrame *Frame = Info.CurrentCall;
6676 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6677 if (!RefValue) {
6678 Info.FFDiag(E);
6679 return false;
6680 }
6681
6682 // Copy out the contents of the RHS object.
6683 LValue RefLValue;
6684 RefLValue.setFrom(Info.Ctx, *RefValue);
6686 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6687 CopyObjectRepresentation);
6688}
6689
6690/// Evaluate a function call.
6692 const FunctionDecl *Callee,
6693 const LValue *ObjectArg, const Expr *E,
6694 ArrayRef<const Expr *> Args, CallRef Call,
6695 const Stmt *Body, EvalInfo &Info,
6696 APValue &Result, const LValue *ResultSlot) {
6697 if (!Info.CheckCallLimit(CallLoc))
6698 return false;
6699
6700 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
6701
6702 // For a trivial copy or move assignment, perform an APValue copy. This is
6703 // essential for unions, where the operations performed by the assignment
6704 // operator cannot be represented as statements.
6705 //
6706 // Skip this for non-union classes with no fields; in that case, the defaulted
6707 // copy/move does not actually read the object.
6708 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6709 if (MD && MD->isDefaulted() &&
6710 (MD->getParent()->isUnion() ||
6711 (MD->isTrivial() &&
6713 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
6714 assert(ObjectArg &&
6716 APValue RHSValue;
6717 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6718 MD->getParent()->isUnion()))
6719 return false;
6720
6721 LValue Obj;
6722 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
6724 RHSValue))
6725 return false;
6726 ObjectArg->moveInto(Result);
6727 return true;
6728 } else if (MD && isLambdaCallOperator(MD)) {
6729 // We're in a lambda; determine the lambda capture field maps unless we're
6730 // just constexpr checking a lambda's call operator. constexpr checking is
6731 // done before the captures have been added to the closure object (unless
6732 // we're inferring constexpr-ness), so we don't have access to them in this
6733 // case. But since we don't need the captures to constexpr check, we can
6734 // just ignore them.
6735 if (!Info.checkingPotentialConstantExpression())
6736 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6737 Frame.LambdaThisCaptureField);
6738 }
6739
6740 StmtResult Ret = {Result, ResultSlot};
6741 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6742 if (ESR == ESR_Succeeded) {
6743 if (Callee->getReturnType()->isVoidType())
6744 return true;
6745 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6746 }
6747 return ESR == ESR_Returned;
6748}
6749
6750/// Evaluate a constructor call.
6751static bool HandleConstructorCall(const Expr *E, const LValue &This,
6752 CallRef Call,
6754 EvalInfo &Info, APValue &Result) {
6755 SourceLocation CallLoc = E->getExprLoc();
6756 if (!Info.CheckCallLimit(CallLoc))
6757 return false;
6758
6759 const CXXRecordDecl *RD = Definition->getParent();
6760 if (RD->getNumVBases()) {
6761 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6762 return false;
6763 }
6764
6765 EvalInfo::EvaluatingConstructorRAII EvalObj(
6766 Info,
6767 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6768 RD->getNumBases());
6769 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6770
6771 // FIXME: Creating an APValue just to hold a nonexistent return value is
6772 // wasteful.
6773 APValue RetVal;
6774 StmtResult Ret = {RetVal, nullptr};
6775
6776 // If it's a delegating constructor, delegate.
6777 if (Definition->isDelegatingConstructor()) {
6779 if ((*I)->getInit()->isValueDependent()) {
6780 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6781 return false;
6782 } else {
6783 FullExpressionRAII InitScope(Info);
6784 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6785 !InitScope.destroy())
6786 return false;
6787 }
6788 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6789 }
6790
6791 // For a trivial copy or move constructor, perform an APValue copy. This is
6792 // essential for unions (or classes with anonymous union members), where the
6793 // operations performed by the constructor cannot be represented by
6794 // ctor-initializers.
6795 //
6796 // Skip this for empty non-union classes; we should not perform an
6797 // lvalue-to-rvalue conversion on them because their copy constructor does not
6798 // actually read them.
6799 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6800 (Definition->getParent()->isUnion() ||
6801 (Definition->isTrivial() &&
6803 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6804 Definition->getParent()->isUnion());
6805 }
6806
6807 // Reserve space for the struct members.
6808 if (!Result.hasValue()) {
6809 if (!RD->isUnion())
6810 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6811 std::distance(RD->field_begin(), RD->field_end()));
6812 else
6813 // A union starts with no active member.
6814 Result = APValue((const FieldDecl*)nullptr);
6815 }
6816
6817 if (RD->isInvalidDecl()) return false;
6818 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6819
6820 // A scope for temporaries lifetime-extended by reference members.
6821 BlockScopeRAII LifetimeExtendedScope(Info);
6822
6823 bool Success = true;
6824 unsigned BasesSeen = 0;
6825#ifndef NDEBUG
6827#endif
6829 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6830 // We might be initializing the same field again if this is an indirect
6831 // field initialization.
6832 if (FieldIt == RD->field_end() ||
6833 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6834 assert(Indirect && "fields out of order?");
6835 return;
6836 }
6837
6838 // Default-initialize any fields with no explicit initializer.
6839 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6840 assert(FieldIt != RD->field_end() && "missing field?");
6841 if (!FieldIt->isUnnamedBitField())
6843 FieldIt->getType(),
6844 Result.getStructField(FieldIt->getFieldIndex()));
6845 }
6846 ++FieldIt;
6847 };
6848 for (const auto *I : Definition->inits()) {
6849 LValue Subobject = This;
6850 LValue SubobjectParent = This;
6851 APValue *Value = &Result;
6852
6853 // Determine the subobject to initialize.
6854 FieldDecl *FD = nullptr;
6855 if (I->isBaseInitializer()) {
6856 QualType BaseType(I->getBaseClass(), 0);
6857#ifndef NDEBUG
6858 // Non-virtual base classes are initialized in the order in the class
6859 // definition. We have already checked for virtual base classes.
6860 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6861 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6862 "base class initializers not in expected order");
6863 ++BaseIt;
6864#endif
6865 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6866 BaseType->getAsCXXRecordDecl(), &Layout))
6867 return false;
6868 Value = &Result.getStructBase(BasesSeen++);
6869 } else if ((FD = I->getMember())) {
6870 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6871 return false;
6872 if (RD->isUnion()) {
6873 Result = APValue(FD);
6874 Value = &Result.getUnionValue();
6875 } else {
6876 SkipToField(FD, false);
6877 Value = &Result.getStructField(FD->getFieldIndex());
6878 }
6879 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6880 // Walk the indirect field decl's chain to find the object to initialize,
6881 // and make sure we've initialized every step along it.
6882 auto IndirectFieldChain = IFD->chain();
6883 for (auto *C : IndirectFieldChain) {
6884 FD = cast<FieldDecl>(C);
6886 // Switch the union field if it differs. This happens if we had
6887 // preceding zero-initialization, and we're now initializing a union
6888 // subobject other than the first.
6889 // FIXME: In this case, the values of the other subobjects are
6890 // specified, since zero-initialization sets all padding bits to zero.
6891 if (!Value->hasValue() ||
6892 (Value->isUnion() &&
6893 !declaresSameEntity(Value->getUnionField(), FD))) {
6894 if (CD->isUnion())
6895 *Value = APValue(FD);
6896 else
6897 // FIXME: This immediately starts the lifetime of all members of
6898 // an anonymous struct. It would be preferable to strictly start
6899 // member lifetime in initialization order.
6901 *Value);
6902 }
6903 // Store Subobject as its parent before updating it for the last element
6904 // in the chain.
6905 if (C == IndirectFieldChain.back())
6906 SubobjectParent = Subobject;
6907 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6908 return false;
6909 if (CD->isUnion())
6910 Value = &Value->getUnionValue();
6911 else {
6912 if (C == IndirectFieldChain.front() && !RD->isUnion())
6913 SkipToField(FD, true);
6914 Value = &Value->getStructField(FD->getFieldIndex());
6915 }
6916 }
6917 } else {
6918 llvm_unreachable("unknown base initializer kind");
6919 }
6920
6921 // Need to override This for implicit field initializers as in this case
6922 // This refers to innermost anonymous struct/union containing initializer,
6923 // not to currently constructed class.
6924 const Expr *Init = I->getInit();
6925 if (Init->isValueDependent()) {
6926 if (!EvaluateDependentExpr(Init, Info))
6927 return false;
6928 } else {
6929 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6931 FullExpressionRAII InitScope(Info);
6932 if (FD && FD->getType()->isReferenceType() &&
6933 !FD->getType()->isFunctionReferenceType()) {
6934 LValue Result;
6935 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
6936 *Value)) {
6937 if (!Info.noteFailure())
6938 return false;
6939 Success = false;
6940 }
6941 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6942 (FD && FD->isBitField() &&
6943 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6944 // If we're checking for a potential constant expression, evaluate all
6945 // initializers even if some of them fail.
6946 if (!Info.noteFailure())
6947 return false;
6948 Success = false;
6949 }
6950 }
6951
6952 // This is the point at which the dynamic type of the object becomes this
6953 // class type.
6954 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6955 EvalObj.finishedConstructingBases();
6956 }
6957
6958 // Default-initialize any remaining fields.
6959 if (!RD->isUnion()) {
6960 for (; FieldIt != RD->field_end(); ++FieldIt) {
6961 if (!FieldIt->isUnnamedBitField())
6963 FieldIt->getType(),
6964 Result.getStructField(FieldIt->getFieldIndex()));
6965 }
6966 }
6967
6968 EvalObj.finishedConstructingFields();
6969
6970 return Success &&
6971 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6972 LifetimeExtendedScope.destroy();
6973}
6974
6975static bool HandleConstructorCall(const Expr *E, const LValue &This,
6978 EvalInfo &Info, APValue &Result) {
6979 CallScopeRAII CallScope(Info);
6980 CallRef Call = Info.CurrentCall->createCall(Definition);
6981 if (!EvaluateArgs(Args, Call, Info, Definition))
6982 return false;
6983
6984 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6985 CallScope.destroy();
6986}
6987
6988static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6989 const LValue &This, APValue &Value,
6990 QualType T) {
6991 // Objects can only be destroyed while they're within their lifetimes.
6992 // FIXME: We have no representation for whether an object of type nullptr_t
6993 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6994 // as indeterminate instead?
6995 if (Value.isAbsent() && !T->isNullPtrType()) {
6996 APValue Printable;
6997 This.moveInto(Printable);
6998 Info.FFDiag(CallRange.getBegin(),
6999 diag::note_constexpr_destroy_out_of_lifetime)
7000 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7001 return false;
7002 }
7003
7004 // Invent an expression for location purposes.
7005 // FIXME: We shouldn't need to do this.
7006 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7007
7008 // For arrays, destroy elements right-to-left.
7009 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7010 uint64_t Size = CAT->getZExtSize();
7011 QualType ElemT = CAT->getElementType();
7012
7013 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7014 return false;
7015
7016 LValue ElemLV = This;
7017 ElemLV.addArray(Info, &LocE, CAT);
7018 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7019 return false;
7020
7021 // Ensure that we have actual array elements available to destroy; the
7022 // destructors might mutate the value, so we can't run them on the array
7023 // filler.
7024 if (Size && Size > Value.getArrayInitializedElts())
7025 expandArray(Value, Value.getArraySize() - 1);
7026
7027 // The size of the array might have been reduced by
7028 // a placement new.
7029 for (Size = Value.getArraySize(); Size != 0; --Size) {
7030 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7031 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7032 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7033 return false;
7034 }
7035
7036 // End the lifetime of this array now.
7037 Value = APValue();
7038 return true;
7039 }
7040
7041 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7042 if (!RD) {
7043 if (T.isDestructedType()) {
7044 Info.FFDiag(CallRange.getBegin(),
7045 diag::note_constexpr_unsupported_destruction)
7046 << T;
7047 return false;
7048 }
7049
7050 Value = APValue();
7051 return true;
7052 }
7053
7054 if (RD->getNumVBases()) {
7055 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7056 return false;
7057 }
7058
7059 const CXXDestructorDecl *DD = RD->getDestructor();
7060 if (!DD && !RD->hasTrivialDestructor()) {
7061 Info.FFDiag(CallRange.getBegin());
7062 return false;
7063 }
7064
7065 if (!DD || DD->isTrivial() ||
7066 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7067 // A trivial destructor just ends the lifetime of the object. Check for
7068 // this case before checking for a body, because we might not bother
7069 // building a body for a trivial destructor. Note that it doesn't matter
7070 // whether the destructor is constexpr in this case; all trivial
7071 // destructors are constexpr.
7072 //
7073 // If an anonymous union would be destroyed, some enclosing destructor must
7074 // have been explicitly defined, and the anonymous union destruction should
7075 // have no effect.
7076 Value = APValue();
7077 return true;
7078 }
7079
7080 if (!Info.CheckCallLimit(CallRange.getBegin()))
7081 return false;
7082
7083 const FunctionDecl *Definition = nullptr;
7084 const Stmt *Body = DD->getBody(Definition);
7085
7086 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7087 return false;
7088
7089 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7090 CallRef());
7091
7092 // We're now in the period of destruction of this object.
7093 unsigned BasesLeft = RD->getNumBases();
7094 EvalInfo::EvaluatingDestructorRAII EvalObj(
7095 Info,
7096 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7097 if (!EvalObj.DidInsert) {
7098 // C++2a [class.dtor]p19:
7099 // the behavior is undefined if the destructor is invoked for an object
7100 // whose lifetime has ended
7101 // (Note that formally the lifetime ends when the period of destruction
7102 // begins, even though certain uses of the object remain valid until the
7103 // period of destruction ends.)
7104 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7105 return false;
7106 }
7107
7108 // FIXME: Creating an APValue just to hold a nonexistent return value is
7109 // wasteful.
7110 APValue RetVal;
7111 StmtResult Ret = {RetVal, nullptr};
7112 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7113 return false;
7114
7115 // A union destructor does not implicitly destroy its members.
7116 if (RD->isUnion())
7117 return true;
7118
7119 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7120
7121 // We don't have a good way to iterate fields in reverse, so collect all the
7122 // fields first and then walk them backwards.
7123 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7124 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7125 if (FD->isUnnamedBitField())
7126 continue;
7127
7128 LValue Subobject = This;
7129 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7130 return false;
7131
7132 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7133 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7134 FD->getType()))
7135 return false;
7136 }
7137
7138 if (BasesLeft != 0)
7139 EvalObj.startedDestroyingBases();
7140
7141 // Destroy base classes in reverse order.
7142 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7143 --BasesLeft;
7144
7145 QualType BaseType = Base.getType();
7146 LValue Subobject = This;
7147 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7148 BaseType->getAsCXXRecordDecl(), &Layout))
7149 return false;
7150
7151 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7152 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7153 BaseType))
7154 return false;
7155 }
7156 assert(BasesLeft == 0 && "NumBases was wrong?");
7157
7158 // The period of destruction ends now. The object is gone.
7159 Value = APValue();
7160 return true;
7161}
7162
7163namespace {
7164struct DestroyObjectHandler {
7165 EvalInfo &Info;
7166 const Expr *E;
7167 const LValue &This;
7168 const AccessKinds AccessKind;
7169
7170 typedef bool result_type;
7171 bool failed() { return false; }
7172 bool found(APValue &Subobj, QualType SubobjType) {
7173 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7174 SubobjType);
7175 }
7176 bool found(APSInt &Value, QualType SubobjType) {
7177 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7178 return false;
7179 }
7180 bool found(APFloat &Value, QualType SubobjType) {
7181 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7182 return false;
7183 }
7184};
7185}
7186
7187/// Perform a destructor or pseudo-destructor call on the given object, which
7188/// might in general not be a complete object.
7189static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7190 const LValue &This, QualType ThisType) {
7191 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7192 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7193 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7194}
7195
7196/// Destroy and end the lifetime of the given complete object.
7197static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7199 QualType T) {
7200 // If we've had an unmodeled side-effect, we can't rely on mutable state
7201 // (such as the object we're about to destroy) being correct.
7202 if (Info.EvalStatus.HasSideEffects)
7203 return false;
7204
7205 LValue LV;
7206 LV.set({LVBase});
7207 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7208}
7209
7210/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7211static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7212 LValue &Result) {
7213 if (Info.checkingPotentialConstantExpression() ||
7214 Info.SpeculativeEvaluationDepth)
7215 return false;
7216
7217 // This is permitted only within a call to std::allocator<T>::allocate.
7218 auto Caller = Info.getStdAllocatorCaller("allocate");
7219 if (!Caller) {
7220 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7221 ? diag::note_constexpr_new_untyped
7222 : diag::note_constexpr_new);
7223 return false;
7224 }
7225
7226 QualType ElemType = Caller.ElemType;
7227 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7228 Info.FFDiag(E->getExprLoc(),
7229 diag::note_constexpr_new_not_complete_object_type)
7230 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7231 return false;
7232 }
7233
7234 APSInt ByteSize;
7235 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7236 return false;
7237 bool IsNothrow = false;
7238 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7239 EvaluateIgnoredValue(Info, E->getArg(I));
7240 IsNothrow |= E->getType()->isNothrowT();
7241 }
7242
7243 CharUnits ElemSize;
7244 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7245 return false;
7246 APInt Size, Remainder;
7247 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7248 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7249 if (Remainder != 0) {
7250 // This likely indicates a bug in the implementation of 'std::allocator'.
7251 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7252 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7253 return false;
7254 }
7255
7256 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7257 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7258 if (IsNothrow) {
7259 Result.setNull(Info.Ctx, E->getType());
7260 return true;
7261 }
7262 return false;
7263 }
7264
7265 QualType AllocType = Info.Ctx.getConstantArrayType(
7266 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7267 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7268 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7269 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7270 return true;
7271}
7272
7274 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7275 if (CXXDestructorDecl *DD = RD->getDestructor())
7276 return DD->isVirtual();
7277 return false;
7278}
7279
7281 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7282 if (CXXDestructorDecl *DD = RD->getDestructor())
7283 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7284 return nullptr;
7285}
7286
7287/// Check that the given object is a suitable pointer to a heap allocation that
7288/// still exists and is of the right kind for the purpose of a deletion.
7289///
7290/// On success, returns the heap allocation to deallocate. On failure, produces
7291/// a diagnostic and returns std::nullopt.
7292static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7293 const LValue &Pointer,
7294 DynAlloc::Kind DeallocKind) {
7295 auto PointerAsString = [&] {
7296 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7297 };
7298
7299 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7300 if (!DA) {
7301 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7302 << PointerAsString();
7303 if (Pointer.Base)
7304 NoteLValueLocation(Info, Pointer.Base);
7305 return std::nullopt;
7306 }
7307
7308 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7309 if (!Alloc) {
7310 Info.FFDiag(E, diag::note_constexpr_double_delete);
7311 return std::nullopt;
7312 }
7313
7314 if (DeallocKind != (*Alloc)->getKind()) {
7315 QualType AllocType = Pointer.Base.getDynamicAllocType();
7316 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7317 << DeallocKind << (*Alloc)->getKind() << AllocType;
7318 NoteLValueLocation(Info, Pointer.Base);
7319 return std::nullopt;
7320 }
7321
7322 bool Subobject = false;
7323 if (DeallocKind == DynAlloc::New) {
7324 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7325 Pointer.Designator.isOnePastTheEnd();
7326 } else {
7327 Subobject = Pointer.Designator.Entries.size() != 1 ||
7328 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7329 }
7330 if (Subobject) {
7331 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7332 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7333 return std::nullopt;
7334 }
7335
7336 return Alloc;
7337}
7338
7339// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7340static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7341 if (Info.checkingPotentialConstantExpression() ||
7342 Info.SpeculativeEvaluationDepth)
7343 return false;
7344
7345 // This is permitted only within a call to std::allocator<T>::deallocate.
7346 if (!Info.getStdAllocatorCaller("deallocate")) {
7347 Info.FFDiag(E->getExprLoc());
7348 return true;
7349 }
7350
7351 LValue Pointer;
7352 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7353 return false;
7354 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7355 EvaluateIgnoredValue(Info, E->getArg(I));
7356
7357 if (Pointer.Designator.Invalid)
7358 return false;
7359
7360 // Deleting a null pointer would have no effect, but it's not permitted by
7361 // std::allocator<T>::deallocate's contract.
7362 if (Pointer.isNullPointer()) {
7363 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7364 return true;
7365 }
7366
7367 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7368 return false;
7369
7370 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7371 return true;
7372}
7373
7374//===----------------------------------------------------------------------===//
7375// Generic Evaluation
7376//===----------------------------------------------------------------------===//
7377namespace {
7378
7379class BitCastBuffer {
7380 // FIXME: We're going to need bit-level granularity when we support
7381 // bit-fields.
7382 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7383 // we don't support a host or target where that is the case. Still, we should
7384 // use a more generic type in case we ever do.
7385 SmallVector<std::optional<unsigned char>, 32> Bytes;
7386
7387 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7388 "Need at least 8 bit unsigned char");
7389
7390 bool TargetIsLittleEndian;
7391
7392public:
7393 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7394 : Bytes(Width.getQuantity()),
7395 TargetIsLittleEndian(TargetIsLittleEndian) {}
7396
7397 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7398 SmallVectorImpl<unsigned char> &Output) const {
7399 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7400 // If a byte of an integer is uninitialized, then the whole integer is
7401 // uninitialized.
7402 if (!Bytes[I.getQuantity()])
7403 return false;
7404 Output.push_back(*Bytes[I.getQuantity()]);
7405 }
7406 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7407 std::reverse(Output.begin(), Output.end());
7408 return true;
7409 }
7410
7411 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7412 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7413 std::reverse(Input.begin(), Input.end());
7414
7415 size_t Index = 0;
7416 for (unsigned char Byte : Input) {
7417 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7418 Bytes[Offset.getQuantity() + Index] = Byte;
7419 ++Index;
7420 }
7421 }
7422
7423 size_t size() { return Bytes.size(); }
7424};
7425
7426/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7427/// target would represent the value at runtime.
7428class APValueToBufferConverter {
7429 EvalInfo &Info;
7430 BitCastBuffer Buffer;
7431 const CastExpr *BCE;
7432
7433 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7434 const CastExpr *BCE)
7435 : Info(Info),
7436 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7437 BCE(BCE) {}
7438
7439 bool visit(const APValue &Val, QualType Ty) {
7440 return visit(Val, Ty, CharUnits::fromQuantity(0));
7441 }
7442
7443 // Write out Val with type Ty into Buffer starting at Offset.
7444 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7445 assert((size_t)Offset.getQuantity() <= Buffer.size());
7446
7447 // As a special case, nullptr_t has an indeterminate value.
7448 if (Ty->isNullPtrType())
7449 return true;
7450
7451 // Dig through Src to find the byte at SrcOffset.
7452 switch (Val.getKind()) {
7454 case APValue::None:
7455 return true;
7456
7457 case APValue::Int:
7458 return visitInt(Val.getInt(), Ty, Offset);
7459 case APValue::Float:
7460 return visitFloat(Val.getFloat(), Ty, Offset);
7461 case APValue::Array:
7462 return visitArray(Val, Ty, Offset);
7463 case APValue::Struct:
7464 return visitRecord(Val, Ty, Offset);
7465 case APValue::Vector:
7466 return visitVector(Val, Ty, Offset);
7467
7470 return visitComplex(Val, Ty, Offset);
7472 // FIXME: We should support these.
7473
7474 case APValue::Union:
7477 Info.FFDiag(BCE->getBeginLoc(),
7478 diag::note_constexpr_bit_cast_unsupported_type)
7479 << Ty;
7480 return false;
7481 }
7482
7483 case APValue::LValue:
7484 llvm_unreachable("LValue subobject in bit_cast?");
7485 }
7486 llvm_unreachable("Unhandled APValue::ValueKind");
7487 }
7488
7489 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7490 const RecordDecl *RD = Ty->getAsRecordDecl();
7491 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7492
7493 // Visit the base classes.
7494 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7495 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7496 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7497 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7498 const APValue &Base = Val.getStructBase(I);
7499
7500 // Can happen in error cases.
7501 if (!Base.isStruct())
7502 return false;
7503
7504 if (!visitRecord(Base, BS.getType(),
7505 Layout.getBaseClassOffset(BaseDecl) + Offset))
7506 return false;
7507 }
7508 }
7509
7510 // Visit the fields.
7511 unsigned FieldIdx = 0;
7512 for (FieldDecl *FD : RD->fields()) {
7513 if (FD->isBitField()) {
7514 Info.FFDiag(BCE->getBeginLoc(),
7515 diag::note_constexpr_bit_cast_unsupported_bitfield);
7516 return false;
7517 }
7518
7519 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7520
7521 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7522 "only bit-fields can have sub-char alignment");
7523 CharUnits FieldOffset =
7524 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7525 QualType FieldTy = FD->getType();
7526 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7527 return false;
7528 ++FieldIdx;
7529 }
7530
7531 return true;
7532 }
7533
7534 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7535 const auto *CAT =
7536 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7537 if (!CAT)
7538 return false;
7539
7540 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7541 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7542 unsigned ArraySize = Val.getArraySize();
7543 // First, initialize the initialized elements.
7544 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7545 const APValue &SubObj = Val.getArrayInitializedElt(I);
7546 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7547 return false;
7548 }
7549
7550 // Next, initialize the rest of the array using the filler.
7551 if (Val.hasArrayFiller()) {
7552 const APValue &Filler = Val.getArrayFiller();
7553 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7554 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7555 return false;
7556 }
7557 }
7558
7559 return true;
7560 }
7561
7562 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7563 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7564 QualType EltTy = ComplexTy->getElementType();
7565 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7566 bool IsInt = Val.isComplexInt();
7567
7568 if (IsInt) {
7569 if (!visitInt(Val.getComplexIntReal(), EltTy,
7570 Offset + (0 * EltSizeChars)))
7571 return false;
7572 if (!visitInt(Val.getComplexIntImag(), EltTy,
7573 Offset + (1 * EltSizeChars)))
7574 return false;
7575 } else {
7576 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7577 Offset + (0 * EltSizeChars)))
7578 return false;
7579 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7580 Offset + (1 * EltSizeChars)))
7581 return false;
7582 }
7583
7584 return true;
7585 }
7586
7587 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7588 const VectorType *VTy = Ty->castAs<VectorType>();
7589 QualType EltTy = VTy->getElementType();
7590 unsigned NElts = VTy->getNumElements();
7591
7592 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7593 // Special handling for OpenCL bool vectors:
7594 // Since these vectors are stored as packed bits, but we can't write
7595 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7596 // together into an appropriately sized APInt and write them all out at
7597 // once. Because we don't accept vectors where NElts * EltSize isn't a
7598 // multiple of the char size, there will be no padding space, so we don't
7599 // have to worry about writing data which should have been left
7600 // uninitialized.
7601 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7602
7603 llvm::APInt Res = llvm::APInt::getZero(NElts);
7604 for (unsigned I = 0; I < NElts; ++I) {
7605 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7606 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7607 "bool vector element must be 1-bit unsigned integer!");
7608
7609 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7610 }
7611
7612 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7613 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7614 Buffer.writeObject(Offset, Bytes);
7615 } else {
7616 // Iterate over each of the elements and write them out to the buffer at
7617 // the appropriate offset.
7618 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7619 for (unsigned I = 0; I < NElts; ++I) {
7620 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7621 return false;
7622 }
7623 }
7624
7625 return true;
7626 }
7627
7628 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7629 APSInt AdjustedVal = Val;
7630 unsigned Width = AdjustedVal.getBitWidth();
7631 if (Ty->isBooleanType()) {
7632 Width = Info.Ctx.getTypeSize(Ty);
7633 AdjustedVal = AdjustedVal.extend(Width);
7634 }
7635
7636 SmallVector<uint8_t, 8> Bytes(Width / 8);
7637 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7638 Buffer.writeObject(Offset, Bytes);
7639 return true;
7640 }
7641
7642 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7643 APSInt AsInt(Val.bitcastToAPInt());
7644 return visitInt(AsInt, Ty, Offset);
7645 }
7646
7647public:
7648 static std::optional<BitCastBuffer>
7649 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7650 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7651 APValueToBufferConverter Converter(Info, DstSize, BCE);
7652 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7653 return std::nullopt;
7654 return Converter.Buffer;
7655 }
7656};
7657
7658/// Write an BitCastBuffer into an APValue.
7659class BufferToAPValueConverter {
7660 EvalInfo &Info;
7661 const BitCastBuffer &Buffer;
7662 const CastExpr *BCE;
7663
7664 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7665 const CastExpr *BCE)
7666 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7667
7668 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7669 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7670 // Ideally this will be unreachable.
7671 std::nullopt_t unsupportedType(QualType Ty) {
7672 Info.FFDiag(BCE->getBeginLoc(),
7673 diag::note_constexpr_bit_cast_unsupported_type)
7674 << Ty;
7675 return std::nullopt;
7676 }
7677
7678 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7679 Info.FFDiag(BCE->getBeginLoc(),
7680 diag::note_constexpr_bit_cast_unrepresentable_value)
7681 << Ty << toString(Val, /*Radix=*/10);
7682 return std::nullopt;
7683 }
7684
7685 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7686 const EnumType *EnumSugar = nullptr) {
7687 if (T->isNullPtrType()) {
7688 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7689 return APValue((Expr *)nullptr,
7690 /*Offset=*/CharUnits::fromQuantity(NullValue),
7691 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7692 }
7693
7694 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7695
7696 // Work around floating point types that contain unused padding bytes. This
7697 // is really just `long double` on x86, which is the only fundamental type
7698 // with padding bytes.
7699 if (T->isRealFloatingType()) {
7700 const llvm::fltSemantics &Semantics =
7701 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7702 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7703 assert(NumBits % 8 == 0);
7704 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7705 if (NumBytes != SizeOf)
7706 SizeOf = NumBytes;
7707 }
7708
7709 SmallVector<uint8_t, 8> Bytes;
7710 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7711 // If this is std::byte or unsigned char, then its okay to store an
7712 // indeterminate value.
7713 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7714 bool IsUChar =
7715 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7716 T->isSpecificBuiltinType(BuiltinType::Char_U));
7717 if (!IsStdByte && !IsUChar) {
7718 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7719 Info.FFDiag(BCE->getExprLoc(),
7720 diag::note_constexpr_bit_cast_indet_dest)
7721 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7722 return std::nullopt;
7723 }
7724
7726 }
7727
7728 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7729 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7730
7732 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7733
7734 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7735 if (IntWidth != Val.getBitWidth()) {
7736 APSInt Truncated = Val.trunc(IntWidth);
7737 if (Truncated.extend(Val.getBitWidth()) != Val)
7738 return unrepresentableValue(QualType(T, 0), Val);
7739 Val = Truncated;
7740 }
7741
7742 return APValue(Val);
7743 }
7744
7745 if (T->isRealFloatingType()) {
7746 const llvm::fltSemantics &Semantics =
7747 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7748 return APValue(APFloat(Semantics, Val));
7749 }
7750
7751 return unsupportedType(QualType(T, 0));
7752 }
7753
7754 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7755 const RecordDecl *RD = RTy->getAsRecordDecl();
7756 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7757
7758 unsigned NumBases = 0;
7759 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7760 NumBases = CXXRD->getNumBases();
7761
7762 APValue ResultVal(APValue::UninitStruct(), NumBases,
7763 std::distance(RD->field_begin(), RD->field_end()));
7764
7765 // Visit the base classes.
7766 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7767 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7768 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7769 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7770
7771 std::optional<APValue> SubObj = visitType(
7772 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7773 if (!SubObj)
7774 return std::nullopt;
7775 ResultVal.getStructBase(I) = *SubObj;
7776 }
7777 }
7778
7779 // Visit the fields.
7780 unsigned FieldIdx = 0;
7781 for (FieldDecl *FD : RD->fields()) {
7782 // FIXME: We don't currently support bit-fields. A lot of the logic for
7783 // this is in CodeGen, so we need to factor it around.
7784 if (FD->isBitField()) {
7785 Info.FFDiag(BCE->getBeginLoc(),
7786 diag::note_constexpr_bit_cast_unsupported_bitfield);
7787 return std::nullopt;
7788 }
7789
7790 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7791 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7792
7793 CharUnits FieldOffset =
7794 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7795 Offset;
7796 QualType FieldTy = FD->getType();
7797 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7798 if (!SubObj)
7799 return std::nullopt;
7800 ResultVal.getStructField(FieldIdx) = *SubObj;
7801 ++FieldIdx;
7802 }
7803
7804 return ResultVal;
7805 }
7806
7807 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7808 QualType RepresentationType =
7809 Ty->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
7810 assert(!RepresentationType.isNull() &&
7811 "enum forward decl should be caught by Sema");
7812 const auto *AsBuiltin =
7813 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7814 // Recurse into the underlying type. Treat std::byte transparently as
7815 // unsigned char.
7816 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7817 }
7818
7819 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7820 size_t Size = Ty->getLimitedSize();
7821 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7822
7823 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7824 for (size_t I = 0; I != Size; ++I) {
7825 std::optional<APValue> ElementValue =
7826 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7827 if (!ElementValue)
7828 return std::nullopt;
7829 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7830 }
7831
7832 return ArrayValue;
7833 }
7834
7835 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7836 QualType ElementType = Ty->getElementType();
7837 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7838 bool IsInt = ElementType->isIntegerType();
7839
7840 std::optional<APValue> Values[2];
7841 for (unsigned I = 0; I != 2; ++I) {
7842 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7843 if (!Values[I])
7844 return std::nullopt;
7845 }
7846
7847 if (IsInt)
7848 return APValue(Values[0]->getInt(), Values[1]->getInt());
7849 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7850 }
7851
7852 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7853 QualType EltTy = VTy->getElementType();
7854 unsigned NElts = VTy->getNumElements();
7855 unsigned EltSize =
7856 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
7857
7858 SmallVector<APValue, 4> Elts;
7859 Elts.reserve(NElts);
7860 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7861 // Special handling for OpenCL bool vectors:
7862 // Since these vectors are stored as packed bits, but we can't read
7863 // individual bits from the BitCastBuffer, we'll buffer all of the
7864 // elements together into an appropriately sized APInt and write them all
7865 // out at once. Because we don't accept vectors where NElts * EltSize
7866 // isn't a multiple of the char size, there will be no padding space, so
7867 // we don't have to worry about reading any padding data which didn't
7868 // actually need to be accessed.
7869 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7870
7871 SmallVector<uint8_t, 8> Bytes;
7872 Bytes.reserve(NElts / 8);
7873 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7874 return std::nullopt;
7875
7876 APSInt SValInt(NElts, true);
7877 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7878
7879 for (unsigned I = 0; I < NElts; ++I) {
7880 llvm::APInt Elt =
7881 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7882 Elts.emplace_back(
7883 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7884 }
7885 } else {
7886 // Iterate over each of the elements and read them from the buffer at
7887 // the appropriate offset.
7888 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7889 for (unsigned I = 0; I < NElts; ++I) {
7890 std::optional<APValue> EltValue =
7891 visitType(EltTy, Offset + I * EltSizeChars);
7892 if (!EltValue)
7893 return std::nullopt;
7894 Elts.push_back(std::move(*EltValue));
7895 }
7896 }
7897
7898 return APValue(Elts.data(), Elts.size());
7899 }
7900
7901 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7902 return unsupportedType(QualType(Ty, 0));
7903 }
7904
7905 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7906 QualType Can = Ty.getCanonicalType();
7907
7908 switch (Can->getTypeClass()) {
7909#define TYPE(Class, Base) \
7910 case Type::Class: \
7911 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7912#define ABSTRACT_TYPE(Class, Base)
7913#define NON_CANONICAL_TYPE(Class, Base) \
7914 case Type::Class: \
7915 llvm_unreachable("non-canonical type should be impossible!");
7916#define DEPENDENT_TYPE(Class, Base) \
7917 case Type::Class: \
7918 llvm_unreachable( \
7919 "dependent types aren't supported in the constant evaluator!");
7920#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7921 case Type::Class: \
7922 llvm_unreachable("either dependent or not canonical!");
7923#include "clang/AST/TypeNodes.inc"
7924 }
7925 llvm_unreachable("Unhandled Type::TypeClass");
7926 }
7927
7928public:
7929 // Pull out a full value of type DstType.
7930 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7931 const CastExpr *BCE) {
7932 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7933 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7934 }
7935};
7936
7937static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7938 QualType Ty, EvalInfo *Info,
7939 const ASTContext &Ctx,
7940 bool CheckingDest) {
7941 Ty = Ty.getCanonicalType();
7942
7943 auto diag = [&](int Reason) {
7944 if (Info)
7945 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7946 << CheckingDest << (Reason == 4) << Reason;
7947 return false;
7948 };
7949 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7950 if (Info)
7951 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7952 << NoteTy << Construct << Ty;
7953 return false;
7954 };
7955
7956 if (Ty->isUnionType())
7957 return diag(0);
7958 if (Ty->isPointerType())
7959 return diag(1);
7960 if (Ty->isMemberPointerType())
7961 return diag(2);
7962 if (Ty.isVolatileQualified())
7963 return diag(3);
7964
7965 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7966 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7967 for (CXXBaseSpecifier &BS : CXXRD->bases())
7968 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7969 CheckingDest))
7970 return note(1, BS.getType(), BS.getBeginLoc());
7971 }
7972 for (FieldDecl *FD : Record->fields()) {
7973 if (FD->getType()->isReferenceType())
7974 return diag(4);
7975 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7976 CheckingDest))
7977 return note(0, FD->getType(), FD->getBeginLoc());
7978 }
7979 }
7980
7981 if (Ty->isArrayType() &&
7982 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7983 Info, Ctx, CheckingDest))
7984 return false;
7985
7986 if (const auto *VTy = Ty->getAs<VectorType>()) {
7987 QualType EltTy = VTy->getElementType();
7988 unsigned NElts = VTy->getNumElements();
7989 unsigned EltSize =
7990 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
7991
7992 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7993 // The vector's size in bits is not a multiple of the target's byte size,
7994 // so its layout is unspecified. For now, we'll simply treat these cases
7995 // as unsupported (this should only be possible with OpenCL bool vectors
7996 // whose element count isn't a multiple of the byte size).
7997 if (Info)
7998 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7999 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8000 return false;
8001 }
8002
8003 if (EltTy->isRealFloatingType() &&
8004 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8005 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8006 // by both clang and LLVM, so for now we won't allow bit_casts involving
8007 // it in a constexpr context.
8008 if (Info)
8009 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8010 << EltTy;
8011 return false;
8012 }
8013 }
8014
8015 return true;
8016}
8017
8018static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8019 const ASTContext &Ctx,
8020 const CastExpr *BCE) {
8021 bool DestOK = checkBitCastConstexprEligibilityType(
8022 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8023 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8024 BCE->getBeginLoc(),
8025 BCE->getSubExpr()->getType(), Info, Ctx, false);
8026 return SourceOK;
8027}
8028
8029static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8030 const APValue &SourceRValue,
8031 const CastExpr *BCE) {
8032 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8033 "no host or target supports non 8-bit chars");
8034
8035 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8036 return false;
8037
8038 // Read out SourceValue into a char buffer.
8039 std::optional<BitCastBuffer> Buffer =
8040 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8041 if (!Buffer)
8042 return false;
8043
8044 // Write out the buffer into a new APValue.
8045 std::optional<APValue> MaybeDestValue =
8046 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8047 if (!MaybeDestValue)
8048 return false;
8049
8050 DestValue = std::move(*MaybeDestValue);
8051 return true;
8052}
8053
8054static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8055 APValue &SourceValue,
8056 const CastExpr *BCE) {
8057 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8058 "no host or target supports non 8-bit chars");
8059 assert(SourceValue.isLValue() &&
8060 "LValueToRValueBitcast requires an lvalue operand!");
8061
8062 LValue SourceLValue;
8063 APValue SourceRValue;
8064 SourceLValue.setFrom(Info.Ctx, SourceValue);
8066 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8067 SourceRValue, /*WantObjectRepresentation=*/true))
8068 return false;
8069
8070 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8071}
8072
8073template <class Derived>
8074class ExprEvaluatorBase
8075 : public ConstStmtVisitor<Derived, bool> {
8076private:
8077 Derived &getDerived() { return static_cast<Derived&>(*this); }
8078 bool DerivedSuccess(const APValue &V, const Expr *E) {
8079 return getDerived().Success(V, E);
8080 }
8081 bool DerivedZeroInitialization(const Expr *E) {
8082 return getDerived().ZeroInitialization(E);
8083 }
8084
8085 // Check whether a conditional operator with a non-constant condition is a
8086 // potential constant expression. If neither arm is a potential constant
8087 // expression, then the conditional operator is not either.
8088 template<typename ConditionalOperator>
8089 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8090 assert(Info.checkingPotentialConstantExpression());
8091
8092 // Speculatively evaluate both arms.
8093 SmallVector<PartialDiagnosticAt, 8> Diag;
8094 {
8095 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8096 StmtVisitorTy::Visit(E->getFalseExpr());
8097 if (Diag.empty())
8098 return;
8099 }
8100
8101 {
8102 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8103 Diag.clear();
8104 StmtVisitorTy::Visit(E->getTrueExpr());
8105 if (Diag.empty())
8106 return;
8107 }
8108
8109 Error(E, diag::note_constexpr_conditional_never_const);
8110 }
8111
8112
8113 template<typename ConditionalOperator>
8114 bool HandleConditionalOperator(const ConditionalOperator *E) {
8115 bool BoolResult;
8116 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8117 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8118 CheckPotentialConstantConditional(E);
8119 return false;
8120 }
8121 if (Info.noteFailure()) {
8122 StmtVisitorTy::Visit(E->getTrueExpr());
8123 StmtVisitorTy::Visit(E->getFalseExpr());
8124 }
8125 return false;
8126 }
8127
8128 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8129 return StmtVisitorTy::Visit(EvalExpr);
8130 }
8131
8132protected:
8133 EvalInfo &Info;
8134 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8135 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8136
8137 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8138 return Info.CCEDiag(E, D);
8139 }
8140
8141 bool ZeroInitialization(const Expr *E) { return Error(E); }
8142
8143 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8144 unsigned BuiltinOp = E->getBuiltinCallee();
8145 return BuiltinOp != 0 &&
8146 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8147 }
8148
8149public:
8150 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8151
8152 EvalInfo &getEvalInfo() { return Info; }
8153
8154 /// Report an evaluation error. This should only be called when an error is
8155 /// first discovered. When propagating an error, just return false.
8156 bool Error(const Expr *E, diag::kind D) {
8157 Info.FFDiag(E, D) << E->getSourceRange();
8158 return false;
8159 }
8160 bool Error(const Expr *E) {
8161 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8162 }
8163
8164 bool VisitStmt(const Stmt *) {
8165 llvm_unreachable("Expression evaluator should not be called on stmts");
8166 }
8167 bool VisitExpr(const Expr *E) {
8168 return Error(E);
8169 }
8170
8171 bool VisitEmbedExpr(const EmbedExpr *E) {
8172 const auto It = E->begin();
8173 return StmtVisitorTy::Visit(*It);
8174 }
8175
8176 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8177 return StmtVisitorTy::Visit(E->getFunctionName());
8178 }
8179 bool VisitConstantExpr(const ConstantExpr *E) {
8180 if (E->hasAPValueResult())
8181 return DerivedSuccess(E->getAPValueResult(), E);
8182
8183 return StmtVisitorTy::Visit(E->getSubExpr());
8184 }
8185
8186 bool VisitParenExpr(const ParenExpr *E)
8187 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8188 bool VisitUnaryExtension(const UnaryOperator *E)
8189 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8190 bool VisitUnaryPlus(const UnaryOperator *E)
8191 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8192 bool VisitChooseExpr(const ChooseExpr *E)
8193 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8194 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8195 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8196 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8197 { return StmtVisitorTy::Visit(E->getReplacement()); }
8198 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8199 TempVersionRAII RAII(*Info.CurrentCall);
8200 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8201 return StmtVisitorTy::Visit(E->getExpr());
8202 }
8203 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8204 TempVersionRAII RAII(*Info.CurrentCall);
8205 // The initializer may not have been parsed yet, or might be erroneous.
8206 if (!E->getExpr())
8207 return Error(E);
8208 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8209 return StmtVisitorTy::Visit(E->getExpr());
8210 }
8211
8212 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8213 FullExpressionRAII Scope(Info);
8214 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8215 }
8216
8217 // Temporaries are registered when created, so we don't care about
8218 // CXXBindTemporaryExpr.
8219 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8220 return StmtVisitorTy::Visit(E->getSubExpr());
8221 }
8222
8223 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8224 CCEDiag(E, diag::note_constexpr_invalid_cast)
8225 << diag::ConstexprInvalidCastKind::Reinterpret;
8226 return static_cast<Derived*>(this)->VisitCastExpr(E);
8227 }
8228 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8229 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8230 CCEDiag(E, diag::note_constexpr_invalid_cast)
8231 << diag::ConstexprInvalidCastKind::Dynamic;
8232 return static_cast<Derived*>(this)->VisitCastExpr(E);
8233 }
8234 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8235 return static_cast<Derived*>(this)->VisitCastExpr(E);
8236 }
8237
8238 bool VisitBinaryOperator(const BinaryOperator *E) {
8239 switch (E->getOpcode()) {
8240 default:
8241 return Error(E);
8242
8243 case BO_Comma:
8244 VisitIgnoredValue(E->getLHS());
8245 return StmtVisitorTy::Visit(E->getRHS());
8246
8247 case BO_PtrMemD:
8248 case BO_PtrMemI: {
8249 LValue Obj;
8250 if (!HandleMemberPointerAccess(Info, E, Obj))
8251 return false;
8253 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8254 return false;
8255 return DerivedSuccess(Result, E);
8256 }
8257 }
8258 }
8259
8260 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8261 return StmtVisitorTy::Visit(E->getSemanticForm());
8262 }
8263
8264 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8265 // Evaluate and cache the common expression. We treat it as a temporary,
8266 // even though it's not quite the same thing.
8267 LValue CommonLV;
8268 if (!Evaluate(Info.CurrentCall->createTemporary(
8269 E->getOpaqueValue(),
8270 getStorageType(Info.Ctx, E->getOpaqueValue()),
8271 ScopeKind::FullExpression, CommonLV),
8272 Info, E->getCommon()))
8273 return false;
8274
8275 return HandleConditionalOperator(E);
8276 }
8277
8278 bool VisitConditionalOperator(const ConditionalOperator *E) {
8279 bool IsBcpCall = false;
8280 // If the condition (ignoring parens) is a __builtin_constant_p call,
8281 // the result is a constant expression if it can be folded without
8282 // side-effects. This is an important GNU extension. See GCC PR38377
8283 // for discussion.
8284 if (const CallExpr *CallCE =
8285 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8286 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8287 IsBcpCall = true;
8288
8289 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8290 // constant expression; we can't check whether it's potentially foldable.
8291 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8292 // it would return 'false' in this mode.
8293 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8294 return false;
8295
8296 FoldConstant Fold(Info, IsBcpCall);
8297 if (!HandleConditionalOperator(E)) {
8298 Fold.keepDiagnostics();
8299 return false;
8300 }
8301
8302 return true;
8303 }
8304
8305 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8306 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8307 Value && !Value->isAbsent())
8308 return DerivedSuccess(*Value, E);
8309
8310 const Expr *Source = E->getSourceExpr();
8311 if (!Source)
8312 return Error(E);
8313 if (Source == E) {
8314 assert(0 && "OpaqueValueExpr recursively refers to itself");
8315 return Error(E);
8316 }
8317 return StmtVisitorTy::Visit(Source);
8318 }
8319
8320 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8321 for (const Expr *SemE : E->semantics()) {
8322 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8323 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8324 // result expression: there could be two different LValues that would
8325 // refer to the same object in that case, and we can't model that.
8326 if (SemE == E->getResultExpr())
8327 return Error(E);
8328
8329 // Unique OVEs get evaluated if and when we encounter them when
8330 // emitting the rest of the semantic form, rather than eagerly.
8331 if (OVE->isUnique())
8332 continue;
8333
8334 LValue LV;
8335 if (!Evaluate(Info.CurrentCall->createTemporary(
8336 OVE, getStorageType(Info.Ctx, OVE),
8337 ScopeKind::FullExpression, LV),
8338 Info, OVE->getSourceExpr()))
8339 return false;
8340 } else if (SemE == E->getResultExpr()) {
8341 if (!StmtVisitorTy::Visit(SemE))
8342 return false;
8343 } else {
8344 if (!EvaluateIgnoredValue(Info, SemE))
8345 return false;
8346 }
8347 }
8348 return true;
8349 }
8350
8351 bool VisitCallExpr(const CallExpr *E) {
8353 if (!handleCallExpr(E, Result, nullptr))
8354 return false;
8355 return DerivedSuccess(Result, E);
8356 }
8357
8358 bool handleCallExpr(const CallExpr *E, APValue &Result,
8359 const LValue *ResultSlot) {
8360 CallScopeRAII CallScope(Info);
8361
8362 const Expr *Callee = E->getCallee()->IgnoreParens();
8363 QualType CalleeType = Callee->getType();
8364
8365 const FunctionDecl *FD = nullptr;
8366 LValue *This = nullptr, ObjectArg;
8367 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8368 bool HasQualifier = false;
8369
8370 CallRef Call;
8371
8372 // Extract function decl and 'this' pointer from the callee.
8373 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8374 const CXXMethodDecl *Member = nullptr;
8375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8376 // Explicit bound member calls, such as x.f() or p->g();
8377 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8378 return false;
8379 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8380 if (!Member)
8381 return Error(Callee);
8382 This = &ObjectArg;
8383 HasQualifier = ME->hasQualifier();
8384 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8385 // Indirect bound member calls ('.*' or '->*').
8386 const ValueDecl *D =
8387 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8388 if (!D)
8389 return false;
8390 Member = dyn_cast<CXXMethodDecl>(D);
8391 if (!Member)
8392 return Error(Callee);
8393 This = &ObjectArg;
8394 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8395 if (!Info.getLangOpts().CPlusPlus20)
8396 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8397 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8398 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8399 } else
8400 return Error(Callee);
8401 FD = Member;
8402 } else if (CalleeType->isFunctionPointerType()) {
8403 LValue CalleeLV;
8404 if (!EvaluatePointer(Callee, CalleeLV, Info))
8405 return false;
8406
8407 if (!CalleeLV.getLValueOffset().isZero())
8408 return Error(Callee);
8409 if (CalleeLV.isNullPointer()) {
8410 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8411 << const_cast<Expr *>(Callee);
8412 return false;
8413 }
8414 FD = dyn_cast_or_null<FunctionDecl>(
8415 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8416 if (!FD)
8417 return Error(Callee);
8418 // Don't call function pointers which have been cast to some other type.
8419 // Per DR (no number yet), the caller and callee can differ in noexcept.
8421 CalleeType->getPointeeType(), FD->getType())) {
8422 return Error(E);
8423 }
8424
8425 // For an (overloaded) assignment expression, evaluate the RHS before the
8426 // LHS.
8427 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8428 if (OCE && OCE->isAssignmentOp()) {
8429 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8430 Call = Info.CurrentCall->createCall(FD);
8431 bool HasThis = false;
8432 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8433 HasThis = MD->isImplicitObjectMemberFunction();
8434 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8435 /*RightToLeft=*/true, &ObjectArg))
8436 return false;
8437 }
8438
8439 // Overloaded operator calls to member functions are represented as normal
8440 // calls with '*this' as the first argument.
8441 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8442 if (MD &&
8443 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8444 // FIXME: When selecting an implicit conversion for an overloaded
8445 // operator delete, we sometimes try to evaluate calls to conversion
8446 // operators without a 'this' parameter!
8447 if (Args.empty())
8448 return Error(E);
8449
8450 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8451 return false;
8452
8453 // If we are calling a static operator, the 'this' argument needs to be
8454 // ignored after being evaluated.
8455 if (MD->isInstance())
8456 This = &ObjectArg;
8457
8458 // If this is syntactically a simple assignment using a trivial
8459 // assignment operator, start the lifetimes of union members as needed,
8460 // per C++20 [class.union]5.
8461 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8462 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8463 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8464 return false;
8465
8466 Args = Args.slice(1);
8467 } else if (MD && MD->isLambdaStaticInvoker()) {
8468 // Map the static invoker for the lambda back to the call operator.
8469 // Conveniently, we don't have to slice out the 'this' argument (as is
8470 // being done for the non-static case), since a static member function
8471 // doesn't have an implicit argument passed in.
8472 const CXXRecordDecl *ClosureClass = MD->getParent();
8473 assert(
8474 ClosureClass->captures().empty() &&
8475 "Number of captures must be zero for conversion to function-ptr");
8476
8477 const CXXMethodDecl *LambdaCallOp =
8478 ClosureClass->getLambdaCallOperator();
8479
8480 // Set 'FD', the function that will be called below, to the call
8481 // operator. If the closure object represents a generic lambda, find
8482 // the corresponding specialization of the call operator.
8483
8484 if (ClosureClass->isGenericLambda()) {
8485 assert(MD->isFunctionTemplateSpecialization() &&
8486 "A generic lambda's static-invoker function must be a "
8487 "template specialization");
8488 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8489 FunctionTemplateDecl *CallOpTemplate =
8490 LambdaCallOp->getDescribedFunctionTemplate();
8491 void *InsertPos = nullptr;
8492 FunctionDecl *CorrespondingCallOpSpecialization =
8493 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8494 assert(CorrespondingCallOpSpecialization &&
8495 "We must always have a function call operator specialization "
8496 "that corresponds to our static invoker specialization");
8497 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8498 FD = CorrespondingCallOpSpecialization;
8499 } else
8500 FD = LambdaCallOp;
8502 if (FD->getDeclName().isAnyOperatorNew()) {
8503 LValue Ptr;
8504 if (!HandleOperatorNewCall(Info, E, Ptr))
8505 return false;
8506 Ptr.moveInto(Result);
8507 return CallScope.destroy();
8508 } else {
8509 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8510 }
8511 }
8512 } else
8513 return Error(E);
8514
8515 // Evaluate the arguments now if we've not already done so.
8516 if (!Call) {
8517 Call = Info.CurrentCall->createCall(FD);
8518 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8519 &ObjectArg))
8520 return false;
8521 }
8522
8523 SmallVector<QualType, 4> CovariantAdjustmentPath;
8524 if (This) {
8525 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8526 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8527 // Perform virtual dispatch, if necessary.
8528 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8529 CovariantAdjustmentPath);
8530 if (!FD)
8531 return false;
8532 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8533 // Check that the 'this' pointer points to an object of the right type.
8534 // FIXME: If this is an assignment operator call, we may need to change
8535 // the active union member before we check this.
8536 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8537 return false;
8538 }
8539 }
8540
8541 // Destructor calls are different enough that they have their own codepath.
8542 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8543 assert(This && "no 'this' pointer for destructor call");
8544 return HandleDestruction(Info, E, *This,
8545 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8546 CallScope.destroy();
8547 }
8548
8549 const FunctionDecl *Definition = nullptr;
8550 Stmt *Body = FD->getBody(Definition);
8551 SourceLocation Loc = E->getExprLoc();
8552
8553 // Treat the object argument as `this` when evaluating defaulted
8554 // special menmber functions
8556 This = &ObjectArg;
8557
8558 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8559 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8560 Result, ResultSlot))
8561 return false;
8562
8563 if (!CovariantAdjustmentPath.empty() &&
8565 CovariantAdjustmentPath))
8566 return false;
8567
8568 return CallScope.destroy();
8569 }
8570
8571 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8572 return StmtVisitorTy::Visit(E->getInitializer());
8573 }
8574 bool VisitInitListExpr(const InitListExpr *E) {
8575 if (E->getNumInits() == 0)
8576 return DerivedZeroInitialization(E);
8577 if (E->getNumInits() == 1)
8578 return StmtVisitorTy::Visit(E->getInit(0));
8579 return Error(E);
8580 }
8581 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8582 return DerivedZeroInitialization(E);
8583 }
8584 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8585 return DerivedZeroInitialization(E);
8586 }
8587 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8588 return DerivedZeroInitialization(E);
8589 }
8590
8591 /// A member expression where the object is a prvalue is itself a prvalue.
8592 bool VisitMemberExpr(const MemberExpr *E) {
8593 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8594 "missing temporary materialization conversion");
8595 assert(!E->isArrow() && "missing call to bound member function?");
8596
8597 APValue Val;
8598 if (!Evaluate(Val, Info, E->getBase()))
8599 return false;
8600
8601 QualType BaseTy = E->getBase()->getType();
8602
8603 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8604 if (!FD) return Error(E);
8605 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8606 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8607 FD->getParent()->getCanonicalDecl() &&
8608 "record / field mismatch");
8609
8610 // Note: there is no lvalue base here. But this case should only ever
8611 // happen in C or in C++98, where we cannot be evaluating a constexpr
8612 // constructor, which is the only case the base matters.
8613 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8614 SubobjectDesignator Designator(BaseTy);
8615 Designator.addDeclUnchecked(FD);
8616
8618 return extractSubobject(Info, E, Obj, Designator, Result) &&
8619 DerivedSuccess(Result, E);
8620 }
8621
8622 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8623 APValue Val;
8624 if (!Evaluate(Val, Info, E->getBase()))
8625 return false;
8626
8627 if (Val.isVector()) {
8628 SmallVector<uint32_t, 4> Indices;
8629 E->getEncodedElementAccess(Indices);
8630 if (Indices.size() == 1) {
8631 // Return scalar.
8632 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8633 } else {
8634 // Construct new APValue vector.
8635 SmallVector<APValue, 4> Elts;
8636 for (unsigned I = 0; I < Indices.size(); ++I) {
8637 Elts.push_back(Val.getVectorElt(Indices[I]));
8638 }
8639 APValue VecResult(Elts.data(), Indices.size());
8640 return DerivedSuccess(VecResult, E);
8641 }
8642 }
8643
8644 return false;
8645 }
8646
8647 bool VisitCastExpr(const CastExpr *E) {
8648 switch (E->getCastKind()) {
8649 default:
8650 break;
8651
8652 case CK_AtomicToNonAtomic: {
8653 APValue AtomicVal;
8654 // This does not need to be done in place even for class/array types:
8655 // atomic-to-non-atomic conversion implies copying the object
8656 // representation.
8657 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8658 return false;
8659 return DerivedSuccess(AtomicVal, E);
8660 }
8661
8662 case CK_NoOp:
8663 case CK_UserDefinedConversion:
8664 return StmtVisitorTy::Visit(E->getSubExpr());
8665
8666 case CK_LValueToRValue: {
8667 LValue LVal;
8668 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8669 return false;
8670 APValue RVal;
8671 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8673 LVal, RVal))
8674 return false;
8675 return DerivedSuccess(RVal, E);
8676 }
8677 case CK_LValueToRValueBitCast: {
8678 APValue DestValue, SourceValue;
8679 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8680 return false;
8681 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8682 return false;
8683 return DerivedSuccess(DestValue, E);
8684 }
8685
8686 case CK_AddressSpaceConversion: {
8687 APValue Value;
8688 if (!Evaluate(Value, Info, E->getSubExpr()))
8689 return false;
8690 return DerivedSuccess(Value, E);
8691 }
8692 }
8693
8694 return Error(E);
8695 }
8696
8697 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8698 return VisitUnaryPostIncDec(UO);
8699 }
8700 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8701 return VisitUnaryPostIncDec(UO);
8702 }
8703 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8704 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8705 return Error(UO);
8706
8707 LValue LVal;
8708 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8709 return false;
8710 APValue RVal;
8711 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8712 UO->isIncrementOp(), &RVal))
8713 return false;
8714 return DerivedSuccess(RVal, UO);
8715 }
8716
8717 bool VisitStmtExpr(const StmtExpr *E) {
8718 // We will have checked the full-expressions inside the statement expression
8719 // when they were completed, and don't need to check them again now.
8720 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8721 false);
8722
8723 const CompoundStmt *CS = E->getSubStmt();
8724 if (CS->body_empty())
8725 return true;
8726
8727 BlockScopeRAII Scope(Info);
8729 BE = CS->body_end();
8730 /**/; ++BI) {
8731 if (BI + 1 == BE) {
8732 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8733 if (!FinalExpr) {
8734 Info.FFDiag((*BI)->getBeginLoc(),
8735 diag::note_constexpr_stmt_expr_unsupported);
8736 return false;
8737 }
8738 return this->Visit(FinalExpr) && Scope.destroy();
8739 }
8740
8742 StmtResult Result = { ReturnValue, nullptr };
8743 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8744 if (ESR != ESR_Succeeded) {
8745 // FIXME: If the statement-expression terminated due to 'return',
8746 // 'break', or 'continue', it would be nice to propagate that to
8747 // the outer statement evaluation rather than bailing out.
8748 if (ESR != ESR_Failed)
8749 Info.FFDiag((*BI)->getBeginLoc(),
8750 diag::note_constexpr_stmt_expr_unsupported);
8751 return false;
8752 }
8753 }
8754
8755 llvm_unreachable("Return from function from the loop above.");
8756 }
8757
8758 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8759 return StmtVisitorTy::Visit(E->getSelectedExpr());
8760 }
8761
8762 /// Visit a value which is evaluated, but whose value is ignored.
8763 void VisitIgnoredValue(const Expr *E) {
8764 EvaluateIgnoredValue(Info, E);
8765 }
8766
8767 /// Potentially visit a MemberExpr's base expression.
8768 void VisitIgnoredBaseExpression(const Expr *E) {
8769 // While MSVC doesn't evaluate the base expression, it does diagnose the
8770 // presence of side-effecting behavior.
8771 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8772 return;
8773 VisitIgnoredValue(E);
8774 }
8775};
8776
8777} // namespace
8778
8779//===----------------------------------------------------------------------===//
8780// Common base class for lvalue and temporary evaluation.
8781//===----------------------------------------------------------------------===//
8782namespace {
8783template<class Derived>
8784class LValueExprEvaluatorBase
8785 : public ExprEvaluatorBase<Derived> {
8786protected:
8787 LValue &Result;
8788 bool InvalidBaseOK;
8789 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8790 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8791
8792 bool Success(APValue::LValueBase B) {
8793 Result.set(B);
8794 return true;
8795 }
8796
8797 bool evaluatePointer(const Expr *E, LValue &Result) {
8798 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8799 }
8800
8801public:
8802 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8803 : ExprEvaluatorBaseTy(Info), Result(Result),
8804 InvalidBaseOK(InvalidBaseOK) {}
8805
8806 bool Success(const APValue &V, const Expr *E) {
8807 Result.setFrom(this->Info.Ctx, V);
8808 return true;
8809 }
8810
8811 bool VisitMemberExpr(const MemberExpr *E) {
8812 // Handle non-static data members.
8813 QualType BaseTy;
8814 bool EvalOK;
8815 if (E->isArrow()) {
8816 EvalOK = evaluatePointer(E->getBase(), Result);
8817 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8818 } else if (E->getBase()->isPRValue()) {
8819 assert(E->getBase()->getType()->isRecordType());
8820 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8821 BaseTy = E->getBase()->getType();
8822 } else {
8823 EvalOK = this->Visit(E->getBase());
8824 BaseTy = E->getBase()->getType();
8825 }
8826 if (!EvalOK) {
8827 if (!InvalidBaseOK)
8828 return false;
8829 Result.setInvalid(E);
8830 return true;
8831 }
8832
8833 const ValueDecl *MD = E->getMemberDecl();
8834 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8835 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8836 FD->getParent()->getCanonicalDecl() &&
8837 "record / field mismatch");
8838 (void)BaseTy;
8839 if (!HandleLValueMember(this->Info, E, Result, FD))
8840 return false;
8841 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8842 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8843 return false;
8844 } else
8845 return this->Error(E);
8846
8847 if (MD->getType()->isReferenceType()) {
8848 APValue RefValue;
8849 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8850 RefValue))
8851 return false;
8852 return Success(RefValue, E);
8853 }
8854 return true;
8855 }
8856
8857 bool VisitBinaryOperator(const BinaryOperator *E) {
8858 switch (E->getOpcode()) {
8859 default:
8860 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8861
8862 case BO_PtrMemD:
8863 case BO_PtrMemI:
8864 return HandleMemberPointerAccess(this->Info, E, Result);
8865 }
8866 }
8867
8868 bool VisitCastExpr(const CastExpr *E) {
8869 switch (E->getCastKind()) {
8870 default:
8871 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8872
8873 case CK_DerivedToBase:
8874 case CK_UncheckedDerivedToBase:
8875 if (!this->Visit(E->getSubExpr()))
8876 return false;
8877
8878 // Now figure out the necessary offset to add to the base LV to get from
8879 // the derived class to the base class.
8880 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8881 Result);
8882 }
8883 }
8884};
8885}
8886
8887//===----------------------------------------------------------------------===//
8888// LValue Evaluation
8889//
8890// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8891// function designators (in C), decl references to void objects (in C), and
8892// temporaries (if building with -Wno-address-of-temporary).
8893//
8894// LValue evaluation produces values comprising a base expression of one of the
8895// following types:
8896// - Declarations
8897// * VarDecl
8898// * FunctionDecl
8899// - Literals
8900// * CompoundLiteralExpr in C (and in global scope in C++)
8901// * StringLiteral
8902// * PredefinedExpr
8903// * ObjCStringLiteralExpr
8904// * ObjCEncodeExpr
8905// * AddrLabelExpr
8906// * BlockExpr
8907// * CallExpr for a MakeStringConstant builtin
8908// - typeid(T) expressions, as TypeInfoLValues
8909// - Locals and temporaries
8910// * MaterializeTemporaryExpr
8911// * Any Expr, with a CallIndex indicating the function in which the temporary
8912// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8913// from the AST (FIXME).
8914// * A MaterializeTemporaryExpr that has static storage duration, with no
8915// CallIndex, for a lifetime-extended temporary.
8916// * The ConstantExpr that is currently being evaluated during evaluation of an
8917// immediate invocation.
8918// plus an offset in bytes.
8919//===----------------------------------------------------------------------===//
8920namespace {
8921class LValueExprEvaluator
8922 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8923public:
8924 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8925 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8926
8927 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8928 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8929
8930 bool VisitCallExpr(const CallExpr *E);
8931 bool VisitDeclRefExpr(const DeclRefExpr *E);
8932 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8933 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8934 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8935 bool VisitMemberExpr(const MemberExpr *E);
8936 bool VisitStringLiteral(const StringLiteral *E) {
8937 return Success(APValue::LValueBase(
8938 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8939 }
8940 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8941 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8942 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8943 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8944 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8945 bool VisitUnaryDeref(const UnaryOperator *E);
8946 bool VisitUnaryReal(const UnaryOperator *E);
8947 bool VisitUnaryImag(const UnaryOperator *E);
8948 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8949 return VisitUnaryPreIncDec(UO);
8950 }
8951 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8952 return VisitUnaryPreIncDec(UO);
8953 }
8954 bool VisitBinAssign(const BinaryOperator *BO);
8955 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8956
8957 bool VisitCastExpr(const CastExpr *E) {
8958 switch (E->getCastKind()) {
8959 default:
8960 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8961
8962 case CK_LValueBitCast:
8963 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8964 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
8965 << Info.Ctx.getLangOpts().CPlusPlus;
8966 if (!Visit(E->getSubExpr()))
8967 return false;
8968 Result.Designator.setInvalid();
8969 return true;
8970
8971 case CK_BaseToDerived:
8972 if (!Visit(E->getSubExpr()))
8973 return false;
8974 return HandleBaseToDerivedCast(Info, E, Result);
8975
8976 case CK_Dynamic:
8977 if (!Visit(E->getSubExpr()))
8978 return false;
8980 }
8981 }
8982};
8983} // end anonymous namespace
8984
8985/// Get an lvalue to a field of a lambda's closure type.
8986static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8987 const CXXMethodDecl *MD, const FieldDecl *FD,
8988 bool LValueToRValueConversion) {
8989 // Static lambda function call operators can't have captures. We already
8990 // diagnosed this, so bail out here.
8991 if (MD->isStatic()) {
8992 assert(Info.CurrentCall->This == nullptr &&
8993 "This should not be set for a static call operator");
8994 return false;
8995 }
8996
8997 // Start with 'Result' referring to the complete closure object...
8999 // Self may be passed by reference or by value.
9000 const ParmVarDecl *Self = MD->getParamDecl(0);
9001 if (Self->getType()->isReferenceType()) {
9002 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9003 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9004 Result.setFrom(Info.Ctx, *RefValue);
9005 } else {
9006 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9007 CallStackFrame *Frame =
9008 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9009 .first;
9010 unsigned Version = Info.CurrentCall->Arguments.Version;
9011 Result.set({VD, Frame->Index, Version});
9012 }
9013 } else
9014 Result = *Info.CurrentCall->This;
9015
9016 // ... then update it to refer to the field of the closure object
9017 // that represents the capture.
9018 if (!HandleLValueMember(Info, E, Result, FD))
9019 return false;
9020
9021 // And if the field is of reference type (or if we captured '*this' by
9022 // reference), update 'Result' to refer to what
9023 // the field refers to.
9024 if (LValueToRValueConversion) {
9025 APValue RVal;
9026 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9027 return false;
9028 Result.setFrom(Info.Ctx, RVal);
9029 }
9030 return true;
9031}
9032
9033/// Evaluate an expression as an lvalue. This can be legitimately called on
9034/// expressions which are not glvalues, in three cases:
9035/// * function designators in C, and
9036/// * "extern void" objects
9037/// * @selector() expressions in Objective-C
9038static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9039 bool InvalidBaseOK) {
9040 assert(!E->isValueDependent());
9041 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9043 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9044}
9045
9046bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9047 const ValueDecl *D = E->getDecl();
9048
9049 // If we are within a lambda's call operator, check whether the 'VD' referred
9050 // to within 'E' actually represents a lambda-capture that maps to a
9051 // data-member/field within the closure object, and if so, evaluate to the
9052 // field or what the field refers to.
9053 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9055 // We don't always have a complete capture-map when checking or inferring if
9056 // the function call operator meets the requirements of a constexpr function
9057 // - but we don't need to evaluate the captures to determine constexprness
9058 // (dcl.constexpr C++17).
9059 if (Info.checkingPotentialConstantExpression())
9060 return false;
9061
9062 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9063 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9064 return HandleLambdaCapture(Info, E, Result, MD, FD,
9065 FD->getType()->isReferenceType());
9066 }
9067 }
9068
9069 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9070 UnnamedGlobalConstantDecl>(D))
9071 return Success(cast<ValueDecl>(D));
9072 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9073 return VisitVarDecl(E, VD);
9074 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9075 return Visit(BD->getBinding());
9076 return Error(E);
9077}
9078
9079bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9080 CallStackFrame *Frame = nullptr;
9081 unsigned Version = 0;
9082 if (VD->hasLocalStorage()) {
9083 // Only if a local variable was declared in the function currently being
9084 // evaluated, do we expect to be able to find its value in the current
9085 // frame. (Otherwise it was likely declared in an enclosing context and
9086 // could either have a valid evaluatable value (for e.g. a constexpr
9087 // variable) or be ill-formed (and trigger an appropriate evaluation
9088 // diagnostic)).
9089 CallStackFrame *CurrFrame = Info.CurrentCall;
9090 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9091 // Function parameters are stored in some caller's frame. (Usually the
9092 // immediate caller, but for an inherited constructor they may be more
9093 // distant.)
9094 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9095 if (CurrFrame->Arguments) {
9096 VD = CurrFrame->Arguments.getOrigParam(PVD);
9097 Frame =
9098 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9099 Version = CurrFrame->Arguments.Version;
9100 }
9101 } else {
9102 Frame = CurrFrame;
9103 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9104 }
9105 }
9106 }
9107
9108 if (!VD->getType()->isReferenceType()) {
9109 if (Frame) {
9110 Result.set({VD, Frame->Index, Version});
9111 return true;
9112 }
9113 return Success(VD);
9114 }
9115
9116 if (!Info.getLangOpts().CPlusPlus11) {
9117 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9118 << VD << VD->getType();
9119 Info.Note(VD->getLocation(), diag::note_declared_at);
9120 }
9121
9122 APValue *V;
9123 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9124 return false;
9125
9126 if (!V) {
9127 Result.set(VD);
9128 Result.AllowConstexprUnknown = true;
9129 return true;
9130 }
9131
9132 return Success(*V, E);
9133}
9134
9135bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9136 if (!IsConstantEvaluatedBuiltinCall(E))
9137 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9138
9139 switch (E->getBuiltinCallee()) {
9140 default:
9141 return false;
9142 case Builtin::BIas_const:
9143 case Builtin::BIforward:
9144 case Builtin::BIforward_like:
9145 case Builtin::BImove:
9146 case Builtin::BImove_if_noexcept:
9147 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9148 return Visit(E->getArg(0));
9149 break;
9150 }
9151
9152 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9153}
9154
9155bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9156 const MaterializeTemporaryExpr *E) {
9157 // Walk through the expression to find the materialized temporary itself.
9160 const Expr *Inner =
9161 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9162
9163 // If we passed any comma operators, evaluate their LHSs.
9164 for (const Expr *E : CommaLHSs)
9165 if (!EvaluateIgnoredValue(Info, E))
9166 return false;
9167
9168 // A materialized temporary with static storage duration can appear within the
9169 // result of a constant expression evaluation, so we need to preserve its
9170 // value for use outside this evaluation.
9171 APValue *Value;
9172 if (E->getStorageDuration() == SD_Static) {
9173 if (Info.EvalMode == EvaluationMode::ConstantFold)
9174 return false;
9175 // FIXME: What about SD_Thread?
9176 Value = E->getOrCreateValue(true);
9177 *Value = APValue();
9178 Result.set(E);
9179 } else {
9180 Value = &Info.CurrentCall->createTemporary(
9181 E, Inner->getType(),
9182 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9183 : ScopeKind::Block,
9184 Result);
9185 }
9186
9187 QualType Type = Inner->getType();
9188
9189 // Materialize the temporary itself.
9190 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9191 *Value = APValue();
9192 return false;
9193 }
9194
9195 // Adjust our lvalue to refer to the desired subobject.
9196 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9197 --I;
9198 switch (Adjustments[I].Kind) {
9200 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9201 Type, Result))
9202 return false;
9203 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9204 break;
9205
9207 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9208 return false;
9209 Type = Adjustments[I].Field->getType();
9210 break;
9211
9213 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9214 Adjustments[I].Ptr.RHS))
9215 return false;
9216 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9217 break;
9218 }
9219 }
9220
9221 return true;
9222}
9223
9224bool
9225LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9226 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9227 "lvalue compound literal in c++?");
9228 APValue *Lit;
9229 // If CompountLiteral has static storage, its value can be used outside
9230 // this expression. So evaluate it once and store it in ASTContext.
9231 if (E->hasStaticStorage()) {
9232 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9233 Result.set(E);
9234 // Reset any previously evaluated state, otherwise evaluation below might
9235 // fail.
9236 // FIXME: Should we just re-use the previously evaluated value instead?
9237 *Lit = APValue();
9238 } else {
9239 assert(!Info.getLangOpts().CPlusPlus);
9240 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9241 ScopeKind::Block, Result);
9242 }
9243 // FIXME: Evaluating in place isn't always right. We should figure out how to
9244 // use appropriate evaluation context here, see
9245 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9246 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9247 *Lit = APValue();
9248 return false;
9249 }
9250 return true;
9251}
9252
9253bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9254 TypeInfoLValue TypeInfo;
9255
9256 if (!E->isPotentiallyEvaluated()) {
9257 if (E->isTypeOperand())
9258 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9259 else
9260 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9261 } else {
9262 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9263 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9264 << E->getExprOperand()->getType()
9265 << E->getExprOperand()->getSourceRange();
9266 }
9267
9268 if (!Visit(E->getExprOperand()))
9269 return false;
9270
9271 std::optional<DynamicType> DynType =
9273 if (!DynType)
9274 return false;
9275
9276 TypeInfo = TypeInfoLValue(
9277 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9278 }
9279
9280 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9281}
9282
9283bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9284 return Success(E->getGuidDecl());
9285}
9286
9287bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9288 // Handle static data members.
9289 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9290 VisitIgnoredBaseExpression(E->getBase());
9291 return VisitVarDecl(E, VD);
9292 }
9293
9294 // Handle static member functions.
9295 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9296 if (MD->isStatic()) {
9297 VisitIgnoredBaseExpression(E->getBase());
9298 return Success(MD);
9299 }
9300 }
9301
9302 // Handle non-static data members.
9303 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9304}
9305
9306bool LValueExprEvaluator::VisitExtVectorElementExpr(
9307 const ExtVectorElementExpr *E) {
9308 bool Success = true;
9309
9310 APValue Val;
9311 if (!Evaluate(Val, Info, E->getBase())) {
9312 if (!Info.noteFailure())
9313 return false;
9314 Success = false;
9315 }
9316
9318 E->getEncodedElementAccess(Indices);
9319 // FIXME: support accessing more than one element
9320 if (Indices.size() > 1)
9321 return false;
9322
9323 if (Success) {
9324 Result.setFrom(Info.Ctx, Val);
9325 QualType BaseType = E->getBase()->getType();
9326 if (E->isArrow())
9327 BaseType = BaseType->getPointeeType();
9328 const auto *VT = BaseType->castAs<VectorType>();
9329 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9330 VT->getNumElements(), Indices[0]);
9331 }
9332
9333 return Success;
9334}
9335
9336bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9337 if (E->getBase()->getType()->isSveVLSBuiltinType())
9338 return Error(E);
9339
9340 APSInt Index;
9341 bool Success = true;
9342
9343 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9344 APValue Val;
9345 if (!Evaluate(Val, Info, E->getBase())) {
9346 if (!Info.noteFailure())
9347 return false;
9348 Success = false;
9349 }
9350
9351 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9352 if (!Info.noteFailure())
9353 return false;
9354 Success = false;
9355 }
9356
9357 if (Success) {
9358 Result.setFrom(Info.Ctx, Val);
9359 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9360 VT->getNumElements(), Index.getExtValue());
9361 }
9362
9363 return Success;
9364 }
9365
9366 // C++17's rules require us to evaluate the LHS first, regardless of which
9367 // side is the base.
9368 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9369 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9370 : !EvaluateInteger(SubExpr, Index, Info)) {
9371 if (!Info.noteFailure())
9372 return false;
9373 Success = false;
9374 }
9375 }
9376
9377 return Success &&
9378 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9379}
9380
9381bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9382 bool Success = evaluatePointer(E->getSubExpr(), Result);
9383 // [C++26][expr.unary.op]
9384 // If the operand points to an object or function, the result
9385 // denotes that object or function; otherwise, the behavior is undefined.
9386 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9387 // immediately.
9389 return Success;
9391 E->getType())) ||
9392 Info.noteUndefinedBehavior();
9393}
9394
9395bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9396 if (!Visit(E->getSubExpr()))
9397 return false;
9398 // __real is a no-op on scalar lvalues.
9399 if (E->getSubExpr()->getType()->isAnyComplexType())
9400 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9401 return true;
9402}
9403
9404bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9405 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9406 "lvalue __imag__ on scalar?");
9407 if (!Visit(E->getSubExpr()))
9408 return false;
9409 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9410 return true;
9411}
9412
9413bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9414 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9415 return Error(UO);
9416
9417 if (!this->Visit(UO->getSubExpr()))
9418 return false;
9419
9420 return handleIncDec(
9421 this->Info, UO, Result, UO->getSubExpr()->getType(),
9422 UO->isIncrementOp(), nullptr);
9423}
9424
9425bool LValueExprEvaluator::VisitCompoundAssignOperator(
9426 const CompoundAssignOperator *CAO) {
9427 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9428 return Error(CAO);
9429
9430 bool Success = true;
9431
9432 // C++17 onwards require that we evaluate the RHS first.
9433 APValue RHS;
9434 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9435 if (!Info.noteFailure())
9436 return false;
9437 Success = false;
9438 }
9439
9440 // The overall lvalue result is the result of evaluating the LHS.
9441 if (!this->Visit(CAO->getLHS()) || !Success)
9442 return false;
9443
9445 this->Info, CAO,
9446 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9447 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9448}
9449
9450bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9451 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9452 return Error(E);
9453
9454 bool Success = true;
9455
9456 // C++17 onwards require that we evaluate the RHS first.
9457 APValue NewVal;
9458 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9459 if (!Info.noteFailure())
9460 return false;
9461 Success = false;
9462 }
9463
9464 if (!this->Visit(E->getLHS()) || !Success)
9465 return false;
9466
9467 if (Info.getLangOpts().CPlusPlus20 &&
9469 return false;
9470
9471 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9472 NewVal);
9473}
9474
9475//===----------------------------------------------------------------------===//
9476// Pointer Evaluation
9477//===----------------------------------------------------------------------===//
9478
9479/// Convenience function. LVal's base must be a call to an alloc_size
9480/// function.
9482 const LValue &LVal,
9483 llvm::APInt &Result) {
9484 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9485 "Can't get the size of a non alloc_size function");
9486 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9487 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9488 std::optional<llvm::APInt> Size =
9489 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9490 if (!Size)
9491 return false;
9492
9493 Result = std::move(*Size);
9494 return true;
9495}
9496
9497/// Attempts to evaluate the given LValueBase as the result of a call to
9498/// a function with the alloc_size attribute. If it was possible to do so, this
9499/// function will return true, make Result's Base point to said function call,
9500/// and mark Result's Base as invalid.
9502 LValue &Result) {
9503 if (Base.isNull())
9504 return false;
9505
9506 // Because we do no form of static analysis, we only support const variables.
9507 //
9508 // Additionally, we can't support parameters, nor can we support static
9509 // variables (in the latter case, use-before-assign isn't UB; in the former,
9510 // we have no clue what they'll be assigned to).
9511 const auto *VD =
9512 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9513 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9514 return false;
9515
9516 const Expr *Init = VD->getAnyInitializer();
9517 if (!Init || Init->getType().isNull())
9518 return false;
9519
9520 const Expr *E = Init->IgnoreParens();
9521 if (!tryUnwrapAllocSizeCall(E))
9522 return false;
9523
9524 // Store E instead of E unwrapped so that the type of the LValue's base is
9525 // what the user wanted.
9526 Result.setInvalid(E);
9527
9528 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9529 Result.addUnsizedArray(Info, E, Pointee);
9530 return true;
9531}
9532
9533namespace {
9534class PointerExprEvaluator
9535 : public ExprEvaluatorBase<PointerExprEvaluator> {
9536 LValue &Result;
9537 bool InvalidBaseOK;
9538
9539 bool Success(const Expr *E) {
9540 Result.set(E);
9541 return true;
9542 }
9543
9544 bool evaluateLValue(const Expr *E, LValue &Result) {
9545 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9546 }
9547
9548 bool evaluatePointer(const Expr *E, LValue &Result) {
9549 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9550 }
9551
9552 bool visitNonBuiltinCallExpr(const CallExpr *E);
9553public:
9554
9555 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9556 : ExprEvaluatorBaseTy(info), Result(Result),
9557 InvalidBaseOK(InvalidBaseOK) {}
9558
9559 bool Success(const APValue &V, const Expr *E) {
9560 Result.setFrom(Info.Ctx, V);
9561 return true;
9562 }
9563 bool ZeroInitialization(const Expr *E) {
9564 Result.setNull(Info.Ctx, E->getType());
9565 return true;
9566 }
9567
9568 bool VisitBinaryOperator(const BinaryOperator *E);
9569 bool VisitCastExpr(const CastExpr* E);
9570 bool VisitUnaryAddrOf(const UnaryOperator *E);
9571 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9572 { return Success(E); }
9573 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9575 return Success(E);
9576 if (Info.noteFailure())
9577 EvaluateIgnoredValue(Info, E->getSubExpr());
9578 return Error(E);
9579 }
9580 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9581 { return Success(E); }
9582 bool VisitCallExpr(const CallExpr *E);
9583 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9584 bool VisitBlockExpr(const BlockExpr *E) {
9585 if (!E->getBlockDecl()->hasCaptures())
9586 return Success(E);
9587 return Error(E);
9588 }
9589 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9590 auto DiagnoseInvalidUseOfThis = [&] {
9591 if (Info.getLangOpts().CPlusPlus11)
9592 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9593 else
9594 Info.FFDiag(E);
9595 };
9596
9597 // Can't look at 'this' when checking a potential constant expression.
9598 if (Info.checkingPotentialConstantExpression())
9599 return false;
9600
9601 bool IsExplicitLambda =
9602 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9603 if (!IsExplicitLambda) {
9604 if (!Info.CurrentCall->This) {
9605 DiagnoseInvalidUseOfThis();
9606 return false;
9607 }
9608
9609 Result = *Info.CurrentCall->This;
9610 }
9611
9612 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9613 // Ensure we actually have captured 'this'. If something was wrong with
9614 // 'this' capture, the error would have been previously reported.
9615 // Otherwise we can be inside of a default initialization of an object
9616 // declared by lambda's body, so no need to return false.
9617 if (!Info.CurrentCall->LambdaThisCaptureField) {
9618 if (IsExplicitLambda && !Info.CurrentCall->This) {
9619 DiagnoseInvalidUseOfThis();
9620 return false;
9621 }
9622
9623 return true;
9624 }
9625
9626 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9627 return HandleLambdaCapture(
9628 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9629 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9630 }
9631 return true;
9632 }
9633
9634 bool VisitCXXNewExpr(const CXXNewExpr *E);
9635
9636 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9637 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9638 APValue LValResult = E->EvaluateInContext(
9639 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9640 Result.setFrom(Info.Ctx, LValResult);
9641 return true;
9642 }
9643
9644 bool VisitEmbedExpr(const EmbedExpr *E) {
9645 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9646 return true;
9647 }
9648
9649 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9650 std::string ResultStr = E->ComputeName(Info.Ctx);
9651
9652 QualType CharTy = Info.Ctx.CharTy.withConst();
9653 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9654 ResultStr.size() + 1);
9655 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9656 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9657
9658 StringLiteral *SL =
9659 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9660 /*Pascal*/ false, ArrayTy, E->getLocation());
9661
9662 evaluateLValue(SL, Result);
9663 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9664 return true;
9665 }
9666
9667 // FIXME: Missing: @protocol, @selector
9668};
9669} // end anonymous namespace
9670
9671static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9672 bool InvalidBaseOK) {
9673 assert(!E->isValueDependent());
9674 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9675 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9676}
9677
9678bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9679 if (E->getOpcode() != BO_Add &&
9680 E->getOpcode() != BO_Sub)
9681 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9682
9683 const Expr *PExp = E->getLHS();
9684 const Expr *IExp = E->getRHS();
9685 if (IExp->getType()->isPointerType())
9686 std::swap(PExp, IExp);
9687
9688 bool EvalPtrOK = evaluatePointer(PExp, Result);
9689 if (!EvalPtrOK && !Info.noteFailure())
9690 return false;
9691
9692 llvm::APSInt Offset;
9693 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9694 return false;
9695
9696 if (E->getOpcode() == BO_Sub)
9697 negateAsSigned(Offset);
9698
9699 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9700 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9701}
9702
9703bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9704 return evaluateLValue(E->getSubExpr(), Result);
9705}
9706
9707// Is the provided decl 'std::source_location::current'?
9709 if (!FD)
9710 return false;
9711 const IdentifierInfo *FnII = FD->getIdentifier();
9712 if (!FnII || !FnII->isStr("current"))
9713 return false;
9714
9715 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9716 if (!RD)
9717 return false;
9718
9719 const IdentifierInfo *ClassII = RD->getIdentifier();
9720 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9721}
9722
9723bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9724 const Expr *SubExpr = E->getSubExpr();
9725
9726 switch (E->getCastKind()) {
9727 default:
9728 break;
9729 case CK_BitCast:
9730 case CK_CPointerToObjCPointerCast:
9731 case CK_BlockPointerToObjCPointerCast:
9732 case CK_AnyPointerToBlockPointerCast:
9733 case CK_AddressSpaceConversion:
9734 if (!Visit(SubExpr))
9735 return false;
9736 if (E->getType()->isFunctionPointerType() ||
9737 SubExpr->getType()->isFunctionPointerType()) {
9738 // Casting between two function pointer types, or between a function
9739 // pointer and an object pointer, is always a reinterpret_cast.
9740 CCEDiag(E, diag::note_constexpr_invalid_cast)
9741 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9742 << Info.Ctx.getLangOpts().CPlusPlus;
9743 Result.Designator.setInvalid();
9744 } else if (!E->getType()->isVoidPointerType()) {
9745 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9746 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9747 // also static_casts, but we disallow them as a resolution to DR1312.
9748 //
9749 // In some circumstances, we permit casting from void* to cv1 T*, when the
9750 // actual pointee object is actually a cv2 T.
9751 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9752 !Result.IsNullPtr;
9753 bool VoidPtrCastMaybeOK =
9754 Result.IsNullPtr ||
9755 (HasValidResult &&
9756 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9757 E->getType()->getPointeeType()));
9758 // 1. We'll allow it in std::allocator::allocate, and anything which that
9759 // calls.
9760 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9761 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9762 // We'll allow it in the body of std::source_location::current. GCC's
9763 // implementation had a parameter of type `void*`, and casts from
9764 // that back to `const __impl*` in its body.
9765 if (VoidPtrCastMaybeOK &&
9766 (Info.getStdAllocatorCaller("allocate") ||
9767 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9768 Info.getLangOpts().CPlusPlus26)) {
9769 // Permitted.
9770 } else {
9771 if (SubExpr->getType()->isVoidPointerType() &&
9772 Info.getLangOpts().CPlusPlus) {
9773 if (HasValidResult)
9774 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9775 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9776 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9777 << E->getType()->getPointeeType();
9778 else
9779 CCEDiag(E, diag::note_constexpr_invalid_cast)
9780 << diag::ConstexprInvalidCastKind::CastFrom
9781 << SubExpr->getType();
9782 } else
9783 CCEDiag(E, diag::note_constexpr_invalid_cast)
9784 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9785 << Info.Ctx.getLangOpts().CPlusPlus;
9786 Result.Designator.setInvalid();
9787 }
9788 }
9789 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9790 ZeroInitialization(E);
9791 return true;
9792
9793 case CK_DerivedToBase:
9794 case CK_UncheckedDerivedToBase:
9795 if (!evaluatePointer(E->getSubExpr(), Result))
9796 return false;
9797 if (!Result.Base && Result.Offset.isZero())
9798 return true;
9799
9800 // Now figure out the necessary offset to add to the base LV to get from
9801 // the derived class to the base class.
9802 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9803 castAs<PointerType>()->getPointeeType(),
9804 Result);
9805
9806 case CK_BaseToDerived:
9807 if (!Visit(E->getSubExpr()))
9808 return false;
9809 if (!Result.Base && Result.Offset.isZero())
9810 return true;
9811 return HandleBaseToDerivedCast(Info, E, Result);
9812
9813 case CK_Dynamic:
9814 if (!Visit(E->getSubExpr()))
9815 return false;
9817
9818 case CK_NullToPointer:
9819 VisitIgnoredValue(E->getSubExpr());
9820 return ZeroInitialization(E);
9821
9822 case CK_IntegralToPointer: {
9823 CCEDiag(E, diag::note_constexpr_invalid_cast)
9824 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9825 << Info.Ctx.getLangOpts().CPlusPlus;
9826
9827 APValue Value;
9828 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9829 break;
9830
9831 if (Value.isInt()) {
9832 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9833 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9834 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
9835 Result.setNull(Info.Ctx, E->getType());
9836 } else {
9837 Result.Base = (Expr *)nullptr;
9838 Result.InvalidBase = false;
9839 Result.Offset = CharUnits::fromQuantity(N);
9840 Result.Designator.setInvalid();
9841 Result.IsNullPtr = false;
9842 }
9843 return true;
9844 } else {
9845 // In rare instances, the value isn't an lvalue.
9846 // For example, when the value is the difference between the addresses of
9847 // two labels. We reject that as a constant expression because we can't
9848 // compute a valid offset to convert into a pointer.
9849 if (!Value.isLValue())
9850 return false;
9851
9852 // Cast is of an lvalue, no need to change value.
9853 Result.setFrom(Info.Ctx, Value);
9854 return true;
9855 }
9856 }
9857
9858 case CK_ArrayToPointerDecay: {
9859 if (SubExpr->isGLValue()) {
9860 if (!evaluateLValue(SubExpr, Result))
9861 return false;
9862 } else {
9863 APValue &Value = Info.CurrentCall->createTemporary(
9864 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9865 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9866 return false;
9867 }
9868 // The result is a pointer to the first element of the array.
9869 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9870 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9871 Result.addArray(Info, E, CAT);
9872 else
9873 Result.addUnsizedArray(Info, E, AT->getElementType());
9874 return true;
9875 }
9876
9877 case CK_FunctionToPointerDecay:
9878 return evaluateLValue(SubExpr, Result);
9879
9880 case CK_LValueToRValue: {
9881 LValue LVal;
9882 if (!evaluateLValue(E->getSubExpr(), LVal))
9883 return false;
9884
9885 APValue RVal;
9886 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9888 LVal, RVal))
9889 return InvalidBaseOK &&
9890 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9891 return Success(RVal, E);
9892 }
9893 }
9894
9895 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9896}
9897
9899 UnaryExprOrTypeTrait ExprKind) {
9900 // C++ [expr.alignof]p3:
9901 // When alignof is applied to a reference type, the result is the
9902 // alignment of the referenced type.
9903 T = T.getNonReferenceType();
9904
9905 if (T.getQualifiers().hasUnaligned())
9906 return CharUnits::One();
9907
9908 const bool AlignOfReturnsPreferred =
9909 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9910
9911 // __alignof is defined to return the preferred alignment.
9912 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9913 // as well.
9914 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9915 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9916 // alignof and _Alignof are defined to return the ABI alignment.
9917 else if (ExprKind == UETT_AlignOf)
9918 return Ctx.getTypeAlignInChars(T.getTypePtr());
9919 else
9920 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9921}
9922
9924 UnaryExprOrTypeTrait ExprKind) {
9925 E = E->IgnoreParens();
9926
9927 // The kinds of expressions that we have special-case logic here for
9928 // should be kept up to date with the special checks for those
9929 // expressions in Sema.
9930
9931 // alignof decl is always accepted, even if it doesn't make sense: we default
9932 // to 1 in those cases.
9933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9934 return Ctx.getDeclAlign(DRE->getDecl(),
9935 /*RefAsPointee*/ true);
9936
9937 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9938 return Ctx.getDeclAlign(ME->getMemberDecl(),
9939 /*RefAsPointee*/ true);
9940
9941 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9942}
9943
9944static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9945 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9946 return Info.Ctx.getDeclAlign(VD);
9947 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9948 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9949 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9950}
9951
9952/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9953/// __builtin_is_aligned and __builtin_assume_aligned.
9954static bool getAlignmentArgument(const Expr *E, QualType ForType,
9955 EvalInfo &Info, APSInt &Alignment) {
9956 if (!EvaluateInteger(E, Alignment, Info))
9957 return false;
9958 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9959 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9960 return false;
9961 }
9962 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9963 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9964 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9965 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9966 << MaxValue << ForType << Alignment;
9967 return false;
9968 }
9969 // Ensure both alignment and source value have the same bit width so that we
9970 // don't assert when computing the resulting value.
9971 APSInt ExtAlignment =
9972 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9973 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9974 "Alignment should not be changed by ext/trunc");
9975 Alignment = ExtAlignment;
9976 assert(Alignment.getBitWidth() == SrcWidth);
9977 return true;
9978}
9979
9980// To be clear: this happily visits unsupported builtins. Better name welcomed.
9981bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9982 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9983 return true;
9984
9985 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
9986 return false;
9987
9988 Result.setInvalid(E);
9989 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9990 Result.addUnsizedArray(Info, E, PointeeTy);
9991 return true;
9992}
9993
9994bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9995 if (!IsConstantEvaluatedBuiltinCall(E))
9996 return visitNonBuiltinCallExpr(E);
9997 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9998}
9999
10000// Determine if T is a character type for which we guarantee that
10001// sizeof(T) == 1.
10003 return T->isCharType() || T->isChar8Type();
10004}
10005
10006bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10007 unsigned BuiltinOp) {
10008 if (IsOpaqueConstantCall(E))
10009 return Success(E);
10010
10011 switch (BuiltinOp) {
10012 case Builtin::BIaddressof:
10013 case Builtin::BI__addressof:
10014 case Builtin::BI__builtin_addressof:
10015 return evaluateLValue(E->getArg(0), Result);
10016 case Builtin::BI__builtin_assume_aligned: {
10017 // We need to be very careful here because: if the pointer does not have the
10018 // asserted alignment, then the behavior is undefined, and undefined
10019 // behavior is non-constant.
10020 if (!evaluatePointer(E->getArg(0), Result))
10021 return false;
10022
10023 LValue OffsetResult(Result);
10024 APSInt Alignment;
10025 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10026 Alignment))
10027 return false;
10028 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10029
10030 if (E->getNumArgs() > 2) {
10031 APSInt Offset;
10032 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10033 return false;
10034
10035 int64_t AdditionalOffset = -Offset.getZExtValue();
10036 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10037 }
10038
10039 // If there is a base object, then it must have the correct alignment.
10040 if (OffsetResult.Base) {
10041 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10042
10043 if (BaseAlignment < Align) {
10044 Result.Designator.setInvalid();
10045 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10046 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10047 return false;
10048 }
10049 }
10050
10051 // The offset must also have the correct alignment.
10052 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10053 Result.Designator.setInvalid();
10054
10055 (OffsetResult.Base
10056 ? CCEDiag(E->getArg(0),
10057 diag::note_constexpr_baa_insufficient_alignment)
10058 << 1
10059 : CCEDiag(E->getArg(0),
10060 diag::note_constexpr_baa_value_insufficient_alignment))
10061 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10062 return false;
10063 }
10064
10065 return true;
10066 }
10067 case Builtin::BI__builtin_align_up:
10068 case Builtin::BI__builtin_align_down: {
10069 if (!evaluatePointer(E->getArg(0), Result))
10070 return false;
10071 APSInt Alignment;
10072 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10073 Alignment))
10074 return false;
10075 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10076 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10077 // For align_up/align_down, we can return the same value if the alignment
10078 // is known to be greater or equal to the requested value.
10079 if (PtrAlign.getQuantity() >= Alignment)
10080 return true;
10081
10082 // The alignment could be greater than the minimum at run-time, so we cannot
10083 // infer much about the resulting pointer value. One case is possible:
10084 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10085 // can infer the correct index if the requested alignment is smaller than
10086 // the base alignment so we can perform the computation on the offset.
10087 if (BaseAlignment.getQuantity() >= Alignment) {
10088 assert(Alignment.getBitWidth() <= 64 &&
10089 "Cannot handle > 64-bit address-space");
10090 uint64_t Alignment64 = Alignment.getZExtValue();
10091 CharUnits NewOffset = CharUnits::fromQuantity(
10092 BuiltinOp == Builtin::BI__builtin_align_down
10093 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10094 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10095 Result.adjustOffset(NewOffset - Result.Offset);
10096 // TODO: diagnose out-of-bounds values/only allow for arrays?
10097 return true;
10098 }
10099 // Otherwise, we cannot constant-evaluate the result.
10100 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10101 << Alignment;
10102 return false;
10103 }
10104 case Builtin::BI__builtin_operator_new:
10105 return HandleOperatorNewCall(Info, E, Result);
10106 case Builtin::BI__builtin_launder:
10107 return evaluatePointer(E->getArg(0), Result);
10108 case Builtin::BIstrchr:
10109 case Builtin::BIwcschr:
10110 case Builtin::BImemchr:
10111 case Builtin::BIwmemchr:
10112 if (Info.getLangOpts().CPlusPlus11)
10113 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10114 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10115 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10116 else
10117 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10118 [[fallthrough]];
10119 case Builtin::BI__builtin_strchr:
10120 case Builtin::BI__builtin_wcschr:
10121 case Builtin::BI__builtin_memchr:
10122 case Builtin::BI__builtin_char_memchr:
10123 case Builtin::BI__builtin_wmemchr: {
10124 if (!Visit(E->getArg(0)))
10125 return false;
10126 APSInt Desired;
10127 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10128 return false;
10129 uint64_t MaxLength = uint64_t(-1);
10130 if (BuiltinOp != Builtin::BIstrchr &&
10131 BuiltinOp != Builtin::BIwcschr &&
10132 BuiltinOp != Builtin::BI__builtin_strchr &&
10133 BuiltinOp != Builtin::BI__builtin_wcschr) {
10134 APSInt N;
10135 if (!EvaluateInteger(E->getArg(2), N, Info))
10136 return false;
10137 MaxLength = N.getZExtValue();
10138 }
10139 // We cannot find the value if there are no candidates to match against.
10140 if (MaxLength == 0u)
10141 return ZeroInitialization(E);
10142 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10143 Result.Designator.Invalid)
10144 return false;
10145 QualType CharTy = Result.Designator.getType(Info.Ctx);
10146 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10147 BuiltinOp == Builtin::BI__builtin_memchr;
10148 assert(IsRawByte ||
10149 Info.Ctx.hasSameUnqualifiedType(
10150 CharTy, E->getArg(0)->getType()->getPointeeType()));
10151 // Pointers to const void may point to objects of incomplete type.
10152 if (IsRawByte && CharTy->isIncompleteType()) {
10153 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10154 return false;
10155 }
10156 // Give up on byte-oriented matching against multibyte elements.
10157 // FIXME: We can compare the bytes in the correct order.
10158 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10159 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10160 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10161 return false;
10162 }
10163 // Figure out what value we're actually looking for (after converting to
10164 // the corresponding unsigned type if necessary).
10165 uint64_t DesiredVal;
10166 bool StopAtNull = false;
10167 switch (BuiltinOp) {
10168 case Builtin::BIstrchr:
10169 case Builtin::BI__builtin_strchr:
10170 // strchr compares directly to the passed integer, and therefore
10171 // always fails if given an int that is not a char.
10172 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10173 E->getArg(1)->getType(),
10174 Desired),
10175 Desired))
10176 return ZeroInitialization(E);
10177 StopAtNull = true;
10178 [[fallthrough]];
10179 case Builtin::BImemchr:
10180 case Builtin::BI__builtin_memchr:
10181 case Builtin::BI__builtin_char_memchr:
10182 // memchr compares by converting both sides to unsigned char. That's also
10183 // correct for strchr if we get this far (to cope with plain char being
10184 // unsigned in the strchr case).
10185 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10186 break;
10187
10188 case Builtin::BIwcschr:
10189 case Builtin::BI__builtin_wcschr:
10190 StopAtNull = true;
10191 [[fallthrough]];
10192 case Builtin::BIwmemchr:
10193 case Builtin::BI__builtin_wmemchr:
10194 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10195 DesiredVal = Desired.getZExtValue();
10196 break;
10197 }
10198
10199 for (; MaxLength; --MaxLength) {
10200 APValue Char;
10201 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10202 !Char.isInt())
10203 return false;
10204 if (Char.getInt().getZExtValue() == DesiredVal)
10205 return true;
10206 if (StopAtNull && !Char.getInt())
10207 break;
10208 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10209 return false;
10210 }
10211 // Not found: return nullptr.
10212 return ZeroInitialization(E);
10213 }
10214
10215 case Builtin::BImemcpy:
10216 case Builtin::BImemmove:
10217 case Builtin::BIwmemcpy:
10218 case Builtin::BIwmemmove:
10219 if (Info.getLangOpts().CPlusPlus11)
10220 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10221 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10222 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10223 else
10224 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10225 [[fallthrough]];
10226 case Builtin::BI__builtin_memcpy:
10227 case Builtin::BI__builtin_memmove:
10228 case Builtin::BI__builtin_wmemcpy:
10229 case Builtin::BI__builtin_wmemmove: {
10230 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10231 BuiltinOp == Builtin::BIwmemmove ||
10232 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10233 BuiltinOp == Builtin::BI__builtin_wmemmove;
10234 bool Move = BuiltinOp == Builtin::BImemmove ||
10235 BuiltinOp == Builtin::BIwmemmove ||
10236 BuiltinOp == Builtin::BI__builtin_memmove ||
10237 BuiltinOp == Builtin::BI__builtin_wmemmove;
10238
10239 // The result of mem* is the first argument.
10240 if (!Visit(E->getArg(0)))
10241 return false;
10242 LValue Dest = Result;
10243
10244 LValue Src;
10245 if (!EvaluatePointer(E->getArg(1), Src, Info))
10246 return false;
10247
10248 APSInt N;
10249 if (!EvaluateInteger(E->getArg(2), N, Info))
10250 return false;
10251 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10252
10253 // If the size is zero, we treat this as always being a valid no-op.
10254 // (Even if one of the src and dest pointers is null.)
10255 if (!N)
10256 return true;
10257
10258 // Otherwise, if either of the operands is null, we can't proceed. Don't
10259 // try to determine the type of the copied objects, because there aren't
10260 // any.
10261 if (!Src.Base || !Dest.Base) {
10262 APValue Val;
10263 (!Src.Base ? Src : Dest).moveInto(Val);
10264 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10265 << Move << WChar << !!Src.Base
10266 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10267 return false;
10268 }
10269 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10270 return false;
10271
10272 // We require that Src and Dest are both pointers to arrays of
10273 // trivially-copyable type. (For the wide version, the designator will be
10274 // invalid if the designated object is not a wchar_t.)
10275 QualType T = Dest.Designator.getType(Info.Ctx);
10276 QualType SrcT = Src.Designator.getType(Info.Ctx);
10277 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10278 // FIXME: Consider using our bit_cast implementation to support this.
10279 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10280 return false;
10281 }
10282 if (T->isIncompleteType()) {
10283 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10284 return false;
10285 }
10286 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10287 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10288 return false;
10289 }
10290
10291 // Figure out how many T's we're copying.
10292 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10293 if (TSize == 0)
10294 return false;
10295 if (!WChar) {
10296 uint64_t Remainder;
10297 llvm::APInt OrigN = N;
10298 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10299 if (Remainder) {
10300 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10301 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10302 << (unsigned)TSize;
10303 return false;
10304 }
10305 }
10306
10307 // Check that the copying will remain within the arrays, just so that we
10308 // can give a more meaningful diagnostic. This implicitly also checks that
10309 // N fits into 64 bits.
10310 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10311 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10312 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10313 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10314 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10315 << toString(N, 10, /*Signed*/false);
10316 return false;
10317 }
10318 uint64_t NElems = N.getZExtValue();
10319 uint64_t NBytes = NElems * TSize;
10320
10321 // Check for overlap.
10322 int Direction = 1;
10323 if (HasSameBase(Src, Dest)) {
10324 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10325 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10326 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10327 // Dest is inside the source region.
10328 if (!Move) {
10329 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10330 return false;
10331 }
10332 // For memmove and friends, copy backwards.
10333 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10334 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10335 return false;
10336 Direction = -1;
10337 } else if (!Move && SrcOffset >= DestOffset &&
10338 SrcOffset - DestOffset < NBytes) {
10339 // Src is inside the destination region for memcpy: invalid.
10340 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10341 return false;
10342 }
10343 }
10344
10345 while (true) {
10346 APValue Val;
10347 // FIXME: Set WantObjectRepresentation to true if we're copying a
10348 // char-like type?
10349 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10350 !handleAssignment(Info, E, Dest, T, Val))
10351 return false;
10352 // Do not iterate past the last element; if we're copying backwards, that
10353 // might take us off the start of the array.
10354 if (--NElems == 0)
10355 return true;
10356 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10357 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10358 return false;
10359 }
10360 }
10361
10362 default:
10363 return false;
10364 }
10365}
10366
10367static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10368 APValue &Result, const InitListExpr *ILE,
10369 QualType AllocType);
10370static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10371 APValue &Result,
10372 const CXXConstructExpr *CCE,
10373 QualType AllocType);
10374
10375bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10376 if (!Info.getLangOpts().CPlusPlus20)
10377 Info.CCEDiag(E, diag::note_constexpr_new);
10378
10379 // We cannot speculatively evaluate a delete expression.
10380 if (Info.SpeculativeEvaluationDepth)
10381 return false;
10382
10383 FunctionDecl *OperatorNew = E->getOperatorNew();
10384 QualType AllocType = E->getAllocatedType();
10385 QualType TargetType = AllocType;
10386
10387 bool IsNothrow = false;
10388 bool IsPlacement = false;
10389
10390 if (E->getNumPlacementArgs() == 1 &&
10391 E->getPlacementArg(0)->getType()->isNothrowT()) {
10392 // The only new-placement list we support is of the form (std::nothrow).
10393 //
10394 // FIXME: There is no restriction on this, but it's not clear that any
10395 // other form makes any sense. We get here for cases such as:
10396 //
10397 // new (std::align_val_t{N}) X(int)
10398 //
10399 // (which should presumably be valid only if N is a multiple of
10400 // alignof(int), and in any case can't be deallocated unless N is
10401 // alignof(X) and X has new-extended alignment).
10402 LValue Nothrow;
10403 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10404 return false;
10405 IsNothrow = true;
10406 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10407 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10408 (Info.CurrentCall->CanEvalMSConstexpr &&
10409 OperatorNew->hasAttr<MSConstexprAttr>())) {
10410 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10411 return false;
10412 if (Result.Designator.Invalid)
10413 return false;
10414 TargetType = E->getPlacementArg(0)->getType();
10415 IsPlacement = true;
10416 } else {
10417 Info.FFDiag(E, diag::note_constexpr_new_placement)
10418 << /*C++26 feature*/ 1 << E->getSourceRange();
10419 return false;
10420 }
10421 } else if (E->getNumPlacementArgs()) {
10422 Info.FFDiag(E, diag::note_constexpr_new_placement)
10423 << /*Unsupported*/ 0 << E->getSourceRange();
10424 return false;
10425 } else if (!OperatorNew
10426 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10427 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10428 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10429 return false;
10430 }
10431
10432 const Expr *Init = E->getInitializer();
10433 const InitListExpr *ResizedArrayILE = nullptr;
10434 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10435 bool ValueInit = false;
10436
10437 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10438 const Expr *Stripped = *ArraySize;
10439 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10440 Stripped = ICE->getSubExpr())
10441 if (ICE->getCastKind() != CK_NoOp &&
10442 ICE->getCastKind() != CK_IntegralCast)
10443 break;
10444
10445 llvm::APSInt ArrayBound;
10446 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10447 return false;
10448
10449 // C++ [expr.new]p9:
10450 // The expression is erroneous if:
10451 // -- [...] its value before converting to size_t [or] applying the
10452 // second standard conversion sequence is less than zero
10453 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10454 if (IsNothrow)
10455 return ZeroInitialization(E);
10456
10457 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10458 << ArrayBound << (*ArraySize)->getSourceRange();
10459 return false;
10460 }
10461
10462 // -- its value is such that the size of the allocated object would
10463 // exceed the implementation-defined limit
10464 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10466 Info.Ctx, AllocType, ArrayBound),
10467 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10468 if (IsNothrow)
10469 return ZeroInitialization(E);
10470 return false;
10471 }
10472
10473 // -- the new-initializer is a braced-init-list and the number of
10474 // array elements for which initializers are provided [...]
10475 // exceeds the number of elements to initialize
10476 if (!Init) {
10477 // No initialization is performed.
10478 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10480 ValueInit = true;
10481 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10482 ResizedArrayCCE = CCE;
10483 } else {
10484 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10485 assert(CAT && "unexpected type for array initializer");
10486
10487 unsigned Bits =
10488 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10489 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10490 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10491 if (InitBound.ugt(AllocBound)) {
10492 if (IsNothrow)
10493 return ZeroInitialization(E);
10494
10495 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10496 << toString(AllocBound, 10, /*Signed=*/false)
10497 << toString(InitBound, 10, /*Signed=*/false)
10498 << (*ArraySize)->getSourceRange();
10499 return false;
10500 }
10501
10502 // If the sizes differ, we must have an initializer list, and we need
10503 // special handling for this case when we initialize.
10504 if (InitBound != AllocBound)
10505 ResizedArrayILE = cast<InitListExpr>(Init);
10506 }
10507
10508 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10509 ArraySizeModifier::Normal, 0);
10510 } else {
10511 assert(!AllocType->isArrayType() &&
10512 "array allocation with non-array new");
10513 }
10514
10515 APValue *Val;
10516 if (IsPlacement) {
10518 struct FindObjectHandler {
10519 EvalInfo &Info;
10520 const Expr *E;
10521 QualType AllocType;
10522 const AccessKinds AccessKind;
10523 APValue *Value;
10524
10525 typedef bool result_type;
10526 bool failed() { return false; }
10527 bool checkConst(QualType QT) {
10528 if (QT.isConstQualified()) {
10529 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10530 return false;
10531 }
10532 return true;
10533 }
10534 bool found(APValue &Subobj, QualType SubobjType) {
10535 if (!checkConst(SubobjType))
10536 return false;
10537 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10538 // old name of the object to be used to name the new object.
10539 unsigned SubobjectSize = 1;
10540 unsigned AllocSize = 1;
10541 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10542 AllocSize = CAT->getZExtSize();
10543 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10544 SubobjectSize = CAT->getZExtSize();
10545 if (SubobjectSize < AllocSize ||
10546 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10547 Info.Ctx.getBaseElementType(AllocType))) {
10548 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10549 << SubobjType << AllocType;
10550 return false;
10551 }
10552 Value = &Subobj;
10553 return true;
10554 }
10555 bool found(APSInt &Value, QualType SubobjType) {
10556 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10557 return false;
10558 }
10559 bool found(APFloat &Value, QualType SubobjType) {
10560 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10561 return false;
10562 }
10563 } Handler = {Info, E, AllocType, AK, nullptr};
10564
10565 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10566 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10567 return false;
10568
10569 Val = Handler.Value;
10570
10571 // [basic.life]p1:
10572 // The lifetime of an object o of type T ends when [...] the storage
10573 // which the object occupies is [...] reused by an object that is not
10574 // nested within o (6.6.2).
10575 *Val = APValue();
10576 } else {
10577 // Perform the allocation and obtain a pointer to the resulting object.
10578 Val = Info.createHeapAlloc(E, AllocType, Result);
10579 if (!Val)
10580 return false;
10581 }
10582
10583 if (ValueInit) {
10584 ImplicitValueInitExpr VIE(AllocType);
10585 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10586 return false;
10587 } else if (ResizedArrayILE) {
10588 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10589 AllocType))
10590 return false;
10591 } else if (ResizedArrayCCE) {
10592 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10593 AllocType))
10594 return false;
10595 } else if (Init) {
10596 if (!EvaluateInPlace(*Val, Info, Result, Init))
10597 return false;
10598 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10599 return false;
10600 }
10601
10602 // Array new returns a pointer to the first element, not a pointer to the
10603 // array.
10604 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10605 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10606
10607 return true;
10608}
10609//===----------------------------------------------------------------------===//
10610// Member Pointer Evaluation
10611//===----------------------------------------------------------------------===//
10612
10613namespace {
10614class MemberPointerExprEvaluator
10615 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10616 MemberPtr &Result;
10617
10618 bool Success(const ValueDecl *D) {
10619 Result = MemberPtr(D);
10620 return true;
10621 }
10622public:
10623
10624 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10625 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10626
10627 bool Success(const APValue &V, const Expr *E) {
10628 Result.setFrom(V);
10629 return true;
10630 }
10631 bool ZeroInitialization(const Expr *E) {
10632 return Success((const ValueDecl*)nullptr);
10633 }
10634
10635 bool VisitCastExpr(const CastExpr *E);
10636 bool VisitUnaryAddrOf(const UnaryOperator *E);
10637};
10638} // end anonymous namespace
10639
10640static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10641 EvalInfo &Info) {
10642 assert(!E->isValueDependent());
10643 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10644 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10645}
10646
10647bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10648 switch (E->getCastKind()) {
10649 default:
10650 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10651
10652 case CK_NullToMemberPointer:
10653 VisitIgnoredValue(E->getSubExpr());
10654 return ZeroInitialization(E);
10655
10656 case CK_BaseToDerivedMemberPointer: {
10657 if (!Visit(E->getSubExpr()))
10658 return false;
10659 if (E->path_empty())
10660 return true;
10661 // Base-to-derived member pointer casts store the path in derived-to-base
10662 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10663 // the wrong end of the derived->base arc, so stagger the path by one class.
10664 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10665 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10666 PathI != PathE; ++PathI) {
10667 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10668 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10669 if (!Result.castToDerived(Derived))
10670 return Error(E);
10671 }
10672 if (!Result.castToDerived(E->getType()
10673 ->castAs<MemberPointerType>()
10674 ->getMostRecentCXXRecordDecl()))
10675 return Error(E);
10676 return true;
10677 }
10678
10679 case CK_DerivedToBaseMemberPointer:
10680 if (!Visit(E->getSubExpr()))
10681 return false;
10682 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10683 PathE = E->path_end(); PathI != PathE; ++PathI) {
10684 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10685 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10686 if (!Result.castToBase(Base))
10687 return Error(E);
10688 }
10689 return true;
10690 }
10691}
10692
10693bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10694 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10695 // member can be formed.
10696 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10697}
10698
10699//===----------------------------------------------------------------------===//
10700// Record Evaluation
10701//===----------------------------------------------------------------------===//
10702
10703namespace {
10704 class RecordExprEvaluator
10705 : public ExprEvaluatorBase<RecordExprEvaluator> {
10706 const LValue &This;
10707 APValue &Result;
10708 public:
10709
10710 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10711 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10712
10713 bool Success(const APValue &V, const Expr *E) {
10714 Result = V;
10715 return true;
10716 }
10717 bool ZeroInitialization(const Expr *E) {
10718 return ZeroInitialization(E, E->getType());
10719 }
10720 bool ZeroInitialization(const Expr *E, QualType T);
10721
10722 bool VisitCallExpr(const CallExpr *E) {
10723 return handleCallExpr(E, Result, &This);
10724 }
10725 bool VisitCastExpr(const CastExpr *E);
10726 bool VisitInitListExpr(const InitListExpr *E);
10727 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10728 return VisitCXXConstructExpr(E, E->getType());
10729 }
10730 bool VisitLambdaExpr(const LambdaExpr *E);
10731 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10732 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10733 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10734 bool VisitBinCmp(const BinaryOperator *E);
10735 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10736 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10737 ArrayRef<Expr *> Args);
10738 };
10739}
10740
10741/// Perform zero-initialization on an object of non-union class type.
10742/// C++11 [dcl.init]p5:
10743/// To zero-initialize an object or reference of type T means:
10744/// [...]
10745/// -- if T is a (possibly cv-qualified) non-union class type,
10746/// each non-static data member and each base-class subobject is
10747/// zero-initialized
10748static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10749 const RecordDecl *RD,
10750 const LValue &This, APValue &Result) {
10751 assert(!RD->isUnion() && "Expected non-union class type");
10752 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10753 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10754 std::distance(RD->field_begin(), RD->field_end()));
10755
10756 if (RD->isInvalidDecl()) return false;
10757 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10758
10759 if (CD) {
10760 unsigned Index = 0;
10762 End = CD->bases_end(); I != End; ++I, ++Index) {
10763 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10764 LValue Subobject = This;
10765 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10766 return false;
10767 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10768 Result.getStructBase(Index)))
10769 return false;
10770 }
10771 }
10772
10773 for (const auto *I : RD->fields()) {
10774 // -- if T is a reference type, no initialization is performed.
10775 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10776 continue;
10777
10778 LValue Subobject = This;
10779 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10780 return false;
10781
10782 ImplicitValueInitExpr VIE(I->getType());
10783 if (!EvaluateInPlace(
10784 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10785 return false;
10786 }
10787
10788 return true;
10789}
10790
10791bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10792 const auto *RD = T->castAsRecordDecl();
10793 if (RD->isInvalidDecl()) return false;
10794 if (RD->isUnion()) {
10795 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10796 // object's first non-static named data member is zero-initialized
10798 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10799 ++I;
10800 if (I == RD->field_end()) {
10801 Result = APValue((const FieldDecl*)nullptr);
10802 return true;
10803 }
10804
10805 LValue Subobject = This;
10806 if (!HandleLValueMember(Info, E, Subobject, *I))
10807 return false;
10808 Result = APValue(*I);
10809 ImplicitValueInitExpr VIE(I->getType());
10810 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10811 }
10812
10813 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10814 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10815 return false;
10816 }
10817
10818 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10819}
10820
10821bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10822 switch (E->getCastKind()) {
10823 default:
10824 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10825
10826 case CK_ConstructorConversion:
10827 return Visit(E->getSubExpr());
10828
10829 case CK_DerivedToBase:
10830 case CK_UncheckedDerivedToBase: {
10831 APValue DerivedObject;
10832 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10833 return false;
10834 if (!DerivedObject.isStruct())
10835 return Error(E->getSubExpr());
10836
10837 // Derived-to-base rvalue conversion: just slice off the derived part.
10838 APValue *Value = &DerivedObject;
10839 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10840 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10841 PathE = E->path_end(); PathI != PathE; ++PathI) {
10842 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10843 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10844 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10845 RD = Base;
10846 }
10847 Result = *Value;
10848 return true;
10849 }
10850 }
10851}
10852
10853bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10854 if (E->isTransparent())
10855 return Visit(E->getInit(0));
10856 return VisitCXXParenListOrInitListExpr(E, E->inits());
10857}
10858
10859bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10860 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10861 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
10862 if (RD->isInvalidDecl()) return false;
10863 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10864 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10865
10866 EvalInfo::EvaluatingConstructorRAII EvalObj(
10867 Info,
10868 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10869 CXXRD && CXXRD->getNumBases());
10870
10871 if (RD->isUnion()) {
10872 const FieldDecl *Field;
10873 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10874 Field = ILE->getInitializedFieldInUnion();
10875 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10876 Field = PLIE->getInitializedFieldInUnion();
10877 } else {
10878 llvm_unreachable(
10879 "Expression is neither an init list nor a C++ paren list");
10880 }
10881
10882 Result = APValue(Field);
10883 if (!Field)
10884 return true;
10885
10886 // If the initializer list for a union does not contain any elements, the
10887 // first element of the union is value-initialized.
10888 // FIXME: The element should be initialized from an initializer list.
10889 // Is this difference ever observable for initializer lists which
10890 // we don't build?
10891 ImplicitValueInitExpr VIE(Field->getType());
10892 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10893
10894 LValue Subobject = This;
10895 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10896 return false;
10897
10898 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10899 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10900 isa<CXXDefaultInitExpr>(InitExpr));
10901
10902 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10903 if (Field->isBitField())
10904 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10905 Field);
10906 return true;
10907 }
10908
10909 return false;
10910 }
10911
10912 if (!Result.hasValue())
10913 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10914 std::distance(RD->field_begin(), RD->field_end()));
10915 unsigned ElementNo = 0;
10916 bool Success = true;
10917
10918 // Initialize base classes.
10919 if (CXXRD && CXXRD->getNumBases()) {
10920 for (const auto &Base : CXXRD->bases()) {
10921 assert(ElementNo < Args.size() && "missing init for base class");
10922 const Expr *Init = Args[ElementNo];
10923
10924 LValue Subobject = This;
10925 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10926 return false;
10927
10928 APValue &FieldVal = Result.getStructBase(ElementNo);
10929 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10930 if (!Info.noteFailure())
10931 return false;
10932 Success = false;
10933 }
10934 ++ElementNo;
10935 }
10936
10937 EvalObj.finishedConstructingBases();
10938 }
10939
10940 // Initialize members.
10941 for (const auto *Field : RD->fields()) {
10942 // Anonymous bit-fields are not considered members of the class for
10943 // purposes of aggregate initialization.
10944 if (Field->isUnnamedBitField())
10945 continue;
10946
10947 LValue Subobject = This;
10948
10949 bool HaveInit = ElementNo < Args.size();
10950
10951 // FIXME: Diagnostics here should point to the end of the initializer
10952 // list, not the start.
10953 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10954 Subobject, Field, &Layout))
10955 return false;
10956
10957 // Perform an implicit value-initialization for members beyond the end of
10958 // the initializer list.
10959 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10960 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10961
10962 if (Field->getType()->isIncompleteArrayType()) {
10963 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10964 if (!CAT->isZeroSize()) {
10965 // Bail out for now. This might sort of "work", but the rest of the
10966 // code isn't really prepared to handle it.
10967 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10968 return false;
10969 }
10970 }
10971 }
10972
10973 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10974 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10976
10977 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10978 if (Field->getType()->isReferenceType()) {
10979 LValue Result;
10981 FieldVal)) {
10982 if (!Info.noteFailure())
10983 return false;
10984 Success = false;
10985 }
10986 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10987 (Field->isBitField() &&
10988 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
10989 if (!Info.noteFailure())
10990 return false;
10991 Success = false;
10992 }
10993 }
10994
10995 EvalObj.finishedConstructingFields();
10996
10997 return Success;
10998}
10999
11000bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11001 QualType T) {
11002 // Note that E's type is not necessarily the type of our class here; we might
11003 // be initializing an array element instead.
11004 const CXXConstructorDecl *FD = E->getConstructor();
11005 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11006
11007 bool ZeroInit = E->requiresZeroInitialization();
11008 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11009 if (ZeroInit)
11010 return ZeroInitialization(E, T);
11011
11013 }
11014
11015 const FunctionDecl *Definition = nullptr;
11016 auto Body = FD->getBody(Definition);
11017
11018 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11019 return false;
11020
11021 // Avoid materializing a temporary for an elidable copy/move constructor.
11022 if (E->isElidable() && !ZeroInit) {
11023 // FIXME: This only handles the simplest case, where the source object
11024 // is passed directly as the first argument to the constructor.
11025 // This should also handle stepping though implicit casts and
11026 // and conversion sequences which involve two steps, with a
11027 // conversion operator followed by a converting constructor.
11028 const Expr *SrcObj = E->getArg(0);
11029 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11030 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11031 if (const MaterializeTemporaryExpr *ME =
11032 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11033 return Visit(ME->getSubExpr());
11034 }
11035
11036 if (ZeroInit && !ZeroInitialization(E, T))
11037 return false;
11038
11039 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11040 return HandleConstructorCall(E, This, Args,
11042 Result);
11043}
11044
11045bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11046 const CXXInheritedCtorInitExpr *E) {
11047 if (!Info.CurrentCall) {
11048 assert(Info.checkingPotentialConstantExpression());
11049 return false;
11050 }
11051
11052 const CXXConstructorDecl *FD = E->getConstructor();
11053 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11054 return false;
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 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11064 Result);
11065}
11066
11067bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11068 const CXXStdInitializerListExpr *E) {
11069 const ConstantArrayType *ArrayType =
11070 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11071
11072 LValue Array;
11073 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11074 return false;
11075
11076 assert(ArrayType && "unexpected type for array initializer");
11077
11078 // Get a pointer to the first element of the array.
11079 Array.addArray(Info, E, ArrayType);
11080
11081 // FIXME: What if the initializer_list type has base classes, etc?
11082 Result = APValue(APValue::UninitStruct(), 0, 2);
11083 Array.moveInto(Result.getStructField(0));
11084
11085 auto *Record = E->getType()->castAsRecordDecl();
11086 RecordDecl::field_iterator Field = Record->field_begin();
11087 assert(Field != Record->field_end() &&
11088 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11089 ArrayType->getElementType()) &&
11090 "Expected std::initializer_list first field to be const E *");
11091 ++Field;
11092 assert(Field != Record->field_end() &&
11093 "Expected std::initializer_list to have two fields");
11094
11095 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11096 // Length.
11097 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11098 } else {
11099 // End pointer.
11100 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11101 ArrayType->getElementType()) &&
11102 "Expected std::initializer_list second field to be const E *");
11103 if (!HandleLValueArrayAdjustment(Info, E, Array,
11104 ArrayType->getElementType(),
11105 ArrayType->getZExtSize()))
11106 return false;
11107 Array.moveInto(Result.getStructField(1));
11108 }
11109
11110 assert(++Field == Record->field_end() &&
11111 "Expected std::initializer_list to only have two fields");
11112
11113 return true;
11114}
11115
11116bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11117 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11118 if (ClosureClass->isInvalidDecl())
11119 return false;
11120
11121 const size_t NumFields =
11122 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11123
11124 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11125 E->capture_init_end()) &&
11126 "The number of lambda capture initializers should equal the number of "
11127 "fields within the closure type");
11128
11129 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11130 // Iterate through all the lambda's closure object's fields and initialize
11131 // them.
11132 auto *CaptureInitIt = E->capture_init_begin();
11133 bool Success = true;
11134 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11135 for (const auto *Field : ClosureClass->fields()) {
11136 assert(CaptureInitIt != E->capture_init_end());
11137 // Get the initializer for this field
11138 Expr *const CurFieldInit = *CaptureInitIt++;
11139
11140 // If there is no initializer, either this is a VLA or an error has
11141 // occurred.
11142 if (!CurFieldInit || CurFieldInit->containsErrors())
11143 return Error(E);
11144
11145 LValue Subobject = This;
11146
11147 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11148 return false;
11149
11150 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11151 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11152 if (!Info.keepEvaluatingAfterFailure())
11153 return false;
11154 Success = false;
11155 }
11156 }
11157 return Success;
11158}
11159
11160static bool EvaluateRecord(const Expr *E, const LValue &This,
11161 APValue &Result, EvalInfo &Info) {
11162 assert(!E->isValueDependent());
11163 assert(E->isPRValue() && E->getType()->isRecordType() &&
11164 "can't evaluate expression as a record rvalue");
11165 return RecordExprEvaluator(Info, This, Result).Visit(E);
11166}
11167
11168//===----------------------------------------------------------------------===//
11169// Temporary Evaluation
11170//
11171// Temporaries are represented in the AST as rvalues, but generally behave like
11172// lvalues. The full-object of which the temporary is a subobject is implicitly
11173// materialized so that a reference can bind to it.
11174//===----------------------------------------------------------------------===//
11175namespace {
11176class TemporaryExprEvaluator
11177 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11178public:
11179 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11180 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11181
11182 /// Visit an expression which constructs the value of this temporary.
11183 bool VisitConstructExpr(const Expr *E) {
11184 APValue &Value = Info.CurrentCall->createTemporary(
11185 E, E->getType(), ScopeKind::FullExpression, Result);
11186 return EvaluateInPlace(Value, Info, Result, E);
11187 }
11188
11189 bool VisitCastExpr(const CastExpr *E) {
11190 switch (E->getCastKind()) {
11191 default:
11192 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11193
11194 case CK_ConstructorConversion:
11195 return VisitConstructExpr(E->getSubExpr());
11196 }
11197 }
11198 bool VisitInitListExpr(const InitListExpr *E) {
11199 return VisitConstructExpr(E);
11200 }
11201 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11202 return VisitConstructExpr(E);
11203 }
11204 bool VisitCallExpr(const CallExpr *E) {
11205 return VisitConstructExpr(E);
11206 }
11207 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11208 return VisitConstructExpr(E);
11209 }
11210 bool VisitLambdaExpr(const LambdaExpr *E) {
11211 return VisitConstructExpr(E);
11212 }
11213};
11214} // end anonymous namespace
11215
11216/// Evaluate an expression of record type as a temporary.
11217static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11218 assert(!E->isValueDependent());
11219 assert(E->isPRValue() && E->getType()->isRecordType());
11220 return TemporaryExprEvaluator(Info, Result).Visit(E);
11221}
11222
11223//===----------------------------------------------------------------------===//
11224// Vector Evaluation
11225//===----------------------------------------------------------------------===//
11226
11227namespace {
11228 class VectorExprEvaluator
11229 : public ExprEvaluatorBase<VectorExprEvaluator> {
11230 APValue &Result;
11231 public:
11232
11233 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11234 : ExprEvaluatorBaseTy(info), Result(Result) {}
11235
11236 bool Success(ArrayRef<APValue> V, const Expr *E) {
11237 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11238 // FIXME: remove this APValue copy.
11239 Result = APValue(V.data(), V.size());
11240 return true;
11241 }
11242 bool Success(const APValue &V, const Expr *E) {
11243 assert(V.isVector());
11244 Result = V;
11245 return true;
11246 }
11247 bool ZeroInitialization(const Expr *E);
11248
11249 bool VisitUnaryReal(const UnaryOperator *E)
11250 { return Visit(E->getSubExpr()); }
11251 bool VisitCastExpr(const CastExpr* E);
11252 bool VisitInitListExpr(const InitListExpr *E);
11253 bool VisitUnaryImag(const UnaryOperator *E);
11254 bool VisitBinaryOperator(const BinaryOperator *E);
11255 bool VisitUnaryOperator(const UnaryOperator *E);
11256 bool VisitCallExpr(const CallExpr *E);
11257 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11258 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11259
11260 // FIXME: Missing: conditional operator (for GNU
11261 // conditional select), ExtVectorElementExpr
11262 };
11263} // end anonymous namespace
11264
11265static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11266 assert(E->isPRValue() && E->getType()->isVectorType() &&
11267 "not a vector prvalue");
11268 return VectorExprEvaluator(Info, Result).Visit(E);
11269}
11270
11271static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11272 assert(Val.isVector() && "expected vector APValue");
11273 unsigned NumElts = Val.getVectorLength();
11274
11275 // Each element is one bit, so create an integer with NumElts bits.
11276 llvm::APInt Result(NumElts, 0);
11277
11278 for (unsigned I = 0; I < NumElts; ++I) {
11279 const APValue &Elt = Val.getVectorElt(I);
11280 assert(Elt.isInt() && "expected integer element in bool vector");
11281
11282 if (Elt.getInt().getBoolValue())
11283 Result.setBit(I);
11284 }
11285
11286 return Result;
11287}
11288
11289bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11290 const VectorType *VTy = E->getType()->castAs<VectorType>();
11291 unsigned NElts = VTy->getNumElements();
11292
11293 const Expr *SE = E->getSubExpr();
11294 QualType SETy = SE->getType();
11295
11296 switch (E->getCastKind()) {
11297 case CK_VectorSplat: {
11298 APValue Val = APValue();
11299 if (SETy->isIntegerType()) {
11300 APSInt IntResult;
11301 if (!EvaluateInteger(SE, IntResult, Info))
11302 return false;
11303 Val = APValue(std::move(IntResult));
11304 } else if (SETy->isRealFloatingType()) {
11305 APFloat FloatResult(0.0);
11306 if (!EvaluateFloat(SE, FloatResult, Info))
11307 return false;
11308 Val = APValue(std::move(FloatResult));
11309 } else {
11310 return Error(E);
11311 }
11312
11313 // Splat and create vector APValue.
11314 SmallVector<APValue, 4> Elts(NElts, Val);
11315 return Success(Elts, E);
11316 }
11317 case CK_BitCast: {
11318 APValue SVal;
11319 if (!Evaluate(SVal, Info, SE))
11320 return false;
11321
11322 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11323 // Give up if the input isn't an int, float, or vector. For example, we
11324 // reject "(v4i16)(intptr_t)&a".
11325 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11326 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11327 << Info.Ctx.getLangOpts().CPlusPlus;
11328 return false;
11329 }
11330
11331 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11332 return false;
11333
11334 return true;
11335 }
11336 case CK_HLSLVectorTruncation: {
11337 APValue Val;
11338 SmallVector<APValue, 4> Elements;
11339 if (!EvaluateVector(SE, Val, Info))
11340 return Error(E);
11341 for (unsigned I = 0; I < NElts; I++)
11342 Elements.push_back(Val.getVectorElt(I));
11343 return Success(Elements, E);
11344 }
11345 default:
11346 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11347 }
11348}
11349
11350bool
11351VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11352 const VectorType *VT = E->getType()->castAs<VectorType>();
11353 unsigned NumInits = E->getNumInits();
11354 unsigned NumElements = VT->getNumElements();
11355
11356 QualType EltTy = VT->getElementType();
11357 SmallVector<APValue, 4> Elements;
11358
11359 // MFloat8 type doesn't have constants and thus constant folding
11360 // is impossible.
11361 if (EltTy->isMFloat8Type())
11362 return false;
11363
11364 // The number of initializers can be less than the number of
11365 // vector elements. For OpenCL, this can be due to nested vector
11366 // initialization. For GCC compatibility, missing trailing elements
11367 // should be initialized with zeroes.
11368 unsigned CountInits = 0, CountElts = 0;
11369 while (CountElts < NumElements) {
11370 // Handle nested vector initialization.
11371 if (CountInits < NumInits
11372 && E->getInit(CountInits)->getType()->isVectorType()) {
11373 APValue v;
11374 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11375 return Error(E);
11376 unsigned vlen = v.getVectorLength();
11377 for (unsigned j = 0; j < vlen; j++)
11378 Elements.push_back(v.getVectorElt(j));
11379 CountElts += vlen;
11380 } else if (EltTy->isIntegerType()) {
11381 llvm::APSInt sInt(32);
11382 if (CountInits < NumInits) {
11383 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11384 return false;
11385 } else // trailing integer zero.
11386 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11387 Elements.push_back(APValue(sInt));
11388 CountElts++;
11389 } else {
11390 llvm::APFloat f(0.0);
11391 if (CountInits < NumInits) {
11392 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11393 return false;
11394 } else // trailing float zero.
11395 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11396 Elements.push_back(APValue(f));
11397 CountElts++;
11398 }
11399 CountInits++;
11400 }
11401 return Success(Elements, E);
11402}
11403
11404bool
11405VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11406 const auto *VT = E->getType()->castAs<VectorType>();
11407 QualType EltTy = VT->getElementType();
11408 APValue ZeroElement;
11409 if (EltTy->isIntegerType())
11410 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11411 else
11412 ZeroElement =
11413 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11414
11415 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11416 return Success(Elements, E);
11417}
11418
11419bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11420 VisitIgnoredValue(E->getSubExpr());
11421 return ZeroInitialization(E);
11422}
11423
11424bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11425 BinaryOperatorKind Op = E->getOpcode();
11426 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11427 "Operation not supported on vector types");
11428
11429 if (Op == BO_Comma)
11430 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11431
11432 Expr *LHS = E->getLHS();
11433 Expr *RHS = E->getRHS();
11434
11435 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11436 "Must both be vector types");
11437 // Checking JUST the types are the same would be fine, except shifts don't
11438 // need to have their types be the same (since you always shift by an int).
11439 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11440 E->getType()->castAs<VectorType>()->getNumElements() &&
11441 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11442 E->getType()->castAs<VectorType>()->getNumElements() &&
11443 "All operands must be the same size.");
11444
11445 APValue LHSValue;
11446 APValue RHSValue;
11447 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11448 if (!LHSOK && !Info.noteFailure())
11449 return false;
11450 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11451 return false;
11452
11453 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11454 return false;
11455
11456 return Success(LHSValue, E);
11457}
11458
11459static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11460 QualType ResultTy,
11462 APValue Elt) {
11463 switch (Op) {
11464 case UO_Plus:
11465 // Nothing to do here.
11466 return Elt;
11467 case UO_Minus:
11468 if (Elt.getKind() == APValue::Int) {
11469 Elt.getInt().negate();
11470 } else {
11471 assert(Elt.getKind() == APValue::Float &&
11472 "Vector can only be int or float type");
11473 Elt.getFloat().changeSign();
11474 }
11475 return Elt;
11476 case UO_Not:
11477 // This is only valid for integral types anyway, so we don't have to handle
11478 // float here.
11479 assert(Elt.getKind() == APValue::Int &&
11480 "Vector operator ~ can only be int");
11481 Elt.getInt().flipAllBits();
11482 return Elt;
11483 case UO_LNot: {
11484 if (Elt.getKind() == APValue::Int) {
11485 Elt.getInt() = !Elt.getInt();
11486 // operator ! on vectors returns -1 for 'truth', so negate it.
11487 Elt.getInt().negate();
11488 return Elt;
11489 }
11490 assert(Elt.getKind() == APValue::Float &&
11491 "Vector can only be int or float type");
11492 // Float types result in an int of the same size, but -1 for true, or 0 for
11493 // false.
11494 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11495 ResultTy->isUnsignedIntegerType()};
11496 if (Elt.getFloat().isZero())
11497 EltResult.setAllBits();
11498 else
11499 EltResult.clearAllBits();
11500
11501 return APValue{EltResult};
11502 }
11503 default:
11504 // FIXME: Implement the rest of the unary operators.
11505 return std::nullopt;
11506 }
11507}
11508
11509bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11510 Expr *SubExpr = E->getSubExpr();
11511 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11512 // This result element type differs in the case of negating a floating point
11513 // vector, since the result type is the a vector of the equivilant sized
11514 // integer.
11515 const QualType ResultEltTy = VD->getElementType();
11516 UnaryOperatorKind Op = E->getOpcode();
11517
11518 APValue SubExprValue;
11519 if (!Evaluate(SubExprValue, Info, SubExpr))
11520 return false;
11521
11522 // FIXME: This vector evaluator someday needs to be changed to be LValue
11523 // aware/keep LValue information around, rather than dealing with just vector
11524 // types directly. Until then, we cannot handle cases where the operand to
11525 // these unary operators is an LValue. The only case I've been able to see
11526 // cause this is operator++ assigning to a member expression (only valid in
11527 // altivec compilations) in C mode, so this shouldn't limit us too much.
11528 if (SubExprValue.isLValue())
11529 return false;
11530
11531 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11532 "Vector length doesn't match type?");
11533
11534 SmallVector<APValue, 4> ResultElements;
11535 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11536 std::optional<APValue> Elt = handleVectorUnaryOperator(
11537 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11538 if (!Elt)
11539 return false;
11540 ResultElements.push_back(*Elt);
11541 }
11542 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11543}
11544
11545static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11546 const Expr *E, QualType SourceTy,
11547 QualType DestTy, APValue const &Original,
11548 APValue &Result) {
11549 if (SourceTy->isIntegerType()) {
11550 if (DestTy->isRealFloatingType()) {
11551 Result = APValue(APFloat(0.0));
11552 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11553 DestTy, Result.getFloat());
11554 }
11555 if (DestTy->isIntegerType()) {
11556 Result = APValue(
11557 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11558 return true;
11559 }
11560 } else if (SourceTy->isRealFloatingType()) {
11561 if (DestTy->isRealFloatingType()) {
11562 Result = Original;
11563 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11564 Result.getFloat());
11565 }
11566 if (DestTy->isIntegerType()) {
11567 Result = APValue(APSInt());
11568 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11569 DestTy, Result.getInt());
11570 }
11571 }
11572
11573 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11574 << SourceTy << DestTy;
11575 return false;
11576}
11577
11578static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
11579 llvm::function_ref<APInt(const APSInt &)> PackFn) {
11580 APValue LHS, RHS;
11581 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
11582 !EvaluateAsRValue(Info, E->getArg(1), RHS))
11583 return false;
11584
11585 unsigned LHSVecLen = LHS.getVectorLength();
11586 unsigned RHSVecLen = RHS.getVectorLength();
11587
11588 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
11589 "pack builtin LHSVecLen must equal to RHSVecLen");
11590
11591 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
11592 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
11593
11594 const VectorType *DstVT = E->getType()->castAs<VectorType>();
11595 QualType DstElemTy = DstVT->getElementType();
11596 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
11597
11598 const unsigned SrcPerLane = 128 / SrcBits;
11599 const unsigned Lanes = LHSVecLen * SrcBits / 128;
11600
11602 Out.reserve(LHSVecLen + RHSVecLen);
11603
11604 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
11605 unsigned base = Lane * SrcPerLane;
11606 for (unsigned I = 0; I != SrcPerLane; ++I)
11607 Out.emplace_back(APValue(
11608 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
11609 for (unsigned I = 0; I != SrcPerLane; ++I)
11610 Out.emplace_back(APValue(
11611 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
11612 }
11613
11614 Result = APValue(Out.data(), Out.size());
11615 return true;
11616}
11617
11618static bool evalPshufBuiltin(EvalInfo &Info, const CallExpr *Call,
11619 bool IsShufHW, APValue &Out) {
11620 APValue Vec;
11621 APSInt Imm;
11622 if (!EvaluateAsRValue(Info, Call->getArg(0), Vec))
11623 return false;
11624 if (!EvaluateInteger(Call->getArg(1), Imm, Info))
11625 return false;
11626
11627 const auto *VT = Call->getType()->getAs<VectorType>();
11628 if (!VT)
11629 return false;
11630
11631 QualType ElemT = VT->getElementType();
11632 unsigned ElemBits = Info.Ctx.getTypeSize(ElemT);
11633 unsigned NumElts = VT->getNumElements();
11634
11635 unsigned LaneBits = 128u;
11636 unsigned LaneElts = LaneBits / ElemBits;
11637 if (!LaneElts || (NumElts % LaneElts) != 0)
11638 return false;
11639
11640 uint8_t Ctl = static_cast<uint8_t>(Imm.getZExtValue());
11641
11642 SmallVector<APValue, 32> ResultElements;
11643 ResultElements.reserve(NumElts);
11644
11645 for (unsigned Idx = 0; Idx != NumElts; Idx++) {
11646 unsigned LaneBase = (Idx / LaneElts) * LaneElts;
11647 unsigned LaneIdx = Idx % LaneElts;
11648 unsigned SrcIdx = Idx;
11649 unsigned Sel = (Ctl >> (2 * LaneIdx)) & 0x3;
11650
11651 if (ElemBits == 32) {
11652 SrcIdx = LaneBase + Sel;
11653 } else {
11654 constexpr unsigned HalfSize = 4;
11655 bool InHigh = LaneIdx >= HalfSize;
11656 if (!IsShufHW && !InHigh) {
11657 SrcIdx = LaneBase + Sel;
11658 } else if (IsShufHW && InHigh) {
11659 unsigned Rel = LaneIdx - HalfSize;
11660 Sel = (Ctl >> (2 * Rel)) & 0x3;
11661 SrcIdx = LaneBase + HalfSize + Sel;
11662 }
11663 }
11664
11665 ResultElements.push_back(Vec.getVectorElt(SrcIdx));
11666 }
11667
11668 Out = APValue(ResultElements.data(), ResultElements.size());
11669 return true;
11670}
11671
11672bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11673 if (!IsConstantEvaluatedBuiltinCall(E))
11674 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11675
11676 auto EvaluateBinOpExpr =
11677 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
11678 APValue SourceLHS, SourceRHS;
11679 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11680 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11681 return false;
11682
11683 auto *DestTy = E->getType()->castAs<VectorType>();
11684 QualType DestEltTy = DestTy->getElementType();
11685 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11686 unsigned SourceLen = SourceLHS.getVectorLength();
11687 SmallVector<APValue, 4> ResultElements;
11688 ResultElements.reserve(SourceLen);
11689
11690 if (SourceRHS.isInt()) {
11691 const APSInt &RHS = SourceRHS.getInt();
11692 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11693 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11694 ResultElements.push_back(
11695 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
11696 }
11697 } else {
11698 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11699 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11700 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
11701 ResultElements.push_back(
11702 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
11703 }
11704 }
11705 return Success(APValue(ResultElements.data(), SourceLen), E);
11706 };
11707
11708 switch (E->getBuiltinCallee()) {
11709 default:
11710 return false;
11711 case Builtin::BI__builtin_elementwise_popcount:
11712 case Builtin::BI__builtin_elementwise_bitreverse: {
11713 APValue Source;
11714 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11715 return false;
11716
11717 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11718 unsigned SourceLen = Source.getVectorLength();
11719 SmallVector<APValue, 4> ResultElements;
11720 ResultElements.reserve(SourceLen);
11721
11722 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11723 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11724 switch (E->getBuiltinCallee()) {
11725 case Builtin::BI__builtin_elementwise_popcount:
11726 ResultElements.push_back(APValue(
11727 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11728 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11729 break;
11730 case Builtin::BI__builtin_elementwise_bitreverse:
11731 ResultElements.push_back(
11732 APValue(APSInt(Elt.reverseBits(),
11733 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11734 break;
11735 }
11736 }
11737
11738 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11739 }
11740 case Builtin::BI__builtin_elementwise_abs: {
11741 APValue Source;
11742 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11743 return false;
11744
11745 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11746 unsigned SourceLen = Source.getVectorLength();
11747 SmallVector<APValue, 4> ResultElements;
11748 ResultElements.reserve(SourceLen);
11749
11750 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11751 APValue CurrentEle = Source.getVectorElt(EltNum);
11752 APValue Val = DestEltTy->isFloatingType()
11753 ? APValue(llvm::abs(CurrentEle.getFloat()))
11754 : APValue(APSInt(
11755 CurrentEle.getInt().abs(),
11756 DestEltTy->isUnsignedIntegerOrEnumerationType()));
11757 ResultElements.push_back(Val);
11758 }
11759
11760 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11761 }
11762
11763 case Builtin::BI__builtin_elementwise_add_sat:
11764 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11765 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
11766 });
11767
11768 case Builtin::BI__builtin_elementwise_sub_sat:
11769 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11770 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
11771 });
11772
11773 case clang::X86::BI__builtin_ia32_pavgb128:
11774 case clang::X86::BI__builtin_ia32_pavgw128:
11775 case clang::X86::BI__builtin_ia32_pavgb256:
11776 case clang::X86::BI__builtin_ia32_pavgw256:
11777 case clang::X86::BI__builtin_ia32_pavgb512:
11778 case clang::X86::BI__builtin_ia32_pavgw512:
11779 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
11780
11781 case clang::X86::BI__builtin_ia32_pmaddubsw128:
11782 case clang::X86::BI__builtin_ia32_pmaddubsw256:
11783 case clang::X86::BI__builtin_ia32_pmaddubsw512:
11784 case clang::X86::BI__builtin_ia32_pmaddwd128:
11785 case clang::X86::BI__builtin_ia32_pmaddwd256:
11786 case clang::X86::BI__builtin_ia32_pmaddwd512: {
11787 APValue SourceLHS, SourceRHS;
11788 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11789 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11790 return false;
11791
11792 auto *DestTy = E->getType()->castAs<VectorType>();
11793 QualType DestEltTy = DestTy->getElementType();
11794 unsigned SourceLen = SourceLHS.getVectorLength();
11795 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11796 SmallVector<APValue, 4> ResultElements;
11797 ResultElements.reserve(SourceLen / 2);
11798
11799 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
11800 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
11801 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
11802 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
11803 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
11804 unsigned BitWidth = 2 * LoLHS.getBitWidth();
11805
11806 switch (E->getBuiltinCallee()) {
11807 case clang::X86::BI__builtin_ia32_pmaddubsw128:
11808 case clang::X86::BI__builtin_ia32_pmaddubsw256:
11809 case clang::X86::BI__builtin_ia32_pmaddubsw512:
11810 ResultElements.push_back(APValue(
11811 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
11812 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
11813 DestUnsigned)));
11814 break;
11815 case clang::X86::BI__builtin_ia32_pmaddwd128:
11816 case clang::X86::BI__builtin_ia32_pmaddwd256:
11817 case clang::X86::BI__builtin_ia32_pmaddwd512:
11818 ResultElements.push_back(
11819 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
11820 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
11821 DestUnsigned)));
11822 break;
11823 }
11824 }
11825
11826 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11827 }
11828
11829 case clang::X86::BI__builtin_ia32_pmulhuw128:
11830 case clang::X86::BI__builtin_ia32_pmulhuw256:
11831 case clang::X86::BI__builtin_ia32_pmulhuw512:
11832 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
11833
11834 case clang::X86::BI__builtin_ia32_pmulhw128:
11835 case clang::X86::BI__builtin_ia32_pmulhw256:
11836 case clang::X86::BI__builtin_ia32_pmulhw512:
11837 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
11838
11839 case clang::X86::BI__builtin_ia32_psllv2di:
11840 case clang::X86::BI__builtin_ia32_psllv4di:
11841 case clang::X86::BI__builtin_ia32_psllv4si:
11842 case clang::X86::BI__builtin_ia32_psllv8di:
11843 case clang::X86::BI__builtin_ia32_psllv8hi:
11844 case clang::X86::BI__builtin_ia32_psllv8si:
11845 case clang::X86::BI__builtin_ia32_psllv16hi:
11846 case clang::X86::BI__builtin_ia32_psllv16si:
11847 case clang::X86::BI__builtin_ia32_psllv32hi:
11848 case clang::X86::BI__builtin_ia32_psllwi128:
11849 case clang::X86::BI__builtin_ia32_pslldi128:
11850 case clang::X86::BI__builtin_ia32_psllqi128:
11851 case clang::X86::BI__builtin_ia32_psllwi256:
11852 case clang::X86::BI__builtin_ia32_pslldi256:
11853 case clang::X86::BI__builtin_ia32_psllqi256:
11854 case clang::X86::BI__builtin_ia32_psllwi512:
11855 case clang::X86::BI__builtin_ia32_pslldi512:
11856 case clang::X86::BI__builtin_ia32_psllqi512:
11857 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11858 if (RHS.uge(LHS.getBitWidth())) {
11859 return APInt::getZero(LHS.getBitWidth());
11860 }
11861 return LHS.shl(RHS.getZExtValue());
11862 });
11863
11864 case clang::X86::BI__builtin_ia32_psrav4si:
11865 case clang::X86::BI__builtin_ia32_psrav8di:
11866 case clang::X86::BI__builtin_ia32_psrav8hi:
11867 case clang::X86::BI__builtin_ia32_psrav8si:
11868 case clang::X86::BI__builtin_ia32_psrav16hi:
11869 case clang::X86::BI__builtin_ia32_psrav16si:
11870 case clang::X86::BI__builtin_ia32_psrav32hi:
11871 case clang::X86::BI__builtin_ia32_psravq128:
11872 case clang::X86::BI__builtin_ia32_psravq256:
11873 case clang::X86::BI__builtin_ia32_psrawi128:
11874 case clang::X86::BI__builtin_ia32_psradi128:
11875 case clang::X86::BI__builtin_ia32_psraqi128:
11876 case clang::X86::BI__builtin_ia32_psrawi256:
11877 case clang::X86::BI__builtin_ia32_psradi256:
11878 case clang::X86::BI__builtin_ia32_psraqi256:
11879 case clang::X86::BI__builtin_ia32_psrawi512:
11880 case clang::X86::BI__builtin_ia32_psradi512:
11881 case clang::X86::BI__builtin_ia32_psraqi512:
11882 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11883 if (RHS.uge(LHS.getBitWidth())) {
11884 return LHS.ashr(LHS.getBitWidth() - 1);
11885 }
11886 return LHS.ashr(RHS.getZExtValue());
11887 });
11888
11889 case clang::X86::BI__builtin_ia32_psrlv2di:
11890 case clang::X86::BI__builtin_ia32_psrlv4di:
11891 case clang::X86::BI__builtin_ia32_psrlv4si:
11892 case clang::X86::BI__builtin_ia32_psrlv8di:
11893 case clang::X86::BI__builtin_ia32_psrlv8hi:
11894 case clang::X86::BI__builtin_ia32_psrlv8si:
11895 case clang::X86::BI__builtin_ia32_psrlv16hi:
11896 case clang::X86::BI__builtin_ia32_psrlv16si:
11897 case clang::X86::BI__builtin_ia32_psrlv32hi:
11898 case clang::X86::BI__builtin_ia32_psrlwi128:
11899 case clang::X86::BI__builtin_ia32_psrldi128:
11900 case clang::X86::BI__builtin_ia32_psrlqi128:
11901 case clang::X86::BI__builtin_ia32_psrlwi256:
11902 case clang::X86::BI__builtin_ia32_psrldi256:
11903 case clang::X86::BI__builtin_ia32_psrlqi256:
11904 case clang::X86::BI__builtin_ia32_psrlwi512:
11905 case clang::X86::BI__builtin_ia32_psrldi512:
11906 case clang::X86::BI__builtin_ia32_psrlqi512:
11907 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11908 if (RHS.uge(LHS.getBitWidth())) {
11909 return APInt::getZero(LHS.getBitWidth());
11910 }
11911 return LHS.lshr(RHS.getZExtValue());
11912 });
11913 case X86::BI__builtin_ia32_packsswb128:
11914 case X86::BI__builtin_ia32_packsswb256:
11915 case X86::BI__builtin_ia32_packsswb512:
11916 case X86::BI__builtin_ia32_packssdw128:
11917 case X86::BI__builtin_ia32_packssdw256:
11918 case X86::BI__builtin_ia32_packssdw512:
11919 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
11920 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
11921 });
11922 case X86::BI__builtin_ia32_packusdw128:
11923 case X86::BI__builtin_ia32_packusdw256:
11924 case X86::BI__builtin_ia32_packusdw512:
11925 case X86::BI__builtin_ia32_packuswb128:
11926 case X86::BI__builtin_ia32_packuswb256:
11927 case X86::BI__builtin_ia32_packuswb512:
11928 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
11929 unsigned DstBits = Src.getBitWidth() / 2;
11930 if (Src.isNegative())
11931 return APInt::getZero(DstBits);
11932 if (Src.isIntN(DstBits))
11933 return APInt((Src).trunc(DstBits));
11934 return APInt::getAllOnes(DstBits);
11935 });
11936 case clang::X86::BI__builtin_ia32_pmuldq128:
11937 case clang::X86::BI__builtin_ia32_pmuldq256:
11938 case clang::X86::BI__builtin_ia32_pmuldq512:
11939 case clang::X86::BI__builtin_ia32_pmuludq128:
11940 case clang::X86::BI__builtin_ia32_pmuludq256:
11941 case clang::X86::BI__builtin_ia32_pmuludq512: {
11942 APValue SourceLHS, SourceRHS;
11943 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11944 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11945 return false;
11946
11947 unsigned SourceLen = SourceLHS.getVectorLength();
11948 SmallVector<APValue, 4> ResultElements;
11949 ResultElements.reserve(SourceLen / 2);
11950
11951 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
11952 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11953 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11954
11955 switch (E->getBuiltinCallee()) {
11956 case clang::X86::BI__builtin_ia32_pmuludq128:
11957 case clang::X86::BI__builtin_ia32_pmuludq256:
11958 case clang::X86::BI__builtin_ia32_pmuludq512:
11959 ResultElements.push_back(
11960 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
11961 break;
11962 case clang::X86::BI__builtin_ia32_pmuldq128:
11963 case clang::X86::BI__builtin_ia32_pmuldq256:
11964 case clang::X86::BI__builtin_ia32_pmuldq512:
11965 ResultElements.push_back(
11966 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
11967 break;
11968 }
11969 }
11970
11971 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11972 }
11973 case clang::X86::BI__builtin_ia32_vprotbi:
11974 case clang::X86::BI__builtin_ia32_vprotdi:
11975 case clang::X86::BI__builtin_ia32_vprotqi:
11976 case clang::X86::BI__builtin_ia32_vprotwi:
11977 case clang::X86::BI__builtin_ia32_prold128:
11978 case clang::X86::BI__builtin_ia32_prold256:
11979 case clang::X86::BI__builtin_ia32_prold512:
11980 case clang::X86::BI__builtin_ia32_prolq128:
11981 case clang::X86::BI__builtin_ia32_prolq256:
11982 case clang::X86::BI__builtin_ia32_prolq512:
11983 return EvaluateBinOpExpr(
11984 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
11985
11986 case clang::X86::BI__builtin_ia32_prord128:
11987 case clang::X86::BI__builtin_ia32_prord256:
11988 case clang::X86::BI__builtin_ia32_prord512:
11989 case clang::X86::BI__builtin_ia32_prorq128:
11990 case clang::X86::BI__builtin_ia32_prorq256:
11991 case clang::X86::BI__builtin_ia32_prorq512:
11992 return EvaluateBinOpExpr(
11993 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
11994
11995 case Builtin::BI__builtin_elementwise_max:
11996 case Builtin::BI__builtin_elementwise_min: {
11997 APValue SourceLHS, SourceRHS;
11998 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11999 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12000 return false;
12001
12002 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12003
12004 if (!DestEltTy->isIntegerType())
12005 return false;
12006
12007 unsigned SourceLen = SourceLHS.getVectorLength();
12008 SmallVector<APValue, 4> ResultElements;
12009 ResultElements.reserve(SourceLen);
12010
12011 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12012 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12013 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12014 switch (E->getBuiltinCallee()) {
12015 case Builtin::BI__builtin_elementwise_max:
12016 ResultElements.push_back(
12017 APValue(APSInt(std::max(LHS, RHS),
12018 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12019 break;
12020 case Builtin::BI__builtin_elementwise_min:
12021 ResultElements.push_back(
12022 APValue(APSInt(std::min(LHS, RHS),
12023 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12024 break;
12025 }
12026 }
12027
12028 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12029 }
12030 case X86::BI__builtin_ia32_vpshldd128:
12031 case X86::BI__builtin_ia32_vpshldd256:
12032 case X86::BI__builtin_ia32_vpshldd512:
12033 case X86::BI__builtin_ia32_vpshldq128:
12034 case X86::BI__builtin_ia32_vpshldq256:
12035 case X86::BI__builtin_ia32_vpshldq512:
12036 case X86::BI__builtin_ia32_vpshldw128:
12037 case X86::BI__builtin_ia32_vpshldw256:
12038 case X86::BI__builtin_ia32_vpshldw512: {
12039 APValue SourceHi, SourceLo, SourceAmt;
12040 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12041 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12042 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12043 return false;
12044
12045 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12046 unsigned SourceLen = SourceHi.getVectorLength();
12047 SmallVector<APValue, 32> ResultElements;
12048 ResultElements.reserve(SourceLen);
12049
12050 APInt Amt = SourceAmt.getInt();
12051 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12052 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12053 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12054 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12055 ResultElements.push_back(
12057 }
12058
12059 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12060 }
12061 case X86::BI__builtin_ia32_vpshrdd128:
12062 case X86::BI__builtin_ia32_vpshrdd256:
12063 case X86::BI__builtin_ia32_vpshrdd512:
12064 case X86::BI__builtin_ia32_vpshrdq128:
12065 case X86::BI__builtin_ia32_vpshrdq256:
12066 case X86::BI__builtin_ia32_vpshrdq512:
12067 case X86::BI__builtin_ia32_vpshrdw128:
12068 case X86::BI__builtin_ia32_vpshrdw256:
12069 case X86::BI__builtin_ia32_vpshrdw512: {
12070 // NOTE: Reversed Hi/Lo operands.
12071 APValue SourceHi, SourceLo, SourceAmt;
12072 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12073 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12074 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12075 return false;
12076
12077 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12078 unsigned SourceLen = SourceHi.getVectorLength();
12079 SmallVector<APValue, 32> ResultElements;
12080 ResultElements.reserve(SourceLen);
12081
12082 APInt Amt = SourceAmt.getInt();
12083 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12084 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12085 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12086 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12087 ResultElements.push_back(
12089 }
12090
12091 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12092 }
12093 case X86::BI__builtin_ia32_blendpd:
12094 case X86::BI__builtin_ia32_blendpd256:
12095 case X86::BI__builtin_ia32_blendps:
12096 case X86::BI__builtin_ia32_blendps256:
12097 case X86::BI__builtin_ia32_pblendw128:
12098 case X86::BI__builtin_ia32_pblendw256:
12099 case X86::BI__builtin_ia32_pblendd128:
12100 case X86::BI__builtin_ia32_pblendd256: {
12101 APValue SourceF, SourceT, SourceC;
12102 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12103 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12104 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12105 return false;
12106
12107 const APInt &C = SourceC.getInt();
12108 unsigned SourceLen = SourceF.getVectorLength();
12109 SmallVector<APValue, 32> ResultElements;
12110 ResultElements.reserve(SourceLen);
12111 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
12112 const APValue &F = SourceF.getVectorElt(EltNum);
12113 const APValue &T = SourceT.getVectorElt(EltNum);
12114 ResultElements.push_back(C[EltNum % 8] ? T : F);
12115 }
12116
12117 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12118 }
12119
12120 case X86::BI__builtin_ia32_blendvpd:
12121 case X86::BI__builtin_ia32_blendvpd256:
12122 case X86::BI__builtin_ia32_blendvps:
12123 case X86::BI__builtin_ia32_blendvps256:
12124 case X86::BI__builtin_ia32_pblendvb128:
12125 case X86::BI__builtin_ia32_pblendvb256: {
12126 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
12127 APValue SourceF, SourceT, SourceC;
12128 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12129 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12130 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12131 return false;
12132
12133 unsigned SourceLen = SourceF.getVectorLength();
12134 SmallVector<APValue, 32> ResultElements;
12135 ResultElements.reserve(SourceLen);
12136
12137 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12138 const APValue &F = SourceF.getVectorElt(EltNum);
12139 const APValue &T = SourceT.getVectorElt(EltNum);
12140 const APValue &C = SourceC.getVectorElt(EltNum);
12141 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
12142 ResultElements.push_back(M.isNegative() ? T : F);
12143 }
12144
12145 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12146 }
12147 case X86::BI__builtin_ia32_selectb_128:
12148 case X86::BI__builtin_ia32_selectb_256:
12149 case X86::BI__builtin_ia32_selectb_512:
12150 case X86::BI__builtin_ia32_selectw_128:
12151 case X86::BI__builtin_ia32_selectw_256:
12152 case X86::BI__builtin_ia32_selectw_512:
12153 case X86::BI__builtin_ia32_selectd_128:
12154 case X86::BI__builtin_ia32_selectd_256:
12155 case X86::BI__builtin_ia32_selectd_512:
12156 case X86::BI__builtin_ia32_selectq_128:
12157 case X86::BI__builtin_ia32_selectq_256:
12158 case X86::BI__builtin_ia32_selectq_512:
12159 case X86::BI__builtin_ia32_selectph_128:
12160 case X86::BI__builtin_ia32_selectph_256:
12161 case X86::BI__builtin_ia32_selectph_512:
12162 case X86::BI__builtin_ia32_selectpbf_128:
12163 case X86::BI__builtin_ia32_selectpbf_256:
12164 case X86::BI__builtin_ia32_selectpbf_512:
12165 case X86::BI__builtin_ia32_selectps_128:
12166 case X86::BI__builtin_ia32_selectps_256:
12167 case X86::BI__builtin_ia32_selectps_512:
12168 case X86::BI__builtin_ia32_selectpd_128:
12169 case X86::BI__builtin_ia32_selectpd_256:
12170 case X86::BI__builtin_ia32_selectpd_512: {
12171 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
12172 APValue SourceMask, SourceLHS, SourceRHS;
12173 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
12174 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
12175 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
12176 return false;
12177
12178 APSInt Mask = SourceMask.getInt();
12179 unsigned SourceLen = SourceLHS.getVectorLength();
12180 SmallVector<APValue, 4> ResultElements;
12181 ResultElements.reserve(SourceLen);
12182
12183 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12184 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
12185 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
12186 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
12187 }
12188
12189 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12190 }
12191
12192 case X86::BI__builtin_ia32_pshuflw:
12193 case X86::BI__builtin_ia32_pshuflw256:
12194 case X86::BI__builtin_ia32_pshuflw512: {
12195 APValue R;
12196 if (!evalPshufBuiltin(Info, E, false, R))
12197 return false;
12198 return Success(R, E);
12199 }
12200
12201 case X86::BI__builtin_ia32_pshufhw:
12202 case X86::BI__builtin_ia32_pshufhw256:
12203 case X86::BI__builtin_ia32_pshufhw512: {
12204 APValue R;
12205 if (!evalPshufBuiltin(Info, E, true, R))
12206 return false;
12207 return Success(R, E);
12208 }
12209
12210 case X86::BI__builtin_ia32_pshufd:
12211 case X86::BI__builtin_ia32_pshufd256:
12212 case X86::BI__builtin_ia32_pshufd512: {
12213 APValue R;
12214 if (!evalPshufBuiltin(Info, E, false, R))
12215 return false;
12216 return Success(R, E);
12217 }
12218
12219 case X86::BI__builtin_ia32_pternlogd128_mask:
12220 case X86::BI__builtin_ia32_pternlogd256_mask:
12221 case X86::BI__builtin_ia32_pternlogd512_mask:
12222 case X86::BI__builtin_ia32_pternlogq128_mask:
12223 case X86::BI__builtin_ia32_pternlogq256_mask:
12224 case X86::BI__builtin_ia32_pternlogq512_mask: {
12225 APValue AValue, BValue, CValue, ImmValue, UValue;
12226 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
12227 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
12228 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
12229 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
12230 !EvaluateAsRValue(Info, E->getArg(4), UValue))
12231 return false;
12232
12233 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12234 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12235 APInt Imm = ImmValue.getInt();
12236 APInt U = UValue.getInt();
12237 unsigned ResultLen = AValue.getVectorLength();
12238 SmallVector<APValue, 16> ResultElements;
12239 ResultElements.reserve(ResultLen);
12240
12241 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
12242 APInt ALane = AValue.getVectorElt(EltNum).getInt();
12243 APInt BLane = BValue.getVectorElt(EltNum).getInt();
12244 APInt CLane = CValue.getVectorElt(EltNum).getInt();
12245
12246 if (U[EltNum]) {
12247 unsigned BitWidth = ALane.getBitWidth();
12248 APInt ResLane(BitWidth, 0);
12249
12250 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
12251 unsigned ABit = ALane[Bit];
12252 unsigned BBit = BLane[Bit];
12253 unsigned CBit = CLane[Bit];
12254
12255 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
12256 ResLane.setBitVal(Bit, Imm[Idx]);
12257 }
12258 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
12259 } else {
12260 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
12261 }
12262 }
12263 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12264 }
12265 case X86::BI__builtin_ia32_pternlogd128_maskz:
12266 case X86::BI__builtin_ia32_pternlogd256_maskz:
12267 case X86::BI__builtin_ia32_pternlogd512_maskz:
12268 case X86::BI__builtin_ia32_pternlogq128_maskz:
12269 case X86::BI__builtin_ia32_pternlogq256_maskz:
12270 case X86::BI__builtin_ia32_pternlogq512_maskz: {
12271 APValue AValue, BValue, CValue, ImmValue, UValue;
12272 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
12273 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
12274 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
12275 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
12276 !EvaluateAsRValue(Info, E->getArg(4), UValue))
12277 return false;
12278
12279 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12280 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12281 APInt Imm = ImmValue.getInt();
12282 APInt U = UValue.getInt();
12283 unsigned ResultLen = AValue.getVectorLength();
12284 SmallVector<APValue, 16> ResultElements;
12285 ResultElements.reserve(ResultLen);
12286
12287 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
12288 APInt ALane = AValue.getVectorElt(EltNum).getInt();
12289 APInt BLane = BValue.getVectorElt(EltNum).getInt();
12290 APInt CLane = CValue.getVectorElt(EltNum).getInt();
12291
12292 unsigned BitWidth = ALane.getBitWidth();
12293 APInt ResLane(BitWidth, 0);
12294
12295 if (U[EltNum]) {
12296 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
12297 unsigned ABit = ALane[Bit];
12298 unsigned BBit = BLane[Bit];
12299 unsigned CBit = CLane[Bit];
12300
12301 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
12302 ResLane.setBitVal(Bit, Imm[Idx]);
12303 }
12304 }
12305 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
12306 }
12307 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12308 }
12309
12310 case Builtin::BI__builtin_elementwise_clzg:
12311 case Builtin::BI__builtin_elementwise_ctzg: {
12312 APValue SourceLHS;
12313 std::optional<APValue> Fallback;
12314 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
12315 return false;
12316 if (E->getNumArgs() > 1) {
12317 APValue FallbackTmp;
12318 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
12319 return false;
12320 Fallback = FallbackTmp;
12321 }
12322
12323 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12324 unsigned SourceLen = SourceLHS.getVectorLength();
12325 SmallVector<APValue, 4> ResultElements;
12326 ResultElements.reserve(SourceLen);
12327
12328 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12329 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12330 if (!LHS) {
12331 // Without a fallback, a zero element is undefined
12332 if (!Fallback) {
12333 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
12334 << /*IsTrailing=*/(E->getBuiltinCallee() ==
12335 Builtin::BI__builtin_elementwise_ctzg);
12336 return false;
12337 }
12338 ResultElements.push_back(Fallback->getVectorElt(EltNum));
12339 continue;
12340 }
12341 switch (E->getBuiltinCallee()) {
12342 case Builtin::BI__builtin_elementwise_clzg:
12343 ResultElements.push_back(APValue(
12344 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
12345 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12346 break;
12347 case Builtin::BI__builtin_elementwise_ctzg:
12348 ResultElements.push_back(APValue(
12349 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
12350 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12351 break;
12352 }
12353 }
12354
12355 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12356 }
12357
12358 case Builtin::BI__builtin_elementwise_fma: {
12359 APValue SourceX, SourceY, SourceZ;
12360 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
12361 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
12362 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
12363 return false;
12364
12365 unsigned SourceLen = SourceX.getVectorLength();
12366 SmallVector<APValue> ResultElements;
12367 ResultElements.reserve(SourceLen);
12368 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
12369 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12370 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
12371 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
12372 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
12373 APFloat Result(X);
12374 (void)Result.fusedMultiplyAdd(Y, Z, RM);
12375 ResultElements.push_back(APValue(Result));
12376 }
12377 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12378 }
12379
12380 case Builtin::BI__builtin_elementwise_fshl:
12381 case Builtin::BI__builtin_elementwise_fshr: {
12382 APValue SourceHi, SourceLo, SourceShift;
12383 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12384 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12385 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
12386 return false;
12387
12388 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12389 if (!DestEltTy->isIntegerType())
12390 return false;
12391
12392 unsigned SourceLen = SourceHi.getVectorLength();
12393 SmallVector<APValue> ResultElements;
12394 ResultElements.reserve(SourceLen);
12395 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12396 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
12397 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
12398 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
12399 switch (E->getBuiltinCallee()) {
12400 case Builtin::BI__builtin_elementwise_fshl:
12401 ResultElements.push_back(APValue(
12402 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
12403 break;
12404 case Builtin::BI__builtin_elementwise_fshr:
12405 ResultElements.push_back(APValue(
12406 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
12407 break;
12408 }
12409 }
12410
12411 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12412 }
12413
12414 case X86::BI__builtin_ia32_insertf32x4_256:
12415 case X86::BI__builtin_ia32_inserti32x4_256:
12416 case X86::BI__builtin_ia32_insertf64x2_256:
12417 case X86::BI__builtin_ia32_inserti64x2_256:
12418 case X86::BI__builtin_ia32_insertf32x4:
12419 case X86::BI__builtin_ia32_inserti32x4:
12420 case X86::BI__builtin_ia32_insertf64x2_512:
12421 case X86::BI__builtin_ia32_inserti64x2_512:
12422 case X86::BI__builtin_ia32_insertf32x8:
12423 case X86::BI__builtin_ia32_inserti32x8:
12424 case X86::BI__builtin_ia32_insertf64x4:
12425 case X86::BI__builtin_ia32_inserti64x4:
12426 case X86::BI__builtin_ia32_vinsertf128_ps256:
12427 case X86::BI__builtin_ia32_vinsertf128_pd256:
12428 case X86::BI__builtin_ia32_vinsertf128_si256:
12429 case X86::BI__builtin_ia32_insert128i256: {
12430 APValue SourceDst, SourceSub;
12431 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
12432 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
12433 return false;
12434
12435 APSInt Imm;
12436 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12437 return false;
12438
12439 assert(SourceDst.isVector() && SourceSub.isVector());
12440 unsigned DstLen = SourceDst.getVectorLength();
12441 unsigned SubLen = SourceSub.getVectorLength();
12442 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
12443 unsigned NumLanes = DstLen / SubLen;
12444 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
12445
12446 SmallVector<APValue, 16> ResultElements;
12447 ResultElements.reserve(DstLen);
12448
12449 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
12450 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
12451 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
12452 else
12453 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
12454 }
12455
12456 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12457 }
12458
12459 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
12460 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
12461 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
12462 case clang::X86::BI__builtin_ia32_vec_set_v4si:
12463 case clang::X86::BI__builtin_ia32_vec_set_v2di:
12464 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
12465 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
12466 case clang::X86::BI__builtin_ia32_vec_set_v8si:
12467 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
12468 APValue VecVal;
12469 APSInt Scalar, IndexAPS;
12470 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
12471 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
12472 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
12473 return false;
12474
12475 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
12476 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
12477 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
12478 Scalar.setIsUnsigned(ElemUnsigned);
12479 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
12480 APValue ElemAV(ElemAPS);
12481
12482 unsigned NumElems = VecVal.getVectorLength();
12483 unsigned Index =
12484 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
12485
12487 Elems.reserve(NumElems);
12488 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
12489 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
12490
12491 return Success(APValue(Elems.data(), NumElems), E);
12492 }
12493 }
12494}
12495
12496bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
12497 APValue Source;
12498 QualType SourceVecType = E->getSrcExpr()->getType();
12499 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
12500 return false;
12501
12502 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
12503 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
12504
12505 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12506
12507 auto SourceLen = Source.getVectorLength();
12508 SmallVector<APValue, 4> ResultElements;
12509 ResultElements.reserve(SourceLen);
12510 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12511 APValue Elt;
12512 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
12513 Source.getVectorElt(EltNum), Elt))
12514 return false;
12515 ResultElements.push_back(std::move(Elt));
12516 }
12517
12518 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12519}
12520
12521static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
12522 QualType ElemType, APValue const &VecVal1,
12523 APValue const &VecVal2, unsigned EltNum,
12524 APValue &Result) {
12525 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
12526 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
12527
12528 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
12529 int64_t index = IndexVal.getExtValue();
12530 // The spec says that -1 should be treated as undef for optimizations,
12531 // but in constexpr we'd have to produce an APValue::Indeterminate,
12532 // which is prohibited from being a top-level constant value. Emit a
12533 // diagnostic instead.
12534 if (index == -1) {
12535 Info.FFDiag(
12536 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
12537 << EltNum;
12538 return false;
12539 }
12540
12541 if (index < 0 ||
12542 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
12543 llvm_unreachable("Out of bounds shuffle index");
12544
12545 if (index >= TotalElementsInInputVector1)
12546 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
12547 else
12548 Result = VecVal1.getVectorElt(index);
12549 return true;
12550}
12551
12552bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
12553 // FIXME: Unary shuffle with mask not currently supported.
12554 if (E->getNumSubExprs() == 2)
12555 return Error(E);
12556 APValue VecVal1;
12557 const Expr *Vec1 = E->getExpr(0);
12558 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
12559 return false;
12560 APValue VecVal2;
12561 const Expr *Vec2 = E->getExpr(1);
12562 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
12563 return false;
12564
12565 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
12566 QualType DestElTy = DestVecTy->getElementType();
12567
12568 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
12569
12570 SmallVector<APValue, 4> ResultElements;
12571 ResultElements.reserve(TotalElementsInOutputVector);
12572 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
12573 APValue Elt;
12574 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
12575 return false;
12576 ResultElements.push_back(std::move(Elt));
12577 }
12578
12579 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12580}
12581
12582//===----------------------------------------------------------------------===//
12583// Array Evaluation
12584//===----------------------------------------------------------------------===//
12585
12586namespace {
12587 class ArrayExprEvaluator
12588 : public ExprEvaluatorBase<ArrayExprEvaluator> {
12589 const LValue &This;
12590 APValue &Result;
12591 public:
12592
12593 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
12594 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12595
12596 bool Success(const APValue &V, const Expr *E) {
12597 assert(V.isArray() && "expected array");
12598 Result = V;
12599 return true;
12600 }
12601
12602 bool ZeroInitialization(const Expr *E) {
12603 const ConstantArrayType *CAT =
12604 Info.Ctx.getAsConstantArrayType(E->getType());
12605 if (!CAT) {
12606 if (E->getType()->isIncompleteArrayType()) {
12607 // We can be asked to zero-initialize a flexible array member; this
12608 // is represented as an ImplicitValueInitExpr of incomplete array
12609 // type. In this case, the array has zero elements.
12610 Result = APValue(APValue::UninitArray(), 0, 0);
12611 return true;
12612 }
12613 // FIXME: We could handle VLAs here.
12614 return Error(E);
12615 }
12616
12617 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
12618 if (!Result.hasArrayFiller())
12619 return true;
12620
12621 // Zero-initialize all elements.
12622 LValue Subobject = This;
12623 Subobject.addArray(Info, E, CAT);
12624 ImplicitValueInitExpr VIE(CAT->getElementType());
12625 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
12626 }
12627
12628 bool VisitCallExpr(const CallExpr *E) {
12629 return handleCallExpr(E, Result, &This);
12630 }
12631 bool VisitInitListExpr(const InitListExpr *E,
12632 QualType AllocType = QualType());
12633 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
12634 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
12635 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
12636 const LValue &Subobject,
12637 APValue *Value, QualType Type);
12638 bool VisitStringLiteral(const StringLiteral *E,
12639 QualType AllocType = QualType()) {
12640 expandStringLiteral(Info, E, Result, AllocType);
12641 return true;
12642 }
12643 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
12644 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
12645 ArrayRef<Expr *> Args,
12646 const Expr *ArrayFiller,
12647 QualType AllocType = QualType());
12648 };
12649} // end anonymous namespace
12650
12651static bool EvaluateArray(const Expr *E, const LValue &This,
12652 APValue &Result, EvalInfo &Info) {
12653 assert(!E->isValueDependent());
12654 assert(E->isPRValue() && E->getType()->isArrayType() &&
12655 "not an array prvalue");
12656 return ArrayExprEvaluator(Info, This, Result).Visit(E);
12657}
12658
12659static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
12660 APValue &Result, const InitListExpr *ILE,
12661 QualType AllocType) {
12662 assert(!ILE->isValueDependent());
12663 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
12664 "not an array prvalue");
12665 return ArrayExprEvaluator(Info, This, Result)
12666 .VisitInitListExpr(ILE, AllocType);
12667}
12668
12669static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
12670 APValue &Result,
12671 const CXXConstructExpr *CCE,
12672 QualType AllocType) {
12673 assert(!CCE->isValueDependent());
12674 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
12675 "not an array prvalue");
12676 return ArrayExprEvaluator(Info, This, Result)
12677 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
12678}
12679
12680// Return true iff the given array filler may depend on the element index.
12681static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
12682 // For now, just allow non-class value-initialization and initialization
12683 // lists comprised of them.
12684 if (isa<ImplicitValueInitExpr>(FillerExpr))
12685 return false;
12686 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
12687 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
12688 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
12689 return true;
12690 }
12691
12692 if (ILE->hasArrayFiller() &&
12693 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
12694 return true;
12695
12696 return false;
12697 }
12698 return true;
12699}
12700
12701bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
12702 QualType AllocType) {
12703 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12704 AllocType.isNull() ? E->getType() : AllocType);
12705 if (!CAT)
12706 return Error(E);
12707
12708 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
12709 // an appropriately-typed string literal enclosed in braces.
12710 if (E->isStringLiteralInit()) {
12711 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
12712 // FIXME: Support ObjCEncodeExpr here once we support it in
12713 // ArrayExprEvaluator generally.
12714 if (!SL)
12715 return Error(E);
12716 return VisitStringLiteral(SL, AllocType);
12717 }
12718 // Any other transparent list init will need proper handling of the
12719 // AllocType; we can't just recurse to the inner initializer.
12720 assert(!E->isTransparent() &&
12721 "transparent array list initialization is not string literal init?");
12722
12723 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
12724 AllocType);
12725}
12726
12727bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
12728 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
12729 QualType AllocType) {
12730 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12731 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
12732
12733 bool Success = true;
12734
12735 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
12736 "zero-initialized array shouldn't have any initialized elts");
12737 APValue Filler;
12738 if (Result.isArray() && Result.hasArrayFiller())
12739 Filler = Result.getArrayFiller();
12740
12741 unsigned NumEltsToInit = Args.size();
12742 unsigned NumElts = CAT->getZExtSize();
12743
12744 // If the initializer might depend on the array index, run it for each
12745 // array element.
12746 if (NumEltsToInit != NumElts &&
12747 MaybeElementDependentArrayFiller(ArrayFiller)) {
12748 NumEltsToInit = NumElts;
12749 } else {
12750 for (auto *Init : Args) {
12751 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
12752 NumEltsToInit += EmbedS->getDataElementCount() - 1;
12753 }
12754 if (NumEltsToInit > NumElts)
12755 NumEltsToInit = NumElts;
12756 }
12757
12758 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
12759 << NumEltsToInit << ".\n");
12760
12761 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
12762
12763 // If the array was previously zero-initialized, preserve the
12764 // zero-initialized values.
12765 if (Filler.hasValue()) {
12766 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
12767 Result.getArrayInitializedElt(I) = Filler;
12768 if (Result.hasArrayFiller())
12769 Result.getArrayFiller() = Filler;
12770 }
12771
12772 LValue Subobject = This;
12773 Subobject.addArray(Info, ExprToVisit, CAT);
12774 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
12775 if (Init->isValueDependent())
12776 return EvaluateDependentExpr(Init, Info);
12777
12778 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
12779 Subobject, Init) ||
12780 !HandleLValueArrayAdjustment(Info, Init, Subobject,
12781 CAT->getElementType(), 1)) {
12782 if (!Info.noteFailure())
12783 return false;
12784 Success = false;
12785 }
12786 return true;
12787 };
12788 unsigned ArrayIndex = 0;
12789 QualType DestTy = CAT->getElementType();
12790 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
12791 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
12792 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
12793 if (ArrayIndex >= NumEltsToInit)
12794 break;
12795 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
12796 StringLiteral *SL = EmbedS->getDataStringLiteral();
12797 for (unsigned I = EmbedS->getStartingElementPos(),
12798 N = EmbedS->getDataElementCount();
12799 I != EmbedS->getStartingElementPos() + N; ++I) {
12800 Value = SL->getCodeUnit(I);
12801 if (DestTy->isIntegerType()) {
12802 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
12803 } else {
12804 assert(DestTy->isFloatingType() && "unexpected type");
12805 const FPOptions FPO =
12806 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12807 APFloat FValue(0.0);
12808 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
12809 DestTy, FValue))
12810 return false;
12811 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
12812 }
12813 ArrayIndex++;
12814 }
12815 } else {
12816 if (!Eval(Init, ArrayIndex))
12817 return false;
12818 ++ArrayIndex;
12819 }
12820 }
12821
12822 if (!Result.hasArrayFiller())
12823 return Success;
12824
12825 // If we get here, we have a trivial filler, which we can just evaluate
12826 // once and splat over the rest of the array elements.
12827 assert(ArrayFiller && "no array filler for incomplete init list");
12828 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
12829 ArrayFiller) &&
12830 Success;
12831}
12832
12833bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
12834 LValue CommonLV;
12835 if (E->getCommonExpr() &&
12836 !Evaluate(Info.CurrentCall->createTemporary(
12837 E->getCommonExpr(),
12838 getStorageType(Info.Ctx, E->getCommonExpr()),
12839 ScopeKind::FullExpression, CommonLV),
12840 Info, E->getCommonExpr()->getSourceExpr()))
12841 return false;
12842
12844
12845 uint64_t Elements = CAT->getZExtSize();
12846 Result = APValue(APValue::UninitArray(), Elements, Elements);
12847
12848 LValue Subobject = This;
12849 Subobject.addArray(Info, E, CAT);
12850
12851 bool Success = true;
12852 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
12853 // C++ [class.temporary]/5
12854 // There are four contexts in which temporaries are destroyed at a different
12855 // point than the end of the full-expression. [...] The second context is
12856 // when a copy constructor is called to copy an element of an array while
12857 // the entire array is copied [...]. In either case, if the constructor has
12858 // one or more default arguments, the destruction of every temporary created
12859 // in a default argument is sequenced before the construction of the next
12860 // array element, if any.
12861 FullExpressionRAII Scope(Info);
12862
12863 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
12864 Info, Subobject, E->getSubExpr()) ||
12865 !HandleLValueArrayAdjustment(Info, E, Subobject,
12866 CAT->getElementType(), 1)) {
12867 if (!Info.noteFailure())
12868 return false;
12869 Success = false;
12870 }
12871
12872 // Make sure we run the destructors too.
12873 Scope.destroy();
12874 }
12875
12876 return Success;
12877}
12878
12879bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
12880 return VisitCXXConstructExpr(E, This, &Result, E->getType());
12881}
12882
12883bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
12884 const LValue &Subobject,
12885 APValue *Value,
12886 QualType Type) {
12887 bool HadZeroInit = Value->hasValue();
12888
12889 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
12890 unsigned FinalSize = CAT->getZExtSize();
12891
12892 // Preserve the array filler if we had prior zero-initialization.
12893 APValue Filler =
12894 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
12895 : APValue();
12896
12897 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
12898 if (FinalSize == 0)
12899 return true;
12900
12901 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
12902 Info, E->getExprLoc(), E->getConstructor(),
12904 LValue ArrayElt = Subobject;
12905 ArrayElt.addArray(Info, E, CAT);
12906 // We do the whole initialization in two passes, first for just one element,
12907 // then for the whole array. It's possible we may find out we can't do const
12908 // init in the first pass, in which case we avoid allocating a potentially
12909 // large array. We don't do more passes because expanding array requires
12910 // copying the data, which is wasteful.
12911 for (const unsigned N : {1u, FinalSize}) {
12912 unsigned OldElts = Value->getArrayInitializedElts();
12913 if (OldElts == N)
12914 break;
12915
12916 // Expand the array to appropriate size.
12917 APValue NewValue(APValue::UninitArray(), N, FinalSize);
12918 for (unsigned I = 0; I < OldElts; ++I)
12919 NewValue.getArrayInitializedElt(I).swap(
12920 Value->getArrayInitializedElt(I));
12921 Value->swap(NewValue);
12922
12923 if (HadZeroInit)
12924 for (unsigned I = OldElts; I < N; ++I)
12925 Value->getArrayInitializedElt(I) = Filler;
12926
12927 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
12928 // If we have a trivial constructor, only evaluate it once and copy
12929 // the result into all the array elements.
12930 APValue &FirstResult = Value->getArrayInitializedElt(0);
12931 for (unsigned I = OldElts; I < FinalSize; ++I)
12932 Value->getArrayInitializedElt(I) = FirstResult;
12933 } else {
12934 for (unsigned I = OldElts; I < N; ++I) {
12935 if (!VisitCXXConstructExpr(E, ArrayElt,
12936 &Value->getArrayInitializedElt(I),
12937 CAT->getElementType()) ||
12938 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
12939 CAT->getElementType(), 1))
12940 return false;
12941 // When checking for const initilization any diagnostic is considered
12942 // an error.
12943 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
12944 !Info.keepEvaluatingAfterFailure())
12945 return false;
12946 }
12947 }
12948 }
12949
12950 return true;
12951 }
12952
12953 if (!Type->isRecordType())
12954 return Error(E);
12955
12956 return RecordExprEvaluator(Info, Subobject, *Value)
12957 .VisitCXXConstructExpr(E, Type);
12958}
12959
12960bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
12961 const CXXParenListInitExpr *E) {
12962 assert(E->getType()->isConstantArrayType() &&
12963 "Expression result is not a constant array type");
12964
12965 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
12966 E->getArrayFiller());
12967}
12968
12969//===----------------------------------------------------------------------===//
12970// Integer Evaluation
12971//
12972// As a GNU extension, we support casting pointers to sufficiently-wide integer
12973// types and back in constant folding. Integer values are thus represented
12974// either as an integer-valued APValue, or as an lvalue-valued APValue.
12975//===----------------------------------------------------------------------===//
12976
12977namespace {
12978class IntExprEvaluator
12979 : public ExprEvaluatorBase<IntExprEvaluator> {
12980 APValue &Result;
12981public:
12982 IntExprEvaluator(EvalInfo &info, APValue &result)
12983 : ExprEvaluatorBaseTy(info), Result(result) {}
12984
12985 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
12986 assert(E->getType()->isIntegralOrEnumerationType() &&
12987 "Invalid evaluation result.");
12988 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
12989 "Invalid evaluation result.");
12990 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12991 "Invalid evaluation result.");
12992 Result = APValue(SI);
12993 return true;
12994 }
12995 bool Success(const llvm::APSInt &SI, const Expr *E) {
12996 return Success(SI, E, Result);
12997 }
12998
12999 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
13000 assert(E->getType()->isIntegralOrEnumerationType() &&
13001 "Invalid evaluation result.");
13002 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
13003 "Invalid evaluation result.");
13004 Result = APValue(APSInt(I));
13005 Result.getInt().setIsUnsigned(
13007 return true;
13008 }
13009 bool Success(const llvm::APInt &I, const Expr *E) {
13010 return Success(I, E, Result);
13011 }
13012
13013 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13014 assert(E->getType()->isIntegralOrEnumerationType() &&
13015 "Invalid evaluation result.");
13016 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
13017 return true;
13018 }
13019 bool Success(uint64_t Value, const Expr *E) {
13020 return Success(Value, E, Result);
13021 }
13022
13023 bool Success(CharUnits Size, const Expr *E) {
13024 return Success(Size.getQuantity(), E);
13025 }
13026
13027 bool Success(const APValue &V, const Expr *E) {
13028 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
13029 // pointer allow further evaluation of the value.
13030 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
13031 V.allowConstexprUnknown()) {
13032 Result = V;
13033 return true;
13034 }
13035 return Success(V.getInt(), E);
13036 }
13037
13038 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
13039
13040 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
13041 const CallExpr *);
13042
13043 //===--------------------------------------------------------------------===//
13044 // Visitor Methods
13045 //===--------------------------------------------------------------------===//
13046
13047 bool VisitIntegerLiteral(const IntegerLiteral *E) {
13048 return Success(E->getValue(), E);
13049 }
13050 bool VisitCharacterLiteral(const CharacterLiteral *E) {
13051 return Success(E->getValue(), E);
13052 }
13053
13054 bool CheckReferencedDecl(const Expr *E, const Decl *D);
13055 bool VisitDeclRefExpr(const DeclRefExpr *E) {
13056 if (CheckReferencedDecl(E, E->getDecl()))
13057 return true;
13058
13059 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
13060 }
13061 bool VisitMemberExpr(const MemberExpr *E) {
13062 if (CheckReferencedDecl(E, E->getMemberDecl())) {
13063 VisitIgnoredBaseExpression(E->getBase());
13064 return true;
13065 }
13066
13067 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
13068 }
13069
13070 bool VisitCallExpr(const CallExpr *E);
13071 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
13072 bool VisitBinaryOperator(const BinaryOperator *E);
13073 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
13074 bool VisitUnaryOperator(const UnaryOperator *E);
13075
13076 bool VisitCastExpr(const CastExpr* E);
13077 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
13078
13079 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
13080 return Success(E->getValue(), E);
13081 }
13082
13083 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
13084 return Success(E->getValue(), E);
13085 }
13086
13087 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
13088 if (Info.ArrayInitIndex == uint64_t(-1)) {
13089 // We were asked to evaluate this subexpression independent of the
13090 // enclosing ArrayInitLoopExpr. We can't do that.
13091 Info.FFDiag(E);
13092 return false;
13093 }
13094 return Success(Info.ArrayInitIndex, E);
13095 }
13096
13097 // Note, GNU defines __null as an integer, not a pointer.
13098 bool VisitGNUNullExpr(const GNUNullExpr *E) {
13099 return ZeroInitialization(E);
13100 }
13101
13102 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
13103 if (E->isStoredAsBoolean())
13104 return Success(E->getBoolValue(), E);
13105 if (E->getAPValue().isAbsent())
13106 return false;
13107 assert(E->getAPValue().isInt() && "APValue type not supported");
13108 return Success(E->getAPValue().getInt(), E);
13109 }
13110
13111 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
13112 return Success(E->getValue(), E);
13113 }
13114
13115 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
13116 return Success(E->getValue(), E);
13117 }
13118
13119 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
13120 // This should not be evaluated during constant expr evaluation, as it
13121 // should always be in an unevaluated context (the args list of a 'gang' or
13122 // 'tile' clause).
13123 return Error(E);
13124 }
13125
13126 bool VisitUnaryReal(const UnaryOperator *E);
13127 bool VisitUnaryImag(const UnaryOperator *E);
13128
13129 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
13130 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
13131 bool VisitSourceLocExpr(const SourceLocExpr *E);
13132 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
13133 bool VisitRequiresExpr(const RequiresExpr *E);
13134 // FIXME: Missing: array subscript of vector, member of vector
13135};
13136
13137class FixedPointExprEvaluator
13138 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
13139 APValue &Result;
13140
13141 public:
13142 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
13143 : ExprEvaluatorBaseTy(info), Result(result) {}
13144
13145 bool Success(const llvm::APInt &I, const Expr *E) {
13146 return Success(
13147 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
13148 }
13149
13150 bool Success(uint64_t Value, const Expr *E) {
13151 return Success(
13152 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
13153 }
13154
13155 bool Success(const APValue &V, const Expr *E) {
13156 return Success(V.getFixedPoint(), E);
13157 }
13158
13159 bool Success(const APFixedPoint &V, const Expr *E) {
13160 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
13161 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
13162 "Invalid evaluation result.");
13163 Result = APValue(V);
13164 return true;
13165 }
13166
13167 bool ZeroInitialization(const Expr *E) {
13168 return Success(0, E);
13169 }
13170
13171 //===--------------------------------------------------------------------===//
13172 // Visitor Methods
13173 //===--------------------------------------------------------------------===//
13174
13175 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
13176 return Success(E->getValue(), E);
13177 }
13178
13179 bool VisitCastExpr(const CastExpr *E);
13180 bool VisitUnaryOperator(const UnaryOperator *E);
13181 bool VisitBinaryOperator(const BinaryOperator *E);
13182};
13183} // end anonymous namespace
13184
13185/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
13186/// produce either the integer value or a pointer.
13187///
13188/// GCC has a heinous extension which folds casts between pointer types and
13189/// pointer-sized integral types. We support this by allowing the evaluation of
13190/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
13191/// Some simple arithmetic on such values is supported (they are treated much
13192/// like char*).
13193static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
13194 EvalInfo &Info) {
13195 assert(!E->isValueDependent());
13196 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
13197 return IntExprEvaluator(Info, Result).Visit(E);
13198}
13199
13200static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
13201 assert(!E->isValueDependent());
13202 APValue Val;
13203 if (!EvaluateIntegerOrLValue(E, Val, Info))
13204 return false;
13205 if (!Val.isInt()) {
13206 // FIXME: It would be better to produce the diagnostic for casting
13207 // a pointer to an integer.
13208 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13209 return false;
13210 }
13211 Result = Val.getInt();
13212 return true;
13213}
13214
13215bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
13217 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
13218 return Success(Evaluated, E);
13219}
13220
13221static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
13222 EvalInfo &Info) {
13223 assert(!E->isValueDependent());
13224 if (E->getType()->isFixedPointType()) {
13225 APValue Val;
13226 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
13227 return false;
13228 if (!Val.isFixedPoint())
13229 return false;
13230
13231 Result = Val.getFixedPoint();
13232 return true;
13233 }
13234 return false;
13235}
13236
13237static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
13238 EvalInfo &Info) {
13239 assert(!E->isValueDependent());
13240 if (E->getType()->isIntegerType()) {
13241 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
13242 APSInt Val;
13243 if (!EvaluateInteger(E, Val, Info))
13244 return false;
13245 Result = APFixedPoint(Val, FXSema);
13246 return true;
13247 } else if (E->getType()->isFixedPointType()) {
13248 return EvaluateFixedPoint(E, Result, Info);
13249 }
13250 return false;
13251}
13252
13253/// Check whether the given declaration can be directly converted to an integral
13254/// rvalue. If not, no diagnostic is produced; there are other things we can
13255/// try.
13256bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
13257 // Enums are integer constant exprs.
13258 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
13259 // Check for signedness/width mismatches between E type and ECD value.
13260 bool SameSign = (ECD->getInitVal().isSigned()
13262 bool SameWidth = (ECD->getInitVal().getBitWidth()
13263 == Info.Ctx.getIntWidth(E->getType()));
13264 if (SameSign && SameWidth)
13265 return Success(ECD->getInitVal(), E);
13266 else {
13267 // Get rid of mismatch (otherwise Success assertions will fail)
13268 // by computing a new value matching the type of E.
13269 llvm::APSInt Val = ECD->getInitVal();
13270 if (!SameSign)
13271 Val.setIsSigned(!ECD->getInitVal().isSigned());
13272 if (!SameWidth)
13273 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
13274 return Success(Val, E);
13275 }
13276 }
13277 return false;
13278}
13279
13280/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
13281/// as GCC.
13283 const LangOptions &LangOpts) {
13284 assert(!T->isDependentType() && "unexpected dependent type");
13285
13286 QualType CanTy = T.getCanonicalType();
13287
13288 switch (CanTy->getTypeClass()) {
13289#define TYPE(ID, BASE)
13290#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
13291#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
13292#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
13293#include "clang/AST/TypeNodes.inc"
13294 case Type::Auto:
13295 case Type::DeducedTemplateSpecialization:
13296 llvm_unreachable("unexpected non-canonical or dependent type");
13297
13298 case Type::Builtin:
13299 switch (cast<BuiltinType>(CanTy)->getKind()) {
13300#define BUILTIN_TYPE(ID, SINGLETON_ID)
13301#define SIGNED_TYPE(ID, SINGLETON_ID) \
13302 case BuiltinType::ID: return GCCTypeClass::Integer;
13303#define FLOATING_TYPE(ID, SINGLETON_ID) \
13304 case BuiltinType::ID: return GCCTypeClass::RealFloat;
13305#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
13306 case BuiltinType::ID: break;
13307#include "clang/AST/BuiltinTypes.def"
13308 case BuiltinType::Void:
13309 return GCCTypeClass::Void;
13310
13311 case BuiltinType::Bool:
13312 return GCCTypeClass::Bool;
13313
13314 case BuiltinType::Char_U:
13315 case BuiltinType::UChar:
13316 case BuiltinType::WChar_U:
13317 case BuiltinType::Char8:
13318 case BuiltinType::Char16:
13319 case BuiltinType::Char32:
13320 case BuiltinType::UShort:
13321 case BuiltinType::UInt:
13322 case BuiltinType::ULong:
13323 case BuiltinType::ULongLong:
13324 case BuiltinType::UInt128:
13325 return GCCTypeClass::Integer;
13326
13327 case BuiltinType::UShortAccum:
13328 case BuiltinType::UAccum:
13329 case BuiltinType::ULongAccum:
13330 case BuiltinType::UShortFract:
13331 case BuiltinType::UFract:
13332 case BuiltinType::ULongFract:
13333 case BuiltinType::SatUShortAccum:
13334 case BuiltinType::SatUAccum:
13335 case BuiltinType::SatULongAccum:
13336 case BuiltinType::SatUShortFract:
13337 case BuiltinType::SatUFract:
13338 case BuiltinType::SatULongFract:
13339 return GCCTypeClass::None;
13340
13341 case BuiltinType::NullPtr:
13342
13343 case BuiltinType::ObjCId:
13344 case BuiltinType::ObjCClass:
13345 case BuiltinType::ObjCSel:
13346#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
13347 case BuiltinType::Id:
13348#include "clang/Basic/OpenCLImageTypes.def"
13349#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
13350 case BuiltinType::Id:
13351#include "clang/Basic/OpenCLExtensionTypes.def"
13352 case BuiltinType::OCLSampler:
13353 case BuiltinType::OCLEvent:
13354 case BuiltinType::OCLClkEvent:
13355 case BuiltinType::OCLQueue:
13356 case BuiltinType::OCLReserveID:
13357#define SVE_TYPE(Name, Id, SingletonId) \
13358 case BuiltinType::Id:
13359#include "clang/Basic/AArch64ACLETypes.def"
13360#define PPC_VECTOR_TYPE(Name, Id, Size) \
13361 case BuiltinType::Id:
13362#include "clang/Basic/PPCTypes.def"
13363#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13364#include "clang/Basic/RISCVVTypes.def"
13365#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13366#include "clang/Basic/WebAssemblyReferenceTypes.def"
13367#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
13368#include "clang/Basic/AMDGPUTypes.def"
13369#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13370#include "clang/Basic/HLSLIntangibleTypes.def"
13371 return GCCTypeClass::None;
13372
13373 case BuiltinType::Dependent:
13374 llvm_unreachable("unexpected dependent type");
13375 };
13376 llvm_unreachable("unexpected placeholder type");
13377
13378 case Type::Enum:
13379 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
13380
13381 case Type::Pointer:
13382 case Type::ConstantArray:
13383 case Type::VariableArray:
13384 case Type::IncompleteArray:
13385 case Type::FunctionNoProto:
13386 case Type::FunctionProto:
13387 case Type::ArrayParameter:
13388 return GCCTypeClass::Pointer;
13389
13390 case Type::MemberPointer:
13391 return CanTy->isMemberDataPointerType()
13394
13395 case Type::Complex:
13396 return GCCTypeClass::Complex;
13397
13398 case Type::Record:
13399 return CanTy->isUnionType() ? GCCTypeClass::Union
13401
13402 case Type::Atomic:
13403 // GCC classifies _Atomic T the same as T.
13405 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
13406
13407 case Type::Vector:
13408 case Type::ExtVector:
13409 return GCCTypeClass::Vector;
13410
13411 case Type::BlockPointer:
13412 case Type::ConstantMatrix:
13413 case Type::ObjCObject:
13414 case Type::ObjCInterface:
13415 case Type::ObjCObjectPointer:
13416 case Type::Pipe:
13417 case Type::HLSLAttributedResource:
13418 case Type::HLSLInlineSpirv:
13419 // Classify all other types that don't fit into the regular
13420 // classification the same way.
13421 return GCCTypeClass::None;
13422
13423 case Type::BitInt:
13424 return GCCTypeClass::BitInt;
13425
13426 case Type::LValueReference:
13427 case Type::RValueReference:
13428 llvm_unreachable("invalid type for expression");
13429 }
13430
13431 llvm_unreachable("unexpected type class");
13432}
13433
13434/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
13435/// as GCC.
13436static GCCTypeClass
13438 // If no argument was supplied, default to None. This isn't
13439 // ideal, however it is what gcc does.
13440 if (E->getNumArgs() == 0)
13441 return GCCTypeClass::None;
13442
13443 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
13444 // being an ICE, but still folds it to a constant using the type of the first
13445 // argument.
13446 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
13447}
13448
13449/// EvaluateBuiltinConstantPForLValue - Determine the result of
13450/// __builtin_constant_p when applied to the given pointer.
13451///
13452/// A pointer is only "constant" if it is null (or a pointer cast to integer)
13453/// or it points to the first character of a string literal.
13456 if (Base.isNull()) {
13457 // A null base is acceptable.
13458 return true;
13459 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
13460 if (!isa<StringLiteral>(E))
13461 return false;
13462 return LV.getLValueOffset().isZero();
13463 } else if (Base.is<TypeInfoLValue>()) {
13464 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
13465 // evaluate to true.
13466 return true;
13467 } else {
13468 // Any other base is not constant enough for GCC.
13469 return false;
13470 }
13471}
13472
13473/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
13474/// GCC as we can manage.
13475static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
13476 // This evaluation is not permitted to have side-effects, so evaluate it in
13477 // a speculative evaluation context.
13478 SpeculativeEvaluationRAII SpeculativeEval(Info);
13479
13480 // Constant-folding is always enabled for the operand of __builtin_constant_p
13481 // (even when the enclosing evaluation context otherwise requires a strict
13482 // language-specific constant expression).
13483 FoldConstant Fold(Info, true);
13484
13485 QualType ArgType = Arg->getType();
13486
13487 // __builtin_constant_p always has one operand. The rules which gcc follows
13488 // are not precisely documented, but are as follows:
13489 //
13490 // - If the operand is of integral, floating, complex or enumeration type,
13491 // and can be folded to a known value of that type, it returns 1.
13492 // - If the operand can be folded to a pointer to the first character
13493 // of a string literal (or such a pointer cast to an integral type)
13494 // or to a null pointer or an integer cast to a pointer, it returns 1.
13495 //
13496 // Otherwise, it returns 0.
13497 //
13498 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
13499 // its support for this did not work prior to GCC 9 and is not yet well
13500 // understood.
13501 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
13502 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
13503 ArgType->isNullPtrType()) {
13504 APValue V;
13505 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
13506 Fold.keepDiagnostics();
13507 return false;
13508 }
13509
13510 // For a pointer (possibly cast to integer), there are special rules.
13511 if (V.getKind() == APValue::LValue)
13513
13514 // Otherwise, any constant value is good enough.
13515 return V.hasValue();
13516 }
13517
13518 // Anything else isn't considered to be sufficiently constant.
13519 return false;
13520}
13521
13522/// Retrieves the "underlying object type" of the given expression,
13523/// as used by __builtin_object_size.
13525 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
13526 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
13527 return VD->getType();
13528 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
13530 return E->getType();
13531 } else if (B.is<TypeInfoLValue>()) {
13532 return B.getTypeInfoType();
13533 } else if (B.is<DynamicAllocLValue>()) {
13534 return B.getDynamicAllocType();
13535 }
13536
13537 return QualType();
13538}
13539
13540/// A more selective version of E->IgnoreParenCasts for
13541/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
13542/// to change the type of E.
13543/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
13544///
13545/// Always returns an RValue with a pointer representation.
13546static const Expr *ignorePointerCastsAndParens(const Expr *E) {
13547 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
13548
13549 const Expr *NoParens = E->IgnoreParens();
13550 const auto *Cast = dyn_cast<CastExpr>(NoParens);
13551 if (Cast == nullptr)
13552 return NoParens;
13553
13554 // We only conservatively allow a few kinds of casts, because this code is
13555 // inherently a simple solution that seeks to support the common case.
13556 auto CastKind = Cast->getCastKind();
13557 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
13558 CastKind != CK_AddressSpaceConversion)
13559 return NoParens;
13560
13561 const auto *SubExpr = Cast->getSubExpr();
13562 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
13563 return NoParens;
13564 return ignorePointerCastsAndParens(SubExpr);
13565}
13566
13567/// Checks to see if the given LValue's Designator is at the end of the LValue's
13568/// record layout. e.g.
13569/// struct { struct { int a, b; } fst, snd; } obj;
13570/// obj.fst // no
13571/// obj.snd // yes
13572/// obj.fst.a // no
13573/// obj.fst.b // no
13574/// obj.snd.a // no
13575/// obj.snd.b // yes
13576///
13577/// Please note: this function is specialized for how __builtin_object_size
13578/// views "objects".
13579///
13580/// If this encounters an invalid RecordDecl or otherwise cannot determine the
13581/// correct result, it will always return true.
13582static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
13583 assert(!LVal.Designator.Invalid);
13584
13585 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
13586 const RecordDecl *Parent = FD->getParent();
13587 if (Parent->isInvalidDecl() || Parent->isUnion())
13588 return true;
13589 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
13590 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
13591 };
13592
13593 auto &Base = LVal.getLValueBase();
13594 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
13595 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
13596 if (!IsLastOrInvalidFieldDecl(FD))
13597 return false;
13598 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
13599 for (auto *FD : IFD->chain()) {
13600 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
13601 return false;
13602 }
13603 }
13604 }
13605
13606 unsigned I = 0;
13607 QualType BaseType = getType(Base);
13608 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
13609 // If we don't know the array bound, conservatively assume we're looking at
13610 // the final array element.
13611 ++I;
13612 if (BaseType->isIncompleteArrayType())
13613 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
13614 else
13615 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
13616 }
13617
13618 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
13619 const auto &Entry = LVal.Designator.Entries[I];
13620 if (BaseType->isArrayType()) {
13621 // Because __builtin_object_size treats arrays as objects, we can ignore
13622 // the index iff this is the last array in the Designator.
13623 if (I + 1 == E)
13624 return true;
13625 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
13626 uint64_t Index = Entry.getAsArrayIndex();
13627 if (Index + 1 != CAT->getZExtSize())
13628 return false;
13629 BaseType = CAT->getElementType();
13630 } else if (BaseType->isAnyComplexType()) {
13631 const auto *CT = BaseType->castAs<ComplexType>();
13632 uint64_t Index = Entry.getAsArrayIndex();
13633 if (Index != 1)
13634 return false;
13635 BaseType = CT->getElementType();
13636 } else if (auto *FD = getAsField(Entry)) {
13637 if (!IsLastOrInvalidFieldDecl(FD))
13638 return false;
13639 BaseType = FD->getType();
13640 } else {
13641 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
13642 return false;
13643 }
13644 }
13645 return true;
13646}
13647
13648/// Tests to see if the LValue has a user-specified designator (that isn't
13649/// necessarily valid). Note that this always returns 'true' if the LValue has
13650/// an unsized array as its first designator entry, because there's currently no
13651/// way to tell if the user typed *foo or foo[0].
13652static bool refersToCompleteObject(const LValue &LVal) {
13653 if (LVal.Designator.Invalid)
13654 return false;
13655
13656 if (!LVal.Designator.Entries.empty())
13657 return LVal.Designator.isMostDerivedAnUnsizedArray();
13658
13659 if (!LVal.InvalidBase)
13660 return true;
13661
13662 // If `E` is a MemberExpr, then the first part of the designator is hiding in
13663 // the LValueBase.
13664 const auto *E = LVal.Base.dyn_cast<const Expr *>();
13665 return !E || !isa<MemberExpr>(E);
13666}
13667
13668/// Attempts to detect a user writing into a piece of memory that's impossible
13669/// to figure out the size of by just using types.
13670static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
13671 const SubobjectDesignator &Designator = LVal.Designator;
13672 // Notes:
13673 // - Users can only write off of the end when we have an invalid base. Invalid
13674 // bases imply we don't know where the memory came from.
13675 // - We used to be a bit more aggressive here; we'd only be conservative if
13676 // the array at the end was flexible, or if it had 0 or 1 elements. This
13677 // broke some common standard library extensions (PR30346), but was
13678 // otherwise seemingly fine. It may be useful to reintroduce this behavior
13679 // with some sort of list. OTOH, it seems that GCC is always
13680 // conservative with the last element in structs (if it's an array), so our
13681 // current behavior is more compatible than an explicit list approach would
13682 // be.
13683 auto isFlexibleArrayMember = [&] {
13685 FAMKind StrictFlexArraysLevel =
13686 Ctx.getLangOpts().getStrictFlexArraysLevel();
13687
13688 if (Designator.isMostDerivedAnUnsizedArray())
13689 return true;
13690
13691 if (StrictFlexArraysLevel == FAMKind::Default)
13692 return true;
13693
13694 if (Designator.getMostDerivedArraySize() == 0 &&
13695 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
13696 return true;
13697
13698 if (Designator.getMostDerivedArraySize() == 1 &&
13699 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
13700 return true;
13701
13702 return false;
13703 };
13704
13705 return LVal.InvalidBase &&
13706 Designator.Entries.size() == Designator.MostDerivedPathLength &&
13707 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
13708 isDesignatorAtObjectEnd(Ctx, LVal);
13709}
13710
13711/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
13712/// Fails if the conversion would cause loss of precision.
13713static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
13714 CharUnits &Result) {
13715 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
13716 if (Int.ugt(CharUnitsMax))
13717 return false;
13718 Result = CharUnits::fromQuantity(Int.getZExtValue());
13719 return true;
13720}
13721
13722/// If we're evaluating the object size of an instance of a struct that
13723/// contains a flexible array member, add the size of the initializer.
13724static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
13725 const LValue &LV, CharUnits &Size) {
13726 if (!T.isNull() && T->isStructureType() &&
13727 T->castAsRecordDecl()->hasFlexibleArrayMember())
13728 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
13729 if (const auto *VD = dyn_cast<VarDecl>(V))
13730 if (VD->hasInit())
13731 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
13732}
13733
13734/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
13735/// determine how many bytes exist from the beginning of the object to either
13736/// the end of the current subobject, or the end of the object itself, depending
13737/// on what the LValue looks like + the value of Type.
13738///
13739/// If this returns false, the value of Result is undefined.
13740static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
13741 unsigned Type, const LValue &LVal,
13742 CharUnits &EndOffset) {
13743 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
13744
13745 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
13746 if (Ty.isNull())
13747 return false;
13748
13749 Ty = Ty.getNonReferenceType();
13750
13751 if (Ty->isIncompleteType() || Ty->isFunctionType())
13752 return false;
13753
13754 return HandleSizeof(Info, ExprLoc, Ty, Result);
13755 };
13756
13757 // We want to evaluate the size of the entire object. This is a valid fallback
13758 // for when Type=1 and the designator is invalid, because we're asked for an
13759 // upper-bound.
13760 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
13761 // Type=3 wants a lower bound, so we can't fall back to this.
13762 if (Type == 3 && !DetermineForCompleteObject)
13763 return false;
13764
13765 llvm::APInt APEndOffset;
13766 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13767 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13768 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13769
13770 if (LVal.InvalidBase)
13771 return false;
13772
13773 QualType BaseTy = getObjectType(LVal.getLValueBase());
13774 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
13775 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
13776 return Ret;
13777 }
13778
13779 // We want to evaluate the size of a subobject.
13780 const SubobjectDesignator &Designator = LVal.Designator;
13781
13782 // The following is a moderately common idiom in C:
13783 //
13784 // struct Foo { int a; char c[1]; };
13785 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
13786 // strcpy(&F->c[0], Bar);
13787 //
13788 // In order to not break too much legacy code, we need to support it.
13789 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
13790 // If we can resolve this to an alloc_size call, we can hand that back,
13791 // because we know for certain how many bytes there are to write to.
13792 llvm::APInt APEndOffset;
13793 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13794 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13795 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13796
13797 // If we cannot determine the size of the initial allocation, then we can't
13798 // given an accurate upper-bound. However, we are still able to give
13799 // conservative lower-bounds for Type=3.
13800 if (Type == 1)
13801 return false;
13802 }
13803
13804 CharUnits BytesPerElem;
13805 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
13806 return false;
13807
13808 // According to the GCC documentation, we want the size of the subobject
13809 // denoted by the pointer. But that's not quite right -- what we actually
13810 // want is the size of the immediately-enclosing array, if there is one.
13811 int64_t ElemsRemaining;
13812 if (Designator.MostDerivedIsArrayElement &&
13813 Designator.Entries.size() == Designator.MostDerivedPathLength) {
13814 uint64_t ArraySize = Designator.getMostDerivedArraySize();
13815 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
13816 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
13817 } else {
13818 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
13819 }
13820
13821 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
13822 return true;
13823}
13824
13825/// Tries to evaluate the __builtin_object_size for @p E. If successful,
13826/// returns true and stores the result in @p Size.
13827///
13828/// If @p WasError is non-null, this will report whether the failure to evaluate
13829/// is to be treated as an Error in IntExprEvaluator.
13830static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
13831 EvalInfo &Info, uint64_t &Size) {
13832 // Determine the denoted object.
13833 LValue LVal;
13834 {
13835 // The operand of __builtin_object_size is never evaluated for side-effects.
13836 // If there are any, but we can determine the pointed-to object anyway, then
13837 // ignore the side-effects.
13838 SpeculativeEvaluationRAII SpeculativeEval(Info);
13839 IgnoreSideEffectsRAII Fold(Info);
13840
13841 if (E->isGLValue()) {
13842 // It's possible for us to be given GLValues if we're called via
13843 // Expr::tryEvaluateObjectSize.
13844 APValue RVal;
13845 if (!EvaluateAsRValue(Info, E, RVal))
13846 return false;
13847 LVal.setFrom(Info.Ctx, RVal);
13848 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
13849 /*InvalidBaseOK=*/true))
13850 return false;
13851 }
13852
13853 // If we point to before the start of the object, there are no accessible
13854 // bytes.
13855 if (LVal.getLValueOffset().isNegative()) {
13856 Size = 0;
13857 return true;
13858 }
13859
13860 CharUnits EndOffset;
13861 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
13862 return false;
13863
13864 // If we've fallen outside of the end offset, just pretend there's nothing to
13865 // write to/read from.
13866 if (EndOffset <= LVal.getLValueOffset())
13867 Size = 0;
13868 else
13869 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
13870 return true;
13871}
13872
13873bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
13874 if (!IsConstantEvaluatedBuiltinCall(E))
13875 return ExprEvaluatorBaseTy::VisitCallExpr(E);
13876 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
13877}
13878
13879static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
13880 APValue &Val, APSInt &Alignment) {
13881 QualType SrcTy = E->getArg(0)->getType();
13882 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
13883 return false;
13884 // Even though we are evaluating integer expressions we could get a pointer
13885 // argument for the __builtin_is_aligned() case.
13886 if (SrcTy->isPointerType()) {
13887 LValue Ptr;
13888 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
13889 return false;
13890 Ptr.moveInto(Val);
13891 } else if (!SrcTy->isIntegralOrEnumerationType()) {
13892 Info.FFDiag(E->getArg(0));
13893 return false;
13894 } else {
13895 APSInt SrcInt;
13896 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
13897 return false;
13898 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
13899 "Bit widths must be the same");
13900 Val = APValue(SrcInt);
13901 }
13902 assert(Val.hasValue());
13903 return true;
13904}
13905
13906bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
13907 unsigned BuiltinOp) {
13908
13909 auto HandleMaskBinOp =
13910 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
13911 -> bool {
13912 APValue LHS, RHS;
13913 if (!Evaluate(LHS, Info, E->getArg(0)) ||
13914 !Evaluate(RHS, Info, E->getArg(1)))
13915 return false;
13916
13917 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
13918
13919 return Success(APValue(ResultInt), E);
13920 };
13921
13922 switch (BuiltinOp) {
13923 default:
13924 return false;
13925
13926 case Builtin::BI__builtin_dynamic_object_size:
13927 case Builtin::BI__builtin_object_size: {
13928 // The type was checked when we built the expression.
13929 unsigned Type =
13930 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13931 assert(Type <= 3 && "unexpected type");
13932
13933 uint64_t Size;
13934 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
13935 return Success(Size, E);
13936
13937 if (E->getArg(0)->HasSideEffects(Info.Ctx))
13938 return Success((Type & 2) ? 0 : -1, E);
13939
13940 // Expression had no side effects, but we couldn't statically determine the
13941 // size of the referenced object.
13942 switch (Info.EvalMode) {
13943 case EvaluationMode::ConstantExpression:
13944 case EvaluationMode::ConstantFold:
13945 case EvaluationMode::IgnoreSideEffects:
13946 // Leave it to IR generation.
13947 return Error(E);
13948 case EvaluationMode::ConstantExpressionUnevaluated:
13949 // Reduce it to a constant now.
13950 return Success((Type & 2) ? 0 : -1, E);
13951 }
13952
13953 llvm_unreachable("unexpected EvalMode");
13954 }
13955
13956 case Builtin::BI__builtin_os_log_format_buffer_size: {
13957 analyze_os_log::OSLogBufferLayout Layout;
13958 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
13959 return Success(Layout.size().getQuantity(), E);
13960 }
13961
13962 case Builtin::BI__builtin_is_aligned: {
13963 APValue Src;
13964 APSInt Alignment;
13965 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13966 return false;
13967 if (Src.isLValue()) {
13968 // If we evaluated a pointer, check the minimum known alignment.
13969 LValue Ptr;
13970 Ptr.setFrom(Info.Ctx, Src);
13971 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
13972 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
13973 // We can return true if the known alignment at the computed offset is
13974 // greater than the requested alignment.
13975 assert(PtrAlign.isPowerOfTwo());
13976 assert(Alignment.isPowerOf2());
13977 if (PtrAlign.getQuantity() >= Alignment)
13978 return Success(1, E);
13979 // If the alignment is not known to be sufficient, some cases could still
13980 // be aligned at run time. However, if the requested alignment is less or
13981 // equal to the base alignment and the offset is not aligned, we know that
13982 // the run-time value can never be aligned.
13983 if (BaseAlignment.getQuantity() >= Alignment &&
13984 PtrAlign.getQuantity() < Alignment)
13985 return Success(0, E);
13986 // Otherwise we can't infer whether the value is sufficiently aligned.
13987 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
13988 // in cases where we can't fully evaluate the pointer.
13989 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
13990 << Alignment;
13991 return false;
13992 }
13993 assert(Src.isInt());
13994 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
13995 }
13996 case Builtin::BI__builtin_align_up: {
13997 APValue Src;
13998 APSInt Alignment;
13999 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
14000 return false;
14001 if (!Src.isInt())
14002 return Error(E);
14003 APSInt AlignedVal =
14004 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
14005 Src.getInt().isUnsigned());
14006 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
14007 return Success(AlignedVal, E);
14008 }
14009 case Builtin::BI__builtin_align_down: {
14010 APValue Src;
14011 APSInt Alignment;
14012 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
14013 return false;
14014 if (!Src.isInt())
14015 return Error(E);
14016 APSInt AlignedVal =
14017 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
14018 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
14019 return Success(AlignedVal, E);
14020 }
14021
14022 case Builtin::BI__builtin_bitreverse8:
14023 case Builtin::BI__builtin_bitreverse16:
14024 case Builtin::BI__builtin_bitreverse32:
14025 case Builtin::BI__builtin_bitreverse64:
14026 case Builtin::BI__builtin_elementwise_bitreverse: {
14027 APSInt Val;
14028 if (!EvaluateInteger(E->getArg(0), Val, Info))
14029 return false;
14030
14031 return Success(Val.reverseBits(), E);
14032 }
14033
14034 case Builtin::BI__builtin_bswap16:
14035 case Builtin::BI__builtin_bswap32:
14036 case Builtin::BI__builtin_bswap64: {
14037 APSInt Val;
14038 if (!EvaluateInteger(E->getArg(0), Val, Info))
14039 return false;
14040
14041 return Success(Val.byteSwap(), E);
14042 }
14043
14044 case Builtin::BI__builtin_classify_type:
14045 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
14046
14047 case Builtin::BI__builtin_clrsb:
14048 case Builtin::BI__builtin_clrsbl:
14049 case Builtin::BI__builtin_clrsbll: {
14050 APSInt Val;
14051 if (!EvaluateInteger(E->getArg(0), Val, Info))
14052 return false;
14053
14054 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
14055 }
14056
14057 case Builtin::BI__builtin_clz:
14058 case Builtin::BI__builtin_clzl:
14059 case Builtin::BI__builtin_clzll:
14060 case Builtin::BI__builtin_clzs:
14061 case Builtin::BI__builtin_clzg:
14062 case Builtin::BI__builtin_elementwise_clzg:
14063 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
14064 case Builtin::BI__lzcnt:
14065 case Builtin::BI__lzcnt64: {
14066 APSInt Val;
14067 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
14068 APValue Vec;
14069 if (!EvaluateVector(E->getArg(0), Vec, Info))
14070 return false;
14071 Val = ConvertBoolVectorToInt(Vec);
14072 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
14073 return false;
14074 }
14075
14076 std::optional<APSInt> Fallback;
14077 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
14078 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
14079 E->getNumArgs() > 1) {
14080 APSInt FallbackTemp;
14081 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
14082 return false;
14083 Fallback = FallbackTemp;
14084 }
14085
14086 if (!Val) {
14087 if (Fallback)
14088 return Success(*Fallback, E);
14089
14090 // When the argument is 0, the result of GCC builtins is undefined,
14091 // whereas for Microsoft intrinsics, the result is the bit-width of the
14092 // argument.
14093 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
14094 BuiltinOp != Builtin::BI__lzcnt &&
14095 BuiltinOp != Builtin::BI__lzcnt64;
14096
14097 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
14098 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14099 << /*IsTrailing=*/false;
14100 }
14101
14102 if (ZeroIsUndefined)
14103 return Error(E);
14104 }
14105
14106 return Success(Val.countl_zero(), E);
14107 }
14108
14109 case Builtin::BI__builtin_constant_p: {
14110 const Expr *Arg = E->getArg(0);
14111 if (EvaluateBuiltinConstantP(Info, Arg))
14112 return Success(true, E);
14113 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
14114 // Outside a constant context, eagerly evaluate to false in the presence
14115 // of side-effects in order to avoid -Wunsequenced false-positives in
14116 // a branch on __builtin_constant_p(expr).
14117 return Success(false, E);
14118 }
14119 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14120 return false;
14121 }
14122
14123 case Builtin::BI__noop:
14124 // __noop always evaluates successfully and returns 0.
14125 return Success(0, E);
14126
14127 case Builtin::BI__builtin_is_constant_evaluated: {
14128 const auto *Callee = Info.CurrentCall->getCallee();
14129 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
14130 (Info.CallStackDepth == 1 ||
14131 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
14132 Callee->getIdentifier() &&
14133 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
14134 // FIXME: Find a better way to avoid duplicated diagnostics.
14135 if (Info.EvalStatus.Diag)
14136 Info.report((Info.CallStackDepth == 1)
14137 ? E->getExprLoc()
14138 : Info.CurrentCall->getCallRange().getBegin(),
14139 diag::warn_is_constant_evaluated_always_true_constexpr)
14140 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
14141 : "std::is_constant_evaluated");
14142 }
14143
14144 return Success(Info.InConstantContext, E);
14145 }
14146
14147 case Builtin::BI__builtin_is_within_lifetime:
14148 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
14149 return Success(*result, E);
14150 return false;
14151
14152 case Builtin::BI__builtin_ctz:
14153 case Builtin::BI__builtin_ctzl:
14154 case Builtin::BI__builtin_ctzll:
14155 case Builtin::BI__builtin_ctzs:
14156 case Builtin::BI__builtin_ctzg:
14157 case Builtin::BI__builtin_elementwise_ctzg: {
14158 APSInt Val;
14159 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
14160 APValue Vec;
14161 if (!EvaluateVector(E->getArg(0), Vec, Info))
14162 return false;
14163 Val = ConvertBoolVectorToInt(Vec);
14164 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
14165 return false;
14166 }
14167
14168 std::optional<APSInt> Fallback;
14169 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
14170 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
14171 E->getNumArgs() > 1) {
14172 APSInt FallbackTemp;
14173 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
14174 return false;
14175 Fallback = FallbackTemp;
14176 }
14177
14178 if (!Val) {
14179 if (Fallback)
14180 return Success(*Fallback, E);
14181
14182 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
14183 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14184 << /*IsTrailing=*/true;
14185 }
14186 return Error(E);
14187 }
14188
14189 return Success(Val.countr_zero(), E);
14190 }
14191
14192 case Builtin::BI__builtin_eh_return_data_regno: {
14193 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
14194 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
14195 return Success(Operand, E);
14196 }
14197
14198 case Builtin::BI__builtin_elementwise_abs: {
14199 APSInt Val;
14200 if (!EvaluateInteger(E->getArg(0), Val, Info))
14201 return false;
14202
14203 return Success(Val.abs(), E);
14204 }
14205
14206 case Builtin::BI__builtin_expect:
14207 case Builtin::BI__builtin_expect_with_probability:
14208 return Visit(E->getArg(0));
14209
14210 case Builtin::BI__builtin_ptrauth_string_discriminator: {
14211 const auto *Literal =
14213 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
14214 return Success(Result, E);
14215 }
14216
14217 case Builtin::BI__builtin_ffs:
14218 case Builtin::BI__builtin_ffsl:
14219 case Builtin::BI__builtin_ffsll: {
14220 APSInt Val;
14221 if (!EvaluateInteger(E->getArg(0), Val, Info))
14222 return false;
14223
14224 unsigned N = Val.countr_zero();
14225 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
14226 }
14227
14228 case Builtin::BI__builtin_fpclassify: {
14229 APFloat Val(0.0);
14230 if (!EvaluateFloat(E->getArg(5), Val, Info))
14231 return false;
14232 unsigned Arg;
14233 switch (Val.getCategory()) {
14234 case APFloat::fcNaN: Arg = 0; break;
14235 case APFloat::fcInfinity: Arg = 1; break;
14236 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
14237 case APFloat::fcZero: Arg = 4; break;
14238 }
14239 return Visit(E->getArg(Arg));
14240 }
14241
14242 case Builtin::BI__builtin_isinf_sign: {
14243 APFloat Val(0.0);
14244 return EvaluateFloat(E->getArg(0), Val, Info) &&
14245 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
14246 }
14247
14248 case Builtin::BI__builtin_isinf: {
14249 APFloat Val(0.0);
14250 return EvaluateFloat(E->getArg(0), Val, Info) &&
14251 Success(Val.isInfinity() ? 1 : 0, E);
14252 }
14253
14254 case Builtin::BI__builtin_isfinite: {
14255 APFloat Val(0.0);
14256 return EvaluateFloat(E->getArg(0), Val, Info) &&
14257 Success(Val.isFinite() ? 1 : 0, E);
14258 }
14259
14260 case Builtin::BI__builtin_isnan: {
14261 APFloat Val(0.0);
14262 return EvaluateFloat(E->getArg(0), Val, Info) &&
14263 Success(Val.isNaN() ? 1 : 0, E);
14264 }
14265
14266 case Builtin::BI__builtin_isnormal: {
14267 APFloat Val(0.0);
14268 return EvaluateFloat(E->getArg(0), Val, Info) &&
14269 Success(Val.isNormal() ? 1 : 0, E);
14270 }
14271
14272 case Builtin::BI__builtin_issubnormal: {
14273 APFloat Val(0.0);
14274 return EvaluateFloat(E->getArg(0), Val, Info) &&
14275 Success(Val.isDenormal() ? 1 : 0, E);
14276 }
14277
14278 case Builtin::BI__builtin_iszero: {
14279 APFloat Val(0.0);
14280 return EvaluateFloat(E->getArg(0), Val, Info) &&
14281 Success(Val.isZero() ? 1 : 0, E);
14282 }
14283
14284 case Builtin::BI__builtin_signbit:
14285 case Builtin::BI__builtin_signbitf:
14286 case Builtin::BI__builtin_signbitl: {
14287 APFloat Val(0.0);
14288 return EvaluateFloat(E->getArg(0), Val, Info) &&
14289 Success(Val.isNegative() ? 1 : 0, E);
14290 }
14291
14292 case Builtin::BI__builtin_isgreater:
14293 case Builtin::BI__builtin_isgreaterequal:
14294 case Builtin::BI__builtin_isless:
14295 case Builtin::BI__builtin_islessequal:
14296 case Builtin::BI__builtin_islessgreater:
14297 case Builtin::BI__builtin_isunordered: {
14298 APFloat LHS(0.0);
14299 APFloat RHS(0.0);
14300 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
14301 !EvaluateFloat(E->getArg(1), RHS, Info))
14302 return false;
14303
14304 return Success(
14305 [&] {
14306 switch (BuiltinOp) {
14307 case Builtin::BI__builtin_isgreater:
14308 return LHS > RHS;
14309 case Builtin::BI__builtin_isgreaterequal:
14310 return LHS >= RHS;
14311 case Builtin::BI__builtin_isless:
14312 return LHS < RHS;
14313 case Builtin::BI__builtin_islessequal:
14314 return LHS <= RHS;
14315 case Builtin::BI__builtin_islessgreater: {
14316 APFloat::cmpResult cmp = LHS.compare(RHS);
14317 return cmp == APFloat::cmpResult::cmpLessThan ||
14318 cmp == APFloat::cmpResult::cmpGreaterThan;
14319 }
14320 case Builtin::BI__builtin_isunordered:
14321 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
14322 default:
14323 llvm_unreachable("Unexpected builtin ID: Should be a floating "
14324 "point comparison function");
14325 }
14326 }()
14327 ? 1
14328 : 0,
14329 E);
14330 }
14331
14332 case Builtin::BI__builtin_issignaling: {
14333 APFloat Val(0.0);
14334 return EvaluateFloat(E->getArg(0), Val, Info) &&
14335 Success(Val.isSignaling() ? 1 : 0, E);
14336 }
14337
14338 case Builtin::BI__builtin_isfpclass: {
14339 APSInt MaskVal;
14340 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
14341 return false;
14342 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
14343 APFloat Val(0.0);
14344 return EvaluateFloat(E->getArg(0), Val, Info) &&
14345 Success((Val.classify() & Test) ? 1 : 0, E);
14346 }
14347
14348 case Builtin::BI__builtin_parity:
14349 case Builtin::BI__builtin_parityl:
14350 case Builtin::BI__builtin_parityll: {
14351 APSInt Val;
14352 if (!EvaluateInteger(E->getArg(0), Val, Info))
14353 return false;
14354
14355 return Success(Val.popcount() % 2, E);
14356 }
14357
14358 case Builtin::BI__builtin_abs:
14359 case Builtin::BI__builtin_labs:
14360 case Builtin::BI__builtin_llabs: {
14361 APSInt Val;
14362 if (!EvaluateInteger(E->getArg(0), Val, Info))
14363 return false;
14364 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
14365 /*IsUnsigned=*/false))
14366 return false;
14367 if (Val.isNegative())
14368 Val.negate();
14369 return Success(Val, E);
14370 }
14371
14372 case Builtin::BI__builtin_popcount:
14373 case Builtin::BI__builtin_popcountl:
14374 case Builtin::BI__builtin_popcountll:
14375 case Builtin::BI__builtin_popcountg:
14376 case Builtin::BI__builtin_elementwise_popcount:
14377 case Builtin::BI__popcnt16: // Microsoft variants of popcount
14378 case Builtin::BI__popcnt:
14379 case Builtin::BI__popcnt64: {
14380 APSInt Val;
14381 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
14382 APValue Vec;
14383 if (!EvaluateVector(E->getArg(0), Vec, Info))
14384 return false;
14385 Val = ConvertBoolVectorToInt(Vec);
14386 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
14387 return false;
14388 }
14389
14390 return Success(Val.popcount(), E);
14391 }
14392
14393 case Builtin::BI__builtin_rotateleft8:
14394 case Builtin::BI__builtin_rotateleft16:
14395 case Builtin::BI__builtin_rotateleft32:
14396 case Builtin::BI__builtin_rotateleft64:
14397 case Builtin::BI_rotl8: // Microsoft variants of rotate right
14398 case Builtin::BI_rotl16:
14399 case Builtin::BI_rotl:
14400 case Builtin::BI_lrotl:
14401 case Builtin::BI_rotl64: {
14402 APSInt Val, Amt;
14403 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14404 !EvaluateInteger(E->getArg(1), Amt, Info))
14405 return false;
14406
14407 return Success(Val.rotl(Amt), E);
14408 }
14409
14410 case Builtin::BI__builtin_rotateright8:
14411 case Builtin::BI__builtin_rotateright16:
14412 case Builtin::BI__builtin_rotateright32:
14413 case Builtin::BI__builtin_rotateright64:
14414 case Builtin::BI_rotr8: // Microsoft variants of rotate right
14415 case Builtin::BI_rotr16:
14416 case Builtin::BI_rotr:
14417 case Builtin::BI_lrotr:
14418 case Builtin::BI_rotr64: {
14419 APSInt Val, Amt;
14420 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14421 !EvaluateInteger(E->getArg(1), Amt, Info))
14422 return false;
14423
14424 return Success(Val.rotr(Amt), E);
14425 }
14426
14427 case Builtin::BI__builtin_elementwise_add_sat: {
14428 APSInt LHS, RHS;
14429 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14430 !EvaluateInteger(E->getArg(1), RHS, Info))
14431 return false;
14432
14433 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
14434 return Success(APSInt(Result, !LHS.isSigned()), E);
14435 }
14436 case Builtin::BI__builtin_elementwise_sub_sat: {
14437 APSInt LHS, RHS;
14438 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14439 !EvaluateInteger(E->getArg(1), RHS, Info))
14440 return false;
14441
14442 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
14443 return Success(APSInt(Result, !LHS.isSigned()), E);
14444 }
14445 case Builtin::BI__builtin_elementwise_max: {
14446 APSInt LHS, RHS;
14447 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14448 !EvaluateInteger(E->getArg(1), RHS, Info))
14449 return false;
14450
14451 APInt Result = std::max(LHS, RHS);
14452 return Success(APSInt(Result, !LHS.isSigned()), E);
14453 }
14454 case Builtin::BI__builtin_elementwise_min: {
14455 APSInt LHS, RHS;
14456 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14457 !EvaluateInteger(E->getArg(1), RHS, Info))
14458 return false;
14459
14460 APInt Result = std::min(LHS, RHS);
14461 return Success(APSInt(Result, !LHS.isSigned()), E);
14462 }
14463 case Builtin::BI__builtin_elementwise_fshl:
14464 case Builtin::BI__builtin_elementwise_fshr: {
14465 APSInt Hi, Lo, Shift;
14466 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
14467 !EvaluateInteger(E->getArg(1), Lo, Info) ||
14468 !EvaluateInteger(E->getArg(2), Shift, Info))
14469 return false;
14470
14471 switch (BuiltinOp) {
14472 case Builtin::BI__builtin_elementwise_fshl: {
14473 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
14474 return Success(Result, E);
14475 }
14476 case Builtin::BI__builtin_elementwise_fshr: {
14477 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
14478 return Success(Result, E);
14479 }
14480 }
14481 llvm_unreachable("Fully covered switch above");
14482 }
14483 case Builtin::BIstrlen:
14484 case Builtin::BIwcslen:
14485 // A call to strlen is not a constant expression.
14486 if (Info.getLangOpts().CPlusPlus11)
14487 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
14488 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
14489 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
14490 else
14491 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
14492 [[fallthrough]];
14493 case Builtin::BI__builtin_strlen:
14494 case Builtin::BI__builtin_wcslen: {
14495 // As an extension, we support __builtin_strlen() as a constant expression,
14496 // and support folding strlen() to a constant.
14497 uint64_t StrLen;
14498 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
14499 return Success(StrLen, E);
14500 return false;
14501 }
14502
14503 case Builtin::BIstrcmp:
14504 case Builtin::BIwcscmp:
14505 case Builtin::BIstrncmp:
14506 case Builtin::BIwcsncmp:
14507 case Builtin::BImemcmp:
14508 case Builtin::BIbcmp:
14509 case Builtin::BIwmemcmp:
14510 // A call to strlen is not a constant expression.
14511 if (Info.getLangOpts().CPlusPlus11)
14512 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
14513 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
14514 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
14515 else
14516 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
14517 [[fallthrough]];
14518 case Builtin::BI__builtin_strcmp:
14519 case Builtin::BI__builtin_wcscmp:
14520 case Builtin::BI__builtin_strncmp:
14521 case Builtin::BI__builtin_wcsncmp:
14522 case Builtin::BI__builtin_memcmp:
14523 case Builtin::BI__builtin_bcmp:
14524 case Builtin::BI__builtin_wmemcmp: {
14525 LValue String1, String2;
14526 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
14527 !EvaluatePointer(E->getArg(1), String2, Info))
14528 return false;
14529
14530 uint64_t MaxLength = uint64_t(-1);
14531 if (BuiltinOp != Builtin::BIstrcmp &&
14532 BuiltinOp != Builtin::BIwcscmp &&
14533 BuiltinOp != Builtin::BI__builtin_strcmp &&
14534 BuiltinOp != Builtin::BI__builtin_wcscmp) {
14535 APSInt N;
14536 if (!EvaluateInteger(E->getArg(2), N, Info))
14537 return false;
14538 MaxLength = N.getZExtValue();
14539 }
14540
14541 // Empty substrings compare equal by definition.
14542 if (MaxLength == 0u)
14543 return Success(0, E);
14544
14545 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14546 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14547 String1.Designator.Invalid || String2.Designator.Invalid)
14548 return false;
14549
14550 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
14551 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
14552
14553 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
14554 BuiltinOp == Builtin::BIbcmp ||
14555 BuiltinOp == Builtin::BI__builtin_memcmp ||
14556 BuiltinOp == Builtin::BI__builtin_bcmp;
14557
14558 assert(IsRawByte ||
14559 (Info.Ctx.hasSameUnqualifiedType(
14560 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
14561 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
14562
14563 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
14564 // 'char8_t', but no other types.
14565 if (IsRawByte &&
14566 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
14567 // FIXME: Consider using our bit_cast implementation to support this.
14568 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
14569 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
14570 << CharTy2;
14571 return false;
14572 }
14573
14574 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
14575 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
14576 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
14577 Char1.isInt() && Char2.isInt();
14578 };
14579 const auto &AdvanceElems = [&] {
14580 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
14581 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
14582 };
14583
14584 bool StopAtNull =
14585 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
14586 BuiltinOp != Builtin::BIwmemcmp &&
14587 BuiltinOp != Builtin::BI__builtin_memcmp &&
14588 BuiltinOp != Builtin::BI__builtin_bcmp &&
14589 BuiltinOp != Builtin::BI__builtin_wmemcmp);
14590 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
14591 BuiltinOp == Builtin::BIwcsncmp ||
14592 BuiltinOp == Builtin::BIwmemcmp ||
14593 BuiltinOp == Builtin::BI__builtin_wcscmp ||
14594 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
14595 BuiltinOp == Builtin::BI__builtin_wmemcmp;
14596
14597 for (; MaxLength; --MaxLength) {
14598 APValue Char1, Char2;
14599 if (!ReadCurElems(Char1, Char2))
14600 return false;
14601 if (Char1.getInt().ne(Char2.getInt())) {
14602 if (IsWide) // wmemcmp compares with wchar_t signedness.
14603 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
14604 // memcmp always compares unsigned chars.
14605 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
14606 }
14607 if (StopAtNull && !Char1.getInt())
14608 return Success(0, E);
14609 assert(!(StopAtNull && !Char2.getInt()));
14610 if (!AdvanceElems())
14611 return false;
14612 }
14613 // We hit the strncmp / memcmp limit.
14614 return Success(0, E);
14615 }
14616
14617 case Builtin::BI__atomic_always_lock_free:
14618 case Builtin::BI__atomic_is_lock_free:
14619 case Builtin::BI__c11_atomic_is_lock_free: {
14620 APSInt SizeVal;
14621 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
14622 return false;
14623
14624 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
14625 // of two less than or equal to the maximum inline atomic width, we know it
14626 // is lock-free. If the size isn't a power of two, or greater than the
14627 // maximum alignment where we promote atomics, we know it is not lock-free
14628 // (at least not in the sense of atomic_is_lock_free). Otherwise,
14629 // the answer can only be determined at runtime; for example, 16-byte
14630 // atomics have lock-free implementations on some, but not all,
14631 // x86-64 processors.
14632
14633 // Check power-of-two.
14634 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
14635 if (Size.isPowerOfTwo()) {
14636 // Check against inlining width.
14637 unsigned InlineWidthBits =
14639 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
14640 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
14641 Size == CharUnits::One())
14642 return Success(1, E);
14643
14644 // If the pointer argument can be evaluated to a compile-time constant
14645 // integer (or nullptr), check if that value is appropriately aligned.
14646 const Expr *PtrArg = E->getArg(1);
14647 Expr::EvalResult ExprResult;
14648 APSInt IntResult;
14649 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
14650 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
14651 Info.Ctx) &&
14652 IntResult.isAligned(Size.getAsAlign()))
14653 return Success(1, E);
14654
14655 // Otherwise, check if the type's alignment against Size.
14656 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
14657 // Drop the potential implicit-cast to 'const volatile void*', getting
14658 // the underlying type.
14659 if (ICE->getCastKind() == CK_BitCast)
14660 PtrArg = ICE->getSubExpr();
14661 }
14662
14663 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
14664 QualType PointeeType = PtrTy->getPointeeType();
14665 if (!PointeeType->isIncompleteType() &&
14666 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
14667 // OK, we will inline operations on this object.
14668 return Success(1, E);
14669 }
14670 }
14671 }
14672 }
14673
14674 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
14675 Success(0, E) : Error(E);
14676 }
14677 case Builtin::BI__builtin_addcb:
14678 case Builtin::BI__builtin_addcs:
14679 case Builtin::BI__builtin_addc:
14680 case Builtin::BI__builtin_addcl:
14681 case Builtin::BI__builtin_addcll:
14682 case Builtin::BI__builtin_subcb:
14683 case Builtin::BI__builtin_subcs:
14684 case Builtin::BI__builtin_subc:
14685 case Builtin::BI__builtin_subcl:
14686 case Builtin::BI__builtin_subcll: {
14687 LValue CarryOutLValue;
14688 APSInt LHS, RHS, CarryIn, CarryOut, Result;
14689 QualType ResultType = E->getArg(0)->getType();
14690 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14691 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14692 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
14693 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
14694 return false;
14695 // Copy the number of bits and sign.
14696 Result = LHS;
14697 CarryOut = LHS;
14698
14699 bool FirstOverflowed = false;
14700 bool SecondOverflowed = false;
14701 switch (BuiltinOp) {
14702 default:
14703 llvm_unreachable("Invalid value for BuiltinOp");
14704 case Builtin::BI__builtin_addcb:
14705 case Builtin::BI__builtin_addcs:
14706 case Builtin::BI__builtin_addc:
14707 case Builtin::BI__builtin_addcl:
14708 case Builtin::BI__builtin_addcll:
14709 Result =
14710 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
14711 break;
14712 case Builtin::BI__builtin_subcb:
14713 case Builtin::BI__builtin_subcs:
14714 case Builtin::BI__builtin_subc:
14715 case Builtin::BI__builtin_subcl:
14716 case Builtin::BI__builtin_subcll:
14717 Result =
14718 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
14719 break;
14720 }
14721
14722 // It is possible for both overflows to happen but CGBuiltin uses an OR so
14723 // this is consistent.
14724 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
14725 APValue APV{CarryOut};
14726 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
14727 return false;
14728 return Success(Result, E);
14729 }
14730 case Builtin::BI__builtin_add_overflow:
14731 case Builtin::BI__builtin_sub_overflow:
14732 case Builtin::BI__builtin_mul_overflow:
14733 case Builtin::BI__builtin_sadd_overflow:
14734 case Builtin::BI__builtin_uadd_overflow:
14735 case Builtin::BI__builtin_uaddl_overflow:
14736 case Builtin::BI__builtin_uaddll_overflow:
14737 case Builtin::BI__builtin_usub_overflow:
14738 case Builtin::BI__builtin_usubl_overflow:
14739 case Builtin::BI__builtin_usubll_overflow:
14740 case Builtin::BI__builtin_umul_overflow:
14741 case Builtin::BI__builtin_umull_overflow:
14742 case Builtin::BI__builtin_umulll_overflow:
14743 case Builtin::BI__builtin_saddl_overflow:
14744 case Builtin::BI__builtin_saddll_overflow:
14745 case Builtin::BI__builtin_ssub_overflow:
14746 case Builtin::BI__builtin_ssubl_overflow:
14747 case Builtin::BI__builtin_ssubll_overflow:
14748 case Builtin::BI__builtin_smul_overflow:
14749 case Builtin::BI__builtin_smull_overflow:
14750 case Builtin::BI__builtin_smulll_overflow: {
14751 LValue ResultLValue;
14752 APSInt LHS, RHS;
14753
14754 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
14755 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14756 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14757 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
14758 return false;
14759
14760 APSInt Result;
14761 bool DidOverflow = false;
14762
14763 // If the types don't have to match, enlarge all 3 to the largest of them.
14764 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14765 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14766 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14767 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
14769 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
14771 uint64_t LHSSize = LHS.getBitWidth();
14772 uint64_t RHSSize = RHS.getBitWidth();
14773 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
14774 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
14775
14776 // Add an additional bit if the signedness isn't uniformly agreed to. We
14777 // could do this ONLY if there is a signed and an unsigned that both have
14778 // MaxBits, but the code to check that is pretty nasty. The issue will be
14779 // caught in the shrink-to-result later anyway.
14780 if (IsSigned && !AllSigned)
14781 ++MaxBits;
14782
14783 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
14784 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
14785 Result = APSInt(MaxBits, !IsSigned);
14786 }
14787
14788 // Find largest int.
14789 switch (BuiltinOp) {
14790 default:
14791 llvm_unreachable("Invalid value for BuiltinOp");
14792 case Builtin::BI__builtin_add_overflow:
14793 case Builtin::BI__builtin_sadd_overflow:
14794 case Builtin::BI__builtin_saddl_overflow:
14795 case Builtin::BI__builtin_saddll_overflow:
14796 case Builtin::BI__builtin_uadd_overflow:
14797 case Builtin::BI__builtin_uaddl_overflow:
14798 case Builtin::BI__builtin_uaddll_overflow:
14799 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
14800 : LHS.uadd_ov(RHS, DidOverflow);
14801 break;
14802 case Builtin::BI__builtin_sub_overflow:
14803 case Builtin::BI__builtin_ssub_overflow:
14804 case Builtin::BI__builtin_ssubl_overflow:
14805 case Builtin::BI__builtin_ssubll_overflow:
14806 case Builtin::BI__builtin_usub_overflow:
14807 case Builtin::BI__builtin_usubl_overflow:
14808 case Builtin::BI__builtin_usubll_overflow:
14809 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
14810 : LHS.usub_ov(RHS, DidOverflow);
14811 break;
14812 case Builtin::BI__builtin_mul_overflow:
14813 case Builtin::BI__builtin_smul_overflow:
14814 case Builtin::BI__builtin_smull_overflow:
14815 case Builtin::BI__builtin_smulll_overflow:
14816 case Builtin::BI__builtin_umul_overflow:
14817 case Builtin::BI__builtin_umull_overflow:
14818 case Builtin::BI__builtin_umulll_overflow:
14819 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
14820 : LHS.umul_ov(RHS, DidOverflow);
14821 break;
14822 }
14823
14824 // In the case where multiple sizes are allowed, truncate and see if
14825 // the values are the same.
14826 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14827 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14828 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14829 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
14830 // since it will give us the behavior of a TruncOrSelf in the case where
14831 // its parameter <= its size. We previously set Result to be at least the
14832 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
14833 // will work exactly like TruncOrSelf.
14834 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
14835 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
14836
14837 if (!APSInt::isSameValue(Temp, Result))
14838 DidOverflow = true;
14839 Result = Temp;
14840 }
14841
14842 APValue APV{Result};
14843 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14844 return false;
14845 return Success(DidOverflow, E);
14846 }
14847
14848 case Builtin::BI__builtin_reduce_add:
14849 case Builtin::BI__builtin_reduce_mul:
14850 case Builtin::BI__builtin_reduce_and:
14851 case Builtin::BI__builtin_reduce_or:
14852 case Builtin::BI__builtin_reduce_xor:
14853 case Builtin::BI__builtin_reduce_min:
14854 case Builtin::BI__builtin_reduce_max: {
14855 APValue Source;
14856 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
14857 return false;
14858
14859 unsigned SourceLen = Source.getVectorLength();
14860 APSInt Reduced = Source.getVectorElt(0).getInt();
14861 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
14862 switch (BuiltinOp) {
14863 default:
14864 return false;
14865 case Builtin::BI__builtin_reduce_add: {
14867 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14868 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
14869 return false;
14870 break;
14871 }
14872 case Builtin::BI__builtin_reduce_mul: {
14874 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14875 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
14876 return false;
14877 break;
14878 }
14879 case Builtin::BI__builtin_reduce_and: {
14880 Reduced &= Source.getVectorElt(EltNum).getInt();
14881 break;
14882 }
14883 case Builtin::BI__builtin_reduce_or: {
14884 Reduced |= Source.getVectorElt(EltNum).getInt();
14885 break;
14886 }
14887 case Builtin::BI__builtin_reduce_xor: {
14888 Reduced ^= Source.getVectorElt(EltNum).getInt();
14889 break;
14890 }
14891 case Builtin::BI__builtin_reduce_min: {
14892 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
14893 break;
14894 }
14895 case Builtin::BI__builtin_reduce_max: {
14896 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
14897 break;
14898 }
14899 }
14900 }
14901
14902 return Success(Reduced, E);
14903 }
14904
14905 case clang::X86::BI__builtin_ia32_addcarryx_u32:
14906 case clang::X86::BI__builtin_ia32_addcarryx_u64:
14907 case clang::X86::BI__builtin_ia32_subborrow_u32:
14908 case clang::X86::BI__builtin_ia32_subborrow_u64: {
14909 LValue ResultLValue;
14910 APSInt CarryIn, LHS, RHS;
14911 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
14912 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
14913 !EvaluateInteger(E->getArg(1), LHS, Info) ||
14914 !EvaluateInteger(E->getArg(2), RHS, Info) ||
14915 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
14916 return false;
14917
14918 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
14919 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
14920
14921 unsigned BitWidth = LHS.getBitWidth();
14922 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
14923 APInt ExResult =
14924 IsAdd
14925 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
14926 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
14927
14928 APInt Result = ExResult.extractBits(BitWidth, 0);
14929 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
14930
14931 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
14932 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14933 return false;
14934 return Success(CarryOut, E);
14935 }
14936
14937 case clang::X86::BI__builtin_ia32_bextr_u32:
14938 case clang::X86::BI__builtin_ia32_bextr_u64:
14939 case clang::X86::BI__builtin_ia32_bextri_u32:
14940 case clang::X86::BI__builtin_ia32_bextri_u64: {
14941 APSInt Val, Idx;
14942 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14943 !EvaluateInteger(E->getArg(1), Idx, Info))
14944 return false;
14945
14946 unsigned BitWidth = Val.getBitWidth();
14947 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
14948 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
14949 Length = Length > BitWidth ? BitWidth : Length;
14950
14951 // Handle out of bounds cases.
14952 if (Length == 0 || Shift >= BitWidth)
14953 return Success(0, E);
14954
14955 uint64_t Result = Val.getZExtValue() >> Shift;
14956 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
14957 return Success(Result, E);
14958 }
14959
14960 case clang::X86::BI__builtin_ia32_bzhi_si:
14961 case clang::X86::BI__builtin_ia32_bzhi_di: {
14962 APSInt Val, Idx;
14963 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14964 !EvaluateInteger(E->getArg(1), Idx, Info))
14965 return false;
14966
14967 unsigned BitWidth = Val.getBitWidth();
14968 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
14969 if (Index < BitWidth)
14970 Val.clearHighBits(BitWidth - Index);
14971 return Success(Val, E);
14972 }
14973
14974 case clang::X86::BI__builtin_ia32_lzcnt_u16:
14975 case clang::X86::BI__builtin_ia32_lzcnt_u32:
14976 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
14977 APSInt Val;
14978 if (!EvaluateInteger(E->getArg(0), Val, Info))
14979 return false;
14980 return Success(Val.countLeadingZeros(), E);
14981 }
14982
14983 case clang::X86::BI__builtin_ia32_tzcnt_u16:
14984 case clang::X86::BI__builtin_ia32_tzcnt_u32:
14985 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
14986 APSInt Val;
14987 if (!EvaluateInteger(E->getArg(0), Val, Info))
14988 return false;
14989 return Success(Val.countTrailingZeros(), E);
14990 }
14991
14992 case clang::X86::BI__builtin_ia32_pdep_si:
14993 case clang::X86::BI__builtin_ia32_pdep_di: {
14994 APSInt Val, Msk;
14995 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14996 !EvaluateInteger(E->getArg(1), Msk, Info))
14997 return false;
14998
14999 unsigned BitWidth = Val.getBitWidth();
15000 APInt Result = APInt::getZero(BitWidth);
15001 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
15002 if (Msk[I])
15003 Result.setBitVal(I, Val[P++]);
15004 return Success(Result, E);
15005 }
15006
15007 case clang::X86::BI__builtin_ia32_pext_si:
15008 case clang::X86::BI__builtin_ia32_pext_di: {
15009 APSInt Val, Msk;
15010 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15011 !EvaluateInteger(E->getArg(1), Msk, Info))
15012 return false;
15013
15014 unsigned BitWidth = Val.getBitWidth();
15015 APInt Result = APInt::getZero(BitWidth);
15016 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
15017 if (Msk[I])
15018 Result.setBitVal(P++, Val[I]);
15019 return Success(Result, E);
15020 }
15021
15022 case X86::BI__builtin_ia32_kandqi:
15023 case X86::BI__builtin_ia32_kandhi:
15024 case X86::BI__builtin_ia32_kandsi:
15025 case X86::BI__builtin_ia32_kanddi: {
15026 return HandleMaskBinOp(
15027 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
15028 }
15029
15030 case X86::BI__builtin_ia32_kandnqi:
15031 case X86::BI__builtin_ia32_kandnhi:
15032 case X86::BI__builtin_ia32_kandnsi:
15033 case X86::BI__builtin_ia32_kandndi: {
15034 return HandleMaskBinOp(
15035 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
15036 }
15037
15038 case X86::BI__builtin_ia32_korqi:
15039 case X86::BI__builtin_ia32_korhi:
15040 case X86::BI__builtin_ia32_korsi:
15041 case X86::BI__builtin_ia32_kordi: {
15042 return HandleMaskBinOp(
15043 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
15044 }
15045
15046 case X86::BI__builtin_ia32_kxnorqi:
15047 case X86::BI__builtin_ia32_kxnorhi:
15048 case X86::BI__builtin_ia32_kxnorsi:
15049 case X86::BI__builtin_ia32_kxnordi: {
15050 return HandleMaskBinOp(
15051 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
15052 }
15053
15054 case X86::BI__builtin_ia32_kxorqi:
15055 case X86::BI__builtin_ia32_kxorhi:
15056 case X86::BI__builtin_ia32_kxorsi:
15057 case X86::BI__builtin_ia32_kxordi: {
15058 return HandleMaskBinOp(
15059 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
15060 }
15061
15062 case X86::BI__builtin_ia32_knotqi:
15063 case X86::BI__builtin_ia32_knothi:
15064 case X86::BI__builtin_ia32_knotsi:
15065 case X86::BI__builtin_ia32_knotdi: {
15066 APSInt Val;
15067 if (!EvaluateInteger(E->getArg(0), Val, Info))
15068 return false;
15069 APSInt Result = ~Val;
15070 return Success(APValue(Result), E);
15071 }
15072
15073 case X86::BI__builtin_ia32_kaddqi:
15074 case X86::BI__builtin_ia32_kaddhi:
15075 case X86::BI__builtin_ia32_kaddsi:
15076 case X86::BI__builtin_ia32_kadddi: {
15077 return HandleMaskBinOp(
15078 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
15079 }
15080
15081 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
15082 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
15083 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
15084 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
15085 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
15086 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
15087 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
15088 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
15089 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
15090 APValue Vec;
15091 APSInt IdxAPS;
15092 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
15093 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
15094 return false;
15095 unsigned N = Vec.getVectorLength();
15096 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
15097 return Success(Vec.getVectorElt(Idx).getInt(), E);
15098 }
15099 }
15100}
15101
15102/// Determine whether this is a pointer past the end of the complete
15103/// object referred to by the lvalue.
15105 const LValue &LV) {
15106 // A null pointer can be viewed as being "past the end" but we don't
15107 // choose to look at it that way here.
15108 if (!LV.getLValueBase())
15109 return false;
15110
15111 // If the designator is valid and refers to a subobject, we're not pointing
15112 // past the end.
15113 if (!LV.getLValueDesignator().Invalid &&
15114 !LV.getLValueDesignator().isOnePastTheEnd())
15115 return false;
15116
15117 // A pointer to an incomplete type might be past-the-end if the type's size is
15118 // zero. We cannot tell because the type is incomplete.
15119 QualType Ty = getType(LV.getLValueBase());
15120 if (Ty->isIncompleteType())
15121 return true;
15122
15123 // Can't be past the end of an invalid object.
15124 if (LV.getLValueDesignator().Invalid)
15125 return false;
15126
15127 // We're a past-the-end pointer if we point to the byte after the object,
15128 // no matter what our type or path is.
15129 auto Size = Ctx.getTypeSizeInChars(Ty);
15130 return LV.getLValueOffset() == Size;
15131}
15132
15133namespace {
15134
15135/// Data recursive integer evaluator of certain binary operators.
15136///
15137/// We use a data recursive algorithm for binary operators so that we are able
15138/// to handle extreme cases of chained binary operators without causing stack
15139/// overflow.
15140class DataRecursiveIntBinOpEvaluator {
15141 struct EvalResult {
15142 APValue Val;
15143 bool Failed = false;
15144
15145 EvalResult() = default;
15146
15147 void swap(EvalResult &RHS) {
15148 Val.swap(RHS.Val);
15149 Failed = RHS.Failed;
15150 RHS.Failed = false;
15151 }
15152 };
15153
15154 struct Job {
15155 const Expr *E;
15156 EvalResult LHSResult; // meaningful only for binary operator expression.
15157 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
15158
15159 Job() = default;
15160 Job(Job &&) = default;
15161
15162 void startSpeculativeEval(EvalInfo &Info) {
15163 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
15164 }
15165
15166 private:
15167 SpeculativeEvaluationRAII SpecEvalRAII;
15168 };
15169
15170 SmallVector<Job, 16> Queue;
15171
15172 IntExprEvaluator &IntEval;
15173 EvalInfo &Info;
15174 APValue &FinalResult;
15175
15176public:
15177 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
15178 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
15179
15180 /// True if \param E is a binary operator that we are going to handle
15181 /// data recursively.
15182 /// We handle binary operators that are comma, logical, or that have operands
15183 /// with integral or enumeration type.
15184 static bool shouldEnqueue(const BinaryOperator *E) {
15185 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
15189 }
15190
15191 bool Traverse(const BinaryOperator *E) {
15192 enqueue(E);
15193 EvalResult PrevResult;
15194 while (!Queue.empty())
15195 process(PrevResult);
15196
15197 if (PrevResult.Failed) return false;
15198
15199 FinalResult.swap(PrevResult.Val);
15200 return true;
15201 }
15202
15203private:
15204 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15205 return IntEval.Success(Value, E, Result);
15206 }
15207 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
15208 return IntEval.Success(Value, E, Result);
15209 }
15210 bool Error(const Expr *E) {
15211 return IntEval.Error(E);
15212 }
15213 bool Error(const Expr *E, diag::kind D) {
15214 return IntEval.Error(E, D);
15215 }
15216
15217 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
15218 return Info.CCEDiag(E, D);
15219 }
15220
15221 // Returns true if visiting the RHS is necessary, false otherwise.
15222 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
15223 bool &SuppressRHSDiags);
15224
15225 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
15226 const BinaryOperator *E, APValue &Result);
15227
15228 void EvaluateExpr(const Expr *E, EvalResult &Result) {
15229 Result.Failed = !Evaluate(Result.Val, Info, E);
15230 if (Result.Failed)
15231 Result.Val = APValue();
15232 }
15233
15234 void process(EvalResult &Result);
15235
15236 void enqueue(const Expr *E) {
15237 E = E->IgnoreParens();
15238 Queue.resize(Queue.size()+1);
15239 Queue.back().E = E;
15240 Queue.back().Kind = Job::AnyExprKind;
15241 }
15242};
15243
15244}
15245
15246bool DataRecursiveIntBinOpEvaluator::
15247 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
15248 bool &SuppressRHSDiags) {
15249 if (E->getOpcode() == BO_Comma) {
15250 // Ignore LHS but note if we could not evaluate it.
15251 if (LHSResult.Failed)
15252 return Info.noteSideEffect();
15253 return true;
15254 }
15255
15256 if (E->isLogicalOp()) {
15257 bool LHSAsBool;
15258 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
15259 // We were able to evaluate the LHS, see if we can get away with not
15260 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
15261 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
15262 Success(LHSAsBool, E, LHSResult.Val);
15263 return false; // Ignore RHS
15264 }
15265 } else {
15266 LHSResult.Failed = true;
15267
15268 // Since we weren't able to evaluate the left hand side, it
15269 // might have had side effects.
15270 if (!Info.noteSideEffect())
15271 return false;
15272
15273 // We can't evaluate the LHS; however, sometimes the result
15274 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
15275 // Don't ignore RHS and suppress diagnostics from this arm.
15276 SuppressRHSDiags = true;
15277 }
15278
15279 return true;
15280 }
15281
15282 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
15284
15285 if (LHSResult.Failed && !Info.noteFailure())
15286 return false; // Ignore RHS;
15287
15288 return true;
15289}
15290
15291static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
15292 bool IsSub) {
15293 // Compute the new offset in the appropriate width, wrapping at 64 bits.
15294 // FIXME: When compiling for a 32-bit target, we should use 32-bit
15295 // offsets.
15296 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
15297 CharUnits &Offset = LVal.getLValueOffset();
15298 uint64_t Offset64 = Offset.getQuantity();
15299 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
15300 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
15301 : Offset64 + Index64);
15302}
15303
15304bool DataRecursiveIntBinOpEvaluator::
15305 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
15306 const BinaryOperator *E, APValue &Result) {
15307 if (E->getOpcode() == BO_Comma) {
15308 if (RHSResult.Failed)
15309 return false;
15310 Result = RHSResult.Val;
15311 return true;
15312 }
15313
15314 if (E->isLogicalOp()) {
15315 bool lhsResult, rhsResult;
15316 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
15317 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
15318
15319 if (LHSIsOK) {
15320 if (RHSIsOK) {
15321 if (E->getOpcode() == BO_LOr)
15322 return Success(lhsResult || rhsResult, E, Result);
15323 else
15324 return Success(lhsResult && rhsResult, E, Result);
15325 }
15326 } else {
15327 if (RHSIsOK) {
15328 // We can't evaluate the LHS; however, sometimes the result
15329 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
15330 if (rhsResult == (E->getOpcode() == BO_LOr))
15331 return Success(rhsResult, E, Result);
15332 }
15333 }
15334
15335 return false;
15336 }
15337
15338 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
15340
15341 if (LHSResult.Failed || RHSResult.Failed)
15342 return false;
15343
15344 const APValue &LHSVal = LHSResult.Val;
15345 const APValue &RHSVal = RHSResult.Val;
15346
15347 // Handle cases like (unsigned long)&a + 4.
15348 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
15349 Result = LHSVal;
15350 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
15351 return true;
15352 }
15353
15354 // Handle cases like 4 + (unsigned long)&a
15355 if (E->getOpcode() == BO_Add &&
15356 RHSVal.isLValue() && LHSVal.isInt()) {
15357 Result = RHSVal;
15358 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
15359 return true;
15360 }
15361
15362 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
15363 // Handle (intptr_t)&&A - (intptr_t)&&B.
15364 if (!LHSVal.getLValueOffset().isZero() ||
15365 !RHSVal.getLValueOffset().isZero())
15366 return false;
15367 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
15368 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
15369 if (!LHSExpr || !RHSExpr)
15370 return false;
15371 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
15372 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
15373 if (!LHSAddrExpr || !RHSAddrExpr)
15374 return false;
15375 // Make sure both labels come from the same function.
15376 if (LHSAddrExpr->getLabel()->getDeclContext() !=
15377 RHSAddrExpr->getLabel()->getDeclContext())
15378 return false;
15379 Result = APValue(LHSAddrExpr, RHSAddrExpr);
15380 return true;
15381 }
15382
15383 // All the remaining cases expect both operands to be an integer
15384 if (!LHSVal.isInt() || !RHSVal.isInt())
15385 return Error(E);
15386
15387 // Set up the width and signedness manually, in case it can't be deduced
15388 // from the operation we're performing.
15389 // FIXME: Don't do this in the cases where we can deduce it.
15390 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
15392 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
15393 RHSVal.getInt(), Value))
15394 return false;
15395 return Success(Value, E, Result);
15396}
15397
15398void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
15399 Job &job = Queue.back();
15400
15401 switch (job.Kind) {
15402 case Job::AnyExprKind: {
15403 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
15404 if (shouldEnqueue(Bop)) {
15405 job.Kind = Job::BinOpKind;
15406 enqueue(Bop->getLHS());
15407 return;
15408 }
15409 }
15410
15411 EvaluateExpr(job.E, Result);
15412 Queue.pop_back();
15413 return;
15414 }
15415
15416 case Job::BinOpKind: {
15417 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
15418 bool SuppressRHSDiags = false;
15419 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
15420 Queue.pop_back();
15421 return;
15422 }
15423 if (SuppressRHSDiags)
15424 job.startSpeculativeEval(Info);
15425 job.LHSResult.swap(Result);
15426 job.Kind = Job::BinOpVisitedLHSKind;
15427 enqueue(Bop->getRHS());
15428 return;
15429 }
15430
15431 case Job::BinOpVisitedLHSKind: {
15432 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
15433 EvalResult RHS;
15434 RHS.swap(Result);
15435 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
15436 Queue.pop_back();
15437 return;
15438 }
15439 }
15440
15441 llvm_unreachable("Invalid Job::Kind!");
15442}
15443
15444namespace {
15445enum class CmpResult {
15446 Unequal,
15447 Less,
15448 Equal,
15449 Greater,
15450 Unordered,
15451};
15452}
15453
15454template <class SuccessCB, class AfterCB>
15455static bool
15457 SuccessCB &&Success, AfterCB &&DoAfter) {
15458 assert(!E->isValueDependent());
15459 assert(E->isComparisonOp() && "expected comparison operator");
15460 assert((E->getOpcode() == BO_Cmp ||
15462 "unsupported binary expression evaluation");
15463 auto Error = [&](const Expr *E) {
15464 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15465 return false;
15466 };
15467
15468 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
15469 bool IsEquality = E->isEqualityOp();
15470
15471 QualType LHSTy = E->getLHS()->getType();
15472 QualType RHSTy = E->getRHS()->getType();
15473
15474 if (LHSTy->isIntegralOrEnumerationType() &&
15475 RHSTy->isIntegralOrEnumerationType()) {
15476 APSInt LHS, RHS;
15477 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
15478 if (!LHSOK && !Info.noteFailure())
15479 return false;
15480 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
15481 return false;
15482 if (LHS < RHS)
15483 return Success(CmpResult::Less, E);
15484 if (LHS > RHS)
15485 return Success(CmpResult::Greater, E);
15486 return Success(CmpResult::Equal, E);
15487 }
15488
15489 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
15490 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
15491 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
15492
15493 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
15494 if (!LHSOK && !Info.noteFailure())
15495 return false;
15496 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
15497 return false;
15498 if (LHSFX < RHSFX)
15499 return Success(CmpResult::Less, E);
15500 if (LHSFX > RHSFX)
15501 return Success(CmpResult::Greater, E);
15502 return Success(CmpResult::Equal, E);
15503 }
15504
15505 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
15506 ComplexValue LHS, RHS;
15507 bool LHSOK;
15508 if (E->isAssignmentOp()) {
15509 LValue LV;
15510 EvaluateLValue(E->getLHS(), LV, Info);
15511 LHSOK = false;
15512 } else if (LHSTy->isRealFloatingType()) {
15513 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
15514 if (LHSOK) {
15515 LHS.makeComplexFloat();
15516 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
15517 }
15518 } else {
15519 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
15520 }
15521 if (!LHSOK && !Info.noteFailure())
15522 return false;
15523
15524 if (E->getRHS()->getType()->isRealFloatingType()) {
15525 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
15526 return false;
15527 RHS.makeComplexFloat();
15528 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
15529 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15530 return false;
15531
15532 if (LHS.isComplexFloat()) {
15533 APFloat::cmpResult CR_r =
15534 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
15535 APFloat::cmpResult CR_i =
15536 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
15537 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
15538 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
15539 } else {
15540 assert(IsEquality && "invalid complex comparison");
15541 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
15542 LHS.getComplexIntImag() == RHS.getComplexIntImag();
15543 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
15544 }
15545 }
15546
15547 if (LHSTy->isRealFloatingType() &&
15548 RHSTy->isRealFloatingType()) {
15549 APFloat RHS(0.0), LHS(0.0);
15550
15551 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
15552 if (!LHSOK && !Info.noteFailure())
15553 return false;
15554
15555 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
15556 return false;
15557
15558 assert(E->isComparisonOp() && "Invalid binary operator!");
15559 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
15560 if (!Info.InConstantContext &&
15561 APFloatCmpResult == APFloat::cmpUnordered &&
15563 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
15564 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
15565 return false;
15566 }
15567 auto GetCmpRes = [&]() {
15568 switch (APFloatCmpResult) {
15569 case APFloat::cmpEqual:
15570 return CmpResult::Equal;
15571 case APFloat::cmpLessThan:
15572 return CmpResult::Less;
15573 case APFloat::cmpGreaterThan:
15574 return CmpResult::Greater;
15575 case APFloat::cmpUnordered:
15576 return CmpResult::Unordered;
15577 }
15578 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
15579 };
15580 return Success(GetCmpRes(), E);
15581 }
15582
15583 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
15584 LValue LHSValue, RHSValue;
15585
15586 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15587 if (!LHSOK && !Info.noteFailure())
15588 return false;
15589
15590 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15591 return false;
15592
15593 // Reject differing bases from the normal codepath; we special-case
15594 // comparisons to null.
15595 if (!HasSameBase(LHSValue, RHSValue)) {
15596 // Bail out early if we're checking potential constant expression.
15597 // Otherwise, prefer to diagnose other issues.
15598 if (Info.checkingPotentialConstantExpression() &&
15599 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
15600 return false;
15601 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
15602 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15603 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15604 Info.FFDiag(E, DiagID)
15605 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
15606 return false;
15607 };
15608 // Inequalities and subtractions between unrelated pointers have
15609 // unspecified or undefined behavior.
15610 if (!IsEquality)
15611 return DiagComparison(
15612 diag::note_constexpr_pointer_comparison_unspecified);
15613 // A constant address may compare equal to the address of a symbol.
15614 // The one exception is that address of an object cannot compare equal
15615 // to a null pointer constant.
15616 // TODO: Should we restrict this to actual null pointers, and exclude the
15617 // case of zero cast to pointer type?
15618 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
15619 (!RHSValue.Base && !RHSValue.Offset.isZero()))
15620 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
15621 !RHSValue.Base);
15622 // C++2c [intro.object]/10:
15623 // Two objects [...] may have the same address if [...] they are both
15624 // potentially non-unique objects.
15625 // C++2c [intro.object]/9:
15626 // An object is potentially non-unique if it is a string literal object,
15627 // the backing array of an initializer list, or a subobject thereof.
15628 //
15629 // This makes the comparison result unspecified, so it's not a constant
15630 // expression.
15631 //
15632 // TODO: Do we need to handle the initializer list case here?
15633 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15634 return DiagComparison(diag::note_constexpr_literal_comparison);
15635 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
15636 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
15637 !IsOpaqueConstantCall(LHSValue));
15638 // We can't tell whether weak symbols will end up pointing to the same
15639 // object.
15640 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
15641 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
15642 !IsWeakLValue(LHSValue));
15643 // We can't compare the address of the start of one object with the
15644 // past-the-end address of another object, per C++ DR1652.
15645 if (LHSValue.Base && LHSValue.Offset.isZero() &&
15646 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
15647 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15648 true);
15649 if (RHSValue.Base && RHSValue.Offset.isZero() &&
15650 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
15651 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15652 false);
15653 // We can't tell whether an object is at the same address as another
15654 // zero sized object.
15655 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
15656 (LHSValue.Base && isZeroSized(RHSValue)))
15657 return DiagComparison(
15658 diag::note_constexpr_pointer_comparison_zero_sized);
15659 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
15660 return DiagComparison(
15661 diag::note_constexpr_pointer_comparison_unspecified);
15662 // FIXME: Verify both variables are live.
15663 return Success(CmpResult::Unequal, E);
15664 }
15665
15666 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15667 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15668
15669 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15670 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15671
15672 // C++11 [expr.rel]p2:
15673 // - If two pointers point to non-static data members of the same object,
15674 // or to subobjects or array elements fo such members, recursively, the
15675 // pointer to the later declared member compares greater provided the
15676 // two members have the same access control and provided their class is
15677 // not a union.
15678 // [...]
15679 // - Otherwise pointer comparisons are unspecified.
15680 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
15681 bool WasArrayIndex;
15682 unsigned Mismatch = FindDesignatorMismatch(
15683 LHSValue.Base.isNull() ? QualType()
15684 : getType(LHSValue.Base).getNonReferenceType(),
15685 LHSDesignator, RHSDesignator, WasArrayIndex);
15686 // At the point where the designators diverge, the comparison has a
15687 // specified value if:
15688 // - we are comparing array indices
15689 // - we are comparing fields of a union, or fields with the same access
15690 // Otherwise, the result is unspecified and thus the comparison is not a
15691 // constant expression.
15692 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
15693 Mismatch < RHSDesignator.Entries.size()) {
15694 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
15695 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
15696 if (!LF && !RF)
15697 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
15698 else if (!LF)
15699 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15700 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
15701 << RF->getParent() << RF;
15702 else if (!RF)
15703 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15704 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
15705 << LF->getParent() << LF;
15706 else if (!LF->getParent()->isUnion() &&
15707 LF->getAccess() != RF->getAccess())
15708 Info.CCEDiag(E,
15709 diag::note_constexpr_pointer_comparison_differing_access)
15710 << LF << LF->getAccess() << RF << RF->getAccess()
15711 << LF->getParent();
15712 }
15713 }
15714
15715 // The comparison here must be unsigned, and performed with the same
15716 // width as the pointer.
15717 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
15718 uint64_t CompareLHS = LHSOffset.getQuantity();
15719 uint64_t CompareRHS = RHSOffset.getQuantity();
15720 assert(PtrSize <= 64 && "Unexpected pointer width");
15721 uint64_t Mask = ~0ULL >> (64 - PtrSize);
15722 CompareLHS &= Mask;
15723 CompareRHS &= Mask;
15724
15725 // If there is a base and this is a relational operator, we can only
15726 // compare pointers within the object in question; otherwise, the result
15727 // depends on where the object is located in memory.
15728 if (!LHSValue.Base.isNull() && IsRelational) {
15729 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
15730 if (BaseTy->isIncompleteType())
15731 return Error(E);
15732 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
15733 uint64_t OffsetLimit = Size.getQuantity();
15734 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
15735 return Error(E);
15736 }
15737
15738 if (CompareLHS < CompareRHS)
15739 return Success(CmpResult::Less, E);
15740 if (CompareLHS > CompareRHS)
15741 return Success(CmpResult::Greater, E);
15742 return Success(CmpResult::Equal, E);
15743 }
15744
15745 if (LHSTy->isMemberPointerType()) {
15746 assert(IsEquality && "unexpected member pointer operation");
15747 assert(RHSTy->isMemberPointerType() && "invalid comparison");
15748
15749 MemberPtr LHSValue, RHSValue;
15750
15751 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
15752 if (!LHSOK && !Info.noteFailure())
15753 return false;
15754
15755 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15756 return false;
15757
15758 // If either operand is a pointer to a weak function, the comparison is not
15759 // constant.
15760 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
15761 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15762 << LHSValue.getDecl();
15763 return false;
15764 }
15765 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
15766 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15767 << RHSValue.getDecl();
15768 return false;
15769 }
15770
15771 // C++11 [expr.eq]p2:
15772 // If both operands are null, they compare equal. Otherwise if only one is
15773 // null, they compare unequal.
15774 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
15775 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
15776 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15777 }
15778
15779 // Otherwise if either is a pointer to a virtual member function, the
15780 // result is unspecified.
15781 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
15782 if (MD->isVirtual())
15783 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15784 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
15785 if (MD->isVirtual())
15786 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15787
15788 // Otherwise they compare equal if and only if they would refer to the
15789 // same member of the same most derived object or the same subobject if
15790 // they were dereferenced with a hypothetical object of the associated
15791 // class type.
15792 bool Equal = LHSValue == RHSValue;
15793 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15794 }
15795
15796 if (LHSTy->isNullPtrType()) {
15797 assert(E->isComparisonOp() && "unexpected nullptr operation");
15798 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
15799 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
15800 // are compared, the result is true of the operator is <=, >= or ==, and
15801 // false otherwise.
15802 LValue Res;
15803 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
15804 !EvaluatePointer(E->getRHS(), Res, Info))
15805 return false;
15806 return Success(CmpResult::Equal, E);
15807 }
15808
15809 return DoAfter();
15810}
15811
15812bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
15813 if (!CheckLiteralType(Info, E))
15814 return false;
15815
15816 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15818 switch (CR) {
15819 case CmpResult::Unequal:
15820 llvm_unreachable("should never produce Unequal for three-way comparison");
15821 case CmpResult::Less:
15822 CCR = ComparisonCategoryResult::Less;
15823 break;
15824 case CmpResult::Equal:
15825 CCR = ComparisonCategoryResult::Equal;
15826 break;
15827 case CmpResult::Greater:
15828 CCR = ComparisonCategoryResult::Greater;
15829 break;
15830 case CmpResult::Unordered:
15831 CCR = ComparisonCategoryResult::Unordered;
15832 break;
15833 }
15834 // Evaluation succeeded. Lookup the information for the comparison category
15835 // type and fetch the VarDecl for the result.
15836 const ComparisonCategoryInfo &CmpInfo =
15837 Info.Ctx.CompCategories.getInfoForType(E->getType());
15838 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
15839 // Check and evaluate the result as a constant expression.
15840 LValue LV;
15841 LV.set(VD);
15842 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15843 return false;
15844 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15845 ConstantExprKind::Normal);
15846 };
15847 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15848 return ExprEvaluatorBaseTy::VisitBinCmp(E);
15849 });
15850}
15851
15852bool RecordExprEvaluator::VisitCXXParenListInitExpr(
15853 const CXXParenListInitExpr *E) {
15854 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
15855}
15856
15857bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15858 // We don't support assignment in C. C++ assignments don't get here because
15859 // assignment is an lvalue in C++.
15860 if (E->isAssignmentOp()) {
15861 Error(E);
15862 if (!Info.noteFailure())
15863 return false;
15864 }
15865
15866 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
15867 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
15868
15869 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
15871 "DataRecursiveIntBinOpEvaluator should have handled integral types");
15872
15873 if (E->isComparisonOp()) {
15874 // Evaluate builtin binary comparisons by evaluating them as three-way
15875 // comparisons and then translating the result.
15876 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15877 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
15878 "should only produce Unequal for equality comparisons");
15879 bool IsEqual = CR == CmpResult::Equal,
15880 IsLess = CR == CmpResult::Less,
15881 IsGreater = CR == CmpResult::Greater;
15882 auto Op = E->getOpcode();
15883 switch (Op) {
15884 default:
15885 llvm_unreachable("unsupported binary operator");
15886 case BO_EQ:
15887 case BO_NE:
15888 return Success(IsEqual == (Op == BO_EQ), E);
15889 case BO_LT:
15890 return Success(IsLess, E);
15891 case BO_GT:
15892 return Success(IsGreater, E);
15893 case BO_LE:
15894 return Success(IsEqual || IsLess, E);
15895 case BO_GE:
15896 return Success(IsEqual || IsGreater, E);
15897 }
15898 };
15899 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15900 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15901 });
15902 }
15903
15904 QualType LHSTy = E->getLHS()->getType();
15905 QualType RHSTy = E->getRHS()->getType();
15906
15907 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
15908 E->getOpcode() == BO_Sub) {
15909 LValue LHSValue, RHSValue;
15910
15911 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15912 if (!LHSOK && !Info.noteFailure())
15913 return false;
15914
15915 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15916 return false;
15917
15918 // Reject differing bases from the normal codepath; we special-case
15919 // comparisons to null.
15920 if (!HasSameBase(LHSValue, RHSValue)) {
15921 if (Info.checkingPotentialConstantExpression() &&
15922 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
15923 return false;
15924
15925 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
15926 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
15927
15928 auto DiagArith = [&](unsigned DiagID) {
15929 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15930 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15931 Info.FFDiag(E, DiagID) << LHS << RHS;
15932 if (LHSExpr && LHSExpr == RHSExpr)
15933 Info.Note(LHSExpr->getExprLoc(),
15934 diag::note_constexpr_repeated_literal_eval)
15935 << LHSExpr->getSourceRange();
15936 return false;
15937 };
15938
15939 if (!LHSExpr || !RHSExpr)
15940 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
15941
15942 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15943 return DiagArith(diag::note_constexpr_literal_arith);
15944
15945 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
15946 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
15947 if (!LHSAddrExpr || !RHSAddrExpr)
15948 return Error(E);
15949 // Make sure both labels come from the same function.
15950 if (LHSAddrExpr->getLabel()->getDeclContext() !=
15951 RHSAddrExpr->getLabel()->getDeclContext())
15952 return Error(E);
15953 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
15954 }
15955 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15956 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15957
15958 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15959 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15960
15961 // C++11 [expr.add]p6:
15962 // Unless both pointers point to elements of the same array object, or
15963 // one past the last element of the array object, the behavior is
15964 // undefined.
15965 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
15966 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
15967 RHSDesignator))
15968 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
15969
15970 QualType Type = E->getLHS()->getType();
15971 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
15972
15973 CharUnits ElementSize;
15974 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
15975 return false;
15976
15977 // As an extension, a type may have zero size (empty struct or union in
15978 // C, array of zero length). Pointer subtraction in such cases has
15979 // undefined behavior, so is not constant.
15980 if (ElementSize.isZero()) {
15981 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
15982 << ElementType;
15983 return false;
15984 }
15985
15986 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
15987 // and produce incorrect results when it overflows. Such behavior
15988 // appears to be non-conforming, but is common, so perhaps we should
15989 // assume the standard intended for such cases to be undefined behavior
15990 // and check for them.
15991
15992 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
15993 // overflow in the final conversion to ptrdiff_t.
15994 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
15995 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
15996 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
15997 false);
15998 APSInt TrueResult = (LHS - RHS) / ElemSize;
15999 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
16000
16001 if (Result.extend(65) != TrueResult &&
16002 !HandleOverflow(Info, E, TrueResult, E->getType()))
16003 return false;
16004 return Success(Result, E);
16005 }
16006
16007 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16008}
16009
16010/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
16011/// a result as the expression's type.
16012bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
16013 const UnaryExprOrTypeTraitExpr *E) {
16014 switch(E->getKind()) {
16015 case UETT_PreferredAlignOf:
16016 case UETT_AlignOf: {
16017 if (E->isArgumentType())
16018 return Success(
16019 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
16020 else
16021 return Success(
16022 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
16023 }
16024
16025 case UETT_PtrAuthTypeDiscriminator: {
16026 if (E->getArgumentType()->isDependentType())
16027 return false;
16028 return Success(
16030 }
16031 case UETT_VecStep: {
16032 QualType Ty = E->getTypeOfArgument();
16033
16034 if (Ty->isVectorType()) {
16035 unsigned n = Ty->castAs<VectorType>()->getNumElements();
16036
16037 // The vec_step built-in functions that take a 3-component
16038 // vector return 4. (OpenCL 1.1 spec 6.11.12)
16039 if (n == 3)
16040 n = 4;
16041
16042 return Success(n, E);
16043 } else
16044 return Success(1, E);
16045 }
16046
16047 case UETT_DataSizeOf:
16048 case UETT_SizeOf: {
16049 QualType SrcTy = E->getTypeOfArgument();
16050 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
16051 // the result is the size of the referenced type."
16052 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
16053 SrcTy = Ref->getPointeeType();
16054
16055 CharUnits Sizeof;
16056 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
16057 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
16058 : SizeOfType::SizeOf)) {
16059 return false;
16060 }
16061 return Success(Sizeof, E);
16062 }
16063 case UETT_OpenMPRequiredSimdAlign:
16064 assert(E->isArgumentType());
16065 return Success(
16066 Info.Ctx.toCharUnitsFromBits(
16068 .getQuantity(),
16069 E);
16070 case UETT_VectorElements: {
16071 QualType Ty = E->getTypeOfArgument();
16072 // If the vector has a fixed size, we can determine the number of elements
16073 // at compile time.
16074 if (const auto *VT = Ty->getAs<VectorType>())
16075 return Success(VT->getNumElements(), E);
16076
16077 assert(Ty->isSizelessVectorType());
16078 if (Info.InConstantContext)
16079 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
16080 << E->getSourceRange();
16081
16082 return false;
16083 }
16084 case UETT_CountOf: {
16085 QualType Ty = E->getTypeOfArgument();
16086 assert(Ty->isArrayType());
16087
16088 // We don't need to worry about array element qualifiers, so getting the
16089 // unsafe array type is fine.
16090 if (const auto *CAT =
16091 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
16092 return Success(CAT->getSize(), E);
16093 }
16094
16095 assert(!Ty->isConstantSizeType());
16096
16097 // If it's a variable-length array type, we need to check whether it is a
16098 // multidimensional array. If so, we need to check the size expression of
16099 // the VLA to see if it's a constant size. If so, we can return that value.
16100 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
16101 assert(VAT);
16102 if (VAT->getElementType()->isArrayType()) {
16103 // Variable array size expression could be missing (e.g. int a[*][10]) In
16104 // that case, it can't be a constant expression.
16105 if (!VAT->getSizeExpr()) {
16106 Info.FFDiag(E->getBeginLoc());
16107 return false;
16108 }
16109
16110 std::optional<APSInt> Res =
16111 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
16112 if (Res) {
16113 // The resulting value always has type size_t, so we need to make the
16114 // returned APInt have the correct sign and bit-width.
16115 APInt Val{
16116 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
16117 Res->getZExtValue()};
16118 return Success(Val, E);
16119 }
16120 }
16121
16122 // Definitely a variable-length type, which is not an ICE.
16123 // FIXME: Better diagnostic.
16124 Info.FFDiag(E->getBeginLoc());
16125 return false;
16126 }
16127 }
16128
16129 llvm_unreachable("unknown expr/type trait");
16130}
16131
16132bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
16133 CharUnits Result;
16134 unsigned n = OOE->getNumComponents();
16135 if (n == 0)
16136 return Error(OOE);
16137 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
16138 for (unsigned i = 0; i != n; ++i) {
16139 OffsetOfNode ON = OOE->getComponent(i);
16140 switch (ON.getKind()) {
16141 case OffsetOfNode::Array: {
16142 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
16143 APSInt IdxResult;
16144 if (!EvaluateInteger(Idx, IdxResult, Info))
16145 return false;
16146 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
16147 if (!AT)
16148 return Error(OOE);
16149 CurrentType = AT->getElementType();
16150 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
16151 Result += IdxResult.getSExtValue() * ElementSize;
16152 break;
16153 }
16154
16155 case OffsetOfNode::Field: {
16156 FieldDecl *MemberDecl = ON.getField();
16157 const auto *RD = CurrentType->getAsRecordDecl();
16158 if (!RD)
16159 return Error(OOE);
16160 if (RD->isInvalidDecl()) return false;
16161 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
16162 unsigned i = MemberDecl->getFieldIndex();
16163 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
16164 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
16165 CurrentType = MemberDecl->getType().getNonReferenceType();
16166 break;
16167 }
16168
16170 llvm_unreachable("dependent __builtin_offsetof");
16171
16172 case OffsetOfNode::Base: {
16173 CXXBaseSpecifier *BaseSpec = ON.getBase();
16174 if (BaseSpec->isVirtual())
16175 return Error(OOE);
16176
16177 // Find the layout of the class whose base we are looking into.
16178 const auto *RD = CurrentType->getAsCXXRecordDecl();
16179 if (!RD)
16180 return Error(OOE);
16181 if (RD->isInvalidDecl()) return false;
16182 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
16183
16184 // Find the base class itself.
16185 CurrentType = BaseSpec->getType();
16186 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
16187 if (!BaseRD)
16188 return Error(OOE);
16189
16190 // Add the offset to the base.
16191 Result += RL.getBaseClassOffset(BaseRD);
16192 break;
16193 }
16194 }
16195 }
16196 return Success(Result, OOE);
16197}
16198
16199bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16200 switch (E->getOpcode()) {
16201 default:
16202 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
16203 // See C99 6.6p3.
16204 return Error(E);
16205 case UO_Extension:
16206 // FIXME: Should extension allow i-c-e extension expressions in its scope?
16207 // If so, we could clear the diagnostic ID.
16208 return Visit(E->getSubExpr());
16209 case UO_Plus:
16210 // The result is just the value.
16211 return Visit(E->getSubExpr());
16212 case UO_Minus: {
16213 if (!Visit(E->getSubExpr()))
16214 return false;
16215 if (!Result.isInt()) return Error(E);
16216 const APSInt &Value = Result.getInt();
16217 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
16218 if (Info.checkingForUndefinedBehavior())
16219 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16220 diag::warn_integer_constant_overflow)
16221 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
16222 /*UpperCase=*/true, /*InsertSeparators=*/true)
16223 << E->getType() << E->getSourceRange();
16224
16225 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
16226 E->getType()))
16227 return false;
16228 }
16229 return Success(-Value, E);
16230 }
16231 case UO_Not: {
16232 if (!Visit(E->getSubExpr()))
16233 return false;
16234 if (!Result.isInt()) return Error(E);
16235 return Success(~Result.getInt(), E);
16236 }
16237 case UO_LNot: {
16238 bool bres;
16239 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
16240 return false;
16241 return Success(!bres, E);
16242 }
16243 }
16244}
16245
16246/// HandleCast - This is used to evaluate implicit or explicit casts where the
16247/// result type is integer.
16248bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
16249 const Expr *SubExpr = E->getSubExpr();
16250 QualType DestType = E->getType();
16251 QualType SrcType = SubExpr->getType();
16252
16253 switch (E->getCastKind()) {
16254 case CK_BaseToDerived:
16255 case CK_DerivedToBase:
16256 case CK_UncheckedDerivedToBase:
16257 case CK_Dynamic:
16258 case CK_ToUnion:
16259 case CK_ArrayToPointerDecay:
16260 case CK_FunctionToPointerDecay:
16261 case CK_NullToPointer:
16262 case CK_NullToMemberPointer:
16263 case CK_BaseToDerivedMemberPointer:
16264 case CK_DerivedToBaseMemberPointer:
16265 case CK_ReinterpretMemberPointer:
16266 case CK_ConstructorConversion:
16267 case CK_IntegralToPointer:
16268 case CK_ToVoid:
16269 case CK_VectorSplat:
16270 case CK_IntegralToFloating:
16271 case CK_FloatingCast:
16272 case CK_CPointerToObjCPointerCast:
16273 case CK_BlockPointerToObjCPointerCast:
16274 case CK_AnyPointerToBlockPointerCast:
16275 case CK_ObjCObjectLValueCast:
16276 case CK_FloatingRealToComplex:
16277 case CK_FloatingComplexToReal:
16278 case CK_FloatingComplexCast:
16279 case CK_FloatingComplexToIntegralComplex:
16280 case CK_IntegralRealToComplex:
16281 case CK_IntegralComplexCast:
16282 case CK_IntegralComplexToFloatingComplex:
16283 case CK_BuiltinFnToFnPtr:
16284 case CK_ZeroToOCLOpaqueType:
16285 case CK_NonAtomicToAtomic:
16286 case CK_AddressSpaceConversion:
16287 case CK_IntToOCLSampler:
16288 case CK_FloatingToFixedPoint:
16289 case CK_FixedPointToFloating:
16290 case CK_FixedPointCast:
16291 case CK_IntegralToFixedPoint:
16292 case CK_MatrixCast:
16293 case CK_HLSLAggregateSplatCast:
16294 llvm_unreachable("invalid cast kind for integral value");
16295
16296 case CK_BitCast:
16297 case CK_Dependent:
16298 case CK_LValueBitCast:
16299 case CK_ARCProduceObject:
16300 case CK_ARCConsumeObject:
16301 case CK_ARCReclaimReturnedObject:
16302 case CK_ARCExtendBlockObject:
16303 case CK_CopyAndAutoreleaseBlockObject:
16304 return Error(E);
16305
16306 case CK_UserDefinedConversion:
16307 case CK_LValueToRValue:
16308 case CK_AtomicToNonAtomic:
16309 case CK_NoOp:
16310 case CK_LValueToRValueBitCast:
16311 case CK_HLSLArrayRValue:
16312 case CK_HLSLElementwiseCast:
16313 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16314
16315 case CK_MemberPointerToBoolean:
16316 case CK_PointerToBoolean:
16317 case CK_IntegralToBoolean:
16318 case CK_FloatingToBoolean:
16319 case CK_BooleanToSignedIntegral:
16320 case CK_FloatingComplexToBoolean:
16321 case CK_IntegralComplexToBoolean: {
16322 bool BoolResult;
16323 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
16324 return false;
16325 uint64_t IntResult = BoolResult;
16326 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
16327 IntResult = (uint64_t)-1;
16328 return Success(IntResult, E);
16329 }
16330
16331 case CK_FixedPointToIntegral: {
16332 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
16333 if (!EvaluateFixedPoint(SubExpr, Src, Info))
16334 return false;
16335 bool Overflowed;
16336 llvm::APSInt Result = Src.convertToInt(
16337 Info.Ctx.getIntWidth(DestType),
16338 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
16339 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
16340 return false;
16341 return Success(Result, E);
16342 }
16343
16344 case CK_FixedPointToBoolean: {
16345 // Unsigned padding does not affect this.
16346 APValue Val;
16347 if (!Evaluate(Val, Info, SubExpr))
16348 return false;
16349 return Success(Val.getFixedPoint().getBoolValue(), E);
16350 }
16351
16352 case CK_IntegralCast: {
16353 if (!Visit(SubExpr))
16354 return false;
16355
16356 if (!Result.isInt()) {
16357 // Allow casts of address-of-label differences if they are no-ops
16358 // or narrowing. (The narrowing case isn't actually guaranteed to
16359 // be constant-evaluatable except in some narrow cases which are hard
16360 // to detect here. We let it through on the assumption the user knows
16361 // what they are doing.)
16362 if (Result.isAddrLabelDiff())
16363 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
16364 // Only allow casts of lvalues if they are lossless.
16365 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
16366 }
16367
16368 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
16369 const auto *ED = DestType->getAsEnumDecl();
16370 // Check that the value is within the range of the enumeration values.
16371 //
16372 // This corressponds to [expr.static.cast]p10 which says:
16373 // A value of integral or enumeration type can be explicitly converted
16374 // to a complete enumeration type ... If the enumeration type does not
16375 // have a fixed underlying type, the value is unchanged if the original
16376 // value is within the range of the enumeration values ([dcl.enum]), and
16377 // otherwise, the behavior is undefined.
16378 //
16379 // This was resolved as part of DR2338 which has CD5 status.
16380 if (!ED->isFixed()) {
16381 llvm::APInt Min;
16382 llvm::APInt Max;
16383
16384 ED->getValueRange(Max, Min);
16385 --Max;
16386
16387 if (ED->getNumNegativeBits() &&
16388 (Max.slt(Result.getInt().getSExtValue()) ||
16389 Min.sgt(Result.getInt().getSExtValue())))
16390 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
16391 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
16392 << Max.getSExtValue() << ED;
16393 else if (!ED->getNumNegativeBits() &&
16394 Max.ult(Result.getInt().getZExtValue()))
16395 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
16396 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
16397 << Max.getZExtValue() << ED;
16398 }
16399 }
16400
16401 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
16402 Result.getInt()), E);
16403 }
16404
16405 case CK_PointerToIntegral: {
16406 CCEDiag(E, diag::note_constexpr_invalid_cast)
16407 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
16408 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
16409
16410 LValue LV;
16411 if (!EvaluatePointer(SubExpr, LV, Info))
16412 return false;
16413
16414 if (LV.getLValueBase()) {
16415 // Only allow based lvalue casts if they are lossless.
16416 // FIXME: Allow a larger integer size than the pointer size, and allow
16417 // narrowing back down to pointer width in subsequent integral casts.
16418 // FIXME: Check integer type's active bits, not its type size.
16419 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
16420 return Error(E);
16421
16422 LV.Designator.setInvalid();
16423 LV.moveInto(Result);
16424 return true;
16425 }
16426
16427 APSInt AsInt;
16428 APValue V;
16429 LV.moveInto(V);
16430 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
16431 llvm_unreachable("Can't cast this!");
16432
16433 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
16434 }
16435
16436 case CK_IntegralComplexToReal: {
16437 ComplexValue C;
16438 if (!EvaluateComplex(SubExpr, C, Info))
16439 return false;
16440 return Success(C.getComplexIntReal(), E);
16441 }
16442
16443 case CK_FloatingToIntegral: {
16444 APFloat F(0.0);
16445 if (!EvaluateFloat(SubExpr, F, Info))
16446 return false;
16447
16448 APSInt Value;
16449 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
16450 return false;
16451 return Success(Value, E);
16452 }
16453 case CK_HLSLVectorTruncation: {
16454 APValue Val;
16455 if (!EvaluateVector(SubExpr, Val, Info))
16456 return Error(E);
16457 return Success(Val.getVectorElt(0), E);
16458 }
16459 }
16460
16461 llvm_unreachable("unknown cast resulting in integral value");
16462}
16463
16464bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
16465 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16466 ComplexValue LV;
16467 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
16468 return false;
16469 if (!LV.isComplexInt())
16470 return Error(E);
16471 return Success(LV.getComplexIntReal(), E);
16472 }
16473
16474 return Visit(E->getSubExpr());
16475}
16476
16477bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
16478 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
16479 ComplexValue LV;
16480 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
16481 return false;
16482 if (!LV.isComplexInt())
16483 return Error(E);
16484 return Success(LV.getComplexIntImag(), E);
16485 }
16486
16487 VisitIgnoredValue(E->getSubExpr());
16488 return Success(0, E);
16489}
16490
16491bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
16492 return Success(E->getPackLength(), E);
16493}
16494
16495bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
16496 return Success(E->getValue(), E);
16497}
16498
16499bool IntExprEvaluator::VisitConceptSpecializationExpr(
16500 const ConceptSpecializationExpr *E) {
16501 return Success(E->isSatisfied(), E);
16502}
16503
16504bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
16505 return Success(E->isSatisfied(), E);
16506}
16507
16508bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16509 switch (E->getOpcode()) {
16510 default:
16511 // Invalid unary operators
16512 return Error(E);
16513 case UO_Plus:
16514 // The result is just the value.
16515 return Visit(E->getSubExpr());
16516 case UO_Minus: {
16517 if (!Visit(E->getSubExpr())) return false;
16518 if (!Result.isFixedPoint())
16519 return Error(E);
16520 bool Overflowed;
16521 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
16522 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
16523 return false;
16524 return Success(Negated, E);
16525 }
16526 case UO_LNot: {
16527 bool bres;
16528 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
16529 return false;
16530 return Success(!bres, E);
16531 }
16532 }
16533}
16534
16535bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
16536 const Expr *SubExpr = E->getSubExpr();
16537 QualType DestType = E->getType();
16538 assert(DestType->isFixedPointType() &&
16539 "Expected destination type to be a fixed point type");
16540 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
16541
16542 switch (E->getCastKind()) {
16543 case CK_FixedPointCast: {
16544 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
16545 if (!EvaluateFixedPoint(SubExpr, Src, Info))
16546 return false;
16547 bool Overflowed;
16548 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
16549 if (Overflowed) {
16550 if (Info.checkingForUndefinedBehavior())
16551 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16552 diag::warn_fixedpoint_constant_overflow)
16553 << Result.toString() << E->getType();
16554 if (!HandleOverflow(Info, E, Result, E->getType()))
16555 return false;
16556 }
16557 return Success(Result, E);
16558 }
16559 case CK_IntegralToFixedPoint: {
16560 APSInt Src;
16561 if (!EvaluateInteger(SubExpr, Src, Info))
16562 return false;
16563
16564 bool Overflowed;
16565 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
16566 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
16567
16568 if (Overflowed) {
16569 if (Info.checkingForUndefinedBehavior())
16570 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16571 diag::warn_fixedpoint_constant_overflow)
16572 << IntResult.toString() << E->getType();
16573 if (!HandleOverflow(Info, E, IntResult, E->getType()))
16574 return false;
16575 }
16576
16577 return Success(IntResult, E);
16578 }
16579 case CK_FloatingToFixedPoint: {
16580 APFloat Src(0.0);
16581 if (!EvaluateFloat(SubExpr, Src, Info))
16582 return false;
16583
16584 bool Overflowed;
16585 APFixedPoint Result = APFixedPoint::getFromFloatValue(
16586 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
16587
16588 if (Overflowed) {
16589 if (Info.checkingForUndefinedBehavior())
16590 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16591 diag::warn_fixedpoint_constant_overflow)
16592 << Result.toString() << E->getType();
16593 if (!HandleOverflow(Info, E, Result, E->getType()))
16594 return false;
16595 }
16596
16597 return Success(Result, E);
16598 }
16599 case CK_NoOp:
16600 case CK_LValueToRValue:
16601 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16602 default:
16603 return Error(E);
16604 }
16605}
16606
16607bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16608 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16609 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16610
16611 const Expr *LHS = E->getLHS();
16612 const Expr *RHS = E->getRHS();
16613 FixedPointSemantics ResultFXSema =
16614 Info.Ctx.getFixedPointSemantics(E->getType());
16615
16616 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
16617 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
16618 return false;
16619 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
16620 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
16621 return false;
16622
16623 bool OpOverflow = false, ConversionOverflow = false;
16624 APFixedPoint Result(LHSFX.getSemantics());
16625 switch (E->getOpcode()) {
16626 case BO_Add: {
16627 Result = LHSFX.add(RHSFX, &OpOverflow)
16628 .convert(ResultFXSema, &ConversionOverflow);
16629 break;
16630 }
16631 case BO_Sub: {
16632 Result = LHSFX.sub(RHSFX, &OpOverflow)
16633 .convert(ResultFXSema, &ConversionOverflow);
16634 break;
16635 }
16636 case BO_Mul: {
16637 Result = LHSFX.mul(RHSFX, &OpOverflow)
16638 .convert(ResultFXSema, &ConversionOverflow);
16639 break;
16640 }
16641 case BO_Div: {
16642 if (RHSFX.getValue() == 0) {
16643 Info.FFDiag(E, diag::note_expr_divide_by_zero);
16644 return false;
16645 }
16646 Result = LHSFX.div(RHSFX, &OpOverflow)
16647 .convert(ResultFXSema, &ConversionOverflow);
16648 break;
16649 }
16650 case BO_Shl:
16651 case BO_Shr: {
16652 FixedPointSemantics LHSSema = LHSFX.getSemantics();
16653 llvm::APSInt RHSVal = RHSFX.getValue();
16654
16655 unsigned ShiftBW =
16656 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
16657 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
16658 // Embedded-C 4.1.6.2.2:
16659 // The right operand must be nonnegative and less than the total number
16660 // of (nonpadding) bits of the fixed-point operand ...
16661 if (RHSVal.isNegative())
16662 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
16663 else if (Amt != RHSVal)
16664 Info.CCEDiag(E, diag::note_constexpr_large_shift)
16665 << RHSVal << E->getType() << ShiftBW;
16666
16667 if (E->getOpcode() == BO_Shl)
16668 Result = LHSFX.shl(Amt, &OpOverflow);
16669 else
16670 Result = LHSFX.shr(Amt, &OpOverflow);
16671 break;
16672 }
16673 default:
16674 return false;
16675 }
16676 if (OpOverflow || ConversionOverflow) {
16677 if (Info.checkingForUndefinedBehavior())
16678 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16679 diag::warn_fixedpoint_constant_overflow)
16680 << Result.toString() << E->getType();
16681 if (!HandleOverflow(Info, E, Result, E->getType()))
16682 return false;
16683 }
16684 return Success(Result, E);
16685}
16686
16687//===----------------------------------------------------------------------===//
16688// Float Evaluation
16689//===----------------------------------------------------------------------===//
16690
16691namespace {
16692class FloatExprEvaluator
16693 : public ExprEvaluatorBase<FloatExprEvaluator> {
16694 APFloat &Result;
16695public:
16696 FloatExprEvaluator(EvalInfo &info, APFloat &result)
16697 : ExprEvaluatorBaseTy(info), Result(result) {}
16698
16699 bool Success(const APValue &V, const Expr *e) {
16700 Result = V.getFloat();
16701 return true;
16702 }
16703
16704 bool ZeroInitialization(const Expr *E) {
16705 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
16706 return true;
16707 }
16708
16709 bool VisitCallExpr(const CallExpr *E);
16710
16711 bool VisitUnaryOperator(const UnaryOperator *E);
16712 bool VisitBinaryOperator(const BinaryOperator *E);
16713 bool VisitFloatingLiteral(const FloatingLiteral *E);
16714 bool VisitCastExpr(const CastExpr *E);
16715
16716 bool VisitUnaryReal(const UnaryOperator *E);
16717 bool VisitUnaryImag(const UnaryOperator *E);
16718
16719 // FIXME: Missing: array subscript of vector, member of vector
16720};
16721} // end anonymous namespace
16722
16723static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
16724 assert(!E->isValueDependent());
16725 assert(E->isPRValue() && E->getType()->isRealFloatingType());
16726 return FloatExprEvaluator(Info, Result).Visit(E);
16727}
16728
16729static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
16730 QualType ResultTy,
16731 const Expr *Arg,
16732 bool SNaN,
16733 llvm::APFloat &Result) {
16734 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
16735 if (!S) return false;
16736
16737 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
16738
16739 llvm::APInt fill;
16740
16741 // Treat empty strings as if they were zero.
16742 if (S->getString().empty())
16743 fill = llvm::APInt(32, 0);
16744 else if (S->getString().getAsInteger(0, fill))
16745 return false;
16746
16747 if (Context.getTargetInfo().isNan2008()) {
16748 if (SNaN)
16749 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16750 else
16751 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16752 } else {
16753 // Prior to IEEE 754-2008, architectures were allowed to choose whether
16754 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
16755 // a different encoding to what became a standard in 2008, and for pre-
16756 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
16757 // sNaN. This is now known as "legacy NaN" encoding.
16758 if (SNaN)
16759 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16760 else
16761 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16762 }
16763
16764 return true;
16765}
16766
16767bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
16768 if (!IsConstantEvaluatedBuiltinCall(E))
16769 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16770
16771 switch (E->getBuiltinCallee()) {
16772 default:
16773 return false;
16774
16775 case Builtin::BI__builtin_huge_val:
16776 case Builtin::BI__builtin_huge_valf:
16777 case Builtin::BI__builtin_huge_vall:
16778 case Builtin::BI__builtin_huge_valf16:
16779 case Builtin::BI__builtin_huge_valf128:
16780 case Builtin::BI__builtin_inf:
16781 case Builtin::BI__builtin_inff:
16782 case Builtin::BI__builtin_infl:
16783 case Builtin::BI__builtin_inff16:
16784 case Builtin::BI__builtin_inff128: {
16785 const llvm::fltSemantics &Sem =
16786 Info.Ctx.getFloatTypeSemantics(E->getType());
16787 Result = llvm::APFloat::getInf(Sem);
16788 return true;
16789 }
16790
16791 case Builtin::BI__builtin_nans:
16792 case Builtin::BI__builtin_nansf:
16793 case Builtin::BI__builtin_nansl:
16794 case Builtin::BI__builtin_nansf16:
16795 case Builtin::BI__builtin_nansf128:
16796 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16797 true, Result))
16798 return Error(E);
16799 return true;
16800
16801 case Builtin::BI__builtin_nan:
16802 case Builtin::BI__builtin_nanf:
16803 case Builtin::BI__builtin_nanl:
16804 case Builtin::BI__builtin_nanf16:
16805 case Builtin::BI__builtin_nanf128:
16806 // If this is __builtin_nan() turn this into a nan, otherwise we
16807 // can't constant fold it.
16808 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16809 false, Result))
16810 return Error(E);
16811 return true;
16812
16813 case Builtin::BI__builtin_elementwise_abs:
16814 case Builtin::BI__builtin_fabs:
16815 case Builtin::BI__builtin_fabsf:
16816 case Builtin::BI__builtin_fabsl:
16817 case Builtin::BI__builtin_fabsf128:
16818 // The C standard says "fabs raises no floating-point exceptions,
16819 // even if x is a signaling NaN. The returned value is independent of
16820 // the current rounding direction mode." Therefore constant folding can
16821 // proceed without regard to the floating point settings.
16822 // Reference, WG14 N2478 F.10.4.3
16823 if (!EvaluateFloat(E->getArg(0), Result, Info))
16824 return false;
16825
16826 if (Result.isNegative())
16827 Result.changeSign();
16828 return true;
16829
16830 case Builtin::BI__arithmetic_fence:
16831 return EvaluateFloat(E->getArg(0), Result, Info);
16832
16833 // FIXME: Builtin::BI__builtin_powi
16834 // FIXME: Builtin::BI__builtin_powif
16835 // FIXME: Builtin::BI__builtin_powil
16836
16837 case Builtin::BI__builtin_copysign:
16838 case Builtin::BI__builtin_copysignf:
16839 case Builtin::BI__builtin_copysignl:
16840 case Builtin::BI__builtin_copysignf128: {
16841 APFloat RHS(0.);
16842 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16843 !EvaluateFloat(E->getArg(1), RHS, Info))
16844 return false;
16845 Result.copySign(RHS);
16846 return true;
16847 }
16848
16849 case Builtin::BI__builtin_fmax:
16850 case Builtin::BI__builtin_fmaxf:
16851 case Builtin::BI__builtin_fmaxl:
16852 case Builtin::BI__builtin_fmaxf16:
16853 case Builtin::BI__builtin_fmaxf128: {
16854 APFloat RHS(0.);
16855 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16856 !EvaluateFloat(E->getArg(1), RHS, Info))
16857 return false;
16858 Result = maxnum(Result, RHS);
16859 return true;
16860 }
16861
16862 case Builtin::BI__builtin_fmin:
16863 case Builtin::BI__builtin_fminf:
16864 case Builtin::BI__builtin_fminl:
16865 case Builtin::BI__builtin_fminf16:
16866 case Builtin::BI__builtin_fminf128: {
16867 APFloat RHS(0.);
16868 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16869 !EvaluateFloat(E->getArg(1), RHS, Info))
16870 return false;
16871 Result = minnum(Result, RHS);
16872 return true;
16873 }
16874
16875 case Builtin::BI__builtin_fmaximum_num:
16876 case Builtin::BI__builtin_fmaximum_numf:
16877 case Builtin::BI__builtin_fmaximum_numl:
16878 case Builtin::BI__builtin_fmaximum_numf16:
16879 case Builtin::BI__builtin_fmaximum_numf128: {
16880 APFloat RHS(0.);
16881 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16882 !EvaluateFloat(E->getArg(1), RHS, Info))
16883 return false;
16884 Result = maximumnum(Result, RHS);
16885 return true;
16886 }
16887
16888 case Builtin::BI__builtin_fminimum_num:
16889 case Builtin::BI__builtin_fminimum_numf:
16890 case Builtin::BI__builtin_fminimum_numl:
16891 case Builtin::BI__builtin_fminimum_numf16:
16892 case Builtin::BI__builtin_fminimum_numf128: {
16893 APFloat RHS(0.);
16894 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16895 !EvaluateFloat(E->getArg(1), RHS, Info))
16896 return false;
16897 Result = minimumnum(Result, RHS);
16898 return true;
16899 }
16900
16901 case Builtin::BI__builtin_elementwise_fma: {
16902 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
16903 !E->getArg(2)->isPRValue()) {
16904 return false;
16905 }
16906 APFloat SourceY(0.), SourceZ(0.);
16907 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16908 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
16909 !EvaluateFloat(E->getArg(2), SourceZ, Info))
16910 return false;
16911 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
16912 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
16913 return true;
16914 }
16915
16916 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
16917 APValue Vec;
16918 APSInt IdxAPS;
16919 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
16920 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
16921 return false;
16922 unsigned N = Vec.getVectorLength();
16923 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
16924 return Success(Vec.getVectorElt(Idx), E);
16925 }
16926 }
16927}
16928
16929bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
16930 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16931 ComplexValue CV;
16932 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16933 return false;
16934 Result = CV.FloatReal;
16935 return true;
16936 }
16937
16938 return Visit(E->getSubExpr());
16939}
16940
16941bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
16942 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16943 ComplexValue CV;
16944 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16945 return false;
16946 Result = CV.FloatImag;
16947 return true;
16948 }
16949
16950 VisitIgnoredValue(E->getSubExpr());
16951 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
16952 Result = llvm::APFloat::getZero(Sem);
16953 return true;
16954}
16955
16956bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16957 switch (E->getOpcode()) {
16958 default: return Error(E);
16959 case UO_Plus:
16960 return EvaluateFloat(E->getSubExpr(), Result, Info);
16961 case UO_Minus:
16962 // In C standard, WG14 N2478 F.3 p4
16963 // "the unary - raises no floating point exceptions,
16964 // even if the operand is signalling."
16965 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
16966 return false;
16967 Result.changeSign();
16968 return true;
16969 }
16970}
16971
16972bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16973 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16974 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16975
16976 APFloat RHS(0.0);
16977 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
16978 if (!LHSOK && !Info.noteFailure())
16979 return false;
16980 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
16981 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
16982}
16983
16984bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
16985 Result = E->getValue();
16986 return true;
16987}
16988
16989bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
16990 const Expr* SubExpr = E->getSubExpr();
16991
16992 switch (E->getCastKind()) {
16993 default:
16994 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16995
16996 case CK_IntegralToFloating: {
16997 APSInt IntResult;
16998 const FPOptions FPO = E->getFPFeaturesInEffect(
16999 Info.Ctx.getLangOpts());
17000 return EvaluateInteger(SubExpr, IntResult, Info) &&
17001 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
17002 IntResult, E->getType(), Result);
17003 }
17004
17005 case CK_FixedPointToFloating: {
17006 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
17007 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
17008 return false;
17009 Result =
17010 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
17011 return true;
17012 }
17013
17014 case CK_FloatingCast: {
17015 if (!Visit(SubExpr))
17016 return false;
17017 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
17018 Result);
17019 }
17020
17021 case CK_FloatingComplexToReal: {
17022 ComplexValue V;
17023 if (!EvaluateComplex(SubExpr, V, Info))
17024 return false;
17025 Result = V.getComplexFloatReal();
17026 return true;
17027 }
17028 case CK_HLSLVectorTruncation: {
17029 APValue Val;
17030 if (!EvaluateVector(SubExpr, Val, Info))
17031 return Error(E);
17032 return Success(Val.getVectorElt(0), E);
17033 }
17034 }
17035}
17036
17037//===----------------------------------------------------------------------===//
17038// Complex Evaluation (for float and integer)
17039//===----------------------------------------------------------------------===//
17040
17041namespace {
17042class ComplexExprEvaluator
17043 : public ExprEvaluatorBase<ComplexExprEvaluator> {
17044 ComplexValue &Result;
17045
17046public:
17047 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
17048 : ExprEvaluatorBaseTy(info), Result(Result) {}
17049
17050 bool Success(const APValue &V, const Expr *e) {
17051 Result.setFrom(V);
17052 return true;
17053 }
17054
17055 bool ZeroInitialization(const Expr *E);
17056
17057 //===--------------------------------------------------------------------===//
17058 // Visitor Methods
17059 //===--------------------------------------------------------------------===//
17060
17061 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
17062 bool VisitCastExpr(const CastExpr *E);
17063 bool VisitBinaryOperator(const BinaryOperator *E);
17064 bool VisitUnaryOperator(const UnaryOperator *E);
17065 bool VisitInitListExpr(const InitListExpr *E);
17066 bool VisitCallExpr(const CallExpr *E);
17067};
17068} // end anonymous namespace
17069
17070static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
17071 EvalInfo &Info) {
17072 assert(!E->isValueDependent());
17073 assert(E->isPRValue() && E->getType()->isAnyComplexType());
17074 return ComplexExprEvaluator(Info, Result).Visit(E);
17075}
17076
17077bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
17078 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
17079 if (ElemTy->isRealFloatingType()) {
17080 Result.makeComplexFloat();
17081 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
17082 Result.FloatReal = Zero;
17083 Result.FloatImag = Zero;
17084 } else {
17085 Result.makeComplexInt();
17086 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
17087 Result.IntReal = Zero;
17088 Result.IntImag = Zero;
17089 }
17090 return true;
17091}
17092
17093bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
17094 const Expr* SubExpr = E->getSubExpr();
17095
17096 if (SubExpr->getType()->isRealFloatingType()) {
17097 Result.makeComplexFloat();
17098 APFloat &Imag = Result.FloatImag;
17099 if (!EvaluateFloat(SubExpr, Imag, Info))
17100 return false;
17101
17102 Result.FloatReal = APFloat(Imag.getSemantics());
17103 return true;
17104 } else {
17105 assert(SubExpr->getType()->isIntegerType() &&
17106 "Unexpected imaginary literal.");
17107
17108 Result.makeComplexInt();
17109 APSInt &Imag = Result.IntImag;
17110 if (!EvaluateInteger(SubExpr, Imag, Info))
17111 return false;
17112
17113 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
17114 return true;
17115 }
17116}
17117
17118bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
17119
17120 switch (E->getCastKind()) {
17121 case CK_BitCast:
17122 case CK_BaseToDerived:
17123 case CK_DerivedToBase:
17124 case CK_UncheckedDerivedToBase:
17125 case CK_Dynamic:
17126 case CK_ToUnion:
17127 case CK_ArrayToPointerDecay:
17128 case CK_FunctionToPointerDecay:
17129 case CK_NullToPointer:
17130 case CK_NullToMemberPointer:
17131 case CK_BaseToDerivedMemberPointer:
17132 case CK_DerivedToBaseMemberPointer:
17133 case CK_MemberPointerToBoolean:
17134 case CK_ReinterpretMemberPointer:
17135 case CK_ConstructorConversion:
17136 case CK_IntegralToPointer:
17137 case CK_PointerToIntegral:
17138 case CK_PointerToBoolean:
17139 case CK_ToVoid:
17140 case CK_VectorSplat:
17141 case CK_IntegralCast:
17142 case CK_BooleanToSignedIntegral:
17143 case CK_IntegralToBoolean:
17144 case CK_IntegralToFloating:
17145 case CK_FloatingToIntegral:
17146 case CK_FloatingToBoolean:
17147 case CK_FloatingCast:
17148 case CK_CPointerToObjCPointerCast:
17149 case CK_BlockPointerToObjCPointerCast:
17150 case CK_AnyPointerToBlockPointerCast:
17151 case CK_ObjCObjectLValueCast:
17152 case CK_FloatingComplexToReal:
17153 case CK_FloatingComplexToBoolean:
17154 case CK_IntegralComplexToReal:
17155 case CK_IntegralComplexToBoolean:
17156 case CK_ARCProduceObject:
17157 case CK_ARCConsumeObject:
17158 case CK_ARCReclaimReturnedObject:
17159 case CK_ARCExtendBlockObject:
17160 case CK_CopyAndAutoreleaseBlockObject:
17161 case CK_BuiltinFnToFnPtr:
17162 case CK_ZeroToOCLOpaqueType:
17163 case CK_NonAtomicToAtomic:
17164 case CK_AddressSpaceConversion:
17165 case CK_IntToOCLSampler:
17166 case CK_FloatingToFixedPoint:
17167 case CK_FixedPointToFloating:
17168 case CK_FixedPointCast:
17169 case CK_FixedPointToBoolean:
17170 case CK_FixedPointToIntegral:
17171 case CK_IntegralToFixedPoint:
17172 case CK_MatrixCast:
17173 case CK_HLSLVectorTruncation:
17174 case CK_HLSLElementwiseCast:
17175 case CK_HLSLAggregateSplatCast:
17176 llvm_unreachable("invalid cast kind for complex value");
17177
17178 case CK_LValueToRValue:
17179 case CK_AtomicToNonAtomic:
17180 case CK_NoOp:
17181 case CK_LValueToRValueBitCast:
17182 case CK_HLSLArrayRValue:
17183 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17184
17185 case CK_Dependent:
17186 case CK_LValueBitCast:
17187 case CK_UserDefinedConversion:
17188 return Error(E);
17189
17190 case CK_FloatingRealToComplex: {
17191 APFloat &Real = Result.FloatReal;
17192 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
17193 return false;
17194
17195 Result.makeComplexFloat();
17196 Result.FloatImag = APFloat(Real.getSemantics());
17197 return true;
17198 }
17199
17200 case CK_FloatingComplexCast: {
17201 if (!Visit(E->getSubExpr()))
17202 return false;
17203
17204 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
17205 QualType From
17206 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
17207
17208 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
17209 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
17210 }
17211
17212 case CK_FloatingComplexToIntegralComplex: {
17213 if (!Visit(E->getSubExpr()))
17214 return false;
17215
17216 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
17217 QualType From
17218 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
17219 Result.makeComplexInt();
17220 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
17221 To, Result.IntReal) &&
17222 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
17223 To, Result.IntImag);
17224 }
17225
17226 case CK_IntegralRealToComplex: {
17227 APSInt &Real = Result.IntReal;
17228 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
17229 return false;
17230
17231 Result.makeComplexInt();
17232 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
17233 return true;
17234 }
17235
17236 case CK_IntegralComplexCast: {
17237 if (!Visit(E->getSubExpr()))
17238 return false;
17239
17240 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
17241 QualType From
17242 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
17243
17244 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
17245 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
17246 return true;
17247 }
17248
17249 case CK_IntegralComplexToFloatingComplex: {
17250 if (!Visit(E->getSubExpr()))
17251 return false;
17252
17253 const FPOptions FPO = E->getFPFeaturesInEffect(
17254 Info.Ctx.getLangOpts());
17255 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
17256 QualType From
17257 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
17258 Result.makeComplexFloat();
17259 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
17260 To, Result.FloatReal) &&
17261 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
17262 To, Result.FloatImag);
17263 }
17264 }
17265
17266 llvm_unreachable("unknown cast resulting in complex value");
17267}
17268
17269void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
17270 APFloat &ResR, APFloat &ResI) {
17271 // This is an implementation of complex multiplication according to the
17272 // constraints laid out in C11 Annex G. The implementation uses the
17273 // following naming scheme:
17274 // (a + ib) * (c + id)
17275
17276 APFloat AC = A * C;
17277 APFloat BD = B * D;
17278 APFloat AD = A * D;
17279 APFloat BC = B * C;
17280 ResR = AC - BD;
17281 ResI = AD + BC;
17282 if (ResR.isNaN() && ResI.isNaN()) {
17283 bool Recalc = false;
17284 if (A.isInfinity() || B.isInfinity()) {
17285 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
17286 A);
17287 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
17288 B);
17289 if (C.isNaN())
17290 C = APFloat::copySign(APFloat(C.getSemantics()), C);
17291 if (D.isNaN())
17292 D = APFloat::copySign(APFloat(D.getSemantics()), D);
17293 Recalc = true;
17294 }
17295 if (C.isInfinity() || D.isInfinity()) {
17296 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
17297 C);
17298 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
17299 D);
17300 if (A.isNaN())
17301 A = APFloat::copySign(APFloat(A.getSemantics()), A);
17302 if (B.isNaN())
17303 B = APFloat::copySign(APFloat(B.getSemantics()), B);
17304 Recalc = true;
17305 }
17306 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
17307 BC.isInfinity())) {
17308 if (A.isNaN())
17309 A = APFloat::copySign(APFloat(A.getSemantics()), A);
17310 if (B.isNaN())
17311 B = APFloat::copySign(APFloat(B.getSemantics()), B);
17312 if (C.isNaN())
17313 C = APFloat::copySign(APFloat(C.getSemantics()), C);
17314 if (D.isNaN())
17315 D = APFloat::copySign(APFloat(D.getSemantics()), D);
17316 Recalc = true;
17317 }
17318 if (Recalc) {
17319 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
17320 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
17321 }
17322 }
17323}
17324
17325void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
17326 APFloat &ResR, APFloat &ResI) {
17327 // This is an implementation of complex division according to the
17328 // constraints laid out in C11 Annex G. The implementation uses the
17329 // following naming scheme:
17330 // (a + ib) / (c + id)
17331
17332 int DenomLogB = 0;
17333 APFloat MaxCD = maxnum(abs(C), abs(D));
17334 if (MaxCD.isFinite()) {
17335 DenomLogB = ilogb(MaxCD);
17336 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
17337 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
17338 }
17339 APFloat Denom = C * C + D * D;
17340 ResR =
17341 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
17342 ResI =
17343 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
17344 if (ResR.isNaN() && ResI.isNaN()) {
17345 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
17346 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
17347 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
17348 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
17349 D.isFinite()) {
17350 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
17351 A);
17352 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
17353 B);
17354 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
17355 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
17356 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
17357 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
17358 C);
17359 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
17360 D);
17361 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
17362 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
17363 }
17364 }
17365}
17366
17367bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
17368 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
17369 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
17370
17371 // Track whether the LHS or RHS is real at the type system level. When this is
17372 // the case we can simplify our evaluation strategy.
17373 bool LHSReal = false, RHSReal = false;
17374
17375 bool LHSOK;
17376 if (E->getLHS()->getType()->isRealFloatingType()) {
17377 LHSReal = true;
17378 APFloat &Real = Result.FloatReal;
17379 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
17380 if (LHSOK) {
17381 Result.makeComplexFloat();
17382 Result.FloatImag = APFloat(Real.getSemantics());
17383 }
17384 } else {
17385 LHSOK = Visit(E->getLHS());
17386 }
17387 if (!LHSOK && !Info.noteFailure())
17388 return false;
17389
17390 ComplexValue RHS;
17391 if (E->getRHS()->getType()->isRealFloatingType()) {
17392 RHSReal = true;
17393 APFloat &Real = RHS.FloatReal;
17394 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
17395 return false;
17396 RHS.makeComplexFloat();
17397 RHS.FloatImag = APFloat(Real.getSemantics());
17398 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
17399 return false;
17400
17401 assert(!(LHSReal && RHSReal) &&
17402 "Cannot have both operands of a complex operation be real.");
17403 switch (E->getOpcode()) {
17404 default: return Error(E);
17405 case BO_Add:
17406 if (Result.isComplexFloat()) {
17407 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
17408 APFloat::rmNearestTiesToEven);
17409 if (LHSReal)
17410 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
17411 else if (!RHSReal)
17412 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
17413 APFloat::rmNearestTiesToEven);
17414 } else {
17415 Result.getComplexIntReal() += RHS.getComplexIntReal();
17416 Result.getComplexIntImag() += RHS.getComplexIntImag();
17417 }
17418 break;
17419 case BO_Sub:
17420 if (Result.isComplexFloat()) {
17421 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
17422 APFloat::rmNearestTiesToEven);
17423 if (LHSReal) {
17424 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
17425 Result.getComplexFloatImag().changeSign();
17426 } else if (!RHSReal) {
17427 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
17428 APFloat::rmNearestTiesToEven);
17429 }
17430 } else {
17431 Result.getComplexIntReal() -= RHS.getComplexIntReal();
17432 Result.getComplexIntImag() -= RHS.getComplexIntImag();
17433 }
17434 break;
17435 case BO_Mul:
17436 if (Result.isComplexFloat()) {
17437 // This is an implementation of complex multiplication according to the
17438 // constraints laid out in C11 Annex G. The implementation uses the
17439 // following naming scheme:
17440 // (a + ib) * (c + id)
17441 ComplexValue LHS = Result;
17442 APFloat &A = LHS.getComplexFloatReal();
17443 APFloat &B = LHS.getComplexFloatImag();
17444 APFloat &C = RHS.getComplexFloatReal();
17445 APFloat &D = RHS.getComplexFloatImag();
17446 APFloat &ResR = Result.getComplexFloatReal();
17447 APFloat &ResI = Result.getComplexFloatImag();
17448 if (LHSReal) {
17449 assert(!RHSReal && "Cannot have two real operands for a complex op!");
17450 ResR = A;
17451 ResI = A;
17452 // ResR = A * C;
17453 // ResI = A * D;
17454 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
17455 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
17456 return false;
17457 } else if (RHSReal) {
17458 // ResR = C * A;
17459 // ResI = C * B;
17460 ResR = C;
17461 ResI = C;
17462 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
17463 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
17464 return false;
17465 } else {
17466 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
17467 }
17468 } else {
17469 ComplexValue LHS = Result;
17470 Result.getComplexIntReal() =
17471 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
17472 LHS.getComplexIntImag() * RHS.getComplexIntImag());
17473 Result.getComplexIntImag() =
17474 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
17475 LHS.getComplexIntImag() * RHS.getComplexIntReal());
17476 }
17477 break;
17478 case BO_Div:
17479 if (Result.isComplexFloat()) {
17480 // This is an implementation of complex division according to the
17481 // constraints laid out in C11 Annex G. The implementation uses the
17482 // following naming scheme:
17483 // (a + ib) / (c + id)
17484 ComplexValue LHS = Result;
17485 APFloat &A = LHS.getComplexFloatReal();
17486 APFloat &B = LHS.getComplexFloatImag();
17487 APFloat &C = RHS.getComplexFloatReal();
17488 APFloat &D = RHS.getComplexFloatImag();
17489 APFloat &ResR = Result.getComplexFloatReal();
17490 APFloat &ResI = Result.getComplexFloatImag();
17491 if (RHSReal) {
17492 ResR = A;
17493 ResI = B;
17494 // ResR = A / C;
17495 // ResI = B / C;
17496 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
17497 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
17498 return false;
17499 } else {
17500 if (LHSReal) {
17501 // No real optimizations we can do here, stub out with zero.
17502 B = APFloat::getZero(A.getSemantics());
17503 }
17504 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
17505 }
17506 } else {
17507 ComplexValue LHS = Result;
17508 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
17509 RHS.getComplexIntImag() * RHS.getComplexIntImag();
17510 if (Den.isZero())
17511 return Error(E, diag::note_expr_divide_by_zero);
17512
17513 Result.getComplexIntReal() =
17514 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
17515 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
17516 Result.getComplexIntImag() =
17517 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
17518 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
17519 }
17520 break;
17521 }
17522
17523 return true;
17524}
17525
17526bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17527 // Get the operand value into 'Result'.
17528 if (!Visit(E->getSubExpr()))
17529 return false;
17530
17531 switch (E->getOpcode()) {
17532 default:
17533 return Error(E);
17534 case UO_Extension:
17535 return true;
17536 case UO_Plus:
17537 // The result is always just the subexpr.
17538 return true;
17539 case UO_Minus:
17540 if (Result.isComplexFloat()) {
17541 Result.getComplexFloatReal().changeSign();
17542 Result.getComplexFloatImag().changeSign();
17543 }
17544 else {
17545 Result.getComplexIntReal() = -Result.getComplexIntReal();
17546 Result.getComplexIntImag() = -Result.getComplexIntImag();
17547 }
17548 return true;
17549 case UO_Not:
17550 if (Result.isComplexFloat())
17551 Result.getComplexFloatImag().changeSign();
17552 else
17553 Result.getComplexIntImag() = -Result.getComplexIntImag();
17554 return true;
17555 }
17556}
17557
17558bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
17559 if (E->getNumInits() == 2) {
17560 if (E->getType()->isComplexType()) {
17561 Result.makeComplexFloat();
17562 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
17563 return false;
17564 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
17565 return false;
17566 } else {
17567 Result.makeComplexInt();
17568 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
17569 return false;
17570 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
17571 return false;
17572 }
17573 return true;
17574 }
17575 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
17576}
17577
17578bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
17579 if (!IsConstantEvaluatedBuiltinCall(E))
17580 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17581
17582 switch (E->getBuiltinCallee()) {
17583 case Builtin::BI__builtin_complex:
17584 Result.makeComplexFloat();
17585 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
17586 return false;
17587 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
17588 return false;
17589 return true;
17590
17591 default:
17592 return false;
17593 }
17594}
17595
17596//===----------------------------------------------------------------------===//
17597// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
17598// implicit conversion.
17599//===----------------------------------------------------------------------===//
17600
17601namespace {
17602class AtomicExprEvaluator :
17603 public ExprEvaluatorBase<AtomicExprEvaluator> {
17604 const LValue *This;
17605 APValue &Result;
17606public:
17607 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
17608 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
17609
17610 bool Success(const APValue &V, const Expr *E) {
17611 Result = V;
17612 return true;
17613 }
17614
17615 bool ZeroInitialization(const Expr *E) {
17616 ImplicitValueInitExpr VIE(
17617 E->getType()->castAs<AtomicType>()->getValueType());
17618 // For atomic-qualified class (and array) types in C++, initialize the
17619 // _Atomic-wrapped subobject directly, in-place.
17620 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
17621 : Evaluate(Result, Info, &VIE);
17622 }
17623
17624 bool VisitCastExpr(const CastExpr *E) {
17625 switch (E->getCastKind()) {
17626 default:
17627 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17628 case CK_NullToPointer:
17629 VisitIgnoredValue(E->getSubExpr());
17630 return ZeroInitialization(E);
17631 case CK_NonAtomicToAtomic:
17632 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
17633 : Evaluate(Result, Info, E->getSubExpr());
17634 }
17635 }
17636};
17637} // end anonymous namespace
17638
17639static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
17640 EvalInfo &Info) {
17641 assert(!E->isValueDependent());
17642 assert(E->isPRValue() && E->getType()->isAtomicType());
17643 return AtomicExprEvaluator(Info, This, Result).Visit(E);
17644}
17645
17646//===----------------------------------------------------------------------===//
17647// Void expression evaluation, primarily for a cast to void on the LHS of a
17648// comma operator
17649//===----------------------------------------------------------------------===//
17650
17651namespace {
17652class VoidExprEvaluator
17653 : public ExprEvaluatorBase<VoidExprEvaluator> {
17654public:
17655 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
17656
17657 bool Success(const APValue &V, const Expr *e) { return true; }
17658
17659 bool ZeroInitialization(const Expr *E) { return true; }
17660
17661 bool VisitCastExpr(const CastExpr *E) {
17662 switch (E->getCastKind()) {
17663 default:
17664 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17665 case CK_ToVoid:
17666 VisitIgnoredValue(E->getSubExpr());
17667 return true;
17668 }
17669 }
17670
17671 bool VisitCallExpr(const CallExpr *E) {
17672 if (!IsConstantEvaluatedBuiltinCall(E))
17673 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17674
17675 switch (E->getBuiltinCallee()) {
17676 case Builtin::BI__assume:
17677 case Builtin::BI__builtin_assume:
17678 // The argument is not evaluated!
17679 return true;
17680
17681 case Builtin::BI__builtin_operator_delete:
17682 return HandleOperatorDeleteCall(Info, E);
17683
17684 default:
17685 return false;
17686 }
17687 }
17688
17689 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
17690};
17691} // end anonymous namespace
17692
17693bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
17694 // We cannot speculatively evaluate a delete expression.
17695 if (Info.SpeculativeEvaluationDepth)
17696 return false;
17697
17698 FunctionDecl *OperatorDelete = E->getOperatorDelete();
17699 if (!OperatorDelete
17700 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17701 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17702 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
17703 return false;
17704 }
17705
17706 const Expr *Arg = E->getArgument();
17707
17708 LValue Pointer;
17709 if (!EvaluatePointer(Arg, Pointer, Info))
17710 return false;
17711 if (Pointer.Designator.Invalid)
17712 return false;
17713
17714 // Deleting a null pointer has no effect.
17715 if (Pointer.isNullPointer()) {
17716 // This is the only case where we need to produce an extension warning:
17717 // the only other way we can succeed is if we find a dynamic allocation,
17718 // and we will have warned when we allocated it in that case.
17719 if (!Info.getLangOpts().CPlusPlus20)
17720 Info.CCEDiag(E, diag::note_constexpr_new);
17721 return true;
17722 }
17723
17724 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
17725 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
17726 if (!Alloc)
17727 return false;
17728 QualType AllocType = Pointer.Base.getDynamicAllocType();
17729
17730 // For the non-array case, the designator must be empty if the static type
17731 // does not have a virtual destructor.
17732 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
17734 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
17735 << Arg->getType()->getPointeeType() << AllocType;
17736 return false;
17737 }
17738
17739 // For a class type with a virtual destructor, the selected operator delete
17740 // is the one looked up when building the destructor.
17741 if (!E->isArrayForm() && !E->isGlobalDelete()) {
17742 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
17743 if (VirtualDelete &&
17744 !VirtualDelete
17745 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17746 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17747 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
17748 return false;
17749 }
17750 }
17751
17752 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
17753 (*Alloc)->Value, AllocType))
17754 return false;
17755
17756 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
17757 // The element was already erased. This means the destructor call also
17758 // deleted the object.
17759 // FIXME: This probably results in undefined behavior before we get this
17760 // far, and should be diagnosed elsewhere first.
17761 Info.FFDiag(E, diag::note_constexpr_double_delete);
17762 return false;
17763 }
17764
17765 return true;
17766}
17767
17768static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
17769 assert(!E->isValueDependent());
17770 assert(E->isPRValue() && E->getType()->isVoidType());
17771 return VoidExprEvaluator(Info).Visit(E);
17772}
17773
17774//===----------------------------------------------------------------------===//
17775// Top level Expr::EvaluateAsRValue method.
17776//===----------------------------------------------------------------------===//
17777
17778static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
17779 assert(!E->isValueDependent());
17780 // In C, function designators are not lvalues, but we evaluate them as if they
17781 // are.
17782 QualType T = E->getType();
17783 if (E->isGLValue() || T->isFunctionType()) {
17784 LValue LV;
17785 if (!EvaluateLValue(E, LV, Info))
17786 return false;
17787 LV.moveInto(Result);
17788 } else if (T->isVectorType()) {
17789 if (!EvaluateVector(E, Result, Info))
17790 return false;
17791 } else if (T->isIntegralOrEnumerationType()) {
17792 if (!IntExprEvaluator(Info, Result).Visit(E))
17793 return false;
17794 } else if (T->hasPointerRepresentation()) {
17795 LValue LV;
17796 if (!EvaluatePointer(E, LV, Info))
17797 return false;
17798 LV.moveInto(Result);
17799 } else if (T->isRealFloatingType()) {
17800 llvm::APFloat F(0.0);
17801 if (!EvaluateFloat(E, F, Info))
17802 return false;
17803 Result = APValue(F);
17804 } else if (T->isAnyComplexType()) {
17805 ComplexValue C;
17806 if (!EvaluateComplex(E, C, Info))
17807 return false;
17808 C.moveInto(Result);
17809 } else if (T->isFixedPointType()) {
17810 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
17811 } else if (T->isMemberPointerType()) {
17812 MemberPtr P;
17813 if (!EvaluateMemberPointer(E, P, Info))
17814 return false;
17815 P.moveInto(Result);
17816 return true;
17817 } else if (T->isArrayType()) {
17818 LValue LV;
17819 APValue &Value =
17820 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17821 if (!EvaluateArray(E, LV, Value, Info))
17822 return false;
17823 Result = Value;
17824 } else if (T->isRecordType()) {
17825 LValue LV;
17826 APValue &Value =
17827 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17828 if (!EvaluateRecord(E, LV, Value, Info))
17829 return false;
17830 Result = Value;
17831 } else if (T->isVoidType()) {
17832 if (!Info.getLangOpts().CPlusPlus11)
17833 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
17834 << E->getType();
17835 if (!EvaluateVoid(E, Info))
17836 return false;
17837 } else if (T->isAtomicType()) {
17838 QualType Unqual = T.getAtomicUnqualifiedType();
17839 if (Unqual->isArrayType() || Unqual->isRecordType()) {
17840 LValue LV;
17841 APValue &Value = Info.CurrentCall->createTemporary(
17842 E, Unqual, ScopeKind::FullExpression, LV);
17843 if (!EvaluateAtomic(E, &LV, Value, Info))
17844 return false;
17845 Result = Value;
17846 } else {
17847 if (!EvaluateAtomic(E, nullptr, Result, Info))
17848 return false;
17849 }
17850 } else if (Info.getLangOpts().CPlusPlus11) {
17851 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
17852 return false;
17853 } else {
17854 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17855 return false;
17856 }
17857
17858 return true;
17859}
17860
17861/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
17862/// cases, the in-place evaluation is essential, since later initializers for
17863/// an object can indirectly refer to subobjects which were initialized earlier.
17864static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
17865 const Expr *E, bool AllowNonLiteralTypes) {
17866 assert(!E->isValueDependent());
17867
17868 // Normally expressions passed to EvaluateInPlace have a type, but not when
17869 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
17870 // replaced with a CXXConstructExpr. This can happen in LLDB.
17871 if (E->getType().isNull())
17872 return false;
17873
17874 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
17875 return false;
17876
17877 if (E->isPRValue()) {
17878 // Evaluate arrays and record types in-place, so that later initializers can
17879 // refer to earlier-initialized members of the object.
17880 QualType T = E->getType();
17881 if (T->isArrayType())
17882 return EvaluateArray(E, This, Result, Info);
17883 else if (T->isRecordType())
17884 return EvaluateRecord(E, This, Result, Info);
17885 else if (T->isAtomicType()) {
17886 QualType Unqual = T.getAtomicUnqualifiedType();
17887 if (Unqual->isArrayType() || Unqual->isRecordType())
17888 return EvaluateAtomic(E, &This, Result, Info);
17889 }
17890 }
17891
17892 // For any other type, in-place evaluation is unimportant.
17893 return Evaluate(Result, Info, E);
17894}
17895
17896/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
17897/// lvalue-to-rvalue cast if it is an lvalue.
17898static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
17899 assert(!E->isValueDependent());
17900
17901 if (E->getType().isNull())
17902 return false;
17903
17904 if (!CheckLiteralType(Info, E))
17905 return false;
17906
17907 if (Info.EnableNewConstInterp) {
17908 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
17909 return false;
17910 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17911 ConstantExprKind::Normal);
17912 }
17913
17914 if (!::Evaluate(Result, Info, E))
17915 return false;
17916
17917 // Implicit lvalue-to-rvalue cast.
17918 if (E->isGLValue()) {
17919 LValue LV;
17920 LV.setFrom(Info.Ctx, Result);
17921 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
17922 return false;
17923 }
17924
17925 // Check this core constant expression is a constant expression.
17926 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17927 ConstantExprKind::Normal) &&
17928 CheckMemoryLeaks(Info);
17929}
17930
17931static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
17932 const ASTContext &Ctx, bool &IsConst) {
17933 // Fast-path evaluations of integer literals, since we sometimes see files
17934 // containing vast quantities of these.
17935 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
17936 Result =
17937 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
17938 IsConst = true;
17939 return true;
17940 }
17941
17942 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
17943 Result = APValue(APSInt(APInt(1, L->getValue())));
17944 IsConst = true;
17945 return true;
17946 }
17947
17948 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
17949 Result = APValue(FL->getValue());
17950 IsConst = true;
17951 return true;
17952 }
17953
17954 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
17955 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
17956 IsConst = true;
17957 return true;
17958 }
17959
17960 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
17961 if (CE->hasAPValueResult()) {
17962 APValue APV = CE->getAPValueResult();
17963 if (!APV.isLValue()) {
17964 Result = std::move(APV);
17965 IsConst = true;
17966 return true;
17967 }
17968 }
17969
17970 // The SubExpr is usually just an IntegerLiteral.
17971 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
17972 }
17973
17974 // This case should be rare, but we need to check it before we check on
17975 // the type below.
17976 if (Exp->getType().isNull()) {
17977 IsConst = false;
17978 return true;
17979 }
17980
17981 return false;
17982}
17983
17986 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
17987 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
17988}
17989
17990static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
17991 const ASTContext &Ctx, EvalInfo &Info) {
17992 assert(!E->isValueDependent());
17993 bool IsConst;
17994 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
17995 return IsConst;
17996
17997 return EvaluateAsRValue(Info, E, Result.Val);
17998}
17999
18001 const ASTContext &Ctx,
18002 Expr::SideEffectsKind AllowSideEffects,
18003 EvalInfo &Info) {
18004 assert(!E->isValueDependent());
18006 return false;
18007
18008 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
18009 !ExprResult.Val.isInt() ||
18010 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
18011 return false;
18012
18013 return true;
18014}
18015
18017 const ASTContext &Ctx,
18018 Expr::SideEffectsKind AllowSideEffects,
18019 EvalInfo &Info) {
18020 assert(!E->isValueDependent());
18021 if (!E->getType()->isFixedPointType())
18022 return false;
18023
18024 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
18025 return false;
18026
18027 if (!ExprResult.Val.isFixedPoint() ||
18028 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
18029 return false;
18030
18031 return true;
18032}
18033
18034/// EvaluateAsRValue - Return true if this is a constant which we can fold using
18035/// any crazy technique (that has nothing to do with language standards) that
18036/// we want to. If this function returns true, it returns the folded constant
18037/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
18038/// will be applied to the result.
18040 bool InConstantContext) const {
18041 assert(!isValueDependent() &&
18042 "Expression evaluator can't be called on a dependent expression.");
18043 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
18044 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
18045 Info.InConstantContext = InConstantContext;
18046 return ::EvaluateAsRValue(this, Result, Ctx, Info);
18047}
18048
18050 bool InConstantContext) const {
18051 assert(!isValueDependent() &&
18052 "Expression evaluator can't be called on a dependent expression.");
18053 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
18054 EvalResult Scratch;
18055 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
18056 HandleConversionToBool(Scratch.Val, Result);
18057}
18058
18060 SideEffectsKind AllowSideEffects,
18061 bool InConstantContext) const {
18062 assert(!isValueDependent() &&
18063 "Expression evaluator can't be called on a dependent expression.");
18064 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
18065 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
18066 Info.InConstantContext = InConstantContext;
18067 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
18068}
18069
18071 SideEffectsKind AllowSideEffects,
18072 bool InConstantContext) const {
18073 assert(!isValueDependent() &&
18074 "Expression evaluator can't be called on a dependent expression.");
18075 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
18076 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
18077 Info.InConstantContext = InConstantContext;
18078 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
18079}
18080
18081bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
18082 SideEffectsKind AllowSideEffects,
18083 bool InConstantContext) const {
18084 assert(!isValueDependent() &&
18085 "Expression evaluator can't be called on a dependent expression.");
18086
18087 if (!getType()->isRealFloatingType())
18088 return false;
18089
18090 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
18092 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
18093 !ExprResult.Val.isFloat() ||
18094 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
18095 return false;
18096
18097 Result = ExprResult.Val.getFloat();
18098 return true;
18099}
18100
18102 bool InConstantContext) const {
18103 assert(!isValueDependent() &&
18104 "Expression evaluator can't be called on a dependent expression.");
18105
18106 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
18107 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
18108 Info.InConstantContext = InConstantContext;
18109 LValue LV;
18110 CheckedTemporaries CheckedTemps;
18111
18112 if (Info.EnableNewConstInterp) {
18113 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
18114 ConstantExprKind::Normal))
18115 return false;
18116
18117 LV.setFrom(Ctx, Result.Val);
18119 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
18120 ConstantExprKind::Normal, CheckedTemps);
18121 }
18122
18123 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
18124 Result.HasSideEffects ||
18127 ConstantExprKind::Normal, CheckedTemps))
18128 return false;
18129
18130 LV.moveInto(Result.Val);
18131 return true;
18132}
18133
18135 APValue DestroyedValue, QualType Type,
18136 SourceLocation Loc, Expr::EvalStatus &EStatus,
18137 bool IsConstantDestruction) {
18138 EvalInfo Info(Ctx, EStatus,
18139 IsConstantDestruction ? EvaluationMode::ConstantExpression
18141 Info.setEvaluatingDecl(Base, DestroyedValue,
18142 EvalInfo::EvaluatingDeclKind::Dtor);
18143 Info.InConstantContext = IsConstantDestruction;
18144
18145 LValue LVal;
18146 LVal.set(Base);
18147
18148 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
18149 EStatus.HasSideEffects)
18150 return false;
18151
18152 if (!Info.discardCleanups())
18153 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
18154
18155 return true;
18156}
18157
18159 ConstantExprKind Kind) const {
18160 assert(!isValueDependent() &&
18161 "Expression evaluator can't be called on a dependent expression.");
18162 bool IsConst;
18163 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
18164 Result.Val.hasValue())
18165 return true;
18166
18167 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
18169 EvalInfo Info(Ctx, Result, EM);
18170 Info.InConstantContext = true;
18171
18172 if (Info.EnableNewConstInterp) {
18173 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
18174 return false;
18175 return CheckConstantExpression(Info, getExprLoc(),
18176 getStorageType(Ctx, this), Result.Val, Kind);
18177 }
18178
18179 // The type of the object we're initializing is 'const T' for a class NTTP.
18180 QualType T = getType();
18181 if (Kind == ConstantExprKind::ClassTemplateArgument)
18182 T.addConst();
18183
18184 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
18185 // represent the result of the evaluation. CheckConstantExpression ensures
18186 // this doesn't escape.
18187 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
18188 APValue::LValueBase Base(&BaseMTE);
18189 Info.setEvaluatingDecl(Base, Result.Val);
18190
18191 LValue LVal;
18192 LVal.set(Base);
18193 // C++23 [intro.execution]/p5
18194 // A full-expression is [...] a constant-expression
18195 // So we need to make sure temporary objects are destroyed after having
18196 // evaluating the expression (per C++23 [class.temporary]/p4).
18197 FullExpressionRAII Scope(Info);
18198 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
18199 Result.HasSideEffects || !Scope.destroy())
18200 return false;
18201
18202 if (!Info.discardCleanups())
18203 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
18204
18205 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
18206 Result.Val, Kind))
18207 return false;
18208 if (!CheckMemoryLeaks(Info))
18209 return false;
18210
18211 // If this is a class template argument, it's required to have constant
18212 // destruction too.
18213 if (Kind == ConstantExprKind::ClassTemplateArgument &&
18215 true) ||
18216 Result.HasSideEffects)) {
18217 // FIXME: Prefix a note to indicate that the problem is lack of constant
18218 // destruction.
18219 return false;
18220 }
18221
18222 return true;
18223}
18224
18226 const VarDecl *VD,
18228 bool IsConstantInitialization) const {
18229 assert(!isValueDependent() &&
18230 "Expression evaluator can't be called on a dependent expression.");
18231 assert(VD && "Need a valid VarDecl");
18232
18233 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
18234 std::string Name;
18235 llvm::raw_string_ostream OS(Name);
18236 VD->printQualifiedName(OS);
18237 return Name;
18238 });
18239
18240 Expr::EvalStatus EStatus;
18241 EStatus.Diag = &Notes;
18242
18243 EvalInfo Info(Ctx, EStatus,
18244 (IsConstantInitialization &&
18245 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
18248 Info.setEvaluatingDecl(VD, Value);
18249 Info.InConstantContext = IsConstantInitialization;
18250
18251 SourceLocation DeclLoc = VD->getLocation();
18252 QualType DeclTy = VD->getType();
18253
18254 if (Info.EnableNewConstInterp) {
18255 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
18256 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
18257 return false;
18258
18259 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
18260 ConstantExprKind::Normal);
18261 } else {
18262 LValue LVal;
18263 LVal.set(VD);
18264
18265 {
18266 // C++23 [intro.execution]/p5
18267 // A full-expression is ... an init-declarator ([dcl.decl]) or a
18268 // mem-initializer.
18269 // So we need to make sure temporary objects are destroyed after having
18270 // evaluated the expression (per C++23 [class.temporary]/p4).
18271 //
18272 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
18273 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
18274 // outermost FullExpr, such as ExprWithCleanups.
18275 FullExpressionRAII Scope(Info);
18276 if (!EvaluateInPlace(Value, Info, LVal, this,
18277 /*AllowNonLiteralTypes=*/true) ||
18278 EStatus.HasSideEffects)
18279 return false;
18280 }
18281
18282 // At this point, any lifetime-extended temporaries are completely
18283 // initialized.
18284 Info.performLifetimeExtension();
18285
18286 if (!Info.discardCleanups())
18287 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
18288 }
18289
18290 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
18291 ConstantExprKind::Normal) &&
18292 CheckMemoryLeaks(Info);
18293}
18294
18297 Expr::EvalStatus EStatus;
18298 EStatus.Diag = &Notes;
18299
18300 // Only treat the destruction as constant destruction if we formally have
18301 // constant initialization (or are usable in a constant expression).
18302 bool IsConstantDestruction = hasConstantInitialization();
18303
18304 // Make a copy of the value for the destructor to mutate, if we know it.
18305 // Otherwise, treat the value as default-initialized; if the destructor works
18306 // anyway, then the destruction is constant (and must be essentially empty).
18307 APValue DestroyedValue;
18308 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
18309 DestroyedValue = *getEvaluatedValue();
18310 else if (!handleDefaultInitValue(getType(), DestroyedValue))
18311 return false;
18312
18313 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
18314 getType(), getLocation(), EStatus,
18315 IsConstantDestruction) ||
18316 EStatus.HasSideEffects)
18317 return false;
18318
18319 ensureEvaluatedStmt()->HasConstantDestruction = true;
18320 return true;
18321}
18322
18323/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
18324/// constant folded, but discard the result.
18326 assert(!isValueDependent() &&
18327 "Expression evaluator can't be called on a dependent expression.");
18328
18330 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
18332}
18333
18334APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
18335 assert(!isValueDependent() &&
18336 "Expression evaluator can't be called on a dependent expression.");
18337
18338 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
18339 EvalResult EVResult;
18340 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
18341 Info.InConstantContext = true;
18342
18343 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
18344 (void)Result;
18345 assert(Result && "Could not evaluate expression");
18346 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
18347
18348 return EVResult.Val.getInt();
18349}
18350
18353 assert(!isValueDependent() &&
18354 "Expression evaluator can't be called on a dependent expression.");
18355
18356 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
18357 EvalResult EVResult;
18358 EVResult.Diag = Diag;
18359 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
18360 Info.InConstantContext = true;
18361 Info.CheckingForUndefinedBehavior = true;
18362
18363 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
18364 (void)Result;
18365 assert(Result && "Could not evaluate expression");
18366 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
18367
18368 return EVResult.Val.getInt();
18369}
18370
18372 assert(!isValueDependent() &&
18373 "Expression evaluator can't be called on a dependent expression.");
18374
18375 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
18376 bool IsConst;
18377 EvalResult EVResult;
18378 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
18379 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
18380 Info.CheckingForUndefinedBehavior = true;
18381 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
18382 }
18383}
18384
18386 assert(Val.isLValue());
18387 return IsGlobalLValue(Val.getLValueBase());
18388}
18389
18390/// isIntegerConstantExpr - this recursive routine will test if an expression is
18391/// an integer constant expression.
18392
18393/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
18394/// comma, etc
18395
18396// CheckICE - This function does the fundamental ICE checking: the returned
18397// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
18398//
18399// Note that to reduce code duplication, this helper does no evaluation
18400// itself; the caller checks whether the expression is evaluatable, and
18401// in the rare cases where CheckICE actually cares about the evaluated
18402// value, it calls into Evaluate.
18403
18404namespace {
18405
18406enum ICEKind {
18407 /// This expression is an ICE.
18408 IK_ICE,
18409 /// This expression is not an ICE, but if it isn't evaluated, it's
18410 /// a legal subexpression for an ICE. This return value is used to handle
18411 /// the comma operator in C99 mode, and non-constant subexpressions.
18412 IK_ICEIfUnevaluated,
18413 /// This expression is not an ICE, and is not a legal subexpression for one.
18414 IK_NotICE
18415};
18416
18417struct ICEDiag {
18418 ICEKind Kind;
18419 SourceLocation Loc;
18420
18421 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
18422};
18423
18424}
18425
18426static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
18427
18428static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
18429
18430static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
18431 Expr::EvalResult EVResult;
18432 Expr::EvalStatus Status;
18433 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
18434
18435 Info.InConstantContext = true;
18436 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
18437 !EVResult.Val.isInt())
18438 return ICEDiag(IK_NotICE, E->getBeginLoc());
18439
18440 return NoDiag();
18441}
18442
18443static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
18444 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
18446 return ICEDiag(IK_NotICE, E->getBeginLoc());
18447
18448 switch (E->getStmtClass()) {
18449#define ABSTRACT_STMT(Node)
18450#define STMT(Node, Base) case Expr::Node##Class:
18451#define EXPR(Node, Base)
18452#include "clang/AST/StmtNodes.inc"
18453 case Expr::PredefinedExprClass:
18454 case Expr::FloatingLiteralClass:
18455 case Expr::ImaginaryLiteralClass:
18456 case Expr::StringLiteralClass:
18457 case Expr::ArraySubscriptExprClass:
18458 case Expr::MatrixSubscriptExprClass:
18459 case Expr::ArraySectionExprClass:
18460 case Expr::OMPArrayShapingExprClass:
18461 case Expr::OMPIteratorExprClass:
18462 case Expr::MemberExprClass:
18463 case Expr::CompoundAssignOperatorClass:
18464 case Expr::CompoundLiteralExprClass:
18465 case Expr::ExtVectorElementExprClass:
18466 case Expr::DesignatedInitExprClass:
18467 case Expr::ArrayInitLoopExprClass:
18468 case Expr::ArrayInitIndexExprClass:
18469 case Expr::NoInitExprClass:
18470 case Expr::DesignatedInitUpdateExprClass:
18471 case Expr::ImplicitValueInitExprClass:
18472 case Expr::ParenListExprClass:
18473 case Expr::VAArgExprClass:
18474 case Expr::AddrLabelExprClass:
18475 case Expr::StmtExprClass:
18476 case Expr::CXXMemberCallExprClass:
18477 case Expr::CUDAKernelCallExprClass:
18478 case Expr::CXXAddrspaceCastExprClass:
18479 case Expr::CXXDynamicCastExprClass:
18480 case Expr::CXXTypeidExprClass:
18481 case Expr::CXXUuidofExprClass:
18482 case Expr::MSPropertyRefExprClass:
18483 case Expr::MSPropertySubscriptExprClass:
18484 case Expr::CXXNullPtrLiteralExprClass:
18485 case Expr::UserDefinedLiteralClass:
18486 case Expr::CXXThisExprClass:
18487 case Expr::CXXThrowExprClass:
18488 case Expr::CXXNewExprClass:
18489 case Expr::CXXDeleteExprClass:
18490 case Expr::CXXPseudoDestructorExprClass:
18491 case Expr::UnresolvedLookupExprClass:
18492 case Expr::RecoveryExprClass:
18493 case Expr::DependentScopeDeclRefExprClass:
18494 case Expr::CXXConstructExprClass:
18495 case Expr::CXXInheritedCtorInitExprClass:
18496 case Expr::CXXStdInitializerListExprClass:
18497 case Expr::CXXBindTemporaryExprClass:
18498 case Expr::ExprWithCleanupsClass:
18499 case Expr::CXXTemporaryObjectExprClass:
18500 case Expr::CXXUnresolvedConstructExprClass:
18501 case Expr::CXXDependentScopeMemberExprClass:
18502 case Expr::UnresolvedMemberExprClass:
18503 case Expr::ObjCStringLiteralClass:
18504 case Expr::ObjCBoxedExprClass:
18505 case Expr::ObjCArrayLiteralClass:
18506 case Expr::ObjCDictionaryLiteralClass:
18507 case Expr::ObjCEncodeExprClass:
18508 case Expr::ObjCMessageExprClass:
18509 case Expr::ObjCSelectorExprClass:
18510 case Expr::ObjCProtocolExprClass:
18511 case Expr::ObjCIvarRefExprClass:
18512 case Expr::ObjCPropertyRefExprClass:
18513 case Expr::ObjCSubscriptRefExprClass:
18514 case Expr::ObjCIsaExprClass:
18515 case Expr::ObjCAvailabilityCheckExprClass:
18516 case Expr::ShuffleVectorExprClass:
18517 case Expr::ConvertVectorExprClass:
18518 case Expr::BlockExprClass:
18519 case Expr::NoStmtClass:
18520 case Expr::OpaqueValueExprClass:
18521 case Expr::PackExpansionExprClass:
18522 case Expr::SubstNonTypeTemplateParmPackExprClass:
18523 case Expr::FunctionParmPackExprClass:
18524 case Expr::AsTypeExprClass:
18525 case Expr::ObjCIndirectCopyRestoreExprClass:
18526 case Expr::MaterializeTemporaryExprClass:
18527 case Expr::PseudoObjectExprClass:
18528 case Expr::AtomicExprClass:
18529 case Expr::LambdaExprClass:
18530 case Expr::CXXFoldExprClass:
18531 case Expr::CoawaitExprClass:
18532 case Expr::DependentCoawaitExprClass:
18533 case Expr::CoyieldExprClass:
18534 case Expr::SYCLUniqueStableNameExprClass:
18535 case Expr::CXXParenListInitExprClass:
18536 case Expr::HLSLOutArgExprClass:
18537 return ICEDiag(IK_NotICE, E->getBeginLoc());
18538
18539 case Expr::InitListExprClass: {
18540 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
18541 // form "T x = { a };" is equivalent to "T x = a;".
18542 // Unless we're initializing a reference, T is a scalar as it is known to be
18543 // of integral or enumeration type.
18544 if (E->isPRValue())
18545 if (cast<InitListExpr>(E)->getNumInits() == 1)
18546 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
18547 return ICEDiag(IK_NotICE, E->getBeginLoc());
18548 }
18549
18550 case Expr::SizeOfPackExprClass:
18551 case Expr::GNUNullExprClass:
18552 case Expr::SourceLocExprClass:
18553 case Expr::EmbedExprClass:
18554 case Expr::OpenACCAsteriskSizeExprClass:
18555 return NoDiag();
18556
18557 case Expr::PackIndexingExprClass:
18558 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
18559
18560 case Expr::SubstNonTypeTemplateParmExprClass:
18561 return
18562 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
18563
18564 case Expr::ConstantExprClass:
18565 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
18566
18567 case Expr::ParenExprClass:
18568 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
18569 case Expr::GenericSelectionExprClass:
18570 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
18571 case Expr::IntegerLiteralClass:
18572 case Expr::FixedPointLiteralClass:
18573 case Expr::CharacterLiteralClass:
18574 case Expr::ObjCBoolLiteralExprClass:
18575 case Expr::CXXBoolLiteralExprClass:
18576 case Expr::CXXScalarValueInitExprClass:
18577 case Expr::TypeTraitExprClass:
18578 case Expr::ConceptSpecializationExprClass:
18579 case Expr::RequiresExprClass:
18580 case Expr::ArrayTypeTraitExprClass:
18581 case Expr::ExpressionTraitExprClass:
18582 case Expr::CXXNoexceptExprClass:
18583 return NoDiag();
18584 case Expr::CallExprClass:
18585 case Expr::CXXOperatorCallExprClass: {
18586 // C99 6.6/3 allows function calls within unevaluated subexpressions of
18587 // constant expressions, but they can never be ICEs because an ICE cannot
18588 // contain an operand of (pointer to) function type.
18589 const CallExpr *CE = cast<CallExpr>(E);
18590 if (CE->getBuiltinCallee())
18591 return CheckEvalInICE(E, Ctx);
18592 return ICEDiag(IK_NotICE, E->getBeginLoc());
18593 }
18594 case Expr::CXXRewrittenBinaryOperatorClass:
18595 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
18596 Ctx);
18597 case Expr::DeclRefExprClass: {
18598 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
18599 if (isa<EnumConstantDecl>(D))
18600 return NoDiag();
18601
18602 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
18603 // integer variables in constant expressions:
18604 //
18605 // C++ 7.1.5.1p2
18606 // A variable of non-volatile const-qualified integral or enumeration
18607 // type initialized by an ICE can be used in ICEs.
18608 //
18609 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
18610 // that mode, use of reference variables should not be allowed.
18611 const VarDecl *VD = dyn_cast<VarDecl>(D);
18612 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
18613 !VD->getType()->isReferenceType())
18614 return NoDiag();
18615
18616 return ICEDiag(IK_NotICE, E->getBeginLoc());
18617 }
18618 case Expr::UnaryOperatorClass: {
18619 const UnaryOperator *Exp = cast<UnaryOperator>(E);
18620 switch (Exp->getOpcode()) {
18621 case UO_PostInc:
18622 case UO_PostDec:
18623 case UO_PreInc:
18624 case UO_PreDec:
18625 case UO_AddrOf:
18626 case UO_Deref:
18627 case UO_Coawait:
18628 // C99 6.6/3 allows increment and decrement within unevaluated
18629 // subexpressions of constant expressions, but they can never be ICEs
18630 // because an ICE cannot contain an lvalue operand.
18631 return ICEDiag(IK_NotICE, E->getBeginLoc());
18632 case UO_Extension:
18633 case UO_LNot:
18634 case UO_Plus:
18635 case UO_Minus:
18636 case UO_Not:
18637 case UO_Real:
18638 case UO_Imag:
18639 return CheckICE(Exp->getSubExpr(), Ctx);
18640 }
18641 llvm_unreachable("invalid unary operator class");
18642 }
18643 case Expr::OffsetOfExprClass: {
18644 // Note that per C99, offsetof must be an ICE. And AFAIK, using
18645 // EvaluateAsRValue matches the proposed gcc behavior for cases like
18646 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
18647 // compliance: we should warn earlier for offsetof expressions with
18648 // array subscripts that aren't ICEs, and if the array subscripts
18649 // are ICEs, the value of the offsetof must be an integer constant.
18650 return CheckEvalInICE(E, Ctx);
18651 }
18652 case Expr::UnaryExprOrTypeTraitExprClass: {
18654 if ((Exp->getKind() == UETT_SizeOf) &&
18656 return ICEDiag(IK_NotICE, E->getBeginLoc());
18657 if (Exp->getKind() == UETT_CountOf) {
18658 QualType ArgTy = Exp->getTypeOfArgument();
18659 if (ArgTy->isVariableArrayType()) {
18660 // We need to look whether the array is multidimensional. If it is,
18661 // then we want to check the size expression manually to see whether
18662 // it is an ICE or not.
18663 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
18664 if (VAT->getElementType()->isArrayType())
18665 // Variable array size expression could be missing (e.g. int a[*][10])
18666 // In that case, it can't be a constant expression.
18667 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
18668 : ICEDiag(IK_NotICE, E->getBeginLoc());
18669
18670 // Otherwise, this is a regular VLA, which is definitely not an ICE.
18671 return ICEDiag(IK_NotICE, E->getBeginLoc());
18672 }
18673 }
18674 return NoDiag();
18675 }
18676 case Expr::BinaryOperatorClass: {
18677 const BinaryOperator *Exp = cast<BinaryOperator>(E);
18678 switch (Exp->getOpcode()) {
18679 case BO_PtrMemD:
18680 case BO_PtrMemI:
18681 case BO_Assign:
18682 case BO_MulAssign:
18683 case BO_DivAssign:
18684 case BO_RemAssign:
18685 case BO_AddAssign:
18686 case BO_SubAssign:
18687 case BO_ShlAssign:
18688 case BO_ShrAssign:
18689 case BO_AndAssign:
18690 case BO_XorAssign:
18691 case BO_OrAssign:
18692 // C99 6.6/3 allows assignments within unevaluated subexpressions of
18693 // constant expressions, but they can never be ICEs because an ICE cannot
18694 // contain an lvalue operand.
18695 return ICEDiag(IK_NotICE, E->getBeginLoc());
18696
18697 case BO_Mul:
18698 case BO_Div:
18699 case BO_Rem:
18700 case BO_Add:
18701 case BO_Sub:
18702 case BO_Shl:
18703 case BO_Shr:
18704 case BO_LT:
18705 case BO_GT:
18706 case BO_LE:
18707 case BO_GE:
18708 case BO_EQ:
18709 case BO_NE:
18710 case BO_And:
18711 case BO_Xor:
18712 case BO_Or:
18713 case BO_Comma:
18714 case BO_Cmp: {
18715 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18716 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18717 if (Exp->getOpcode() == BO_Div ||
18718 Exp->getOpcode() == BO_Rem) {
18719 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
18720 // we don't evaluate one.
18721 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
18722 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
18723 if (REval == 0)
18724 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18725 if (REval.isSigned() && REval.isAllOnes()) {
18726 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
18727 if (LEval.isMinSignedValue())
18728 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18729 }
18730 }
18731 }
18732 if (Exp->getOpcode() == BO_Comma) {
18733 if (Ctx.getLangOpts().C99) {
18734 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
18735 // if it isn't evaluated.
18736 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
18737 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18738 } else {
18739 // In both C89 and C++, commas in ICEs are illegal.
18740 return ICEDiag(IK_NotICE, E->getBeginLoc());
18741 }
18742 }
18743 return Worst(LHSResult, RHSResult);
18744 }
18745 case BO_LAnd:
18746 case BO_LOr: {
18747 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18748 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18749 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
18750 // Rare case where the RHS has a comma "side-effect"; we need
18751 // to actually check the condition to see whether the side
18752 // with the comma is evaluated.
18753 if ((Exp->getOpcode() == BO_LAnd) !=
18754 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
18755 return RHSResult;
18756 return NoDiag();
18757 }
18758
18759 return Worst(LHSResult, RHSResult);
18760 }
18761 }
18762 llvm_unreachable("invalid binary operator kind");
18763 }
18764 case Expr::ImplicitCastExprClass:
18765 case Expr::CStyleCastExprClass:
18766 case Expr::CXXFunctionalCastExprClass:
18767 case Expr::CXXStaticCastExprClass:
18768 case Expr::CXXReinterpretCastExprClass:
18769 case Expr::CXXConstCastExprClass:
18770 case Expr::ObjCBridgedCastExprClass: {
18771 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
18772 if (isa<ExplicitCastExpr>(E)) {
18773 if (const FloatingLiteral *FL
18774 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
18775 unsigned DestWidth = Ctx.getIntWidth(E->getType());
18776 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
18777 APSInt IgnoredVal(DestWidth, !DestSigned);
18778 bool Ignored;
18779 // If the value does not fit in the destination type, the behavior is
18780 // undefined, so we are not required to treat it as a constant
18781 // expression.
18782 if (FL->getValue().convertToInteger(IgnoredVal,
18783 llvm::APFloat::rmTowardZero,
18784 &Ignored) & APFloat::opInvalidOp)
18785 return ICEDiag(IK_NotICE, E->getBeginLoc());
18786 return NoDiag();
18787 }
18788 }
18789 switch (cast<CastExpr>(E)->getCastKind()) {
18790 case CK_LValueToRValue:
18791 case CK_AtomicToNonAtomic:
18792 case CK_NonAtomicToAtomic:
18793 case CK_NoOp:
18794 case CK_IntegralToBoolean:
18795 case CK_IntegralCast:
18796 return CheckICE(SubExpr, Ctx);
18797 default:
18798 return ICEDiag(IK_NotICE, E->getBeginLoc());
18799 }
18800 }
18801 case Expr::BinaryConditionalOperatorClass: {
18803 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
18804 if (CommonResult.Kind == IK_NotICE) return CommonResult;
18805 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18806 if (FalseResult.Kind == IK_NotICE) return FalseResult;
18807 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
18808 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
18809 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
18810 return FalseResult;
18811 }
18812 case Expr::ConditionalOperatorClass: {
18814 // If the condition (ignoring parens) is a __builtin_constant_p call,
18815 // then only the true side is actually considered in an integer constant
18816 // expression, and it is fully evaluated. This is an important GNU
18817 // extension. See GCC PR38377 for discussion.
18818 if (const CallExpr *CallCE
18819 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
18820 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
18821 return CheckEvalInICE(E, Ctx);
18822 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
18823 if (CondResult.Kind == IK_NotICE)
18824 return CondResult;
18825
18826 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
18827 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18828
18829 if (TrueResult.Kind == IK_NotICE)
18830 return TrueResult;
18831 if (FalseResult.Kind == IK_NotICE)
18832 return FalseResult;
18833 if (CondResult.Kind == IK_ICEIfUnevaluated)
18834 return CondResult;
18835 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
18836 return NoDiag();
18837 // Rare case where the diagnostics depend on which side is evaluated
18838 // Note that if we get here, CondResult is 0, and at least one of
18839 // TrueResult and FalseResult is non-zero.
18840 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
18841 return FalseResult;
18842 return TrueResult;
18843 }
18844 case Expr::CXXDefaultArgExprClass:
18845 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
18846 case Expr::CXXDefaultInitExprClass:
18847 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
18848 case Expr::ChooseExprClass: {
18849 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
18850 }
18851 case Expr::BuiltinBitCastExprClass: {
18852 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
18853 return ICEDiag(IK_NotICE, E->getBeginLoc());
18854 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
18855 }
18856 }
18857
18858 llvm_unreachable("Invalid StmtClass!");
18859}
18860
18861/// Evaluate an expression as a C++11 integral constant expression.
18863 const Expr *E,
18864 llvm::APSInt *Value) {
18866 return false;
18867
18868 APValue Result;
18869 if (!E->isCXX11ConstantExpr(Ctx, &Result))
18870 return false;
18871
18872 if (!Result.isInt())
18873 return false;
18874
18875 if (Value) *Value = Result.getInt();
18876 return true;
18877}
18878
18880 assert(!isValueDependent() &&
18881 "Expression evaluator can't be called on a dependent expression.");
18882
18883 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
18884
18885 if (Ctx.getLangOpts().CPlusPlus11)
18886 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
18887
18888 ICEDiag D = CheckICE(this, Ctx);
18889 if (D.Kind != IK_ICE)
18890 return false;
18891 return true;
18892}
18893
18894std::optional<llvm::APSInt>
18896 if (isValueDependent()) {
18897 // Expression evaluator can't succeed on a dependent expression.
18898 return std::nullopt;
18899 }
18900
18901 if (Ctx.getLangOpts().CPlusPlus11) {
18902 APSInt Value;
18904 return Value;
18905 return std::nullopt;
18906 }
18907
18908 if (!isIntegerConstantExpr(Ctx))
18909 return std::nullopt;
18910
18911 // The only possible side-effects here are due to UB discovered in the
18912 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
18913 // required to treat the expression as an ICE, so we produce the folded
18914 // value.
18916 Expr::EvalStatus Status;
18917 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
18918 Info.InConstantContext = true;
18919
18920 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
18921 llvm_unreachable("ICE cannot be evaluated!");
18922
18923 return ExprResult.Val.getInt();
18924}
18925
18927 assert(!isValueDependent() &&
18928 "Expression evaluator can't be called on a dependent expression.");
18929
18930 return CheckICE(this, Ctx).Kind == IK_ICE;
18931}
18932
18934 assert(!isValueDependent() &&
18935 "Expression evaluator can't be called on a dependent expression.");
18936
18937 // We support this checking in C++98 mode in order to diagnose compatibility
18938 // issues.
18939 assert(Ctx.getLangOpts().CPlusPlus);
18940
18941 bool IsConst;
18942 APValue Scratch;
18943 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
18944 if (Result)
18945 *Result = Scratch;
18946 return true;
18947 }
18948
18949 // Build evaluation settings.
18950 Expr::EvalStatus Status;
18952 Status.Diag = &Diags;
18953 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
18954
18955 bool IsConstExpr =
18956 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
18957 // FIXME: We don't produce a diagnostic for this, but the callers that
18958 // call us on arbitrary full-expressions should generally not care.
18959 Info.discardCleanups() && !Status.HasSideEffects;
18960
18961 return IsConstExpr && Diags.empty();
18962}
18963
18965 const FunctionDecl *Callee,
18967 const Expr *This) const {
18968 assert(!isValueDependent() &&
18969 "Expression evaluator can't be called on a dependent expression.");
18970
18971 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
18972 std::string Name;
18973 llvm::raw_string_ostream OS(Name);
18974 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
18975 /*Qualified=*/true);
18976 return Name;
18977 });
18978
18979 Expr::EvalStatus Status;
18980 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
18981 Info.InConstantContext = true;
18982
18983 LValue ThisVal;
18984 const LValue *ThisPtr = nullptr;
18985 if (This) {
18986#ifndef NDEBUG
18987 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
18988 assert(MD && "Don't provide `this` for non-methods.");
18989 assert(MD->isImplicitObjectMemberFunction() &&
18990 "Don't provide `this` for methods without an implicit object.");
18991#endif
18992 if (!This->isValueDependent() &&
18993 EvaluateObjectArgument(Info, This, ThisVal) &&
18994 !Info.EvalStatus.HasSideEffects)
18995 ThisPtr = &ThisVal;
18996
18997 // Ignore any side-effects from a failed evaluation. This is safe because
18998 // they can't interfere with any other argument evaluation.
18999 Info.EvalStatus.HasSideEffects = false;
19000 }
19001
19002 CallRef Call = Info.CurrentCall->createCall(Callee);
19003 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
19004 I != E; ++I) {
19005 unsigned Idx = I - Args.begin();
19006 if (Idx >= Callee->getNumParams())
19007 break;
19008 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
19009 if ((*I)->isValueDependent() ||
19010 !EvaluateCallArg(PVD, *I, Call, Info) ||
19011 Info.EvalStatus.HasSideEffects) {
19012 // If evaluation fails, throw away the argument entirely.
19013 if (APValue *Slot = Info.getParamSlot(Call, PVD))
19014 *Slot = APValue();
19015 }
19016
19017 // Ignore any side-effects from a failed evaluation. This is safe because
19018 // they can't interfere with any other argument evaluation.
19019 Info.EvalStatus.HasSideEffects = false;
19020 }
19021
19022 // Parameter cleanups happen in the caller and are not part of this
19023 // evaluation.
19024 Info.discardCleanups();
19025 Info.EvalStatus.HasSideEffects = false;
19026
19027 // Build fake call to Callee.
19028 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
19029 Call);
19030 // FIXME: Missing ExprWithCleanups in enable_if conditions?
19031 FullExpressionRAII Scope(Info);
19032 return Evaluate(Value, Info, this) && Scope.destroy() &&
19033 !Info.EvalStatus.HasSideEffects;
19034}
19035
19038 PartialDiagnosticAt> &Diags) {
19039 // FIXME: It would be useful to check constexpr function templates, but at the
19040 // moment the constant expression evaluator cannot cope with the non-rigorous
19041 // ASTs which we build for dependent expressions.
19042 if (FD->isDependentContext())
19043 return true;
19044
19045 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
19046 std::string Name;
19047 llvm::raw_string_ostream OS(Name);
19049 /*Qualified=*/true);
19050 return Name;
19051 });
19052
19053 Expr::EvalStatus Status;
19054 Status.Diag = &Diags;
19055
19056 EvalInfo Info(FD->getASTContext(), Status,
19058 Info.InConstantContext = true;
19059 Info.CheckingPotentialConstantExpression = true;
19060
19061 // The constexpr VM attempts to compile all methods to bytecode here.
19062 if (Info.EnableNewConstInterp) {
19063 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
19064 return Diags.empty();
19065 }
19066
19067 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
19068 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
19069
19070 // Fabricate an arbitrary expression on the stack and pretend that it
19071 // is a temporary being used as the 'this' pointer.
19072 LValue This;
19073 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
19074 : Info.Ctx.IntTy);
19075 This.set({&VIE, Info.CurrentCall->Index});
19076
19078
19079 APValue Scratch;
19080 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
19081 // Evaluate the call as a constant initializer, to allow the construction
19082 // of objects of non-literal types.
19083 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
19084 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
19085 } else {
19086 SourceLocation Loc = FD->getLocation();
19088 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
19089 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
19090 /*ResultSlot=*/nullptr);
19091 }
19092
19093 return Diags.empty();
19094}
19095
19097 const FunctionDecl *FD,
19099 PartialDiagnosticAt> &Diags) {
19100 assert(!E->isValueDependent() &&
19101 "Expression evaluator can't be called on a dependent expression.");
19102
19103 Expr::EvalStatus Status;
19104 Status.Diag = &Diags;
19105
19106 EvalInfo Info(FD->getASTContext(), Status,
19108 Info.InConstantContext = true;
19109 Info.CheckingPotentialConstantExpression = true;
19110
19111 if (Info.EnableNewConstInterp) {
19113 return Diags.empty();
19114 }
19115
19116 // Fabricate a call stack frame to give the arguments a plausible cover story.
19117 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
19118 /*CallExpr=*/nullptr, CallRef());
19119
19120 APValue ResultScratch;
19121 Evaluate(ResultScratch, Info, E);
19122 return Diags.empty();
19123}
19124
19126 unsigned Type) const {
19127 if (!getType()->isPointerType())
19128 return false;
19129
19130 Expr::EvalStatus Status;
19131 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
19132 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
19133}
19134
19135static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
19136 EvalInfo &Info, std::string *StringResult) {
19137 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
19138 return false;
19139
19140 LValue String;
19141
19142 if (!EvaluatePointer(E, String, Info))
19143 return false;
19144
19145 QualType CharTy = E->getType()->getPointeeType();
19146
19147 // Fast path: if it's a string literal, search the string value.
19148 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
19149 String.getLValueBase().dyn_cast<const Expr *>())) {
19150 StringRef Str = S->getBytes();
19151 int64_t Off = String.Offset.getQuantity();
19152 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
19153 S->getCharByteWidth() == 1 &&
19154 // FIXME: Add fast-path for wchar_t too.
19155 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
19156 Str = Str.substr(Off);
19157
19158 StringRef::size_type Pos = Str.find(0);
19159 if (Pos != StringRef::npos)
19160 Str = Str.substr(0, Pos);
19161
19162 Result = Str.size();
19163 if (StringResult)
19164 *StringResult = Str;
19165 return true;
19166 }
19167
19168 // Fall through to slow path.
19169 }
19170
19171 // Slow path: scan the bytes of the string looking for the terminating 0.
19172 for (uint64_t Strlen = 0; /**/; ++Strlen) {
19173 APValue Char;
19174 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
19175 !Char.isInt())
19176 return false;
19177 if (!Char.getInt()) {
19178 Result = Strlen;
19179 return true;
19180 } else if (StringResult)
19181 StringResult->push_back(Char.getInt().getExtValue());
19182 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
19183 return false;
19184 }
19185}
19186
19187std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
19188 Expr::EvalStatus Status;
19189 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
19190 uint64_t Result;
19191 std::string StringResult;
19192
19193 if (Info.EnableNewConstInterp) {
19194 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
19195 return std::nullopt;
19196 return StringResult;
19197 }
19198
19199 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
19200 return StringResult;
19201 return std::nullopt;
19202}
19203
19204template <typename T>
19205static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
19206 const Expr *SizeExpression,
19207 const Expr *PtrExpression,
19208 ASTContext &Ctx,
19209 Expr::EvalResult &Status) {
19210 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
19211 Info.InConstantContext = true;
19212
19213 if (Info.EnableNewConstInterp)
19214 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
19215 PtrExpression, Result);
19216
19217 LValue String;
19218 FullExpressionRAII Scope(Info);
19219 APSInt SizeValue;
19220 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
19221 return false;
19222
19223 uint64_t Size = SizeValue.getZExtValue();
19224
19225 // FIXME: better protect against invalid or excessive sizes
19226 if constexpr (std::is_same_v<APValue, T>)
19227 Result = APValue(APValue::UninitArray{}, Size, Size);
19228 else {
19229 if (Size < Result.max_size())
19230 Result.reserve(Size);
19231 }
19232 if (!::EvaluatePointer(PtrExpression, String, Info))
19233 return false;
19234
19235 QualType CharTy = PtrExpression->getType()->getPointeeType();
19236 for (uint64_t I = 0; I < Size; ++I) {
19237 APValue Char;
19238 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
19239 Char))
19240 return false;
19241
19242 if constexpr (std::is_same_v<APValue, T>) {
19243 Result.getArrayInitializedElt(I) = std::move(Char);
19244 } else {
19245 APSInt C = Char.getInt();
19246
19247 assert(C.getBitWidth() <= 8 &&
19248 "string element not representable in char");
19249
19250 Result.push_back(static_cast<char>(C.getExtValue()));
19251 }
19252
19253 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
19254 return false;
19255 }
19256
19257 return Scope.destroy() && CheckMemoryLeaks(Info);
19258}
19259
19261 const Expr *SizeExpression,
19262 const Expr *PtrExpression, ASTContext &Ctx,
19263 EvalResult &Status) const {
19264 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
19265 PtrExpression, Ctx, Status);
19266}
19267
19269 const Expr *SizeExpression,
19270 const Expr *PtrExpression, ASTContext &Ctx,
19271 EvalResult &Status) const {
19272 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
19273 PtrExpression, Ctx, Status);
19274}
19275
19276bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
19277 Expr::EvalStatus Status;
19278 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
19279
19280 if (Info.EnableNewConstInterp)
19281 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
19282
19283 return EvaluateBuiltinStrLen(this, Result, Info);
19284}
19285
19286namespace {
19287struct IsWithinLifetimeHandler {
19288 EvalInfo &Info;
19289 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
19290 using result_type = std::optional<bool>;
19291 std::optional<bool> failed() { return std::nullopt; }
19292 template <typename T>
19293 std::optional<bool> found(T &Subobj, QualType SubobjType) {
19294 return true;
19295 }
19296};
19297
19298std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
19299 const CallExpr *E) {
19300 EvalInfo &Info = IEE.Info;
19301 // Sometimes this is called during some sorts of constant folding / early
19302 // evaluation. These are meant for non-constant expressions and are not
19303 // necessary since this consteval builtin will never be evaluated at runtime.
19304 // Just fail to evaluate when not in a constant context.
19305 if (!Info.InConstantContext)
19306 return std::nullopt;
19307 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
19308 const Expr *Arg = E->getArg(0);
19309 if (Arg->isValueDependent())
19310 return std::nullopt;
19311 LValue Val;
19312 if (!EvaluatePointer(Arg, Val, Info))
19313 return std::nullopt;
19314
19315 if (Val.allowConstexprUnknown())
19316 return true;
19317
19318 auto Error = [&](int Diag) {
19319 bool CalledFromStd = false;
19320 const auto *Callee = Info.CurrentCall->getCallee();
19321 if (Callee && Callee->isInStdNamespace()) {
19322 const IdentifierInfo *Identifier = Callee->getIdentifier();
19323 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
19324 }
19325 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
19326 : E->getExprLoc(),
19327 diag::err_invalid_is_within_lifetime)
19328 << (CalledFromStd ? "std::is_within_lifetime"
19329 : "__builtin_is_within_lifetime")
19330 << Diag;
19331 return std::nullopt;
19332 };
19333 // C++2c [meta.const.eval]p4:
19334 // During the evaluation of an expression E as a core constant expression, a
19335 // call to this function is ill-formed unless p points to an object that is
19336 // usable in constant expressions or whose complete object's lifetime began
19337 // within E.
19338
19339 // Make sure it points to an object
19340 // nullptr does not point to an object
19341 if (Val.isNullPointer() || Val.getLValueBase().isNull())
19342 return Error(0);
19343 QualType T = Val.getLValueBase().getType();
19344 assert(!T->isFunctionType() &&
19345 "Pointers to functions should have been typed as function pointers "
19346 "which would have been rejected earlier");
19347 assert(T->isObjectType());
19348 // Hypothetical array element is not an object
19349 if (Val.getLValueDesignator().isOnePastTheEnd())
19350 return Error(1);
19351 assert(Val.getLValueDesignator().isValidSubobject() &&
19352 "Unchecked case for valid subobject");
19353 // All other ill-formed values should have failed EvaluatePointer, so the
19354 // object should be a pointer to an object that is usable in a constant
19355 // expression or whose complete lifetime began within the expression
19356 CompleteObject CO =
19357 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
19358 // The lifetime hasn't begun yet if we are still evaluating the
19359 // initializer ([basic.life]p(1.2))
19360 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
19361 return Error(2);
19362
19363 if (!CO)
19364 return false;
19365 IsWithinLifetimeHandler handler{Info};
19366 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
19367}
19368} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
llvm::APSInt APSInt
Definition Compiler.cpp:23
static Decl::Kind getKind(const Decl *D)
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 evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result, llvm::function_ref< APInt(const APSInt &)> PackFn)
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. This ignores some c...
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. C++11 [dcl.init]p5: To zero-initial...
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 evalPshufBuiltin(EvalInfo &Info, const CallExpr *Call, bool IsShufHW, APValue &Out)
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. If successful, returns true and stores the result ...
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. In some cases, the in-place evaluati...
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. This can be legitimately called on expressions which are not glv...
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. LVal's base must be a call to an alloc_size 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. Fails if the conversion would ...
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
llvm::SmallPtrSet< const MaterializeTemporaryExpr *, 8 > CheckedTemporaries
Materialized temporaries that we've already checked to determine if they're initializsed by a constan...
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)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
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.
#define X(type, name)
Definition Value.h:97
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.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
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)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
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
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:221
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:220
SourceManager & getSourceManager()
Definition ASTContext.h:833
const ConstantArrayType * getAsConstantArrayType(QualType T) const
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.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
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,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
CanQualType VoidPtrTy
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:774
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
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<=>,...
CanQualType CharTy
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CanQualType IntTy
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
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:825
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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.
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.
const VariableArrayType * getAsVariableArrayType(QualType T) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
DiagnosticsEngine & getDiagnostics() const
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
LabelDecl * getLabel() const
Definition Expr.h:4507
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5917
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
uint64_t getValue() const
Definition ExprCXX.h:3046
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
QualType getElementType() const
Definition TypeBase.h:3734
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8093
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:4387
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4441
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4425
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4422
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4066
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4072
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4119
SourceLocation getExprLoc() const
Definition Expr.h:4013
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4049
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4108
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4773
const BlockDecl * getBlockDecl() const
Definition Expr.h:6570
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
bool isConstantEvaluated(unsigned ID) const
Return true if this function can be constant evaluated by Clang frontend.
Definition Builtins.h:431
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
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
const Expr * getSubExpr() const
Definition ExprCXX.h:1516
bool getValue() const
Definition ExprCXX.h:740
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1618
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1651
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
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
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2667
bool isArrayForm() const
Definition ExprCXX.h:2654
bool isGlobalDelete() const
Definition ExprCXX.h:2653
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1790
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
QualType getAllocatedType() const
Definition ExprCXX.h:2436
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2471
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2505
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2496
SourceRange getSourceRange() const
Definition ExprCXX.h:2612
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2461
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2535
bool getValue() const
Definition ExprCXX.h:4334
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5183
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
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
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.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:304
bool isImplicit() const
Definition ExprCXX.h:1178
bool isTypeOperand() const
Definition ExprCXX.h:884
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:161
Expr * getExprOperand() const
Definition ExprCXX.h:895
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1115
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3569
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1588
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
Decl * getCalleeDecl()
Definition Expr.h:3054
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
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:3610
path_iterator path_begin()
Definition Expr.h:3680
unsigned path_size() const
Definition Expr.h:3679
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3677
bool path_empty() const
Definition Expr.h:3678
Expr * getSubExpr()
Definition Expr.h:3660
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3724
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
unsigned getValue() const
Definition Expr.h:1629
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4818
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:3275
QualType getElementType() const
Definition TypeBase.h:3285
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4234
QualType getComputationLHSType() const
Definition Expr.h:4268
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3539
bool hasStaticStorage() const
Definition Expr.h:3584
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5538
bool isFileScope() const
Definition Expr.h:3571
const Expr * getInitializer() const
Definition Expr.h:3567
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
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4357
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4348
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4352
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3823
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:3849
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3830
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3856
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3836
APValue getAPValueResult() const
Definition Expr.cpp:409
bool hasAPValueResult() const
Definition Expr.h:1157
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4730
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4743
Represents the current source location and context used to determine the value of the source location...
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 Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1474
ValueDecl * getDecl()
Definition Expr.h:1338
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
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
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
A decomposition declaration.
Definition DeclCXX.h:4249
auto flat_bindings() const
Definition DeclCXX.h:4292
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
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
ChildElementIter< false > begin()
Definition Expr.h:5166
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3862
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3889
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:3090
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
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...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:3963
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
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:3081
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:3665
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:3248
Expr()=delete
ConstantExprKind
Definition Expr.h:749
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
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4412
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4444
const Expr * getBase() const
Definition Expr.h:6515
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4740
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3245
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3407
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:103
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1575
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2888
Stmt * getInit()
Definition Stmt.h:2903
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1078
Stmt * getBody()
Definition Stmt.h:2932
Expr * getInc()
Definition Stmt.h:2931
Expr * getCond()
Definition Stmt.h:2930
const Expr * getSubExpr() const
Definition Expr.h:1062
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
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:4193
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4181
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3853
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4317
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition Decl.h:2783
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
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:2385
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
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6396
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
const Expr * getSubExpr() const
Definition Expr.h:1743
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:5991
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3488
Describes an C or C++ initializer list.
Definition Expr.h:5233
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2457
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2443
unsigned getNumInits() const
Definition Expr.h:5263
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5335
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
ArrayRef< Expr * > inits()
Definition Expr.h:5283
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2108
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2096
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1400
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4922
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4947
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4939
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4955
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:153
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2586
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2574
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2567
unsigned getNumComponents() const
Definition Expr.h:2582
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2479
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2485
@ Array
An index into an array.
Definition Expr.h:2426
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2430
@ Field
A field.
Definition Expr.h:2428
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2433
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2475
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2495
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
Expr * getSelectedExpr() const
Definition ExprCXX.h:4641
const Expr * getSubExpr() const
Definition Expr.h:2199
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
bool isExplicitObjectParameter() const
Definition Decl.h:1878
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
StringLiteral * getFunctionName()
Definition Expr.h:2049
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6738
ArrayRef< Expr * > semantics()
Definition Expr.h:6762
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8378
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:8294
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:8479
QualType getCanonicalType() const
Definition TypeBase.h:8346
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8388
void removeLocalVolatile()
Definition TypeBase.h:8410
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1164
void removeLocalConst()
Definition TypeBase.h:8402
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8367
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:8340
Represents a struct/union/class.
Definition Decl.h:4312
field_iterator field_end() const
Definition Decl.h:4518
field_range fields() const
Definition Decl.h:4515
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4512
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4364
bool field_empty() const
Definition Decl.h:4523
field_iterator field_begin() const
Definition Decl.cpp:5201
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2155
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:583
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:4577
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4629
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4610
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4616
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4517
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2277
bool isIntType() const
Definition Expr.h:4975
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
std::string printToString(const SourceManager &SM) const
CompoundStmt * getSubStmt()
Definition Expr.h:4546
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
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:1799
unsigned getLength() const
Definition Expr.h:1909
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1875
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1882
StringRef getString() const
Definition Expr.h:1867
unsigned getCharByteWidth() const
Definition Expr.h:1910
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:4887
bool isUnion() const
Definition Decl.h:3922
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:853
bool isBigEndian() const
virtual int getEHDataRegisterNumber(unsigned RegNo) const
Return the register number that __builtin_eh_return_regno would return with the specified argument.
unsigned getCharWidth() const
Definition TargetInfo.h:517
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
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:8276
bool getBoolValue() const
Definition ExprCXX.h:2949
const APValue & getAPValue() const
Definition ExprCXX.h:2954
bool isStoredAsBoolean() const
Definition ExprCXX.h:2945
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8887
bool isBooleanType() const
Definition TypeBase.h:9017
bool isFunctionReferenceType() const
Definition TypeBase.h:8605
bool isMFloat8Type() const
Definition TypeBase.h:8912
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
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:2994
bool isIncompleteArrayType() const
Definition TypeBase.h:8638
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
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:9183
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
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:8634
bool isNothrowT() const
Definition Type.cpp:3171
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:2426
bool isArrayType() const
Definition TypeBase.h:8630
bool isFunctionPointerType() const
Definition TypeBase.h:8598
bool isPointerType() const
Definition TypeBase.h:8531
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8931
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9174
bool isReferenceType() const
Definition TypeBase.h:8555
bool isEnumeralType() const
Definition TypeBase.h:8662
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1909
bool isVariableArrayType() const
Definition TypeBase.h:8642
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
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:9005
bool isExtVectorBoolType() const
Definition TypeBase.h:8678
bool isMemberDataPointerType() const
Definition TypeBase.h:8623
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8856
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8666
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8943
bool isMemberPointerType() const
Definition TypeBase.h:8612
bool isAtomicType() const
Definition TypeBase.h:8713
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:9160
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
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:2436
bool isFunctionType() const
Definition TypeBase.h:8527
bool isVectorType() const
Definition TypeBase.h:8670
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
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:2253
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2928
bool isAnyPointerType() const
Definition TypeBase.h:8539
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9107
bool isNullPtrType() const
Definition TypeBase.h:8924
bool isRecordType() const
Definition TypeBase.h:8658
bool isUnionType() const
Definition Type.cpp:718
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9051
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
QualType getArgumentType() const
Definition Expr.h:2668
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2704
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2694
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2657
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
SourceLocation getExprLoc() const
Definition Expr.h:2368
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2326
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2298
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5500
QualType getType() const
Definition Value.cpp:237
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:926
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
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:1578
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
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2557
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:1208
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
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:1184
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:1253
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:1358
Expr * getSizeExpr() const
Definition TypeBase.h:3980
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
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
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:224
bool evaluateString(State &Parent, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:240
bool evaluateStrlen(State &Parent, const Expr *E, uint64_t &Result)
Evalute.
Definition Context.cpp:286
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:57
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:37
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:70
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:100
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:79
#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
unsigned kind
All of the diagnostics that can be emitted by the frontend.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1260
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:41
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2815
llvm::APFloat APFloat
Definition Floating.h:27
llvm::APInt APInt
Definition FixedPoint.h:19
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition Interp.h:3488
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
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.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1042
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:204
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
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
@ Result
The result type of a method or function.
Definition TypeBase.h:905
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
const FunctionProtoType * T
@ Type
The name was classified as a type.
Definition Sema.h:562
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
EvaluationMode
Definition State.h:53
@ ConstantFold
Fold the expression to a constant.
Definition State.h:67
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:63
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:56
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:71
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:830
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5876
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
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
bool isGlobalLValue() const
Return true if the evaluated lvalue expression is global.
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 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 trunc(__x)
Definition tgmath.h:1216
#define scalbn(__x, __y)
Definition tgmath.h:1165